diff --git a/deps/exla/cache/xla_extension/include/include/cpuinfo.h b/deps/exla/cache/xla_extension/include/include/cpuinfo.h new file mode 100644 index 0000000000000000000000000000000000000000..f1d35d4dbf9885cc9ac3b412f2aad86fdfa7615f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/cpuinfo.h @@ -0,0 +1,2331 @@ +#pragma once +#ifndef CPUINFO_H +#define CPUINFO_H + +#ifndef __cplusplus +#include +#endif + +#ifdef __APPLE__ +#include +#endif + +#include + +/* Identify architecture and define corresponding macro */ + +#if defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_M_IX86) +#define CPUINFO_ARCH_X86 1 +#endif + +#if defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64) +#define CPUINFO_ARCH_X86_64 1 +#endif + +#if defined(__arm__) || defined(_M_ARM) +#define CPUINFO_ARCH_ARM 1 +#endif + +#if defined(__aarch64__) || defined(_M_ARM64) +#define CPUINFO_ARCH_ARM64 1 +#endif + +#if defined(__PPC64__) || defined(__powerpc64__) || defined(_ARCH_PPC64) +#define CPUINFO_ARCH_PPC64 1 +#endif + +#if defined(__asmjs__) +#define CPUINFO_ARCH_ASMJS 1 +#endif + +#if defined(__wasm__) +#if defined(__wasm_simd128__) +#define CPUINFO_ARCH_WASMSIMD 1 +#else +#define CPUINFO_ARCH_WASM 1 +#endif +#endif + +#if defined(__riscv) +#if (__riscv_xlen == 32) +#define CPUINFO_ARCH_RISCV32 1 +#elif (__riscv_xlen == 64) +#define CPUINFO_ARCH_RISCV64 1 +#endif +#endif + +/* Define other architecture-specific macros as 0 */ + +#ifndef CPUINFO_ARCH_X86 +#define CPUINFO_ARCH_X86 0 +#endif + +#ifndef CPUINFO_ARCH_X86_64 +#define CPUINFO_ARCH_X86_64 0 +#endif + +#ifndef CPUINFO_ARCH_ARM +#define CPUINFO_ARCH_ARM 0 +#endif + +#ifndef CPUINFO_ARCH_ARM64 +#define CPUINFO_ARCH_ARM64 0 +#endif + +#ifndef CPUINFO_ARCH_PPC64 +#define CPUINFO_ARCH_PPC64 0 +#endif + +#ifndef CPUINFO_ARCH_ASMJS +#define CPUINFO_ARCH_ASMJS 0 +#endif + +#ifndef CPUINFO_ARCH_WASM +#define CPUINFO_ARCH_WASM 0 +#endif + +#ifndef CPUINFO_ARCH_WASMSIMD +#define CPUINFO_ARCH_WASMSIMD 0 +#endif + +#ifndef CPUINFO_ARCH_RISCV32 +#define CPUINFO_ARCH_RISCV32 0 +#endif + +#ifndef CPUINFO_ARCH_RISCV64 +#define CPUINFO_ARCH_RISCV64 0 +#endif + +#if CPUINFO_ARCH_X86 && defined(_MSC_VER) +#define CPUINFO_ABI __cdecl +#elif CPUINFO_ARCH_X86 && defined(__GNUC__) +#define CPUINFO_ABI __attribute__((__cdecl__)) +#else +#define CPUINFO_ABI +#endif + +#define CPUINFO_CACHE_UNIFIED 0x00000001 +#define CPUINFO_CACHE_INCLUSIVE 0x00000002 +#define CPUINFO_CACHE_COMPLEX_INDEXING 0x00000004 + +struct cpuinfo_cache { + /** Cache size in bytes */ + uint32_t size; + /** Number of ways of associativity */ + uint32_t associativity; + /** Number of sets */ + uint32_t sets; + /** Number of partitions */ + uint32_t partitions; + /** Line size in bytes */ + uint32_t line_size; + /** + * Binary characteristics of the cache (unified cache, inclusive cache, + * cache with complex indexing). + * + * @see CPUINFO_CACHE_UNIFIED, CPUINFO_CACHE_INCLUSIVE, + * CPUINFO_CACHE_COMPLEX_INDEXING + */ + uint32_t flags; + /** Index of the first logical processor that shares this cache */ + uint32_t processor_start; + /** Number of logical processors that share this cache */ + uint32_t processor_count; +}; + +struct cpuinfo_trace_cache { + uint32_t uops; + uint32_t associativity; +}; + +#define CPUINFO_PAGE_SIZE_4KB 0x1000 +#define CPUINFO_PAGE_SIZE_1MB 0x100000 +#define CPUINFO_PAGE_SIZE_2MB 0x200000 +#define CPUINFO_PAGE_SIZE_4MB 0x400000 +#define CPUINFO_PAGE_SIZE_16MB 0x1000000 +#define CPUINFO_PAGE_SIZE_1GB 0x40000000 + +struct cpuinfo_tlb { + uint32_t entries; + uint32_t associativity; + uint64_t pages; +}; + +/** Vendor of processor core design */ +enum cpuinfo_vendor { + /** Processor vendor is not known to the library, or the library failed + to get vendor information from the OS. */ + cpuinfo_vendor_unknown = 0, + + /* Active vendors of modern CPUs */ + + /** + * Intel Corporation. Vendor of x86, x86-64, IA64, and ARM processor + * microarchitectures. + * + * Sold its ARM design subsidiary in 2006. The last ARM processor design + * was released in 2004. + */ + cpuinfo_vendor_intel = 1, + /** Advanced Micro Devices, Inc. Vendor of x86 and x86-64 processor + microarchitectures. */ + cpuinfo_vendor_amd = 2, + /** ARM Holdings plc. Vendor of ARM and ARM64 processor + microarchitectures. */ + cpuinfo_vendor_arm = 3, + /** Qualcomm Incorporated. Vendor of ARM and ARM64 processor + microarchitectures. */ + cpuinfo_vendor_qualcomm = 4, + /** Apple Inc. Vendor of ARM and ARM64 processor microarchitectures. */ + cpuinfo_vendor_apple = 5, + /** Samsung Electronics Co., Ltd. Vendir if ARM64 processor + microarchitectures. */ + cpuinfo_vendor_samsung = 6, + /** Nvidia Corporation. Vendor of ARM64-compatible processor + microarchitectures. */ + cpuinfo_vendor_nvidia = 7, + /** MIPS Technologies, Inc. Vendor of MIPS processor microarchitectures. + */ + cpuinfo_vendor_mips = 8, + /** International Business Machines Corporation. Vendor of PowerPC + processor microarchitectures. */ + cpuinfo_vendor_ibm = 9, + /** Ingenic Semiconductor. Vendor of MIPS processor microarchitectures. + */ + cpuinfo_vendor_ingenic = 10, + /** + * VIA Technologies, Inc. Vendor of x86 and x86-64 processor + * microarchitectures. + * + * Processors are designed by Centaur Technology, a subsidiary of VIA + * Technologies. + */ + cpuinfo_vendor_via = 11, + /** Cavium, Inc. Vendor of ARM64 processor microarchitectures. */ + cpuinfo_vendor_cavium = 12, + /** Broadcom, Inc. Vendor of ARM processor microarchitectures. */ + cpuinfo_vendor_broadcom = 13, + /** Applied Micro Circuits Corporation (APM). Vendor of ARM64 processor + microarchitectures. */ + cpuinfo_vendor_apm = 14, + /** + * Huawei Technologies Co., Ltd. Vendor of ARM64 processor + * microarchitectures. + * + * Processors are designed by HiSilicon, a subsidiary of Huawei. + */ + cpuinfo_vendor_huawei = 15, + /** + * Hygon (Chengdu Haiguang Integrated Circuit Design Co., Ltd), Vendor + * of x86-64 processor microarchitectures. + * + * Processors are variants of AMD cores. + */ + cpuinfo_vendor_hygon = 16, + /** SiFive, Inc. Vendor of RISC-V processor microarchitectures. */ + cpuinfo_vendor_sifive = 17, + + /* Active vendors of embedded CPUs */ + + /** Texas Instruments Inc. Vendor of ARM processor microarchitectures. + */ + cpuinfo_vendor_texas_instruments = 30, + /** Marvell Technology Group Ltd. Vendor of ARM processor + * microarchitectures. + */ + cpuinfo_vendor_marvell = 31, + /** RDC Semiconductor Co., Ltd. Vendor of x86 processor + microarchitectures. */ + cpuinfo_vendor_rdc = 32, + /** DM&P Electronics Inc. Vendor of x86 processor microarchitectures. */ + cpuinfo_vendor_dmp = 33, + /** Motorola, Inc. Vendor of PowerPC and ARM processor + microarchitectures. */ + cpuinfo_vendor_motorola = 34, + + /* Defunct CPU vendors */ + + /** + * Transmeta Corporation. Vendor of x86 processor microarchitectures. + * + * Now defunct. The last processor design was released in 2004. + * Transmeta processors implemented VLIW ISA and used binary translation + * to execute x86 code. + */ + cpuinfo_vendor_transmeta = 50, + /** + * Cyrix Corporation. Vendor of x86 processor microarchitectures. + * + * Now defunct. The last processor design was released in 1996. + */ + cpuinfo_vendor_cyrix = 51, + /** + * Rise Technology. Vendor of x86 processor microarchitectures. + * + * Now defunct. The last processor design was released in 1999. + */ + cpuinfo_vendor_rise = 52, + /** + * National Semiconductor. Vendor of x86 processor microarchitectures. + * + * Sold its x86 design subsidiary in 1999. The last processor design was + * released in 1998. + */ + cpuinfo_vendor_nsc = 53, + /** + * Silicon Integrated Systems. Vendor of x86 processor + * microarchitectures. + * + * Sold its x86 design subsidiary in 2001. The last processor design was + * released in 2001. + */ + cpuinfo_vendor_sis = 54, + /** + * NexGen. Vendor of x86 processor microarchitectures. + * + * Now defunct. The last processor design was released in 1994. + * NexGen designed the first x86 microarchitecture which decomposed x86 + * instructions into simple microoperations. + */ + cpuinfo_vendor_nexgen = 55, + /** + * United Microelectronics Corporation. Vendor of x86 processor + * microarchitectures. + * + * Ceased x86 in the early 1990s. The last processor design was released + * in 1991. Designed U5C and U5D processors. Both are 486 level. + */ + cpuinfo_vendor_umc = 56, + /** + * Digital Equipment Corporation. Vendor of ARM processor + * microarchitecture. + * + * Sold its ARM designs in 1997. The last processor design was released + * in 1997. + */ + cpuinfo_vendor_dec = 57, +}; + +/** + * Processor microarchitecture + * + * Processors with different microarchitectures often have different instruction + * performance characteristics, and may have dramatically different pipeline + * organization. + */ +enum cpuinfo_uarch { + /** Microarchitecture is unknown, or the library failed to get + information about the microarchitecture from OS */ + cpuinfo_uarch_unknown = 0, + + /** Pentium and Pentium MMX microarchitecture. */ + cpuinfo_uarch_p5 = 0x00100100, + /** Intel Quark microarchitecture. */ + cpuinfo_uarch_quark = 0x00100101, + + /** Pentium Pro, Pentium II, and Pentium III. */ + cpuinfo_uarch_p6 = 0x00100200, + /** Pentium M. */ + cpuinfo_uarch_dothan = 0x00100201, + /** Intel Core microarchitecture. */ + cpuinfo_uarch_yonah = 0x00100202, + /** Intel Core 2 microarchitecture on 65 nm process. */ + cpuinfo_uarch_conroe = 0x00100203, + /** Intel Core 2 microarchitecture on 45 nm process. */ + cpuinfo_uarch_penryn = 0x00100204, + /** Intel Nehalem and Westmere microarchitectures (Core i3/i5/i7 1st + gen). */ + cpuinfo_uarch_nehalem = 0x00100205, + /** Intel Sandy Bridge microarchitecture (Core i3/i5/i7 2nd gen). */ + cpuinfo_uarch_sandy_bridge = 0x00100206, + /** Intel Ivy Bridge microarchitecture (Core i3/i5/i7 3rd gen). */ + cpuinfo_uarch_ivy_bridge = 0x00100207, + /** Intel Haswell microarchitecture (Core i3/i5/i7 4th gen). */ + cpuinfo_uarch_haswell = 0x00100208, + /** Intel Broadwell microarchitecture. */ + cpuinfo_uarch_broadwell = 0x00100209, + /** Intel Sky Lake microarchitecture (14 nm, including + Kaby/Coffee/Whiskey/Amber/Comet/Cascade/Cooper Lake). */ + cpuinfo_uarch_sky_lake = 0x0010020A, + /** DEPRECATED (Intel Kaby Lake microarchitecture). */ + cpuinfo_uarch_kaby_lake = 0x0010020A, + /** Intel Palm Cove microarchitecture (10 nm, Cannon Lake). */ + cpuinfo_uarch_palm_cove = 0x0010020B, + /** Intel Sunny Cove microarchitecture (10 nm, Ice Lake). */ + cpuinfo_uarch_sunny_cove = 0x0010020C, + + /** Pentium 4 with Willamette, Northwood, or Foster cores. */ + cpuinfo_uarch_willamette = 0x00100300, + /** Pentium 4 with Prescott and later cores. */ + cpuinfo_uarch_prescott = 0x00100301, + + /** Intel Atom on 45 nm process. */ + cpuinfo_uarch_bonnell = 0x00100400, + /** Intel Atom on 32 nm process. */ + cpuinfo_uarch_saltwell = 0x00100401, + /** Intel Silvermont microarchitecture (22 nm out-of-order Atom). */ + cpuinfo_uarch_silvermont = 0x00100402, + /** Intel Airmont microarchitecture (14 nm out-of-order Atom). */ + cpuinfo_uarch_airmont = 0x00100403, + /** Intel Goldmont microarchitecture (Denverton, Apollo Lake). */ + cpuinfo_uarch_goldmont = 0x00100404, + /** Intel Goldmont Plus microarchitecture (Gemini Lake). */ + cpuinfo_uarch_goldmont_plus = 0x00100405, + + /** Intel Knights Ferry HPC boards. */ + cpuinfo_uarch_knights_ferry = 0x00100500, + /** Intel Knights Corner HPC boards (aka Xeon Phi). */ + cpuinfo_uarch_knights_corner = 0x00100501, + /** Intel Knights Landing microarchitecture (second-gen MIC). */ + cpuinfo_uarch_knights_landing = 0x00100502, + /** Intel Knights Hill microarchitecture (third-gen MIC). */ + cpuinfo_uarch_knights_hill = 0x00100503, + /** Intel Knights Mill Xeon Phi. */ + cpuinfo_uarch_knights_mill = 0x00100504, + + /** Intel/Marvell XScale series. */ + cpuinfo_uarch_xscale = 0x00100600, + + /** AMD K5. */ + cpuinfo_uarch_k5 = 0x00200100, + /** AMD K6 and alike. */ + cpuinfo_uarch_k6 = 0x00200101, + /** AMD Athlon and Duron. */ + cpuinfo_uarch_k7 = 0x00200102, + /** AMD Athlon 64, Opteron 64. */ + cpuinfo_uarch_k8 = 0x00200103, + /** AMD Family 10h (Barcelona, Istambul, Magny-Cours). */ + cpuinfo_uarch_k10 = 0x00200104, + /** + * AMD Bulldozer microarchitecture + * Zambezi FX-series CPUs, Zurich, Valencia and Interlagos Opteron CPUs. + */ + cpuinfo_uarch_bulldozer = 0x00200105, + /** + * AMD Piledriver microarchitecture + * Vishera FX-series CPUs, Trinity and Richland APUs, Delhi, Seoul, Abu + * Dhabi Opteron CPUs. + */ + cpuinfo_uarch_piledriver = 0x00200106, + /** AMD Steamroller microarchitecture (Kaveri APUs). */ + cpuinfo_uarch_steamroller = 0x00200107, + /** AMD Excavator microarchitecture (Carizzo APUs). */ + cpuinfo_uarch_excavator = 0x00200108, + /** AMD Zen microarchitecture (12/14 nm Ryzen and EPYC CPUs). */ + cpuinfo_uarch_zen = 0x00200109, + /** AMD Zen 2 microarchitecture (7 nm Ryzen and EPYC CPUs). */ + cpuinfo_uarch_zen2 = 0x0020010A, + /** AMD Zen 3 microarchitecture. */ + cpuinfo_uarch_zen3 = 0x0020010B, + /** AMD Zen 4 microarchitecture. */ + cpuinfo_uarch_zen4 = 0x0020010C, + /** AMD Zen 5 microarchitecture. */ + cpuinfo_uarch_zen5 = 0x0020010D, + + /** NSC Geode and AMD Geode GX and LX. */ + cpuinfo_uarch_geode = 0x00200200, + /** AMD Bobcat mobile microarchitecture. */ + cpuinfo_uarch_bobcat = 0x00200201, + /** AMD Jaguar mobile microarchitecture. */ + cpuinfo_uarch_jaguar = 0x00200202, + /** AMD Puma mobile microarchitecture. */ + cpuinfo_uarch_puma = 0x00200203, + + /** ARM7 series. */ + cpuinfo_uarch_arm7 = 0x00300100, + /** ARM9 series. */ + cpuinfo_uarch_arm9 = 0x00300101, + /** ARM 1136, ARM 1156, ARM 1176, or ARM 11MPCore. */ + cpuinfo_uarch_arm11 = 0x00300102, + + /** ARM Cortex-A5. */ + cpuinfo_uarch_cortex_a5 = 0x00300205, + /** ARM Cortex-A7. */ + cpuinfo_uarch_cortex_a7 = 0x00300207, + /** ARM Cortex-A8. */ + cpuinfo_uarch_cortex_a8 = 0x00300208, + /** ARM Cortex-A9. */ + cpuinfo_uarch_cortex_a9 = 0x00300209, + /** ARM Cortex-A12. */ + cpuinfo_uarch_cortex_a12 = 0x00300212, + /** ARM Cortex-A15. */ + cpuinfo_uarch_cortex_a15 = 0x00300215, + /** ARM Cortex-A17. */ + cpuinfo_uarch_cortex_a17 = 0x00300217, + + /** ARM Cortex-A32. */ + cpuinfo_uarch_cortex_a32 = 0x00300332, + /** ARM Cortex-A35. */ + cpuinfo_uarch_cortex_a35 = 0x00300335, + /** ARM Cortex-A53. */ + cpuinfo_uarch_cortex_a53 = 0x00300353, + /** ARM Cortex-A55 revision 0 (restricted dual-issue capabilities + compared to revision 1+). */ + cpuinfo_uarch_cortex_a55r0 = 0x00300354, + /** ARM Cortex-A55. */ + cpuinfo_uarch_cortex_a55 = 0x00300355, + /** ARM Cortex-A57. */ + cpuinfo_uarch_cortex_a57 = 0x00300357, + /** ARM Cortex-A65. */ + cpuinfo_uarch_cortex_a65 = 0x00300365, + /** ARM Cortex-A72. */ + cpuinfo_uarch_cortex_a72 = 0x00300372, + /** ARM Cortex-A73. */ + cpuinfo_uarch_cortex_a73 = 0x00300373, + /** ARM Cortex-A75. */ + cpuinfo_uarch_cortex_a75 = 0x00300375, + /** ARM Cortex-A76. */ + cpuinfo_uarch_cortex_a76 = 0x00300376, + /** ARM Cortex-A77. */ + cpuinfo_uarch_cortex_a77 = 0x00300377, + /** ARM Cortex-A78. */ + cpuinfo_uarch_cortex_a78 = 0x00300378, + + /** ARM Neoverse N1. */ + cpuinfo_uarch_neoverse_n1 = 0x00300400, + /** ARM Neoverse E1. */ + cpuinfo_uarch_neoverse_e1 = 0x00300401, + /** ARM Neoverse V1. */ + cpuinfo_uarch_neoverse_v1 = 0x00300402, + /** ARM Neoverse N2. */ + cpuinfo_uarch_neoverse_n2 = 0x00300403, + /** ARM Neoverse V2. */ + cpuinfo_uarch_neoverse_v2 = 0x00300404, + + /** ARM Cortex-X1. */ + cpuinfo_uarch_cortex_x1 = 0x00300501, + /** ARM Cortex-X2. */ + cpuinfo_uarch_cortex_x2 = 0x00300502, + /** ARM Cortex-X3. */ + cpuinfo_uarch_cortex_x3 = 0x00300503, + /** ARM Cortex-X4. */ + cpuinfo_uarch_cortex_x4 = 0x00300504, + + /** ARM Cortex-A510. */ + cpuinfo_uarch_cortex_a510 = 0x00300551, + /** ARM Cortex-A520. */ + cpuinfo_uarch_cortex_a520 = 0x00300552, + /** ARM Cortex-A710. */ + cpuinfo_uarch_cortex_a710 = 0x00300571, + /** ARM Cortex-A715. */ + cpuinfo_uarch_cortex_a715 = 0x00300572, + /** ARM Cortex-A720. */ + cpuinfo_uarch_cortex_a720 = 0x00300573, + + /** Qualcomm Scorpion. */ + cpuinfo_uarch_scorpion = 0x00400100, + /** Qualcomm Krait. */ + cpuinfo_uarch_krait = 0x00400101, + /** Qualcomm Kryo. */ + cpuinfo_uarch_kryo = 0x00400102, + /** Qualcomm Falkor. */ + cpuinfo_uarch_falkor = 0x00400103, + /** Qualcomm Saphira. */ + cpuinfo_uarch_saphira = 0x00400104, + /** Qualcomm Oryon. */ + cpuinfo_uarch_oryon = 0x00400105, + + /** Nvidia Denver. */ + cpuinfo_uarch_denver = 0x00500100, + /** Nvidia Denver 2. */ + cpuinfo_uarch_denver2 = 0x00500101, + /** Nvidia Carmel. */ + cpuinfo_uarch_carmel = 0x00500102, + + /** Samsung Exynos M1 (Exynos 8890 big cores). */ + cpuinfo_uarch_exynos_m1 = 0x00600100, + /** Samsung Exynos M2 (Exynos 8895 big cores). */ + cpuinfo_uarch_exynos_m2 = 0x00600101, + /** Samsung Exynos M3 (Exynos 9810 big cores). */ + cpuinfo_uarch_exynos_m3 = 0x00600102, + /** Samsung Exynos M4 (Exynos 9820 big cores). */ + cpuinfo_uarch_exynos_m4 = 0x00600103, + /** Samsung Exynos M5 (Exynos 9830 big cores). */ + cpuinfo_uarch_exynos_m5 = 0x00600104, + + /* Deprecated synonym for Cortex-A76 */ + cpuinfo_uarch_cortex_a76ae = 0x00300376, + /* Deprecated names for Exynos. */ + cpuinfo_uarch_mongoose_m1 = 0x00600100, + cpuinfo_uarch_mongoose_m2 = 0x00600101, + cpuinfo_uarch_meerkat_m3 = 0x00600102, + cpuinfo_uarch_meerkat_m4 = 0x00600103, + + /** Apple A6 and A6X processors. */ + cpuinfo_uarch_swift = 0x00700100, + /** Apple A7 processor. */ + cpuinfo_uarch_cyclone = 0x00700101, + /** Apple A8 and A8X processor. */ + cpuinfo_uarch_typhoon = 0x00700102, + /** Apple A9 and A9X processor. */ + cpuinfo_uarch_twister = 0x00700103, + /** Apple A10 and A10X processor. */ + cpuinfo_uarch_hurricane = 0x00700104, + /** Apple A11 processor (big cores). */ + cpuinfo_uarch_monsoon = 0x00700105, + /** Apple A11 processor (little cores). */ + cpuinfo_uarch_mistral = 0x00700106, + /** Apple A12 processor (big cores). */ + cpuinfo_uarch_vortex = 0x00700107, + /** Apple A12 processor (little cores). */ + cpuinfo_uarch_tempest = 0x00700108, + /** Apple A13 processor (big cores). */ + cpuinfo_uarch_lightning = 0x00700109, + /** Apple A13 processor (little cores). */ + cpuinfo_uarch_thunder = 0x0070010A, + /** Apple A14 / M1 processor (big cores). */ + cpuinfo_uarch_firestorm = 0x0070010B, + /** Apple A14 / M1 processor (little cores). */ + cpuinfo_uarch_icestorm = 0x0070010C, + /** Apple A15 / M2 processor (big cores). */ + cpuinfo_uarch_avalanche = 0x0070010D, + /** Apple A15 / M2 processor (little cores). */ + cpuinfo_uarch_blizzard = 0x0070010E, + + /** Cavium ThunderX. */ + cpuinfo_uarch_thunderx = 0x00800100, + /** Cavium ThunderX2 (originally Broadcom Vulkan). */ + cpuinfo_uarch_thunderx2 = 0x00800200, + + /** Marvell PJ4. */ + cpuinfo_uarch_pj4 = 0x00900100, + + /** Broadcom Brahma B15. */ + cpuinfo_uarch_brahma_b15 = 0x00A00100, + /** Broadcom Brahma B53. */ + cpuinfo_uarch_brahma_b53 = 0x00A00101, + + /** Applied Micro X-Gene. */ + cpuinfo_uarch_xgene = 0x00B00100, + + /* Hygon Dhyana (a modification of AMD Zen for Chinese market). */ + cpuinfo_uarch_dhyana = 0x01000100, + + /** HiSilicon TaiShan v110 (Huawei Kunpeng 920 series processors). */ + cpuinfo_uarch_taishan_v110 = 0x00C00100, +}; + +struct cpuinfo_processor { + /** SMT (hyperthread) ID within a core */ + uint32_t smt_id; + /** Core containing this logical processor */ + const struct cpuinfo_core* core; + /** Cluster of cores containing this logical processor */ + const struct cpuinfo_cluster* cluster; + /** Physical package containing this logical processor */ + const struct cpuinfo_package* package; +#if defined(__linux__) + /** + * Linux-specific ID for the logical processor: + * - Linux kernel exposes information about this logical processor in + * /sys/devices/system/cpu/cpu/ + * - Bit in the cpu_set_t identifies this logical processor + */ + int linux_id; +#endif +#if defined(_WIN32) || defined(__CYGWIN__) + /** Windows-specific ID for the group containing the logical processor. + */ + uint16_t windows_group_id; + /** + * Windows-specific ID of the logical processor within its group: + * - Bit in the KAFFINITY mask identifies this + * logical processor within its group. + */ + uint16_t windows_processor_id; +#endif +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + /** APIC ID (unique x86-specific ID of the logical processor) */ + uint32_t apic_id; +#endif + struct { + /** Level 1 instruction cache */ + const struct cpuinfo_cache* l1i; + /** Level 1 data cache */ + const struct cpuinfo_cache* l1d; + /** Level 2 unified or data cache */ + const struct cpuinfo_cache* l2; + /** Level 3 unified or data cache */ + const struct cpuinfo_cache* l3; + /** Level 4 unified or data cache */ + const struct cpuinfo_cache* l4; + } cache; +}; + +struct cpuinfo_core { + /** Index of the first logical processor on this core. */ + uint32_t processor_start; + /** Number of logical processors on this core */ + uint32_t processor_count; + /** Core ID within a package */ + uint32_t core_id; + /** Cluster containing this core */ + const struct cpuinfo_cluster* cluster; + /** Physical package containing this core. */ + const struct cpuinfo_package* package; + /** Vendor of the CPU microarchitecture for this core */ + enum cpuinfo_vendor vendor; + /** CPU microarchitecture for this core */ + enum cpuinfo_uarch uarch; +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + /** Value of CPUID leaf 1 EAX register for this core */ + uint32_t cpuid; +#elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + /** Value of Main ID Register (MIDR) for this core */ + uint32_t midr; +#endif + /** Clock rate (non-Turbo) of the core, in Hz */ + uint64_t frequency; +}; + +struct cpuinfo_cluster { + /** Index of the first logical processor in the cluster */ + uint32_t processor_start; + /** Number of logical processors in the cluster */ + uint32_t processor_count; + /** Index of the first core in the cluster */ + uint32_t core_start; + /** Number of cores on the cluster */ + uint32_t core_count; + /** Cluster ID within a package */ + uint32_t cluster_id; + /** Physical package containing the cluster */ + const struct cpuinfo_package* package; + /** CPU microarchitecture vendor of the cores in the cluster */ + enum cpuinfo_vendor vendor; + /** CPU microarchitecture of the cores in the cluster */ + enum cpuinfo_uarch uarch; +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + /** Value of CPUID leaf 1 EAX register of the cores in the cluster */ + uint32_t cpuid; +#elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + /** Value of Main ID Register (MIDR) of the cores in the cluster */ + uint32_t midr; +#endif + /** Clock rate (non-Turbo) of the cores in the cluster, in Hz */ + uint64_t frequency; +}; + +#define CPUINFO_PACKAGE_NAME_MAX 48 + +struct cpuinfo_package { + /** SoC or processor chip model name */ + char name[CPUINFO_PACKAGE_NAME_MAX]; + /** Index of the first logical processor on this physical package */ + uint32_t processor_start; + /** Number of logical processors on this physical package */ + uint32_t processor_count; + /** Index of the first core on this physical package */ + uint32_t core_start; + /** Number of cores on this physical package */ + uint32_t core_count; + /** Index of the first cluster of cores on this physical package */ + uint32_t cluster_start; + /** Number of clusters of cores on this physical package */ + uint32_t cluster_count; +}; + +struct cpuinfo_uarch_info { + /** Type of CPU microarchitecture */ + enum cpuinfo_uarch uarch; +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + /** Value of CPUID leaf 1 EAX register for the microarchitecture */ + uint32_t cpuid; +#elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + /** Value of Main ID Register (MIDR) for the microarchitecture */ + uint32_t midr; +#endif + /** Number of logical processors with the microarchitecture */ + uint32_t processor_count; + /** Number of cores with the microarchitecture */ + uint32_t core_count; +}; + +#ifdef __cplusplus +extern "C" { +#endif + +bool CPUINFO_ABI cpuinfo_initialize(void); + +void CPUINFO_ABI cpuinfo_deinitialize(void); + +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 +/* This structure is not a part of stable API. Use cpuinfo_has_x86_* functions + * instead. */ +struct cpuinfo_x86_isa { +#if CPUINFO_ARCH_X86 + bool rdtsc; +#endif + bool rdtscp; + bool rdpid; + bool sysenter; +#if CPUINFO_ARCH_X86 + bool syscall; +#endif + bool msr; + bool clzero; + bool clflush; + bool clflushopt; + bool mwait; + bool mwaitx; +#if CPUINFO_ARCH_X86 + bool emmx; +#endif + bool fxsave; + bool xsave; +#if CPUINFO_ARCH_X86 + bool fpu; + bool mmx; + bool mmx_plus; +#endif + bool three_d_now; + bool three_d_now_plus; +#if CPUINFO_ARCH_X86 + bool three_d_now_geode; +#endif + bool prefetch; + bool prefetchw; + bool prefetchwt1; +#if CPUINFO_ARCH_X86 + bool daz; + bool sse; + bool sse2; +#endif + bool sse3; + bool ssse3; + bool sse4_1; + bool sse4_2; + bool sse4a; + bool misaligned_sse; + bool avx; + bool avxvnni; + bool fma3; + bool fma4; + bool xop; + bool f16c; + bool avx2; + bool avx512f; + bool avx512pf; + bool avx512er; + bool avx512cd; + bool avx512dq; + bool avx512bw; + bool avx512vl; + bool avx512ifma; + bool avx512vbmi; + bool avx512vbmi2; + bool avx512bitalg; + bool avx512vpopcntdq; + bool avx512vnni; + bool avx512bf16; + bool avx512fp16; + bool avx512vp2intersect; + bool avx512_4vnniw; + bool avx512_4fmaps; + bool avx10_1; + bool avx10_2; + bool amx_bf16; + bool amx_tile; + bool amx_int8; + bool amx_fp16; + bool avx_vnni_int8; + bool avx_vnni_int16; + bool avx_ne_convert; + bool hle; + bool rtm; + bool xtest; + bool mpx; +#if CPUINFO_ARCH_X86 + bool cmov; + bool cmpxchg8b; +#endif + bool cmpxchg16b; + bool clwb; + bool movbe; +#if CPUINFO_ARCH_X86_64 + bool lahf_sahf; +#endif + bool fs_gs_base; + bool lzcnt; + bool popcnt; + bool tbm; + bool bmi; + bool bmi2; + bool adx; + bool aes; + bool vaes; + bool pclmulqdq; + bool vpclmulqdq; + bool gfni; + bool rdrand; + bool rdseed; + bool sha; + bool rng; + bool ace; + bool ace2; + bool phe; + bool pmm; + bool lwp; +}; + +extern struct cpuinfo_x86_isa cpuinfo_isa; +#endif + +static inline bool cpuinfo_has_x86_rdtsc(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.rdtsc; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_rdtscp(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.rdtscp; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_rdpid(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.rdpid; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_clzero(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.clzero; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_mwait(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.mwait; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_mwaitx(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.mwaitx; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_fxsave(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.fxsave; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_xsave(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.xsave; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_fpu(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.fpu; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_mmx(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.mmx; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_mmx_plus(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.mmx_plus; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_3dnow(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.three_d_now; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_3dnow_plus(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.three_d_now_plus; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_3dnow_geode(void) { +#if CPUINFO_ARCH_X86_64 + return false; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return false; +#else + return cpuinfo_isa.three_d_now_geode; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_prefetch(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.prefetch; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_prefetchw(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.prefetchw; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_prefetchwt1(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.prefetchwt1; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_daz(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.daz; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sse(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.sse; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sse2(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.sse2; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sse3(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.sse3; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_ssse3(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.ssse3; +#endif +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sse4_1(void) { +#if CPUINFO_ARCH_X86_64 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.sse4_1; +#endif +#elif CPUINFO_ARCH_X86 + return cpuinfo_isa.sse4_1; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sse4_2(void) { +#if CPUINFO_ARCH_X86_64 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.sse4_2; +#endif +#elif CPUINFO_ARCH_X86 + return cpuinfo_isa.sse4_2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sse4a(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.sse4a; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_misaligned_sse(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.misaligned_sse; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avxvnni(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avxvnni; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_fma3(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.fma3; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_fma4(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.fma4; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_xop(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.xop; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_f16c(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.f16c; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx2(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512f(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512f; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512pf(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512pf; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512er(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512er; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512cd(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512cd; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512dq(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512dq; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512bw(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512bw; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512vl(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512vl; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512ifma(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512ifma; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512vbmi(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512vbmi; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512vbmi2(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512vbmi2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512bitalg(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512bitalg; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512vpopcntdq(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512vpopcntdq; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512vnni(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512vnni; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512bf16(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512bf16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512fp16(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512fp16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512vp2intersect(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512vp2intersect; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512_4vnniw(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512_4vnniw; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx512_4fmaps(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx512_4fmaps; +#else + return false; +#endif +} + +/* [NOTE] Intel Advanced Matrix Extensions (AMX) detection + * + * I. AMX is a new extensions to the x86 ISA to work on matrices, consists of + * 1) 2-dimentional registers (tiles), hold sub-matrices from larger matrices in memory + * 2) Accelerator called Tile Matrix Multiply (TMUL), contains instructions operating on tiles + * + * II. Platforms that supports AMX: + * +-----------------+-----+----------+----------+----------+----------+ + * | Platforms | Gen | amx-bf16 | amx-tile | amx-int8 | amx-fp16 | + * +-----------------+-----+----------+----------+----------+----------+ + * | Sapphire Rapids | 4th | YES | YES | YES | NO | + * +-----------------+-----+----------+----------+----------+----------+ + * | Emerald Rapids | 5th | YES | YES | YES | NO | + * +-----------------+-----+----------+----------+----------+----------+ + * | Granite Rapids | 6th | YES | YES | YES | YES | + * +-----------------+-----+----------+----------+----------+----------+ + * + * Reference: https://www.intel.com/content/www/us/en/products/docs + * /accelerator-engines/advanced-matrix-extensions/overview.html + */ +static inline bool cpuinfo_has_x86_amx_bf16(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.amx_bf16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_amx_tile(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.amx_tile; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_amx_int8(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.amx_int8; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_amx_fp16(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.amx_fp16; +#else + return false; +#endif +} + +/* + * Intel AVX Vector Neural Network Instructions (VNNI) INT8 + * Supported Platfroms: Sierra Forest, Arrow Lake, Lunar Lake + */ +static inline bool cpuinfo_has_x86_avx_vnni_int8(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx_vnni_int8; +#else + return false; +#endif +} + +/* + * Intel AVX Vector Neural Network Instructions (VNNI) INT16 + * Supported Platfroms: Arrow Lake, Lunar Lake + */ +static inline bool cpuinfo_has_x86_avx_vnni_int16(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx_vnni_int16; +#else + return false; +#endif +} + +/* + * A new set of instructions, which can convert low precision floating point + * like BF16/FP16 to high precision floating point FP32, as well as convert FP32 + * elements to BF16. This instruction allows the platform to have improved AI + * capabilities and better compatibility. + * + * Supported Platforms: Sierra Forest, Arrow Lake, Lunar Lake + */ +static inline bool cpuinfo_has_x86_avx_ne_convert(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx_ne_convert; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx10_1(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx10_1; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_avx10_2(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.avx10_2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_hle(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.hle; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_rtm(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.rtm; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_xtest(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.xtest; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_mpx(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.mpx; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_cmov(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 + return cpuinfo_isa.cmov; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_cmpxchg8b(void) { +#if CPUINFO_ARCH_X86_64 + return true; +#elif CPUINFO_ARCH_X86 + return cpuinfo_isa.cmpxchg8b; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_cmpxchg16b(void) { +#if CPUINFO_ARCH_X86_64 + return cpuinfo_isa.cmpxchg16b; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_clwb(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.clwb; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_movbe(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.movbe; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_lahf_sahf(void) { +#if CPUINFO_ARCH_X86 + return true; +#elif CPUINFO_ARCH_X86_64 + return cpuinfo_isa.lahf_sahf; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_lzcnt(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.lzcnt; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_popcnt(void) { +#if CPUINFO_ARCH_X86_64 +#if defined(__ANDROID__) + return true; +#else + return cpuinfo_isa.popcnt; +#endif +#elif CPUINFO_ARCH_X86 + return cpuinfo_isa.popcnt; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_tbm(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.tbm; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_bmi(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.bmi; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_bmi2(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.bmi2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_adx(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.adx; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_aes(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.aes; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_vaes(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.vaes; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_pclmulqdq(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.pclmulqdq; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_vpclmulqdq(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.vpclmulqdq; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_gfni(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.gfni; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_rdrand(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.rdrand; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_rdseed(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.rdseed; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_x86_sha(void) { +#if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64 + return cpuinfo_isa.sha; +#else + return false; +#endif +} + +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 +/* This structure is not a part of stable API. Use cpuinfo_has_arm_* functions + * instead. */ +struct cpuinfo_arm_isa { +#if CPUINFO_ARCH_ARM + bool thumb; + bool thumb2; + bool thumbee; + bool jazelle; + bool armv5e; + bool armv6; + bool armv6k; + bool armv7; + bool armv7mp; + bool armv8; + bool idiv; + + bool vfpv2; + bool vfpv3; + bool d32; + bool fp16; + bool fma; + + bool wmmx; + bool wmmx2; + bool neon; +#endif +#if CPUINFO_ARCH_ARM64 + bool atomics; + bool bf16; + bool sve; + bool sve2; + bool i8mm; + bool sme; + bool sme2; + bool sme2p1; + bool sme_i16i32; + bool sme_bi32i32; + bool sme_b16b16; + bool sme_f16f16; + uint32_t svelen; + uint32_t smelen; +#endif + bool rdm; + bool fp16arith; + bool dot; + bool jscvt; + bool fcma; + bool fhm; + + bool aes; + bool sha1; + bool sha2; + bool pmull; + bool crc32; +}; + +extern struct cpuinfo_arm_isa cpuinfo_isa; +#endif + +static inline bool cpuinfo_has_arm_thumb(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.thumb; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_thumb2(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.thumb2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_v5e(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.armv5e; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_v6(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.armv6; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_v6k(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.armv6k; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_v7(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.armv7; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_v7mp(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.armv7mp; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_v8(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.armv8; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_idiv(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.idiv; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv2(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv3(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv3; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv3_d32(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv3 && cpuinfo_isa.d32; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv3_fp16(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv3 && cpuinfo_isa.fp16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv3_fp16_d32(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv3 && cpuinfo_isa.fp16 && cpuinfo_isa.d32; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv4(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv3 && cpuinfo_isa.fma; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_vfpv4_d32(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.vfpv3 && cpuinfo_isa.fma && cpuinfo_isa.d32; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_fp16_arith(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.fp16arith; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_bf16(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.bf16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_wmmx(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.wmmx; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_wmmx2(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.wmmx2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.neon; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_fp16(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.neon && cpuinfo_isa.fp16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_fma(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.neon && cpuinfo_isa.fma; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_v8(void) { +#if CPUINFO_ARCH_ARM64 + return true; +#elif CPUINFO_ARCH_ARM + return cpuinfo_isa.neon && cpuinfo_isa.armv8; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_atomics(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.atomics; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_rdm(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.rdm; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_fp16_arith(void) { +#if CPUINFO_ARCH_ARM + return cpuinfo_isa.neon && cpuinfo_isa.fp16arith; +#elif CPUINFO_ARCH_ARM64 + return cpuinfo_isa.fp16arith; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_fhm(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.fhm; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_dot(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.dot; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_neon_bf16(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.bf16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_jscvt(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.jscvt; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_fcma(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.fcma; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_i8mm(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.i8mm; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_aes(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.aes; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sha1(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sha1; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sha2(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sha2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_pmull(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.pmull; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_crc32(void) { +#if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64 + return cpuinfo_isa.crc32; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sve(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sve; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sve_bf16(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sve && cpuinfo_isa.bf16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sve2(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sve2; +#else + return false; +#endif +} + +// Function to get the max SVE vector length on ARM CPU's which support SVE. +static inline uint32_t cpuinfo_get_max_arm_sve_length(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.svelen * 8; // bytes * 8 = bit length(vector length) +#else + return 0; +#endif +} + +// Function to get the max SME vector length on ARM CPU's which support SME. +static inline uint32_t cpuinfo_get_max_arm_sme_length(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.smelen * 8; // bytes * 8 = bit length(vector length) +#else + return 0; +#endif +} + +static inline bool cpuinfo_has_arm_sme(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sme2(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme2; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sme2p1(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme2p1; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sme_i16i32(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme_i16i32; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sme_bi32i32(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme_bi32i32; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sme_b16b16(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme_b16b16; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_arm_sme_f16f16(void) { +#if CPUINFO_ARCH_ARM64 + return cpuinfo_isa.sme_f16f16; +#else + return false; +#endif +} + +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 +/* This structure is not a part of stable API. Use cpuinfo_has_riscv_* functions + * instead. */ +struct cpuinfo_riscv_isa { + /** + * Keep fields in line with the canonical order as defined by + * Section 27.11 Subset Naming Convention. + */ + /* RV32I/64I/128I Base ISA. */ + bool i; +#if CPUINFO_ARCH_RISCV32 + /* RV32E Base ISA. */ + bool e; +#endif + /* Integer Multiply/Divide Extension. */ + bool m; + /* Atomic Extension. */ + bool a; + /* Single-Precision Floating-Point Extension. */ + bool f; + /* Double-Precision Floating-Point Extension. */ + bool d; + /* Compressed Extension. */ + bool c; + /* Vector Extension. */ + bool v; +}; + +extern struct cpuinfo_riscv_isa cpuinfo_isa; +#endif + +static inline bool cpuinfo_has_riscv_i(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.i; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_e(void) { +#if CPUINFO_ARCH_RISCV32 + return cpuinfo_isa.e; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_m(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.m; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_a(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.a; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_f(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.f; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_d(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.d; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_g(void) { + // The 'G' extension is simply shorthand for 'IMAFD'. + return cpuinfo_has_riscv_i() && cpuinfo_has_riscv_m() && cpuinfo_has_riscv_a() && cpuinfo_has_riscv_f() && + cpuinfo_has_riscv_d(); +} + +static inline bool cpuinfo_has_riscv_c(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.c; +#else + return false; +#endif +} + +static inline bool cpuinfo_has_riscv_v(void) { +#if CPUINFO_ARCH_RISCV32 || CPUINFO_ARCH_RISCV64 + return cpuinfo_isa.v; +#else + return false; +#endif +} + +const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_processors(void); +const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_cores(void); +const struct cpuinfo_cluster* CPUINFO_ABI cpuinfo_get_clusters(void); +const struct cpuinfo_package* CPUINFO_ABI cpuinfo_get_packages(void); +const struct cpuinfo_uarch_info* CPUINFO_ABI cpuinfo_get_uarchs(void); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1i_caches(void); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1d_caches(void); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l2_caches(void); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l3_caches(void); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l4_caches(void); + +const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_processor(uint32_t index); +const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_core(uint32_t index); +const struct cpuinfo_cluster* CPUINFO_ABI cpuinfo_get_cluster(uint32_t index); +const struct cpuinfo_package* CPUINFO_ABI cpuinfo_get_package(uint32_t index); +const struct cpuinfo_uarch_info* CPUINFO_ABI cpuinfo_get_uarch(uint32_t index); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1i_cache(uint32_t index); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1d_cache(uint32_t index); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l2_cache(uint32_t index); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l3_cache(uint32_t index); +const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l4_cache(uint32_t index); + +uint32_t CPUINFO_ABI cpuinfo_get_processors_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_cores_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_clusters_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_packages_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_uarchs_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_l1i_caches_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_l1d_caches_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_l2_caches_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_l3_caches_count(void); +uint32_t CPUINFO_ABI cpuinfo_get_l4_caches_count(void); + +/** + * Returns upper bound on cache size. + */ +uint32_t CPUINFO_ABI cpuinfo_get_max_cache_size(void); + +/** + * Identify the logical processor that executes the current thread. + * + * There is no guarantee that the thread will stay on the same logical processor + * for any time. Callers should treat the result as only a hint, and be prepared + * to handle NULL return value. + */ +const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_current_processor(void); + +/** + * Identify the core that executes the current thread. + * + * There is no guarantee that the thread will stay on the same core for any + * time. Callers should treat the result as only a hint, and be prepared to + * handle NULL return value. + */ +const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_current_core(void); + +/** + * Identify the microarchitecture index of the core that executes the current + * thread. If the system does not support such identification, the function + * returns 0. + * + * There is no guarantee that the thread will stay on the same type of core for + * any time. Callers should treat the result as only a hint. + */ +uint32_t CPUINFO_ABI cpuinfo_get_current_uarch_index(void); + +/** + * Identify the microarchitecture index of the core that executes the current + * thread. If the system does not support such identification, the function + * returns the user-specified default value. + * + * There is no guarantee that the thread will stay on the same type of core for + * any time. Callers should treat the result as only a hint. + */ +uint32_t CPUINFO_ABI cpuinfo_get_current_uarch_index_with_default(uint32_t default_uarch_index); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* CPUINFO_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl.h b/deps/exla/cache/xla_extension/include/include/dnnl.h new file mode 100644 index 0000000000000000000000000000000000000000..bc74bf644f4b628018d7a9103ba63320abc466d5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_H +#define DNNL_H + +#include "oneapi/dnnl/dnnl.h" + +#endif /* DNNL_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl.hpp b/deps/exla/cache/xla_extension/include/include/dnnl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3c8835cacf35effc8e5c89a041f8bdcbe8203daa --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_HPP +#define DNNL_HPP + +#include "oneapi/dnnl/dnnl.hpp" + +#endif /* DNNL_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_config.h b/deps/exla/cache/xla_extension/include/include/dnnl_config.h new file mode 100644 index 0000000000000000000000000000000000000000..48925e1e3ab49ae135c6e9c4c501aa2f5e030913 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_config.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_CONFIG_H +#define DNNL_CONFIG_H + +#include "oneapi/dnnl/dnnl_config.h" + +#endif /* DNNL_CONFIG_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_debug.h b/deps/exla/cache/xla_extension/include/include/dnnl_debug.h new file mode 100644 index 0000000000000000000000000000000000000000..5044971832bbbe56127920a527508b207a803eea --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_debug.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_DEBUG_H +#define DNNL_DEBUG_H + +#include "oneapi/dnnl/dnnl_debug.h" + +#endif /* DNNL_DEBUG_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_ocl.h b/deps/exla/cache/xla_extension/include/include/dnnl_ocl.h new file mode 100644 index 0000000000000000000000000000000000000000..ad731150b28babe7bd5a911acd8de70c57e85254 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_ocl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_OCL_H +#define DNNL_OCL_H + +#include "oneapi/dnnl/dnnl_ocl.h" + +#endif /* DNNL_OCL_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_ocl.hpp b/deps/exla/cache/xla_extension/include/include/dnnl_ocl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..150254227927f032195f71451bc5c9768d7bc627 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_ocl.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_OCL_HPP +#define DNNL_OCL_HPP + +#include "oneapi/dnnl/dnnl_ocl.hpp" + +#endif /* DNNL_OCL_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_sycl.h b/deps/exla/cache/xla_extension/include/include/dnnl_sycl.h new file mode 100644 index 0000000000000000000000000000000000000000..4501598c2f461021f0fa818e95fd1972ce2d3ace --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_sycl.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_SYCL_H +#define DNNL_SYCL_H + +#include "oneapi/dnnl/dnnl_sycl.h" + +#endif /* DNNL_SYCL_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_sycl.hpp b/deps/exla/cache/xla_extension/include/include/dnnl_sycl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2479ceca3544363779e9d5d53028c93712a091af --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_sycl.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_SYCL_HPP +#define DNNL_SYCL_HPP + +#include "oneapi/dnnl/dnnl_sycl.hpp" + +#endif /* DNNL_SYCL_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_sycl_types.h b/deps/exla/cache/xla_extension/include/include/dnnl_sycl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..a4a854a4cf138103f4c53030083e119cc0732cf1 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_sycl_types.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_SYCL_TYPES_H +#define DNNL_SYCL_TYPES_H + +#include "oneapi/dnnl/dnnl_sycl_types.h" + +#endif /* DNNL_SYCL_TYPES_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_threadpool.h b/deps/exla/cache/xla_extension/include/include/dnnl_threadpool.h new file mode 100644 index 0000000000000000000000000000000000000000..e27e584a65ed16740d4fde93da3a1a049dd111aa --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_threadpool.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_THREADPOOL_H +#define DNNL_THREADPOOL_H + +#include "oneapi/dnnl/dnnl_threadpool.h" + +#endif /* DNNL_THREADPOOL_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_threadpool.hpp b/deps/exla/cache/xla_extension/include/include/dnnl_threadpool.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6aa65d60129389ab2b5e3bec1b5c4d7bee495081 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_threadpool.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_THREADPOOL_HPP +#define DNNL_THREADPOOL_HPP + +#include "oneapi/dnnl/dnnl_threadpool.hpp" + +#endif /* DNNL_THREADPOOL_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_threadpool_iface.hpp b/deps/exla/cache/xla_extension/include/include/dnnl_threadpool_iface.hpp new file mode 100644 index 0000000000000000000000000000000000000000..82639005efcd9477843c9e486b102fbbf34ef29b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_threadpool_iface.hpp @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_THREADPOOL_IFACE_HPP +#define DNNL_THREADPOOL_IFACE_HPP + +#include "oneapi/dnnl/dnnl_threadpool_iface.hpp" + +#endif /* DNNL_THREADPOOL_IFACE_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_types.h b/deps/exla/cache/xla_extension/include/include/dnnl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..6f4261b712dc37ec2416ba60c0c68bb30f6995e0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_types.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_TYPES_H +#define DNNL_TYPES_H + +#include "oneapi/dnnl/dnnl_types.h" + +#endif /* DNNL_TYPES_H */ diff --git a/deps/exla/cache/xla_extension/include/include/dnnl_version.h b/deps/exla/cache/xla_extension/include/include/dnnl_version.h new file mode 100644 index 0000000000000000000000000000000000000000..32a3d5cf839b1d593f069520febfd60b323730e9 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/dnnl_version.h @@ -0,0 +1,22 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef DNNL_VERSION_H +#define DNNL_VERSION_H + +#include "oneapi/dnnl/dnnl_version.h" + +#endif /* DNNL_VERSION_H */ diff --git a/deps/exla/cache/xla_extension/include/include/fxdiv.h b/deps/exla/cache/xla_extension/include/include/fxdiv.h new file mode 100644 index 0000000000000000000000000000000000000000..2c35038d97c55c524bb97caba2e3560cab9da504 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/fxdiv.h @@ -0,0 +1,425 @@ +#pragma once +#ifndef FXDIV_H +#define FXDIV_H + +#if defined(__cplusplus) && (__cplusplus >= 201103L) + #include + #include + #include +#elif !defined(__OPENCL_VERSION__) + #include + #include + #include +#endif + +#if defined(_MSC_VER) + #include + #if defined(_M_IX86) || defined(_M_X64) + #include + #endif +#endif + +#ifndef FXDIV_USE_INLINE_ASSEMBLY + #define FXDIV_USE_INLINE_ASSEMBLY 0 +#endif + +static inline uint64_t fxdiv_mulext_uint32_t(uint32_t a, uint32_t b) { +#if defined(_MSC_VER) && defined(_M_IX86) + return (uint64_t) __emulu((unsigned int) a, (unsigned int) b); +#else + return (uint64_t) a * (uint64_t) b; +#endif +} + +static inline uint32_t fxdiv_mulhi_uint32_t(uint32_t a, uint32_t b) { +#if defined(__OPENCL_VERSION__) + return mul_hi(a, b); +#elif defined(__CUDA_ARCH__) + return (uint32_t) __umulhi((unsigned int) a, (unsigned int) b); +#elif defined(_MSC_VER) && defined(_M_IX86) + return (uint32_t) (__emulu((unsigned int) a, (unsigned int) b) >> 32); +#elif defined(_MSC_VER) && defined(_M_ARM) + return (uint32_t) _MulUnsignedHigh((unsigned long) a, (unsigned long) b); +#else + return (uint32_t) (((uint64_t) a * (uint64_t) b) >> 32); +#endif +} + +static inline uint64_t fxdiv_mulhi_uint64_t(uint64_t a, uint64_t b) { +#if defined(__OPENCL_VERSION__) + return mul_hi(a, b); +#elif defined(__CUDA_ARCH__) + return (uint64_t) __umul64hi((unsigned long long) a, (unsigned long long) b); +#elif defined(_MSC_VER) && defined(_M_X64) + return (uint64_t) __umulh((unsigned __int64) a, (unsigned __int64) b); +#elif defined(__GNUC__) && defined(__SIZEOF_INT128__) + return (uint64_t) (((((unsigned __int128) a) * ((unsigned __int128) b))) >> 64); +#else + const uint32_t a_lo = (uint32_t) a; + const uint32_t a_hi = (uint32_t) (a >> 32); + const uint32_t b_lo = (uint32_t) b; + const uint32_t b_hi = (uint32_t) (b >> 32); + + const uint64_t t = fxdiv_mulext_uint32_t(a_hi, b_lo) + + (uint64_t) fxdiv_mulhi_uint32_t(a_lo, b_lo); + return fxdiv_mulext_uint32_t(a_hi, b_hi) + (t >> 32) + + ((fxdiv_mulext_uint32_t(a_lo, b_hi) + (uint64_t) (uint32_t) t) >> 32); +#endif +} + +static inline size_t fxdiv_mulhi_size_t(size_t a, size_t b) { +#if SIZE_MAX == UINT32_MAX + return (size_t) fxdiv_mulhi_uint32_t((uint32_t) a, (uint32_t) b); +#elif SIZE_MAX == UINT64_MAX + return (size_t) fxdiv_mulhi_uint64_t((uint64_t) a, (uint64_t) b); +#else + #error Unsupported platform +#endif +} + +struct fxdiv_divisor_uint32_t { + uint32_t value; + uint32_t m; + uint8_t s1; + uint8_t s2; +}; + +struct fxdiv_result_uint32_t { + uint32_t quotient; + uint32_t remainder; +}; + +struct fxdiv_divisor_uint64_t { + uint64_t value; + uint64_t m; + uint8_t s1; + uint8_t s2; +}; + +struct fxdiv_result_uint64_t { + uint64_t quotient; + uint64_t remainder; +}; + +struct fxdiv_divisor_size_t { + size_t value; + size_t m; + uint8_t s1; + uint8_t s2; +}; + +struct fxdiv_result_size_t { + size_t quotient; + size_t remainder; +}; + +static inline struct fxdiv_divisor_uint32_t fxdiv_init_uint32_t(uint32_t d) { + struct fxdiv_divisor_uint32_t result = { d }; + if (d == 1) { + result.m = UINT32_C(1); + result.s1 = 0; + result.s2 = 0; + } else { + #if defined(__OPENCL_VERSION__) + const uint32_t l_minus_1 = 31 - clz(d - 1); + #elif defined(__CUDA_ARCH__) + const uint32_t l_minus_1 = 31 - __clz((int) (d - 1)); + #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM) || defined(_M_ARM64)) + unsigned long l_minus_1; + _BitScanReverse(&l_minus_1, (unsigned long) (d - 1)); + #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && FXDIV_USE_INLINE_ASSEMBLY + uint32_t l_minus_1; + __asm__("BSRL %[d_minus_1], %[l_minus_1]" + : [l_minus_1] "=r" (l_minus_1) + : [d_minus_1] "r" (d - 1) + : "cc"); + #elif defined(__GNUC__) + const uint32_t l_minus_1 = 31 - __builtin_clz(d - 1); + #else + /* Based on Algorithm 2 from Hacker's delight */ + + uint32_t l_minus_1 = 0; + uint32_t x = d - 1; + uint32_t y = x >> 16; + if (y != 0) { + l_minus_1 += 16; + x = y; + } + y = x >> 8; + if (y != 0) { + l_minus_1 += 8; + x = y; + } + y = x >> 4; + if (y != 0) { + l_minus_1 += 4; + x = y; + } + y = x >> 2; + if (y != 0) { + l_minus_1 += 2; + x = y; + } + if ((x & 2) != 0) { + l_minus_1 += 1; + } + #endif + uint32_t u_hi = (UINT32_C(2) << (uint32_t) l_minus_1) - d; + + /* Division of 64-bit number u_hi:UINT32_C(0) by 32-bit number d, 32-bit quotient output q */ + #if defined(__GNUC__) && defined(__i386__) && FXDIV_USE_INLINE_ASSEMBLY + uint32_t q; + __asm__("DIVL %[d]" + : "=a" (q), "+d" (u_hi) + : [d] "r" (d), "a" (0) + : "cc"); + #elif (defined(_MSC_VER) && _MSC_VER >= 1920) && !defined(__clang__) && !defined(__INTEL_COMPILER) && (defined(_M_IX86) || defined(_M_X64)) + unsigned int remainder; + const uint32_t q = (uint32_t) _udiv64((unsigned __int64) ((uint64_t) u_hi << 32), (unsigned int) d, &remainder); + #else + const uint32_t q = ((uint64_t) u_hi << 32) / d; + #endif + + result.m = q + UINT32_C(1); + result.s1 = 1; + result.s2 = (uint8_t) l_minus_1; + } + return result; +} + +static inline struct fxdiv_divisor_uint64_t fxdiv_init_uint64_t(uint64_t d) { + struct fxdiv_divisor_uint64_t result = { d }; + if (d == 1) { + result.m = UINT64_C(1); + result.s1 = 0; + result.s2 = 0; + } else { + #if defined(__OPENCL_VERSION__) + const uint32_t nlz_d = clz(d); + const uint32_t l_minus_1 = 63 - clz(d - 1); + #elif defined(__CUDA_ARCH__) + const uint32_t nlz_d = __clzll((long long) d); + const uint32_t l_minus_1 = 63 - __clzll((long long) (d - 1)); + #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64)) + unsigned long l_minus_1; + _BitScanReverse64(&l_minus_1, (unsigned __int64) (d - 1)); + unsigned long bsr_d; + _BitScanReverse64(&bsr_d, (unsigned __int64) d); + const uint32_t nlz_d = bsr_d ^ 0x3F; + #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM)) + const uint64_t d_minus_1 = d - 1; + const uint8_t d_is_power_of_2 = (d & d_minus_1) == 0; + unsigned long l_minus_1; + if ((uint32_t) (d_minus_1 >> 32) == 0) { + _BitScanReverse(&l_minus_1, (unsigned long) d_minus_1); + } else { + _BitScanReverse(&l_minus_1, (unsigned long) (uint32_t) (d_minus_1 >> 32)); + l_minus_1 += 32; + } + const uint32_t nlz_d = ((uint8_t) l_minus_1 ^ UINT8_C(0x3F)) - d_is_power_of_2; + #elif defined(__GNUC__) && defined(__x86_64__) && FXDIV_USE_INLINE_ASSEMBLY + uint64_t l_minus_1; + __asm__("BSRQ %[d_minus_1], %[l_minus_1]" + : [l_minus_1] "=r" (l_minus_1) + : [d_minus_1] "r" (d - 1) + : "cc"); + #elif defined(__GNUC__) + const uint32_t l_minus_1 = 63 - __builtin_clzll(d - 1); + const uint32_t nlz_d = __builtin_clzll(d); + #else + /* Based on Algorithm 2 from Hacker's delight */ + const uint64_t d_minus_1 = d - 1; + const uint32_t d_is_power_of_2 = (d & d_minus_1) == 0; + uint32_t l_minus_1 = 0; + uint32_t x = (uint32_t) d_minus_1; + uint32_t y = d_minus_1 >> 32; + if (y != 0) { + l_minus_1 += 32; + x = y; + } + y = x >> 16; + if (y != 0) { + l_minus_1 += 16; + x = y; + } + y = x >> 8; + if (y != 0) { + l_minus_1 += 8; + x = y; + } + y = x >> 4; + if (y != 0) { + l_minus_1 += 4; + x = y; + } + y = x >> 2; + if (y != 0) { + l_minus_1 += 2; + x = y; + } + if ((x & 2) != 0) { + l_minus_1 += 1; + } + const uint32_t nlz_d = (l_minus_1 ^ UINT32_C(0x3F)) - d_is_power_of_2; + #endif + uint64_t u_hi = (UINT64_C(2) << (uint32_t) l_minus_1) - d; + + /* Division of 128-bit number u_hi:UINT64_C(0) by 64-bit number d, 64-bit quotient output q */ + #if defined(__GNUC__) && defined(__x86_64__) && FXDIV_USE_INLINE_ASSEMBLY + uint64_t q; + __asm__("DIVQ %[d]" + : "=a" (q), "+d" (u_hi) + : [d] "r" (d), "a" (UINT64_C(0)) + : "cc"); + #elif 0 && defined(__GNUC__) && defined(__SIZEOF_INT128__) + /* GCC, Clang, and Intel Compiler fail to inline optimized implementation and call into support library for 128-bit division */ + const uint64_t q = (uint64_t) (((unsigned __int128) u_hi << 64) / ((unsigned __int128) d)); + #elif (defined(_MSC_VER) && _MSC_VER >= 1920) && !defined(__clang__) && !defined(__INTEL_COMPILER) && defined(_M_X64) + unsigned __int64 remainder; + const uint64_t q = (uint64_t) _udiv128((unsigned __int64) u_hi, 0, (unsigned __int64) d, &remainder); + #else + /* Implementation based on code from Hacker's delight */ + + /* Normalize divisor and shift divident left */ + d <<= nlz_d; + u_hi <<= nlz_d; + /* Break divisor up into two 32-bit digits */ + const uint64_t d_hi = (uint32_t) (d >> 32); + const uint32_t d_lo = (uint32_t) d; + + /* Compute the first quotient digit, q1 */ + uint64_t q1 = u_hi / d_hi; + uint64_t r1 = u_hi - q1 * d_hi; + + while ((q1 >> 32) != 0 || fxdiv_mulext_uint32_t((uint32_t) q1, d_lo) > (r1 << 32)) { + q1 -= 1; + r1 += d_hi; + if ((r1 >> 32) != 0) { + break; + } + } + + /* Multiply and subtract. */ + u_hi = (u_hi << 32) - q1 * d; + + /* Compute the second quotient digit, q0 */ + uint64_t q0 = u_hi / d_hi; + uint64_t r0 = u_hi - q0 * d_hi; + + while ((q0 >> 32) != 0 || fxdiv_mulext_uint32_t((uint32_t) q0, d_lo) > (r0 << 32)) { + q0 -= 1; + r0 += d_hi; + if ((r0 >> 32) != 0) { + break; + } + } + const uint64_t q = (q1 << 32) | (uint32_t) q0; + #endif + result.m = q + UINT64_C(1); + result.s1 = 1; + result.s2 = (uint8_t) l_minus_1; + } + return result; +} + +static inline struct fxdiv_divisor_size_t fxdiv_init_size_t(size_t d) { +#if SIZE_MAX == UINT32_MAX + const struct fxdiv_divisor_uint32_t uint_result = fxdiv_init_uint32_t((uint32_t) d); +#elif SIZE_MAX == UINT64_MAX + const struct fxdiv_divisor_uint64_t uint_result = fxdiv_init_uint64_t((uint64_t) d); +#else + #error Unsupported platform +#endif + struct fxdiv_divisor_size_t size_result = { + (size_t) uint_result.value, + (size_t) uint_result.m, + uint_result.s1, + uint_result.s2 + }; + return size_result; +} + +static inline uint32_t fxdiv_quotient_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) { + const uint32_t t = fxdiv_mulhi_uint32_t(n, divisor.m); + return (t + ((n - t) >> divisor.s1)) >> divisor.s2; +} + +static inline uint64_t fxdiv_quotient_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) { + const uint64_t t = fxdiv_mulhi_uint64_t(n, divisor.m); + return (t + ((n - t) >> divisor.s1)) >> divisor.s2; +} + +static inline size_t fxdiv_quotient_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) { +#if SIZE_MAX == UINT32_MAX + const struct fxdiv_divisor_uint32_t uint32_divisor = { + (uint32_t) divisor.value, + (uint32_t) divisor.m, + divisor.s1, + divisor.s2 + }; + return fxdiv_quotient_uint32_t((uint32_t) n, uint32_divisor); +#elif SIZE_MAX == UINT64_MAX + const struct fxdiv_divisor_uint64_t uint64_divisor = { + (uint64_t) divisor.value, + (uint64_t) divisor.m, + divisor.s1, + divisor.s2 + }; + return fxdiv_quotient_uint64_t((uint64_t) n, uint64_divisor); +#else + #error Unsupported platform +#endif +} + +static inline uint32_t fxdiv_remainder_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) { + const uint32_t quotient = fxdiv_quotient_uint32_t(n, divisor); + return n - quotient * divisor.value; +} + +static inline uint64_t fxdiv_remainder_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) { + const uint64_t quotient = fxdiv_quotient_uint64_t(n, divisor); + return n - quotient * divisor.value; +} + +static inline size_t fxdiv_remainder_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) { + const size_t quotient = fxdiv_quotient_size_t(n, divisor); + return n - quotient * divisor.value; +} + +static inline uint32_t fxdiv_round_down_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t granularity) { + const uint32_t quotient = fxdiv_quotient_uint32_t(n, granularity); + return quotient * granularity.value; +} + +static inline uint64_t fxdiv_round_down_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t granularity) { + const uint64_t quotient = fxdiv_quotient_uint64_t(n, granularity); + return quotient * granularity.value; +} + +static inline size_t fxdiv_round_down_size_t(size_t n, const struct fxdiv_divisor_size_t granularity) { + const size_t quotient = fxdiv_quotient_size_t(n, granularity); + return quotient * granularity.value; +} + +static inline struct fxdiv_result_uint32_t fxdiv_divide_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) { + const uint32_t quotient = fxdiv_quotient_uint32_t(n, divisor); + const uint32_t remainder = n - quotient * divisor.value; + struct fxdiv_result_uint32_t result = { quotient, remainder }; + return result; +} + +static inline struct fxdiv_result_uint64_t fxdiv_divide_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) { + const uint64_t quotient = fxdiv_quotient_uint64_t(n, divisor); + const uint64_t remainder = n - quotient * divisor.value; + struct fxdiv_result_uint64_t result = { quotient, remainder }; + return result; +} + +static inline struct fxdiv_result_size_t fxdiv_divide_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) { + const size_t quotient = fxdiv_quotient_size_t(n, divisor); + const size_t remainder = n - quotient * divisor.value; + struct fxdiv_result_size_t result = { quotient, remainder }; + return result; +} + +#endif /* FXDIV_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc.h b/deps/exla/cache/xla_extension/include/include/hwloc.h new file mode 100644 index 0000000000000000000000000000000000000000..35bbcc71784e4241a4fdc4d1cdf6044443b3e5f4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc.h @@ -0,0 +1,2578 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2021 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2020 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/*===================================================================== + * PLEASE GO READ THE DOCUMENTATION! + * ------------------------------------------------ + * $tarball_directory/doc/doxygen-doc/ + * or + * https://www.open-mpi.org/projects/hwloc/doc/ + *===================================================================== + * + * FAIR WARNING: Do NOT expect to be able to figure out all the + * subtleties of hwloc by simply reading function prototypes and + * constant descrptions here in this file. + * + * Hwloc has wonderful documentation in both PDF and HTML formats for + * your reading pleasure. The formal documentation explains a LOT of + * hwloc-specific concepts, provides definitions, and discusses the + * "big picture" for many of the things that you'll find here in this + * header file. + * + * The PDF/HTML documentation was generated via Doxygen; much of what + * you'll see in there is also here in this file. BUT THERE IS A LOT + * THAT IS IN THE PDF/HTML THAT IS ***NOT*** IN hwloc.h! + * + * There are entire paragraph-length descriptions, discussions, and + * pretty pictures to explain subtle corner cases, provide concrete + * examples, etc. + * + * Please, go read the documentation. :-) + * + * Moreover there are several examples of hwloc use under doc/examples + * in the source tree. + * + *=====================================================================*/ + +/** \file + * \brief The hwloc API. + * + * See hwloc/bitmap.h for bitmap specific macros. + * See hwloc/helper.h for high-level topology traversal helpers. + * See hwloc/inlines.h for the actual inline code of some functions below. + * See hwloc/export.h for exporting topologies to XML or to synthetic descriptions. + * See hwloc/distances.h for querying and modifying distances between objects. + * See hwloc/diff.h for manipulating differences between similar topologies. + */ + +#ifndef HWLOC_H +#define HWLOC_H + +#include "hwloc/autogen/config.h" + +#include +#include +#include +#include + +/* + * Symbol transforms + */ +#include "hwloc/rename.h" + +/* + * Bitmap definitions + */ + +#include "hwloc/bitmap.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \defgroup hwlocality_api_version API version + * @{ + */ + +/** \brief Indicate at build time which hwloc API version is being used. + * + * This number is updated to (X<<16)+(Y<<8)+Z when a new release X.Y.Z + * actually modifies the API. + * + * Users may check for available features at build time using this number + * (see \ref faq_version_api). + * + * \note This should not be confused with HWLOC_VERSION, the library version. + * Two stable releases of the same series usually have the same ::HWLOC_API_VERSION + * even if their HWLOC_VERSION are different. + */ +#define HWLOC_API_VERSION 0x00020500 + +/** \brief Indicate at runtime which hwloc API version was used at build time. + * + * Should be ::HWLOC_API_VERSION if running on the same version. + */ +HWLOC_DECLSPEC unsigned hwloc_get_api_version(void); + +/** \brief Current component and plugin ABI version (see hwloc/plugins.h) */ +#define HWLOC_COMPONENT_ABI 7 + +/** @} */ + + + +/** \defgroup hwlocality_object_sets Object Sets (hwloc_cpuset_t and hwloc_nodeset_t) + * + * Hwloc uses bitmaps to represent two distinct kinds of object sets: + * CPU sets (::hwloc_cpuset_t) and NUMA node sets (::hwloc_nodeset_t). + * These types are both typedefs to a common back end type + * (::hwloc_bitmap_t), and therefore all the hwloc bitmap functions + * are applicable to both ::hwloc_cpuset_t and ::hwloc_nodeset_t (see + * \ref hwlocality_bitmap). + * + * The rationale for having two different types is that even though + * the actions one wants to perform on these types are the same (e.g., + * enable and disable individual items in the set/mask), they're used + * in very different contexts: one for specifying which processors to + * use and one for specifying which NUMA nodes to use. Hence, the + * name difference is really just to reflect the intent of where the + * type is used. + * + * @{ + */ + +/** \brief A CPU set is a bitmap whose bits are set according to CPU + * physical OS indexes. + * + * It may be consulted and modified with the bitmap API as any + * ::hwloc_bitmap_t (see hwloc/bitmap.h). + * + * Each bit may be converted into a PU object using + * hwloc_get_pu_obj_by_os_index(). + */ +typedef hwloc_bitmap_t hwloc_cpuset_t; +/** \brief A non-modifiable ::hwloc_cpuset_t. */ +typedef hwloc_const_bitmap_t hwloc_const_cpuset_t; + +/** \brief A node set is a bitmap whose bits are set according to NUMA + * memory node physical OS indexes. + * + * It may be consulted and modified with the bitmap API as any + * ::hwloc_bitmap_t (see hwloc/bitmap.h). + * Each bit may be converted into a NUMA node object using + * hwloc_get_numanode_obj_by_os_index(). + * + * When binding memory on a system without any NUMA node, + * the single main memory bank is considered as NUMA node #0. + * + * See also \ref hwlocality_helper_nodeset_convert. + */ +typedef hwloc_bitmap_t hwloc_nodeset_t; +/** \brief A non-modifiable ::hwloc_nodeset_t. + */ +typedef hwloc_const_bitmap_t hwloc_const_nodeset_t; + +/** @} */ + + + +/** \defgroup hwlocality_object_types Object Types + * @{ + */ + +/** \brief Type of topology object. + * + * \note Do not rely on the ordering or completeness of the values as new ones + * may be defined in the future! If you need to compare types, use + * hwloc_compare_types() instead. + */ +typedef enum { + +/** \cond */ +#define HWLOC_OBJ_TYPE_MIN HWLOC_OBJ_MACHINE /* Sentinel value */ +/** \endcond */ + + HWLOC_OBJ_MACHINE, /**< \brief Machine. + * A set of processors and memory with cache + * coherency. + * + * This type is always used for the root object of a topology, + * and never used anywhere else. + * Hence its parent is always \c NULL. + */ + + HWLOC_OBJ_PACKAGE, /**< \brief Physical package. + * The physical package that usually gets inserted + * into a socket on the motherboard. + * A processor package usually contains multiple cores, + * and possibly some dies. + */ + HWLOC_OBJ_CORE, /**< \brief Core. + * A computation unit (may be shared by several + * PUs, aka logical processors). + */ + HWLOC_OBJ_PU, /**< \brief Processing Unit, or (Logical) Processor. + * An execution unit (may share a core with some + * other logical processors, e.g. in the case of + * an SMT core). + * + * This is the smallest object representing CPU resources, + * it cannot have any child except Misc objects. + * + * Objects of this kind are always reported and can + * thus be used as fallback when others are not. + */ + + HWLOC_OBJ_L1CACHE, /**< \brief Level 1 Data (or Unified) Cache. */ + HWLOC_OBJ_L2CACHE, /**< \brief Level 2 Data (or Unified) Cache. */ + HWLOC_OBJ_L3CACHE, /**< \brief Level 3 Data (or Unified) Cache. */ + HWLOC_OBJ_L4CACHE, /**< \brief Level 4 Data (or Unified) Cache. */ + HWLOC_OBJ_L5CACHE, /**< \brief Level 5 Data (or Unified) Cache. */ + + HWLOC_OBJ_L1ICACHE, /**< \brief Level 1 instruction Cache (filtered out by default). */ + HWLOC_OBJ_L2ICACHE, /**< \brief Level 2 instruction Cache (filtered out by default). */ + HWLOC_OBJ_L3ICACHE, /**< \brief Level 3 instruction Cache (filtered out by default). */ + + HWLOC_OBJ_GROUP, /**< \brief Group objects. + * Objects which do not fit in the above but are + * detected by hwloc and are useful to take into + * account for affinity. For instance, some operating systems + * expose their arbitrary processors aggregation this + * way. And hwloc may insert such objects to group + * NUMA nodes according to their distances. + * See also \ref faq_groups. + * + * These objects are removed when they do not bring + * any structure (see ::HWLOC_TYPE_FILTER_KEEP_STRUCTURE). + */ + + HWLOC_OBJ_NUMANODE, /**< \brief NUMA node. + * An object that contains memory that is directly + * and byte-accessible to the host processors. + * It is usually close to some cores (the corresponding objects + * are descendants of the NUMA node object in the hwloc tree). + * + * This is the smallest object representing Memory resources, + * it cannot have any child except Misc objects. + * However it may have Memory-side cache parents. + * + * There is always at least one such object in the topology + * even if the machine is not NUMA. + * + * Memory objects are not listed in the main children list, + * but rather in the dedicated Memory children list. + * + * NUMA nodes have a special depth ::HWLOC_TYPE_DEPTH_NUMANODE + * instead of a normal depth just like other objects in the + * main tree. + */ + + HWLOC_OBJ_BRIDGE, /**< \brief Bridge (filtered out by default). + * Any bridge (or PCI switch) that connects the host or an I/O bus, + * to another I/O bus. + * + * Bridges are not added to the topology unless their + * filtering is changed (see hwloc_topology_set_type_filter() + * and hwloc_topology_set_io_types_filter()). + * + * I/O objects are not listed in the main children list, + * but rather in the dedicated io children list. + * I/O objects have NULL CPU and node sets. + */ + HWLOC_OBJ_PCI_DEVICE, /**< \brief PCI device (filtered out by default). + * + * PCI devices are not added to the topology unless their + * filtering is changed (see hwloc_topology_set_type_filter() + * and hwloc_topology_set_io_types_filter()). + * + * I/O objects are not listed in the main children list, + * but rather in the dedicated io children list. + * I/O objects have NULL CPU and node sets. + */ + HWLOC_OBJ_OS_DEVICE, /**< \brief Operating system device (filtered out by default). + * + * OS devices are not added to the topology unless their + * filtering is changed (see hwloc_topology_set_type_filter() + * and hwloc_topology_set_io_types_filter()). + * + * I/O objects are not listed in the main children list, + * but rather in the dedicated io children list. + * I/O objects have NULL CPU and node sets. + */ + + HWLOC_OBJ_MISC, /**< \brief Miscellaneous objects (filtered out by default). + * Objects without particular meaning, that can e.g. be + * added by the application for its own use, or by hwloc + * for miscellaneous objects such as MemoryModule (DIMMs). + * + * They are not added to the topology unless their filtering + * is changed (see hwloc_topology_set_type_filter()). + * + * These objects are not listed in the main children list, + * but rather in the dedicated misc children list. + * Misc objects may only have Misc objects as children, + * and those are in the dedicated misc children list as well. + * Misc objects have NULL CPU and node sets. + */ + + HWLOC_OBJ_MEMCACHE, /**< \brief Memory-side cache (filtered out by default). + * A cache in front of a specific NUMA node. + * + * This object always has at least one NUMA node as a memory child. + * + * Memory objects are not listed in the main children list, + * but rather in the dedicated Memory children list. + * + * Memory-side cache have a special depth ::HWLOC_TYPE_DEPTH_MEMCACHE + * instead of a normal depth just like other objects in the + * main tree. + */ + + HWLOC_OBJ_DIE, /**< \brief Die within a physical package. + * A subpart of the physical package, that contains multiple cores. + */ + + HWLOC_OBJ_TYPE_MAX /**< \private Sentinel value */ +} hwloc_obj_type_t; + +/** \brief Cache type. */ +typedef enum hwloc_obj_cache_type_e { + HWLOC_OBJ_CACHE_UNIFIED, /**< \brief Unified cache. */ + HWLOC_OBJ_CACHE_DATA, /**< \brief Data cache. */ + HWLOC_OBJ_CACHE_INSTRUCTION /**< \brief Instruction cache (filtered out by default). */ +} hwloc_obj_cache_type_t; + +/** \brief Type of one side (upstream or downstream) of an I/O bridge. */ +typedef enum hwloc_obj_bridge_type_e { + HWLOC_OBJ_BRIDGE_HOST, /**< \brief Host-side of a bridge, only possible upstream. */ + HWLOC_OBJ_BRIDGE_PCI /**< \brief PCI-side of a bridge. */ +} hwloc_obj_bridge_type_t; + +/** \brief Type of a OS device. */ +typedef enum hwloc_obj_osdev_type_e { + HWLOC_OBJ_OSDEV_BLOCK, /**< \brief Operating system block device, or non-volatile memory device. + * For instance "sda" or "dax2.0" on Linux. */ + HWLOC_OBJ_OSDEV_GPU, /**< \brief Operating system GPU device. + * For instance ":0.0" for a GL display, + * "card0" for a Linux DRM device. */ + HWLOC_OBJ_OSDEV_NETWORK, /**< \brief Operating system network device. + * For instance the "eth0" interface on Linux. */ + HWLOC_OBJ_OSDEV_OPENFABRICS, /**< \brief Operating system openfabrics device. + * For instance the "mlx4_0" InfiniBand HCA, + * "hfi1_0" Omni-Path interface, + * or "bxi0" Atos/Bull BXI HCA on Linux. */ + HWLOC_OBJ_OSDEV_DMA, /**< \brief Operating system dma engine device. + * For instance the "dma0chan0" DMA channel on Linux. */ + HWLOC_OBJ_OSDEV_COPROC /**< \brief Operating system co-processor device. + * For instance "opencl0d0" for a OpenCL device, + * "cuda0" for a CUDA device. */ +} hwloc_obj_osdev_type_t; + +/** \brief Compare the depth of two object types + * + * Types shouldn't be compared as they are, since newer ones may be added in + * the future. This function returns less than, equal to, or greater than zero + * respectively if \p type1 objects usually include \p type2 objects, are the + * same as \p type2 objects, or are included in \p type2 objects. If the types + * can not be compared (because neither is usually contained in the other), + * ::HWLOC_TYPE_UNORDERED is returned. Object types containing CPUs can always + * be compared (usually, a system contains machines which contain nodes which + * contain packages which contain caches, which contain cores, which contain + * processors). + * + * \note ::HWLOC_OBJ_PU will always be the deepest, + * while ::HWLOC_OBJ_MACHINE is always the highest. + * + * \note This does not mean that the actual topology will respect that order: + * e.g. as of today cores may also contain caches, and packages may also contain + * nodes. This is thus just to be seen as a fallback comparison method. + */ +HWLOC_DECLSPEC int hwloc_compare_types (hwloc_obj_type_t type1, hwloc_obj_type_t type2) __hwloc_attribute_const; + +/** \brief Value returned by hwloc_compare_types() when types can not be compared. \hideinitializer */ +#define HWLOC_TYPE_UNORDERED INT_MAX + +/** @} */ + + + +/** \defgroup hwlocality_objects Object Structure and Attributes + * @{ + */ + +union hwloc_obj_attr_u; + +/** \brief Structure of a topology object + * + * Applications must not modify any field except \p hwloc_obj.userdata. + */ +struct hwloc_obj { + /* physical information */ + hwloc_obj_type_t type; /**< \brief Type of object */ + char *subtype; /**< \brief Subtype string to better describe the type field. */ + + unsigned os_index; /**< \brief OS-provided physical index number. + * It is not guaranteed unique across the entire machine, + * except for PUs and NUMA nodes. + * Set to HWLOC_UNKNOWN_INDEX if unknown or irrelevant for this object. + */ +#define HWLOC_UNKNOWN_INDEX (unsigned)-1 + + char *name; /**< \brief Object-specific name if any. + * Mostly used for identifying OS devices and Misc objects where + * a name string is more useful than numerical indexes. + */ + + hwloc_uint64_t total_memory; /**< \brief Total memory (in bytes) in NUMA nodes below this object. */ + + union hwloc_obj_attr_u *attr; /**< \brief Object type-specific Attributes, + * may be \c NULL if no attribute value was found */ + + /* global position */ + int depth; /**< \brief Vertical index in the hierarchy. + * + * For normal objects, this is the depth of the horizontal level + * that contains this object and its cousins of the same type. + * If the topology is symmetric, this is equal to the parent depth + * plus one, and also equal to the number of parent/child links + * from the root object to here. + * + * For special objects (NUMA nodes, I/O and Misc) that are not + * in the main tree, this is a special negative value that + * corresponds to their dedicated level, + * see hwloc_get_type_depth() and ::hwloc_get_type_depth_e. + * Those special values can be passed to hwloc functions such + * hwloc_get_nbobjs_by_depth() as usual. + */ + unsigned logical_index; /**< \brief Horizontal index in the whole list of similar objects, + * hence guaranteed unique across the entire machine. + * Could be a "cousin_rank" since it's the rank within the "cousin" list below + * Note that this index may change when restricting the topology + * or when inserting a group. + */ + + /* cousins are all objects of the same type (and depth) across the entire topology */ + struct hwloc_obj *next_cousin; /**< \brief Next object of same type and depth */ + struct hwloc_obj *prev_cousin; /**< \brief Previous object of same type and depth */ + + /* children of the same parent are siblings, even if they may have different type and depth */ + struct hwloc_obj *parent; /**< \brief Parent, \c NULL if root (Machine object) */ + unsigned sibling_rank; /**< \brief Index in parent's \c children[] array. Or the index in parent's Memory, I/O or Misc children list. */ + struct hwloc_obj *next_sibling; /**< \brief Next object below the same parent (inside the same list of children). */ + struct hwloc_obj *prev_sibling; /**< \brief Previous object below the same parent (inside the same list of children). */ + /** @name List and array of normal children below this object (except Memory, I/O and Misc children). */ + /**@{*/ + unsigned arity; /**< \brief Number of normal children. + * Memory, Misc and I/O children are not listed here + * but rather in their dedicated children list. + */ + struct hwloc_obj **children; /**< \brief Normal children, \c children[0 .. arity -1] */ + struct hwloc_obj *first_child; /**< \brief First normal child */ + struct hwloc_obj *last_child; /**< \brief Last normal child */ + /**@}*/ + + int symmetric_subtree; /**< \brief Set if the subtree of normal objects below this object is symmetric, + * which means all normal children and their children have identical subtrees. + * + * Memory, I/O and Misc children are ignored. + * + * If set in the topology root object, lstopo may export the topology + * as a synthetic string. + */ + + /** @name List of Memory children below this object. */ + /**@{*/ + unsigned memory_arity; /**< \brief Number of Memory children. + * These children are listed in \p memory_first_child. + */ + struct hwloc_obj *memory_first_child; /**< \brief First Memory child. + * NUMA nodes and Memory-side caches are listed here + * (\p memory_arity and \p memory_first_child) + * instead of in the normal children list. + * See also hwloc_obj_type_is_memory(). + * + * A memory hierarchy starts from a normal CPU-side object + * (e.g. Package) and ends with NUMA nodes as leaves. + * There might exist some memory-side caches between them + * in the middle of the memory subtree. + */ + /**@}*/ + + /** @name List of I/O children below this object. */ + /**@{*/ + unsigned io_arity; /**< \brief Number of I/O children. + * These children are listed in \p io_first_child. + */ + struct hwloc_obj *io_first_child; /**< \brief First I/O child. + * Bridges, PCI and OS devices are listed here (\p io_arity and \p io_first_child) + * instead of in the normal children list. + * See also hwloc_obj_type_is_io(). + */ + /**@}*/ + + /** @name List of Misc children below this object. */ + /**@{*/ + unsigned misc_arity; /**< \brief Number of Misc children. + * These children are listed in \p misc_first_child. + */ + struct hwloc_obj *misc_first_child; /**< \brief First Misc child. + * Misc objects are listed here (\p misc_arity and \p misc_first_child) + * instead of in the normal children list. + */ + /**@}*/ + + /* cpusets and nodesets */ + hwloc_cpuset_t cpuset; /**< \brief CPUs covered by this object + * + * This is the set of CPUs for which there are PU objects in the topology + * under this object, i.e. which are known to be physically contained in this + * object and known how (the children path between this object and the PU + * objects). + * + * If the ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED configuration flag is set, + * some of these CPUs may be online but not allowed for binding, + * see hwloc_topology_get_allowed_cpuset(). + * + * \note All objects have non-NULL CPU and node sets except Misc and I/O objects. + * + * \note Its value must not be changed, hwloc_bitmap_dup() must be used instead. + */ + hwloc_cpuset_t complete_cpuset; /**< \brief The complete CPU set of processors of this object, + * + * This may include not only the same as the cpuset field, but also some CPUs for + * which topology information is unknown or incomplete, some offlines CPUs, and + * the CPUs that are ignored when the ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED flag + * is not set. + * Thus no corresponding PU object may be found in the topology, because the + * precise position is undefined. It is however known that it would be somewhere + * under this object. + * + * \note Its value must not be changed, hwloc_bitmap_dup() must be used instead. + */ + + hwloc_nodeset_t nodeset; /**< \brief NUMA nodes covered by this object or containing this object + * + * This is the set of NUMA nodes for which there are NUMA node objects in the + * topology under or above this object, i.e. which are known to be physically + * contained in this object or containing it and known how (the children path + * between this object and the NUMA node objects). + * + * In the end, these nodes are those that are close to the current object. + * Function hwloc_get_local_numanode_objs() may be used to list those NUMA + * nodes more precisely. + * + * If the ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED configuration flag is set, + * some of these nodes may be online but not allowed for allocation, + * see hwloc_topology_get_allowed_nodeset(). + * + * If there are no NUMA nodes in the machine, all the memory is close to this + * object, so only the first bit may be set in \p nodeset. + * + * \note All objects have non-NULL CPU and node sets except Misc and I/O objects. + * + * \note Its value must not be changed, hwloc_bitmap_dup() must be used instead. + */ + hwloc_nodeset_t complete_nodeset; /**< \brief The complete NUMA node set of this object, + * + * This may include not only the same as the nodeset field, but also some NUMA + * nodes for which topology information is unknown or incomplete, some offlines + * nodes, and the nodes that are ignored when the ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED + * flag is not set. + * Thus no corresponding NUMA node object may be found in the topology, because the + * precise position is undefined. It is however known that it would be + * somewhere under this object. + * + * If there are no NUMA nodes in the machine, all the memory is close to this + * object, so only the first bit is set in \p complete_nodeset. + * + * \note Its value must not be changed, hwloc_bitmap_dup() must be used instead. + */ + + struct hwloc_info_s *infos; /**< \brief Array of stringified info type=name. */ + unsigned infos_count; /**< \brief Size of infos array. */ + + /* misc */ + void *userdata; /**< \brief Application-given private data pointer, + * initialized to \c NULL, use it as you wish. + * See hwloc_topology_set_userdata_export_callback() in hwloc/export.h + * if you wish to export this field to XML. */ + + hwloc_uint64_t gp_index; /**< \brief Global persistent index. + * Generated by hwloc, unique across the topology (contrary to os_index) + * and persistent across topology changes (contrary to logical_index). + * Mostly used internally, but could also be used by application to identify objects. + */ +}; +/** + * \brief Convenience typedef; a pointer to a struct hwloc_obj. + */ +typedef struct hwloc_obj * hwloc_obj_t; + +/** \brief Object type-specific Attributes */ +union hwloc_obj_attr_u { + /** \brief NUMA node-specific Object Attributes */ + struct hwloc_numanode_attr_s { + hwloc_uint64_t local_memory; /**< \brief Local memory (in bytes) */ + unsigned page_types_len; /**< \brief Size of array \p page_types */ + /** \brief Array of local memory page types, \c NULL if no local memory and \p page_types is 0. + * + * The array is sorted by increasing \p size fields. + * It contains \p page_types_len slots. + */ + struct hwloc_memory_page_type_s { + hwloc_uint64_t size; /**< \brief Size of pages */ + hwloc_uint64_t count; /**< \brief Number of pages of this size */ + } * page_types; + } numanode; + + /** \brief Cache-specific Object Attributes */ + struct hwloc_cache_attr_s { + hwloc_uint64_t size; /**< \brief Size of cache in bytes */ + unsigned depth; /**< \brief Depth of cache (e.g., L1, L2, ...etc.) */ + unsigned linesize; /**< \brief Cache-line size in bytes. 0 if unknown */ + int associativity; /**< \brief Ways of associativity, + * -1 if fully associative, 0 if unknown */ + hwloc_obj_cache_type_t type; /**< \brief Cache type */ + } cache; + /** \brief Group-specific Object Attributes */ + struct hwloc_group_attr_s { + unsigned depth; /**< \brief Depth of group object. + * It may change if intermediate Group objects are added. */ + unsigned kind; /**< \brief Internally-used kind of group. */ + unsigned subkind; /**< \brief Internally-used subkind to distinguish different levels of groups with same kind */ + unsigned char dont_merge; /**< \brief Flag preventing groups from being automatically merged with identical parent or children. */ + } group; + /** \brief PCI Device specific Object Attributes */ + struct hwloc_pcidev_attr_s { +#ifndef HWLOC_HAVE_32BITS_PCI_DOMAIN + unsigned short domain; /* Only 16bits PCI domains are supported by default */ +#else + unsigned int domain; /* 32bits PCI domain support break the library ABI, hence it's disabled by default */ +#endif + unsigned char bus, dev, func; + unsigned short class_id; + unsigned short vendor_id, device_id, subvendor_id, subdevice_id; + unsigned char revision; + float linkspeed; /* in GB/s */ + } pcidev; + /** \brief Bridge specific Object Attributes */ + struct hwloc_bridge_attr_s { + union { + struct hwloc_pcidev_attr_s pci; + } upstream; + hwloc_obj_bridge_type_t upstream_type; + union { + struct { +#ifndef HWLOC_HAVE_32BITS_PCI_DOMAIN + unsigned short domain; /* Only 16bits PCI domains are supported by default */ +#else + unsigned int domain; /* 32bits PCI domain support break the library ABI, hence it's disabled by default */ +#endif + unsigned char secondary_bus, subordinate_bus; + } pci; + } downstream; + hwloc_obj_bridge_type_t downstream_type; + unsigned depth; + } bridge; + /** \brief OS Device specific Object Attributes */ + struct hwloc_osdev_attr_s { + hwloc_obj_osdev_type_t type; + } osdev; +}; + +/** \brief Object info + * + * \sa hwlocality_info_attr + */ +struct hwloc_info_s { + char *name; /**< \brief Info name */ + char *value; /**< \brief Info value */ +}; + +/** @} */ + + + +/** \defgroup hwlocality_creation Topology Creation and Destruction + * @{ + */ + +struct hwloc_topology; +/** \brief Topology context + * + * To be initialized with hwloc_topology_init() and built with hwloc_topology_load(). + */ +typedef struct hwloc_topology * hwloc_topology_t; + +/** \brief Allocate a topology context. + * + * \param[out] topologyp is assigned a pointer to the new allocated context. + * + * \return 0 on success, -1 on error. + */ +HWLOC_DECLSPEC int hwloc_topology_init (hwloc_topology_t *topologyp); + +/** \brief Build the actual topology + * + * Build the actual topology once initialized with hwloc_topology_init() and + * tuned with \ref hwlocality_configuration and \ref hwlocality_setsource routines. + * No other routine may be called earlier using this topology context. + * + * \param topology is the topology to be loaded with objects. + * + * \return 0 on success, -1 on error. + * + * \note On failure, the topology is reinitialized. It should be either + * destroyed with hwloc_topology_destroy() or configured and loaded again. + * + * \note This function may be called only once per topology. + * + * \note The binding of the current thread or process may temporarily change + * during this call but it will be restored before it returns. + * + * \sa hwlocality_configuration and hwlocality_setsource + */ +HWLOC_DECLSPEC int hwloc_topology_load(hwloc_topology_t topology); + +/** \brief Terminate and free a topology context + * + * \param topology is the topology to be freed + */ +HWLOC_DECLSPEC void hwloc_topology_destroy (hwloc_topology_t topology); + +/** \brief Duplicate a topology. + * + * The entire topology structure as well as its objects + * are duplicated into a new one. + * + * This is useful for keeping a backup while modifying a topology. + * + * \note Object userdata is not duplicated since hwloc does not know what it point to. + * The objects of both old and new topologies will point to the same userdata. + */ +HWLOC_DECLSPEC int hwloc_topology_dup(hwloc_topology_t *newtopology, hwloc_topology_t oldtopology); + +/** \brief Verify that the topology is compatible with the current hwloc library. + * + * This is useful when using the same topology structure (in memory) + * in different libraries that may use different hwloc installations + * (for instance if one library embeds a specific version of hwloc, + * while another library uses a default system-wide hwloc installation). + * + * If all libraries/programs use the same hwloc installation, this function + * always returns success. + * + * \return \c 0 on success. + * + * \return \c -1 with \p errno set to \c EINVAL if incompatible. + * + * \note If sharing between processes with hwloc_shmem_topology_write(), + * the relevant check is already performed inside hwloc_shmem_topology_adopt(). + */ +HWLOC_DECLSPEC int hwloc_topology_abi_check(hwloc_topology_t topology); + +/** \brief Run internal checks on a topology structure + * + * The program aborts if an inconsistency is detected in the given topology. + * + * \param topology is the topology to be checked + * + * \note This routine is only useful to developers. + * + * \note The input topology should have been previously loaded with + * hwloc_topology_load(). + */ +HWLOC_DECLSPEC void hwloc_topology_check(hwloc_topology_t topology); + +/** @} */ + + + +/** \defgroup hwlocality_levels Object levels, depths and types + * @{ + * + * Be sure to see the figure in \ref termsanddefs that shows a + * complete topology tree, including depths, child/sibling/cousin + * relationships, and an example of an asymmetric topology where one + * package has fewer caches than its peers. + */ + +/** \brief Get the depth of the hierarchical tree of objects. + * + * This is the depth of ::HWLOC_OBJ_PU objects plus one. + * + * \note NUMA nodes, I/O and Misc objects are ignored when computing + * the depth of the tree (they are placed on special levels). + */ +HWLOC_DECLSPEC int hwloc_topology_get_depth(hwloc_topology_t __hwloc_restrict topology) __hwloc_attribute_pure; + +/** \brief Returns the depth of objects of type \p type. + * + * If no object of this type is present on the underlying architecture, or if + * the OS doesn't provide this kind of information, the function returns + * ::HWLOC_TYPE_DEPTH_UNKNOWN. + * + * If type is absent but a similar type is acceptable, see also + * hwloc_get_type_or_below_depth() and hwloc_get_type_or_above_depth(). + * + * If ::HWLOC_OBJ_GROUP is given, the function may return ::HWLOC_TYPE_DEPTH_MULTIPLE + * if multiple levels of Groups exist. + * + * If a NUMA node, I/O or Misc object type is given, the function returns a virtual + * value because these objects are stored in special levels that are not CPU-related. + * This virtual depth may be passed to other hwloc functions such as + * hwloc_get_obj_by_depth() but it should not be considered as an actual + * depth by the application. In particular, it should not be compared with + * any other object depth or with the entire topology depth. + * \sa hwloc_get_memory_parents_depth(). + * + * \sa hwloc_type_sscanf_as_depth() for returning the depth of objects + * whose type is given as a string. + */ +HWLOC_DECLSPEC int hwloc_get_type_depth (hwloc_topology_t topology, hwloc_obj_type_t type); + +enum hwloc_get_type_depth_e { + HWLOC_TYPE_DEPTH_UNKNOWN = -1, /**< \brief No object of given type exists in the topology. \hideinitializer */ + HWLOC_TYPE_DEPTH_MULTIPLE = -2, /**< \brief Objects of given type exist at different depth in the topology (only for Groups). \hideinitializer */ + HWLOC_TYPE_DEPTH_NUMANODE = -3, /**< \brief Virtual depth for NUMA nodes. \hideinitializer */ + HWLOC_TYPE_DEPTH_BRIDGE = -4, /**< \brief Virtual depth for bridge object level. \hideinitializer */ + HWLOC_TYPE_DEPTH_PCI_DEVICE = -5, /**< \brief Virtual depth for PCI device object level. \hideinitializer */ + HWLOC_TYPE_DEPTH_OS_DEVICE = -6, /**< \brief Virtual depth for software device object level. \hideinitializer */ + HWLOC_TYPE_DEPTH_MISC = -7, /**< \brief Virtual depth for Misc object. \hideinitializer */ + HWLOC_TYPE_DEPTH_MEMCACHE = -8 /**< \brief Virtual depth for MemCache object. \hideinitializer */ +}; + +/** \brief Return the depth of parents where memory objects are attached. + * + * Memory objects have virtual negative depths because they are not part of + * the main CPU-side hierarchy of objects. This depth should not be compared + * with other level depths. + * + * If all Memory objects are attached to Normal parents at the same depth, + * this parent depth may be compared to other as usual, for instance + * for knowing whether NUMA nodes is attached above or below Packages. + * + * \return The depth of Normal parents of all memory children + * if all these parents have the same depth. For instance the depth of + * the Package level if all NUMA nodes are attached to Package objects. + * + * \return ::HWLOC_TYPE_DEPTH_MULTIPLE if Normal parents of all + * memory children do not have the same depth. For instance if some + * NUMA nodes are attached to Packages while others are attached to + * Groups. + */ +HWLOC_DECLSPEC int hwloc_get_memory_parents_depth (hwloc_topology_t topology); + +/** \brief Returns the depth of objects of type \p type or below + * + * If no object of this type is present on the underlying architecture, the + * function returns the depth of the first "present" object typically found + * inside \p type. + * + * This function is only meaningful for normal object types. + * If a memory, I/O or Misc object type is given, the corresponding virtual + * depth is always returned (see hwloc_get_type_depth()). + * + * May return ::HWLOC_TYPE_DEPTH_MULTIPLE for ::HWLOC_OBJ_GROUP just like + * hwloc_get_type_depth(). + */ +static __hwloc_inline int +hwloc_get_type_or_below_depth (hwloc_topology_t topology, hwloc_obj_type_t type) __hwloc_attribute_pure; + +/** \brief Returns the depth of objects of type \p type or above + * + * If no object of this type is present on the underlying architecture, the + * function returns the depth of the first "present" object typically + * containing \p type. + * + * This function is only meaningful for normal object types. + * If a memory, I/O or Misc object type is given, the corresponding virtual + * depth is always returned (see hwloc_get_type_depth()). + * + * May return ::HWLOC_TYPE_DEPTH_MULTIPLE for ::HWLOC_OBJ_GROUP just like + * hwloc_get_type_depth(). + */ +static __hwloc_inline int +hwloc_get_type_or_above_depth (hwloc_topology_t topology, hwloc_obj_type_t type) __hwloc_attribute_pure; + +/** \brief Returns the type of objects at depth \p depth. + * + * \p depth should between 0 and hwloc_topology_get_depth()-1, + * or a virtual depth such as ::HWLOC_TYPE_DEPTH_NUMANODE. + * + * \return (hwloc_obj_type_t)-1 if depth \p depth does not exist. + */ +HWLOC_DECLSPEC hwloc_obj_type_t hwloc_get_depth_type (hwloc_topology_t topology, int depth) __hwloc_attribute_pure; + +/** \brief Returns the width of level at depth \p depth. + */ +HWLOC_DECLSPEC unsigned hwloc_get_nbobjs_by_depth (hwloc_topology_t topology, int depth) __hwloc_attribute_pure; + +/** \brief Returns the width of level type \p type + * + * If no object for that type exists, 0 is returned. + * If there are several levels with objects of that type, -1 is returned. + */ +static __hwloc_inline int +hwloc_get_nbobjs_by_type (hwloc_topology_t topology, hwloc_obj_type_t type) __hwloc_attribute_pure; + +/** \brief Returns the top-object of the topology-tree. + * + * Its type is ::HWLOC_OBJ_MACHINE. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_root_obj (hwloc_topology_t topology) __hwloc_attribute_pure; + +/** \brief Returns the topology object at logical index \p idx from depth \p depth */ +HWLOC_DECLSPEC hwloc_obj_t hwloc_get_obj_by_depth (hwloc_topology_t topology, int depth, unsigned idx) __hwloc_attribute_pure; + +/** \brief Returns the topology object at logical index \p idx with type \p type + * + * If no object for that type exists, \c NULL is returned. + * If there are several levels with objects of that type (::HWLOC_OBJ_GROUP), + * \c NULL is returned and the caller may fallback to hwloc_get_obj_by_depth(). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_by_type (hwloc_topology_t topology, hwloc_obj_type_t type, unsigned idx) __hwloc_attribute_pure; + +/** \brief Returns the next object at depth \p depth. + * + * If \p prev is \c NULL, return the first object at depth \p depth. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_by_depth (hwloc_topology_t topology, int depth, hwloc_obj_t prev); + +/** \brief Returns the next object of type \p type. + * + * If \p prev is \c NULL, return the first object at type \p type. If + * there are multiple or no depth for given type, return \c NULL and + * let the caller fallback to hwloc_get_next_obj_by_depth(). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_by_type (hwloc_topology_t topology, hwloc_obj_type_t type, + hwloc_obj_t prev); + +/** @} */ + + + +/** \defgroup hwlocality_object_strings Converting between Object Types and Attributes, and Strings + * @{ + */ + +/** \brief Return a constant stringified object type. + * + * This function is the basic way to convert a generic type into a string. + * The output string may be parsed back by hwloc_type_sscanf(). + * + * hwloc_obj_type_snprintf() may return a more precise output for a specific + * object, but it requires the caller to provide the output buffer. + */ +HWLOC_DECLSPEC const char * hwloc_obj_type_string (hwloc_obj_type_t type) __hwloc_attribute_const; + +/** \brief Stringify the type of a given topology object into a human-readable form. + * + * Contrary to hwloc_obj_type_string(), this function includes object-specific + * attributes (such as the Group depth, the Bridge type, or OS device type) + * in the output, and it requires the caller to provide the output buffer. + * + * The output is guaranteed to be the same for all objects of a same topology level. + * + * If \p verbose is 1, longer type names are used, e.g. L1Cache instead of L1. + * + * The output string may be parsed back by hwloc_type_sscanf(). + * + * If \p size is 0, \p string may safely be \c NULL. + * + * \return the number of character that were actually written if not truncating, + * or that would have been written (not including the ending \\0). + */ +HWLOC_DECLSPEC int hwloc_obj_type_snprintf(char * __hwloc_restrict string, size_t size, + hwloc_obj_t obj, + int verbose); + +/** \brief Stringify the attributes of a given topology object into a human-readable form. + * + * Attribute values are separated by \p separator. + * + * Only the major attributes are printed in non-verbose mode. + * + * If \p size is 0, \p string may safely be \c NULL. + * + * \return the number of character that were actually written if not truncating, + * or that would have been written (not including the ending \\0). + */ +HWLOC_DECLSPEC int hwloc_obj_attr_snprintf(char * __hwloc_restrict string, size_t size, + hwloc_obj_t obj, const char * __hwloc_restrict separator, + int verbose); + +/** \brief Return an object type and attributes from a type string. + * + * Convert strings such as "Package" or "L1iCache" into the corresponding types. + * Matching is case-insensitive, and only the first letters are actually + * required to match. + * + * The matched object type is set in \p typep (which cannot be \c NULL). + * + * Type-specific attributes, for instance Cache type, Cache depth, Group depth, + * Bridge type or OS Device type may be returned in \p attrp. + * Attributes that are not specified in the string (for instance "Group" + * without a depth, or "L2Cache" without a cache type) are set to -1. + * + * \p attrp is only filled if not \c NULL and if its size specified in \p attrsize + * is large enough. It should be at least as large as union hwloc_obj_attr_u. + * + * \return 0 if a type was correctly identified, otherwise -1. + * + * \note This function is guaranteed to match any string returned by + * hwloc_obj_type_string() or hwloc_obj_type_snprintf(). + * + * \note This is an extended version of the now deprecated hwloc_obj_type_sscanf(). + */ +HWLOC_DECLSPEC int hwloc_type_sscanf(const char *string, + hwloc_obj_type_t *typep, + union hwloc_obj_attr_u *attrp, size_t attrsize); + +/** \brief Return an object type and its level depth from a type string. + * + * Convert strings such as "Package" or "L1iCache" into the corresponding types + * and return in \p depthp the depth of the corresponding level in the + * topology \p topology. + * + * If no object of this type is present on the underlying architecture, + * ::HWLOC_TYPE_DEPTH_UNKNOWN is returned. + * + * If multiple such levels exist (for instance if giving Group without any depth), + * the function may return ::HWLOC_TYPE_DEPTH_MULTIPLE instead. + * + * The matched object type is set in \p typep if \p typep is non \c NULL. + * + * \note This function is similar to hwloc_type_sscanf() followed + * by hwloc_get_type_depth() but it also automatically disambiguates + * multiple group levels etc. + * + * \note This function is guaranteed to match any string returned by + * hwloc_obj_type_string() or hwloc_obj_type_snprintf(). + */ +HWLOC_DECLSPEC int hwloc_type_sscanf_as_depth(const char *string, + hwloc_obj_type_t *typep, + hwloc_topology_t topology, int *depthp); + +/** @} */ + + + +/** \defgroup hwlocality_info_attr Consulting and Adding Key-Value Info Attributes + * + * @{ + */ + +/** \brief Search the given key name in object infos and return the corresponding value. + * + * If multiple keys match the given name, only the first one is returned. + * + * \return \c NULL if no such key exists. + */ +static __hwloc_inline const char * +hwloc_obj_get_info_by_name(hwloc_obj_t obj, const char *name) __hwloc_attribute_pure; + +/** \brief Add the given info name and value pair to the given object. + * + * The info is appended to the existing info array even if another key + * with the same name already exists. + * + * The input strings are copied before being added in the object infos. + * + * \return \c 0 on success, \c -1 on error. + * + * \note This function may be used to enforce object colors in the lstopo + * graphical output by using "lstopoStyle" as a name and "Background=#rrggbb" + * as a value. See CUSTOM COLORS in the lstopo(1) manpage for details. + * + * \note If \p value contains some non-printable characters, they will + * be dropped when exporting to XML, see hwloc_topology_export_xml() in hwloc/export.h. + */ +HWLOC_DECLSPEC int hwloc_obj_add_info(hwloc_obj_t obj, const char *name, const char *value); + +/** @} */ + + + +/** \defgroup hwlocality_cpubinding CPU binding + * + * Some operating systems only support binding threads or processes to a single PU. + * Others allow binding to larger sets such as entire Cores or Packages or + * even random sets of individual PUs. In such operating system, the scheduler + * is free to run the task on one of these PU, then migrate it to another PU, etc. + * It is often useful to call hwloc_bitmap_singlify() on the target CPU set before + * passing it to the binding function to avoid these expensive migrations. + * See the documentation of hwloc_bitmap_singlify() for details. + * + * Some operating systems do not provide all hwloc-supported + * mechanisms to bind processes, threads, etc. + * hwloc_topology_get_support() may be used to query about the actual CPU + * binding support in the currently used operating system. + * + * When the requested binding operation is not available and the + * ::HWLOC_CPUBIND_STRICT flag was passed, the function returns -1. + * \p errno is set to \c ENOSYS when it is not possible to bind the requested kind of object + * processes/threads. errno is set to \c EXDEV when the requested cpuset + * can not be enforced (e.g. some systems only allow one CPU, and some + * other systems only allow one NUMA node). + * + * If ::HWLOC_CPUBIND_STRICT was not passed, the function may fail as well, + * or the operating system may use a slightly different operation + * (with side-effects, smaller binding set, etc.) + * when the requested operation is not exactly supported. + * + * The most portable version that should be preferred over the others, + * whenever possible, is the following one which just binds the current program, + * assuming it is single-threaded: + * + * \code + * hwloc_set_cpubind(topology, set, 0), + * \endcode + * + * If the program may be multithreaded, the following one should be preferred + * to only bind the current thread: + * + * \code + * hwloc_set_cpubind(topology, set, HWLOC_CPUBIND_THREAD), + * \endcode + * + * \sa Some example codes are available under doc/examples/ in the source tree. + * + * \note To unbind, just call the binding function with either a full cpuset or + * a cpuset equal to the system cpuset. + * + * \note On some operating systems, CPU binding may have effects on memory binding, see + * ::HWLOC_CPUBIND_NOMEMBIND + * + * \note Running lstopo \--top or hwloc-ps can be a very convenient tool to check + * how binding actually happened. + * @{ + */ + +/** \brief Process/Thread binding flags. + * + * These bit flags can be used to refine the binding policy. + * + * The default (0) is to bind the current process, assumed to be + * single-threaded, in a non-strict way. This is the most portable + * way to bind as all operating systems usually provide it. + * + * \note Not all systems support all kinds of binding. See the + * "Detailed Description" section of \ref hwlocality_cpubinding for a + * description of errors that can occur. + */ +typedef enum { + /** \brief Bind all threads of the current (possibly) multithreaded process. + * \hideinitializer */ + HWLOC_CPUBIND_PROCESS = (1<<0), + + /** \brief Bind current thread of current process. + * \hideinitializer */ + HWLOC_CPUBIND_THREAD = (1<<1), + + /** \brief Request for strict binding from the OS. + * + * By default, when the designated CPUs are all busy while other + * CPUs are idle, operating systems may execute the thread/process + * on those other CPUs instead of the designated CPUs, to let them + * progress anyway. Strict binding means that the thread/process + * will _never_ execute on other CPUs than the designated CPUs, even + * when those are busy with other tasks and other CPUs are idle. + * + * \note Depending on the operating system, strict binding may not + * be possible (e.g., the OS does not implement it) or not allowed + * (e.g., for an administrative reasons), and the function will fail + * in that case. + * + * When retrieving the binding of a process, this flag checks + * whether all its threads actually have the same binding. If the + * flag is not given, the binding of each thread will be + * accumulated. + * + * \note This flag is meaningless when retrieving the binding of a + * thread. + * \hideinitializer + */ + HWLOC_CPUBIND_STRICT = (1<<2), + + /** \brief Avoid any effect on memory binding + * + * On some operating systems, some CPU binding function would also + * bind the memory on the corresponding NUMA node. It is often not + * a problem for the application, but if it is, setting this flag + * will make hwloc avoid using OS functions that would also bind + * memory. This will however reduce the support of CPU bindings, + * i.e. potentially return -1 with errno set to ENOSYS in some + * cases. + * + * This flag is only meaningful when used with functions that set + * the CPU binding. It is ignored when used with functions that get + * CPU binding information. + * \hideinitializer + */ + HWLOC_CPUBIND_NOMEMBIND = (1<<3) +} hwloc_cpubind_flags_t; + +/** \brief Bind current process or thread on CPUs given in physical bitmap \p set. + * + * \return -1 with errno set to ENOSYS if the action is not supported + * \return -1 with errno set to EXDEV if the binding cannot be enforced + */ +HWLOC_DECLSPEC int hwloc_set_cpubind(hwloc_topology_t topology, hwloc_const_cpuset_t set, int flags); + +/** \brief Get current process or thread binding. + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the list of PUs which the process or + * thread (according to \e flags) was last bound to. + */ +HWLOC_DECLSPEC int hwloc_get_cpubind(hwloc_topology_t topology, hwloc_cpuset_t set, int flags); + +/** \brief Bind a process \p pid on CPUs given in physical bitmap \p set. + * + * \note \p hwloc_pid_t is \p pid_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + * + * \note As a special case on Linux, if a tid (thread ID) is supplied + * instead of a pid (process ID) and ::HWLOC_CPUBIND_THREAD is passed in flags, + * the binding is applied to that specific thread. + * + * \note On non-Linux systems, ::HWLOC_CPUBIND_THREAD can not be used in \p flags. + */ +HWLOC_DECLSPEC int hwloc_set_proc_cpubind(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_const_cpuset_t set, int flags); + +/** \brief Get the current physical binding of process \p pid. + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the list of PUs which the process + * was last bound to. + * + * \note \p hwloc_pid_t is \p pid_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + * + * \note As a special case on Linux, if a tid (thread ID) is supplied + * instead of a pid (process ID) and HWLOC_CPUBIND_THREAD is passed in flags, + * the binding for that specific thread is returned. + * + * \note On non-Linux systems, HWLOC_CPUBIND_THREAD can not be used in \p flags. + */ +HWLOC_DECLSPEC int hwloc_get_proc_cpubind(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_cpuset_t set, int flags); + +#ifdef hwloc_thread_t +/** \brief Bind a thread \p thread on CPUs given in physical bitmap \p set. + * + * \note \p hwloc_thread_t is \p pthread_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + * + * \note ::HWLOC_CPUBIND_PROCESS can not be used in \p flags. + */ +HWLOC_DECLSPEC int hwloc_set_thread_cpubind(hwloc_topology_t topology, hwloc_thread_t thread, hwloc_const_cpuset_t set, int flags); +#endif + +#ifdef hwloc_thread_t +/** \brief Get the current physical binding of thread \p tid. + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the list of PUs which the thread + * was last bound to. + * + * \note \p hwloc_thread_t is \p pthread_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + * + * \note ::HWLOC_CPUBIND_PROCESS can not be used in \p flags. + */ +HWLOC_DECLSPEC int hwloc_get_thread_cpubind(hwloc_topology_t topology, hwloc_thread_t thread, hwloc_cpuset_t set, int flags); +#endif + +/** \brief Get the last physical CPU where the current process or thread ran. + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the list of PUs which the process or + * thread (according to \e flags) last ran on. + * + * The operating system may move some tasks from one processor + * to another at any time according to their binding, + * so this function may return something that is already + * outdated. + * + * \p flags can include either ::HWLOC_CPUBIND_PROCESS or ::HWLOC_CPUBIND_THREAD to + * specify whether the query should be for the whole process (union of all CPUs + * on which all threads are running), or only the current thread. If the + * process is single-threaded, flags can be set to zero to let hwloc use + * whichever method is available on the underlying OS. + */ +HWLOC_DECLSPEC int hwloc_get_last_cpu_location(hwloc_topology_t topology, hwloc_cpuset_t set, int flags); + +/** \brief Get the last physical CPU where a process ran. + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the list of PUs which the process + * last ran on. + * + * The operating system may move some tasks from one processor + * to another at any time according to their binding, + * so this function may return something that is already + * outdated. + * + * \note \p hwloc_pid_t is \p pid_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + * + * \note As a special case on Linux, if a tid (thread ID) is supplied + * instead of a pid (process ID) and ::HWLOC_CPUBIND_THREAD is passed in flags, + * the last CPU location of that specific thread is returned. + * + * \note On non-Linux systems, ::HWLOC_CPUBIND_THREAD can not be used in \p flags. + */ +HWLOC_DECLSPEC int hwloc_get_proc_last_cpu_location(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_cpuset_t set, int flags); + +/** @} */ + + + +/** \defgroup hwlocality_membinding Memory binding + * + * Memory binding can be done three ways: + * + * - explicit memory allocation thanks to hwloc_alloc_membind() and friends: + * the binding will have effect on the memory allocated by these functions. + * - implicit memory binding through binding policy: hwloc_set_membind() and + * friends only define the current policy of the process, which will be + * applied to the subsequent calls to malloc() and friends. + * - migration of existing memory ranges, thanks to hwloc_set_area_membind() + * and friends, which move already-allocated data. + * + * Not all operating systems support all three ways. + * hwloc_topology_get_support() may be used to query about the actual memory + * binding support in the currently used operating system. + * + * When the requested binding operation is not available and the + * ::HWLOC_MEMBIND_STRICT flag was passed, the function returns -1. + * \p errno will be set to \c ENOSYS when the system does support + * the specified action or policy + * (e.g., some systems only allow binding memory on a per-thread + * basis, whereas other systems only allow binding memory for all + * threads in a process). + * \p errno will be set to EXDEV when the requested set can not be enforced + * (e.g., some systems only allow binding memory to a single NUMA node). + * + * If ::HWLOC_MEMBIND_STRICT was not passed, the function may fail as well, + * or the operating system may use a slightly different operation + * (with side-effects, smaller binding set, etc.) + * when the requested operation is not exactly supported. + * + * The most portable form that should be preferred over the others + * whenever possible is as follows. + * It allocates some memory hopefully bound to the specified set. + * To do so, hwloc will possibly have to change the current memory + * binding policy in order to actually get the memory bound, if the OS + * does not provide any other way to simply allocate bound memory + * without changing the policy for all allocations. That is the + * difference with hwloc_alloc_membind(), which will never change the + * current memory binding policy. + * + * \code + * hwloc_alloc_membind_policy(topology, size, set, + * HWLOC_MEMBIND_BIND, 0); + * \endcode + * + * Each hwloc memory binding function takes a bitmap argument that + * is a CPU set by default, or a NUMA memory node set if the flag + * ::HWLOC_MEMBIND_BYNODESET is specified. + * See \ref hwlocality_object_sets and \ref hwlocality_bitmap for a + * discussion of CPU sets and NUMA memory node sets. + * It is also possible to convert between CPU set and node set using + * hwloc_cpuset_to_nodeset() or hwloc_cpuset_from_nodeset(). + * + * Memory binding by CPU set cannot work for CPU-less NUMA memory nodes. + * Binding by nodeset should therefore be preferred whenever possible. + * + * \sa Some example codes are available under doc/examples/ in the source tree. + * + * \note On some operating systems, memory binding affects the CPU + * binding; see ::HWLOC_MEMBIND_NOCPUBIND + * @{ + */ + +/** \brief Memory binding policy. + * + * These constants can be used to choose the binding policy. Only one policy can + * be used at a time (i.e., the values cannot be OR'ed together). + * + * Not all systems support all kinds of binding. + * hwloc_topology_get_support() may be used to query about the actual memory + * binding policy support in the currently used operating system. + * See the "Detailed Description" section of \ref hwlocality_membinding + * for a description of errors that can occur. + */ +typedef enum { + /** \brief Reset the memory allocation policy to the system default. + * Depending on the operating system, this may correspond to + * ::HWLOC_MEMBIND_FIRSTTOUCH (Linux, FreeBSD), + * or ::HWLOC_MEMBIND_BIND (AIX, HP-UX, Solaris, Windows). + * This policy is never returned by get membind functions. + * The nodeset argument is ignored. + * \hideinitializer */ + HWLOC_MEMBIND_DEFAULT = 0, + + /** \brief Allocate each memory page individually on the local NUMA + * node of the thread that touches it. + * + * The given nodeset should usually be hwloc_topology_get_topology_nodeset() + * so that the touching thread may run and allocate on any node in the system. + * + * On AIX, if the nodeset is smaller, pages are allocated locally (if the local + * node is in the nodeset) or from a random non-local node (otherwise). + * \hideinitializer */ + HWLOC_MEMBIND_FIRSTTOUCH = 1, + + /** \brief Allocate memory on the specified nodes. + * \hideinitializer */ + HWLOC_MEMBIND_BIND = 2, + + /** \brief Allocate memory on the given nodes in an interleaved + * / round-robin manner. The precise layout of the memory across + * multiple NUMA nodes is OS/system specific. Interleaving can be + * useful when threads distributed across the specified NUMA nodes + * will all be accessing the whole memory range concurrently, since + * the interleave will then balance the memory references. + * \hideinitializer */ + HWLOC_MEMBIND_INTERLEAVE = 3, + + /** \brief For each page bound with this policy, by next time + * it is touched (and next time only), it is moved from its current + * location to the local NUMA node of the thread where the memory + * reference occurred (if it needs to be moved at all). + * \hideinitializer */ + HWLOC_MEMBIND_NEXTTOUCH = 4, + + /** \brief Returned by get_membind() functions when multiple + * threads or parts of a memory area have differing memory binding + * policies. + * Also returned when binding is unknown because binding hooks are empty + * when the topology is loaded from XML without HWLOC_THISSYSTEM=1, etc. + * \hideinitializer */ + HWLOC_MEMBIND_MIXED = -1 +} hwloc_membind_policy_t; + +/** \brief Memory binding flags. + * + * These flags can be used to refine the binding policy. + * All flags can be logically OR'ed together with the exception of + * ::HWLOC_MEMBIND_PROCESS and ::HWLOC_MEMBIND_THREAD; + * these two flags are mutually exclusive. + * + * Not all systems support all kinds of binding. + * hwloc_topology_get_support() may be used to query about the actual memory + * binding support in the currently used operating system. + * See the "Detailed Description" section of \ref hwlocality_membinding + * for a description of errors that can occur. + */ +typedef enum { + /** \brief Set policy for all threads of the specified (possibly + * multithreaded) process. This flag is mutually exclusive with + * ::HWLOC_MEMBIND_THREAD. + * \hideinitializer */ + HWLOC_MEMBIND_PROCESS = (1<<0), + + /** \brief Set policy for a specific thread of the current process. + * This flag is mutually exclusive with ::HWLOC_MEMBIND_PROCESS. + * \hideinitializer */ + HWLOC_MEMBIND_THREAD = (1<<1), + + /** Request strict binding from the OS. The function will fail if + * the binding can not be guaranteed / completely enforced. + * + * This flag has slightly different meanings depending on which + * function it is used with. + * \hideinitializer */ + HWLOC_MEMBIND_STRICT = (1<<2), + + /** \brief Migrate existing allocated memory. If the memory cannot + * be migrated and the ::HWLOC_MEMBIND_STRICT flag is passed, an error + * will be returned. + * \hideinitializer */ + HWLOC_MEMBIND_MIGRATE = (1<<3), + + /** \brief Avoid any effect on CPU binding. + * + * On some operating systems, some underlying memory binding + * functions also bind the application to the corresponding CPU(s). + * Using this flag will cause hwloc to avoid using OS functions that + * could potentially affect CPU bindings. Note, however, that using + * NOCPUBIND may reduce hwloc's overall memory binding + * support. Specifically: some of hwloc's memory binding functions + * may fail with errno set to ENOSYS when used with NOCPUBIND. + * \hideinitializer + */ + HWLOC_MEMBIND_NOCPUBIND = (1<<4), + + /** \brief Consider the bitmap argument as a nodeset. + * + * The bitmap argument is considered a nodeset if this flag is given, + * or a cpuset otherwise by default. + * + * Memory binding by CPU set cannot work for CPU-less NUMA memory nodes. + * Binding by nodeset should therefore be preferred whenever possible. + * \hideinitializer + */ + HWLOC_MEMBIND_BYNODESET = (1<<5) +} hwloc_membind_flags_t; + +/** \brief Set the default memory binding policy of the current + * process or thread to prefer the NUMA node(s) specified by \p set + * + * If neither ::HWLOC_MEMBIND_PROCESS nor ::HWLOC_MEMBIND_THREAD is + * specified, the current process is assumed to be single-threaded. + * This is the most portable form as it permits hwloc to use either + * process-based OS functions or thread-based OS functions, depending + * on which are available. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * \return -1 with errno set to ENOSYS if the action is not supported + * \return -1 with errno set to EXDEV if the binding cannot be enforced + */ +HWLOC_DECLSPEC int hwloc_set_membind(hwloc_topology_t topology, hwloc_const_bitmap_t set, hwloc_membind_policy_t policy, int flags); + +/** \brief Query the default memory binding policy and physical locality of the + * current process or thread. + * + * The bitmap \p set (previously allocated by the caller) + * is filled with the process or thread memory binding. + * + * This function has two output parameters: \p set and \p policy. + * The values returned in these parameters depend on both the \p flags + * passed in and the current memory binding policies and nodesets in + * the queried target. + * + * Passing the ::HWLOC_MEMBIND_PROCESS flag specifies that the query + * target is the current policies and nodesets for all the threads in + * the current process. Passing ::HWLOC_MEMBIND_THREAD specifies that + * the query target is the current policy and nodeset for only the + * thread invoking this function. + * + * If neither of these flags are passed (which is the most portable + * method), the process is assumed to be single threaded. This allows + * hwloc to use either process-based OS functions or thread-based OS + * functions, depending on which are available. + * + * ::HWLOC_MEMBIND_STRICT is only meaningful when ::HWLOC_MEMBIND_PROCESS + * is also specified. In this case, hwloc will check the default + * memory policies and nodesets for all threads in the process. If + * they are not identical, -1 is returned and errno is set to EXDEV. + * If they are identical, the values are returned in \p set and \p + * policy. + * + * Otherwise, if ::HWLOC_MEMBIND_PROCESS is specified (and + * ::HWLOC_MEMBIND_STRICT is \em not specified), the default set + * from each thread is logically OR'ed together. + * If all threads' default policies are the same, \p policy is set to + * that policy. If they are different, \p policy is set to + * ::HWLOC_MEMBIND_MIXED. + * + * In the ::HWLOC_MEMBIND_THREAD case (or when neither + * ::HWLOC_MEMBIND_PROCESS or ::HWLOC_MEMBIND_THREAD is specified), there + * is only one set and policy; they are returned in \p set and + * \p policy, respectively. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * If any other flags are specified, -1 is returned and errno is set + * to EINVAL. + */ +HWLOC_DECLSPEC int hwloc_get_membind(hwloc_topology_t topology, hwloc_bitmap_t set, hwloc_membind_policy_t * policy, int flags); + +/** \brief Set the default memory binding policy of the specified + * process to prefer the NUMA node(s) specified by \p set + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * \return -1 with errno set to ENOSYS if the action is not supported + * \return -1 with errno set to EXDEV if the binding cannot be enforced + * + * \note \p hwloc_pid_t is \p pid_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + */ +HWLOC_DECLSPEC int hwloc_set_proc_membind(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_const_bitmap_t set, hwloc_membind_policy_t policy, int flags); + +/** \brief Query the default memory binding policy and physical locality of the + * specified process. + * + * The bitmap \p set (previously allocated by the caller) + * is filled with the process memory binding. + * + * This function has two output parameters: \p set and \p policy. + * The values returned in these parameters depend on both the \p flags + * passed in and the current memory binding policies and nodesets in + * the queried target. + * + * Passing the ::HWLOC_MEMBIND_PROCESS flag specifies that the query + * target is the current policies and nodesets for all the threads in + * the specified process. If ::HWLOC_MEMBIND_PROCESS is not specified + * (which is the most portable method), the process is assumed to be + * single threaded. This allows hwloc to use either process-based OS + * functions or thread-based OS functions, depending on which are + * available. + * + * Note that it does not make sense to pass ::HWLOC_MEMBIND_THREAD to + * this function. + * + * If ::HWLOC_MEMBIND_STRICT is specified, hwloc will check the default + * memory policies and nodesets for all threads in the specified + * process. If they are not identical, -1 is returned and errno is + * set to EXDEV. If they are identical, the values are returned in \p + * set and \p policy. + * + * Otherwise, \p set is set to the logical OR of all threads' + * default set. If all threads' default policies + * are the same, \p policy is set to that policy. If they are + * different, \p policy is set to ::HWLOC_MEMBIND_MIXED. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * If any other flags are specified, -1 is returned and errno is set + * to EINVAL. + * + * \note \p hwloc_pid_t is \p pid_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + */ +HWLOC_DECLSPEC int hwloc_get_proc_membind(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_bitmap_t set, hwloc_membind_policy_t * policy, int flags); + +/** \brief Bind the already-allocated memory identified by (addr, len) + * to the NUMA node(s) specified by \p set. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * \return 0 if \p len is 0. + * \return -1 with errno set to ENOSYS if the action is not supported + * \return -1 with errno set to EXDEV if the binding cannot be enforced + */ +HWLOC_DECLSPEC int hwloc_set_area_membind(hwloc_topology_t topology, const void *addr, size_t len, hwloc_const_bitmap_t set, hwloc_membind_policy_t policy, int flags); + +/** \brief Query the CPUs near the physical NUMA node(s) and binding policy of + * the memory identified by (\p addr, \p len ). + * + * The bitmap \p set (previously allocated by the caller) + * is filled with the memory area binding. + * + * This function has two output parameters: \p set and \p policy. + * The values returned in these parameters depend on both the \p flags + * passed in and the memory binding policies and nodesets of the pages + * in the address range. + * + * If ::HWLOC_MEMBIND_STRICT is specified, the target pages are first + * checked to see if they all have the same memory binding policy and + * nodeset. If they do not, -1 is returned and errno is set to EXDEV. + * If they are identical across all pages, the set and policy are + * returned in \p set and \p policy, respectively. + * + * If ::HWLOC_MEMBIND_STRICT is not specified, the union of all NUMA + * node(s) containing pages in the address range is calculated. + * If all pages in the target have the same policy, it is returned in + * \p policy. Otherwise, \p policy is set to ::HWLOC_MEMBIND_MIXED. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * If any other flags are specified, -1 is returned and errno is set + * to EINVAL. + * + * If \p len is 0, -1 is returned and errno is set to EINVAL. + */ +HWLOC_DECLSPEC int hwloc_get_area_membind(hwloc_topology_t topology, const void *addr, size_t len, hwloc_bitmap_t set, hwloc_membind_policy_t * policy, int flags); + +/** \brief Get the NUMA nodes where memory identified by (\p addr, \p len ) is physically allocated. + * + * The bitmap \p set (previously allocated by the caller) + * is filled according to the NUMA nodes where the memory area pages + * are physically allocated. If no page is actually allocated yet, + * \p set may be empty. + * + * If pages spread to multiple nodes, it is not specified whether they spread + * equitably, or whether most of them are on a single node, etc. + * + * The operating system may move memory pages from one processor + * to another at any time according to their binding, + * so this function may return something that is already + * outdated. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified in \p flags, set is + * considered a nodeset. Otherwise it's a cpuset. + * + * If \p len is 0, \p set is emptied. + */ +HWLOC_DECLSPEC int hwloc_get_area_memlocation(hwloc_topology_t topology, const void *addr, size_t len, hwloc_bitmap_t set, int flags); + +/** \brief Allocate some memory + * + * This is equivalent to malloc(), except that it tries to allocate + * page-aligned memory from the OS. + * + * \note The allocated memory should be freed with hwloc_free(). + */ +HWLOC_DECLSPEC void *hwloc_alloc(hwloc_topology_t topology, size_t len); + +/** \brief Allocate some memory on NUMA memory nodes specified by \p set + * + * \return NULL with errno set to ENOSYS if the action is not supported + * and ::HWLOC_MEMBIND_STRICT is given + * \return NULL with errno set to EXDEV if the binding cannot be enforced + * and ::HWLOC_MEMBIND_STRICT is given + * \return NULL with errno set to ENOMEM if the memory allocation failed + * even before trying to bind. + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + * + * \note The allocated memory should be freed with hwloc_free(). + */ +HWLOC_DECLSPEC void *hwloc_alloc_membind(hwloc_topology_t topology, size_t len, hwloc_const_bitmap_t set, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_malloc; + +/** \brief Allocate some memory on NUMA memory nodes specified by \p set + * + * First, try to allocate properly with hwloc_alloc_membind(). + * On failure, the current process or thread memory binding policy + * is changed with hwloc_set_membind() before allocating memory. + * Thus this function works in more cases, at the expense of changing + * the current state (possibly affecting future allocations that + * would not specify any policy). + * + * If ::HWLOC_MEMBIND_BYNODESET is specified, set is considered a nodeset. + * Otherwise it's a cpuset. + */ +static __hwloc_inline void * +hwloc_alloc_membind_policy(hwloc_topology_t topology, size_t len, hwloc_const_bitmap_t set, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_malloc; + +/** \brief Free memory that was previously allocated by hwloc_alloc() + * or hwloc_alloc_membind(). + */ +HWLOC_DECLSPEC int hwloc_free(hwloc_topology_t topology, void *addr, size_t len); + +/** @} */ + + + +/** \defgroup hwlocality_setsource Changing the Source of Topology Discovery + * + * If none of the functions below is called, the default is to detect all the objects + * of the machine that the caller is allowed to access. + * + * This default behavior may also be modified through environment variables + * if the application did not modify it already. + * Setting HWLOC_XMLFILE in the environment enforces the discovery from a XML + * file as if hwloc_topology_set_xml() had been called. + * Setting HWLOC_SYNTHETIC enforces a synthetic topology as if + * hwloc_topology_set_synthetic() had been called. + * + * Finally, HWLOC_THISSYSTEM enforces the return value of + * hwloc_topology_is_thissystem(). + * + * @{ + */ + +/** \brief Change which process the topology is viewed from. + * + * On some systems, processes may have different views of the machine, for + * instance the set of allowed CPUs. By default, hwloc exposes the view from + * the current process. Calling hwloc_topology_set_pid() permits to make it + * expose the topology of the machine from the point of view of another + * process. + * + * \note \p hwloc_pid_t is \p pid_t on Unix platforms, + * and \p HANDLE on native Windows platforms. + * + * \note -1 is returned and errno is set to ENOSYS on platforms that do not + * support this feature. + */ +HWLOC_DECLSPEC int hwloc_topology_set_pid(hwloc_topology_t __hwloc_restrict topology, hwloc_pid_t pid); + +/** \brief Enable synthetic topology. + * + * Gather topology information from the given \p description, + * a space-separated string of describing + * the object type and arity at each level. + * All types may be omitted (space-separated string of numbers) so that + * hwloc chooses all types according to usual topologies. + * See also the \ref synthetic. + * + * Setting the environment variable HWLOC_SYNTHETIC + * may also result in this behavior. + * + * If \p description was properly parsed and describes a valid topology + * configuration, this function returns 0. + * Otherwise -1 is returned and errno is set to EINVAL. + * + * Note that this function does not actually load topology + * information; it just tells hwloc where to load it from. You'll + * still need to invoke hwloc_topology_load() to actually load the + * topology information. + * + * \note For convenience, this backend provides empty binding hooks which just + * return success. + * + * \note On success, the synthetic component replaces the previously enabled + * component (if any), but the topology is not actually modified until + * hwloc_topology_load(). + */ +HWLOC_DECLSPEC int hwloc_topology_set_synthetic(hwloc_topology_t __hwloc_restrict topology, const char * __hwloc_restrict description); + +/** \brief Enable XML-file based topology. + * + * Gather topology information from the XML file given at \p xmlpath. + * Setting the environment variable HWLOC_XMLFILE may also result in this behavior. + * This file may have been generated earlier with hwloc_topology_export_xml() in hwloc/export.h, + * or lstopo file.xml. + * + * Note that this function does not actually load topology + * information; it just tells hwloc where to load it from. You'll + * still need to invoke hwloc_topology_load() to actually load the + * topology information. + * + * \return -1 with errno set to EINVAL on failure to read the XML file. + * + * \note See also hwloc_topology_set_userdata_import_callback() + * for importing application-specific object userdata. + * + * \note For convenience, this backend provides empty binding hooks which just + * return success. To have hwloc still actually call OS-specific hooks, the + * ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM has to be set to assert that the loaded + * file is really the underlying system. + * + * \note On success, the XML component replaces the previously enabled + * component (if any), but the topology is not actually modified until + * hwloc_topology_load(). + */ +HWLOC_DECLSPEC int hwloc_topology_set_xml(hwloc_topology_t __hwloc_restrict topology, const char * __hwloc_restrict xmlpath); + +/** \brief Enable XML based topology using a memory buffer (instead of + * a file, as with hwloc_topology_set_xml()). + * + * Gather topology information from the XML memory buffer given at \p + * buffer and of length \p size. This buffer may have been filled + * earlier with hwloc_topology_export_xmlbuffer() in hwloc/export.h. + * + * Note that this function does not actually load topology + * information; it just tells hwloc where to load it from. You'll + * still need to invoke hwloc_topology_load() to actually load the + * topology information. + * + * \return -1 with errno set to EINVAL on failure to read the XML buffer. + * + * \note See also hwloc_topology_set_userdata_import_callback() + * for importing application-specific object userdata. + * + * \note For convenience, this backend provides empty binding hooks which just + * return success. To have hwloc still actually call OS-specific hooks, the + * ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM has to be set to assert that the loaded + * file is really the underlying system. + * + * \note On success, the XML component replaces the previously enabled + * component (if any), but the topology is not actually modified until + * hwloc_topology_load(). + */ +HWLOC_DECLSPEC int hwloc_topology_set_xmlbuffer(hwloc_topology_t __hwloc_restrict topology, const char * __hwloc_restrict buffer, int size); + +/** \brief Flags to be passed to hwloc_topology_set_components() + */ +enum hwloc_topology_components_flag_e { + /** \brief Blacklist the target component from being used. + * \hideinitializer + */ + HWLOC_TOPOLOGY_COMPONENTS_FLAG_BLACKLIST = (1UL<<0) +}; + +/** \brief Prevent a discovery component from being used for a topology. + * + * \p name is the name of the discovery component that should not be used + * when loading topology \p topology. The name is a string such as "cuda". + * + * For components with multiple phases, it may also be suffixed with the name + * of a phase, for instance "linux:io". + * + * \p flags should be ::HWLOC_TOPOLOGY_COMPONENTS_FLAG_BLACKLIST. + * + * This may be used to avoid expensive parts of the discovery process. + * For instance, CUDA-specific discovery may be expensive and unneeded + * while generic I/O discovery could still be useful. + */ +HWLOC_DECLSPEC int hwloc_topology_set_components(hwloc_topology_t __hwloc_restrict topology, unsigned long flags, const char * __hwloc_restrict name); + +/** @} */ + + + +/** \defgroup hwlocality_configuration Topology Detection Configuration and Query + * + * Several functions can optionally be called between hwloc_topology_init() and + * hwloc_topology_load() to configure how the detection should be performed, + * e.g. to ignore some objects types, define a synthetic topology, etc. + * + * @{ + */ + +/** \brief Flags to be set onto a topology context before load. + * + * Flags should be given to hwloc_topology_set_flags(). + * They may also be returned by hwloc_topology_get_flags(). + */ +enum hwloc_topology_flags_e { + /** \brief Detect the whole system, ignore reservations, include disallowed objects. + * + * Gather all online resources, even if some were disabled by the administrator. + * For instance, ignore Linux Cgroup/Cpusets and gather all processors and memory nodes. + * However offline PUs and NUMA nodes are still ignored. + * + * When this flag is not set, PUs and NUMA nodes that are disallowed are not added to the topology. + * Parent objects (package, core, cache, etc.) are added only if some of their children are allowed. + * All existing PUs and NUMA nodes in the topology are allowed. + * hwloc_topology_get_allowed_cpuset() and hwloc_topology_get_allowed_nodeset() + * are equal to the root object cpuset and nodeset. + * + * When this flag is set, the actual sets of allowed PUs and NUMA nodes are given + * by hwloc_topology_get_allowed_cpuset() and hwloc_topology_get_allowed_nodeset(). + * They may be smaller than the root object cpuset and nodeset. + * + * If the current topology is exported to XML and reimported later, this flag + * should be set again in the reimported topology so that disallowed resources + * are reimported as well. + * \hideinitializer + */ + HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED = (1UL<<0), + + /** \brief Assume that the selected backend provides the topology for the + * system on which we are running. + * + * This forces hwloc_topology_is_thissystem() to return 1, i.e. makes hwloc assume that + * the selected backend provides the topology for the system on which we are running, + * even if it is not the OS-specific backend but the XML backend for instance. + * This means making the binding functions actually call the OS-specific + * system calls and really do binding, while the XML backend would otherwise + * provide empty hooks just returning success. + * + * Setting the environment variable HWLOC_THISSYSTEM may also result in the + * same behavior. + * + * This can be used for efficiency reasons to first detect the topology once, + * save it to an XML file, and quickly reload it later through the XML + * backend, but still having binding functions actually do bind. + * \hideinitializer + */ + HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM = (1UL<<1), + + /** \brief Get the set of allowed resources from the local operating system even if the topology was loaded from XML or synthetic description. + * + * If the topology was loaded from XML or from a synthetic string, + * restrict it by applying the current process restrictions such as + * Linux Cgroup/Cpuset. + * + * This is useful when the topology is not loaded directly from + * the local machine (e.g. for performance reason) and it comes + * with all resources, while the running process is restricted + * to only parts of the machine. + * + * This flag is ignored unless ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM is + * also set since the loaded topology must match the underlying machine + * where restrictions will be gathered from. + * + * Setting the environment variable HWLOC_THISSYSTEM_ALLOWED_RESOURCES + * would result in the same behavior. + * \hideinitializer + */ + HWLOC_TOPOLOGY_FLAG_THISSYSTEM_ALLOWED_RESOURCES = (1UL<<2), + + /** \brief Import support from the imported topology. + * + * When importing a XML topology from a remote machine, binding is + * disabled by default (see ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM). + * This disabling is also marked by putting zeroes in the corresponding + * supported feature bits reported by hwloc_topology_get_support(). + * + * The flag ::HWLOC_TOPOLOGY_FLAG_IMPORT_SUPPORT actually imports + * support bits from the remote machine. It also sets the flag + * \p imported_support in the struct hwloc_topology_misc_support array. + * If the imported XML did not contain any support information + * (exporter hwloc is too old), this flag is not set. + * + * Note that these supported features are only relevant for the hwloc + * installation that actually exported the XML topology + * (it may vary with the operating system, or with how hwloc was compiled). + * + * Note that setting this flag however does not enable binding for the + * locally imported hwloc topology, it only reports what the remote + * hwloc and machine support. + * + */ + HWLOC_TOPOLOGY_FLAG_IMPORT_SUPPORT = (1UL<<3), + + /** \brief Do not consider resources outside of the process CPU binding. + * + * If the binding of the process is limited to a subset of cores, + * ignore the other cores during discovery. + * + * The resulting topology is identical to what a call to hwloc_topology_restrict() + * would generate, but this flag also prevents hwloc from ever touching other + * resources during the discovery. + * + * This flag especially tells the x86 backend to never temporarily + * rebind a thread on any excluded core. This is useful on Windows + * because such temporary rebinding can change the process binding. + * Another use-case is to avoid cores that would not be able to + * perform the hwloc discovery anytime soon because they are busy + * executing some high-priority real-time tasks. + * + * If process CPU binding is not supported, + * the thread CPU binding is considered instead if supported, + * or the flag is ignored. + * + * This flag requires ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM as well + * since binding support is required. + */ + HWLOC_TOPOLOGY_FLAG_RESTRICT_TO_CPUBINDING = (1UL<<4), + + /** \brief Do not consider resources outside of the process memory binding. + * + * If the binding of the process is limited to a subset of NUMA nodes, + * ignore the other NUMA nodes during discovery. + * + * The resulting topology is identical to what a call to hwloc_topology_restrict() + * would generate, but this flag also prevents hwloc from ever touching other + * resources during the discovery. + * + * This flag is meant to be used together with + * ::HWLOC_TOPOLOGY_FLAG_RESTRICT_TO_CPUBINDING when both cores + * and NUMA nodes should be ignored outside of the process binding. + * + * If process memory binding is not supported, + * the thread memory binding is considered instead if supported, + * or the flag is ignored. + * + * This flag requires ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM as well + * since binding support is required. + */ + HWLOC_TOPOLOGY_FLAG_RESTRICT_TO_MEMBINDING = (1UL<<5), + + /** \brief Do not ever modify the process or thread binding during discovery. + * + * This flag disables all hwloc discovery steps that require a change of + * the process or thread binding. This currently only affects the x86 + * backend which gets entirely disabled. + * + * This is useful when hwloc_topology_load() is called while the + * application also creates additional threads or modifies the binding. + * + * This flag is also a strict way to make sure the process binding will + * not change to due thread binding changes on Windows + * (see ::HWLOC_TOPOLOGY_FLAG_RESTRICT_TO_CPUBINDING). + */ + HWLOC_TOPOLOGY_FLAG_DONT_CHANGE_BINDING = (1UL<<6) +}; + +/** \brief Set OR'ed flags to non-yet-loaded topology. + * + * Set a OR'ed set of ::hwloc_topology_flags_e onto a topology that was not yet loaded. + * + * If this function is called multiple times, the last invocation will erase + * and replace the set of flags that was previously set. + * + * By default, no flags are set (\c 0). + * + * The flags set in a topology may be retrieved with hwloc_topology_get_flags(). + */ +HWLOC_DECLSPEC int hwloc_topology_set_flags (hwloc_topology_t topology, unsigned long flags); + +/** \brief Get OR'ed flags of a topology. + * + * Get the OR'ed set of ::hwloc_topology_flags_e of a topology. + * + * If hwloc_topology_set_flags() was not called earlier, + * no flags are set (\c 0 is returned). + * + * \return the flags previously set with hwloc_topology_set_flags(). + */ +HWLOC_DECLSPEC unsigned long hwloc_topology_get_flags (hwloc_topology_t topology); + +/** \brief Does the topology context come from this system? + * + * \return 1 if this topology context was built using the system + * running this program. + * \return 0 instead (for instance if using another file-system root, + * a XML topology file, or a synthetic topology). + */ +HWLOC_DECLSPEC int hwloc_topology_is_thissystem(hwloc_topology_t __hwloc_restrict topology) __hwloc_attribute_pure; + +/** \brief Flags describing actual discovery support for this topology. */ +struct hwloc_topology_discovery_support { + /** \brief Detecting the number of PU objects is supported. */ + unsigned char pu; + /** \brief Detecting the number of NUMA nodes is supported. */ + unsigned char numa; + /** \brief Detecting the amount of memory in NUMA nodes is supported. */ + unsigned char numa_memory; + /** \brief Detecting and identifying PU objects that are not available to the current process is supported. */ + unsigned char disallowed_pu; + /** \brief Detecting and identifying NUMA nodes that are not available to the current process is supported. */ + unsigned char disallowed_numa; + /** \brief Detecting the efficiency of CPU kinds is supported, see \ref hwlocality_cpukinds. */ + unsigned char cpukind_efficiency; +}; + +/** \brief Flags describing actual PU binding support for this topology. + * + * A flag may be set even if the feature isn't supported in all cases + * (e.g. binding to random sets of non-contiguous objects). + */ +struct hwloc_topology_cpubind_support { + /** Binding the whole current process is supported. */ + unsigned char set_thisproc_cpubind; + /** Getting the binding of the whole current process is supported. */ + unsigned char get_thisproc_cpubind; + /** Binding a whole given process is supported. */ + unsigned char set_proc_cpubind; + /** Getting the binding of a whole given process is supported. */ + unsigned char get_proc_cpubind; + /** Binding the current thread only is supported. */ + unsigned char set_thisthread_cpubind; + /** Getting the binding of the current thread only is supported. */ + unsigned char get_thisthread_cpubind; + /** Binding a given thread only is supported. */ + unsigned char set_thread_cpubind; + /** Getting the binding of a given thread only is supported. */ + unsigned char get_thread_cpubind; + /** Getting the last processors where the whole current process ran is supported */ + unsigned char get_thisproc_last_cpu_location; + /** Getting the last processors where a whole process ran is supported */ + unsigned char get_proc_last_cpu_location; + /** Getting the last processors where the current thread ran is supported */ + unsigned char get_thisthread_last_cpu_location; +}; + +/** \brief Flags describing actual memory binding support for this topology. + * + * A flag may be set even if the feature isn't supported in all cases + * (e.g. binding to random sets of non-contiguous objects). + */ +struct hwloc_topology_membind_support { + /** Binding the whole current process is supported. */ + unsigned char set_thisproc_membind; + /** Getting the binding of the whole current process is supported. */ + unsigned char get_thisproc_membind; + /** Binding a whole given process is supported. */ + unsigned char set_proc_membind; + /** Getting the binding of a whole given process is supported. */ + unsigned char get_proc_membind; + /** Binding the current thread only is supported. */ + unsigned char set_thisthread_membind; + /** Getting the binding of the current thread only is supported. */ + unsigned char get_thisthread_membind; + /** Binding a given memory area is supported. */ + unsigned char set_area_membind; + /** Getting the binding of a given memory area is supported. */ + unsigned char get_area_membind; + /** Allocating a bound memory area is supported. */ + unsigned char alloc_membind; + /** First-touch policy is supported. */ + unsigned char firsttouch_membind; + /** Bind policy is supported. */ + unsigned char bind_membind; + /** Interleave policy is supported. */ + unsigned char interleave_membind; + /** Next-touch migration policy is supported. */ + unsigned char nexttouch_membind; + /** Migration flags is supported. */ + unsigned char migrate_membind; + /** Getting the last NUMA nodes where a memory area was allocated is supported */ + unsigned char get_area_memlocation; +}; + +/** \brief Flags describing miscellaneous features. + */ +struct hwloc_topology_misc_support { + /** Support was imported when importing another topology, see ::HWLOC_TOPOLOGY_FLAG_IMPORT_SUPPORT. */ + unsigned char imported_support; +}; + +/** \brief Set of flags describing actual support for this topology. + * + * This is retrieved with hwloc_topology_get_support() and will be valid until + * the topology object is destroyed. Note: the values are correct only after + * discovery. + */ +struct hwloc_topology_support { + struct hwloc_topology_discovery_support *discovery; + struct hwloc_topology_cpubind_support *cpubind; + struct hwloc_topology_membind_support *membind; + struct hwloc_topology_misc_support *misc; +}; + +/** \brief Retrieve the topology support. + * + * Each flag indicates whether a feature is supported. + * If set to 0, the feature is not supported. + * If set to 1, the feature is supported, but the corresponding + * call may still fail in some corner cases. + * + * These features are also listed by hwloc-info \--support + * + * The reported features are what the current topology supports + * on the current machine. If the topology was exported to XML + * from another machine and later imported here, support still + * describes what is supported for this imported topology after + * import. By default, binding will be reported as unsupported + * in this case (see ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM). + * + * Topology flag ::HWLOC_TOPOLOGY_FLAG_IMPORT_SUPPORT may be used + * to report the supported features of the original remote machine + * instead. If it was successfully imported, \p imported_support + * will be set in the struct hwloc_topology_misc_support array. + */ +HWLOC_DECLSPEC const struct hwloc_topology_support *hwloc_topology_get_support(hwloc_topology_t __hwloc_restrict topology); + +/** \brief Type filtering flags. + * + * By default, most objects are kept (::HWLOC_TYPE_FILTER_KEEP_ALL). + * Instruction caches, I/O and Misc objects are ignored by default (::HWLOC_TYPE_FILTER_KEEP_NONE). + * Die and Group levels are ignored unless they bring structure (::HWLOC_TYPE_FILTER_KEEP_STRUCTURE). + * + * Note that group objects are also ignored individually (without the entire level) + * when they do not bring structure. + */ +enum hwloc_type_filter_e { + /** \brief Keep all objects of this type. + * + * Cannot be set for ::HWLOC_OBJ_GROUP (groups are designed only to add more structure to the topology). + * \hideinitializer + */ + HWLOC_TYPE_FILTER_KEEP_ALL = 0, + + /** \brief Ignore all objects of this type. + * + * The bottom-level type ::HWLOC_OBJ_PU, the ::HWLOC_OBJ_NUMANODE type, and + * the top-level type ::HWLOC_OBJ_MACHINE may not be ignored. + * \hideinitializer + */ + HWLOC_TYPE_FILTER_KEEP_NONE = 1, + + /** \brief Only ignore objects if their entire level does not bring any structure. + * + * Keep the entire level of objects if at least one of these objects adds + * structure to the topology. An object brings structure when it has multiple + * children and it is not the only child of its parent. + * + * If all objects in the level are the only child of their parent, and if none + * of them has multiple children, the entire level is removed. + * + * Cannot be set for I/O and Misc objects since the topology structure does not matter there. + * \hideinitializer + */ + HWLOC_TYPE_FILTER_KEEP_STRUCTURE = 2, + + /** \brief Only keep likely-important objects of the given type. + * + * It is only useful for I/O object types. + * For ::HWLOC_OBJ_PCI_DEVICE and ::HWLOC_OBJ_OS_DEVICE, it means that only objects + * of major/common kinds are kept (storage, network, OpenFabrics, CUDA, + * OpenCL, RSMI, NVML, and displays). + * Also, only OS devices directly attached on PCI (e.g. no USB) are reported. + * For ::HWLOC_OBJ_BRIDGE, it means that bridges are kept only if they have children. + * + * This flag equivalent to ::HWLOC_TYPE_FILTER_KEEP_ALL for Normal, Memory and Misc types + * since they are likely important. + * \hideinitializer + */ + HWLOC_TYPE_FILTER_KEEP_IMPORTANT = 3 +}; + +/** \brief Set the filtering for the given object type. + */ +HWLOC_DECLSPEC int hwloc_topology_set_type_filter(hwloc_topology_t topology, hwloc_obj_type_t type, enum hwloc_type_filter_e filter); + +/** \brief Get the current filtering for the given object type. + */ +HWLOC_DECLSPEC int hwloc_topology_get_type_filter(hwloc_topology_t topology, hwloc_obj_type_t type, enum hwloc_type_filter_e *filter); + +/** \brief Set the filtering for all object types. + * + * If some types do not support this filtering, they are silently ignored. + */ +HWLOC_DECLSPEC int hwloc_topology_set_all_types_filter(hwloc_topology_t topology, enum hwloc_type_filter_e filter); + +/** \brief Set the filtering for all CPU cache object types. + * + * Memory-side caches are not involved since they are not CPU caches. + */ +HWLOC_DECLSPEC int hwloc_topology_set_cache_types_filter(hwloc_topology_t topology, enum hwloc_type_filter_e filter); + +/** \brief Set the filtering for all CPU instruction cache object types. + * + * Memory-side caches are not involved since they are not CPU caches. + */ +HWLOC_DECLSPEC int hwloc_topology_set_icache_types_filter(hwloc_topology_t topology, enum hwloc_type_filter_e filter); + +/** \brief Set the filtering for all I/O object types. + */ +HWLOC_DECLSPEC int hwloc_topology_set_io_types_filter(hwloc_topology_t topology, enum hwloc_type_filter_e filter); + +/** \brief Set the topology-specific userdata pointer. + * + * Each topology may store one application-given private data pointer. + * It is initialized to \c NULL. + * hwloc will never modify it. + * + * Use it as you wish, after hwloc_topology_init() and until hwloc_topolog_destroy(). + * + * This pointer is not exported to XML. + */ +HWLOC_DECLSPEC void hwloc_topology_set_userdata(hwloc_topology_t topology, const void *userdata); + +/** \brief Retrieve the topology-specific userdata pointer. + * + * Retrieve the application-given private data pointer that was + * previously set with hwloc_topology_set_userdata(). + */ +HWLOC_DECLSPEC void * hwloc_topology_get_userdata(hwloc_topology_t topology); + +/** @} */ + + + +/** \defgroup hwlocality_tinker Modifying a loaded Topology + * @{ + */ + +/** \brief Flags to be given to hwloc_topology_restrict(). */ +enum hwloc_restrict_flags_e { + /** \brief Remove all objects that became CPU-less. + * By default, only objects that contain no PU and no memory are removed. + * This flag may not be used with ::HWLOC_RESTRICT_FLAG_BYNODESET. + * \hideinitializer + */ + HWLOC_RESTRICT_FLAG_REMOVE_CPULESS = (1UL<<0), + + /** \brief Restrict by nodeset instead of CPU set. + * Only keep objects whose nodeset is included or partially included in the given set. + * This flag may not be used with ::HWLOC_RESTRICT_FLAG_REMOVE_CPULESS. + */ + HWLOC_RESTRICT_FLAG_BYNODESET = (1UL<<3), + + /** \brief Remove all objects that became Memory-less. + * By default, only objects that contain no PU and no memory are removed. + * This flag may only be used with ::HWLOC_RESTRICT_FLAG_BYNODESET. + * \hideinitializer + */ + HWLOC_RESTRICT_FLAG_REMOVE_MEMLESS = (1UL<<4), + + /** \brief Move Misc objects to ancestors if their parents are removed during restriction. + * If this flag is not set, Misc objects are removed when their parents are removed. + * \hideinitializer + */ + HWLOC_RESTRICT_FLAG_ADAPT_MISC = (1UL<<1), + + /** \brief Move I/O objects to ancestors if their parents are removed during restriction. + * If this flag is not set, I/O devices and bridges are removed when their parents are removed. + * \hideinitializer + */ + HWLOC_RESTRICT_FLAG_ADAPT_IO = (1UL<<2) +}; + +/** \brief Restrict the topology to the given CPU set or nodeset. + * + * Topology \p topology is modified so as to remove all objects that + * are not included (or partially included) in the CPU set \p set. + * All objects CPU and node sets are restricted accordingly. + * + * If ::HWLOC_RESTRICT_FLAG_BYNODESET is passed in \p flags, + * \p set is considered a nodeset instead of a CPU set. + * + * \p flags is a OR'ed set of ::hwloc_restrict_flags_e. + * + * \note This call may not be reverted by restricting back to a larger + * set. Once dropped during restriction, objects may not be brought + * back, except by loading another topology with hwloc_topology_load(). + * + * \return 0 on success. + * + * \return -1 with errno set to EINVAL if the input set is invalid. + * The topology is not modified in this case. + * + * \return -1 with errno set to ENOMEM on failure to allocate internal data. + * The topology is reinitialized in this case. It should be either + * destroyed with hwloc_topology_destroy() or configured and loaded again. + */ +HWLOC_DECLSPEC int hwloc_topology_restrict(hwloc_topology_t __hwloc_restrict topology, hwloc_const_bitmap_t set, unsigned long flags); + +/** \brief Flags to be given to hwloc_topology_allow(). */ +enum hwloc_allow_flags_e { + /** \brief Mark all objects as allowed in the topology. + * + * \p cpuset and \p nođeset given to hwloc_topology_allow() must be \c NULL. + * \hideinitializer */ + HWLOC_ALLOW_FLAG_ALL = (1UL<<0), + + /** \brief Only allow objects that are available to the current process. + * + * The topology must have ::HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM so that the set + * of available resources can actually be retrieved from the operating system. + * + * \p cpuset and \p nođeset given to hwloc_topology_allow() must be \c NULL. + * \hideinitializer */ + HWLOC_ALLOW_FLAG_LOCAL_RESTRICTIONS = (1UL<<1), + + /** \brief Allow a custom set of objects, given to hwloc_topology_allow() as \p cpuset and/or \p nodeset parameters. + * \hideinitializer */ + HWLOC_ALLOW_FLAG_CUSTOM = (1UL<<2) +}; + +/** \brief Change the sets of allowed PUs and NUMA nodes in the topology. + * + * This function only works if the ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED + * was set on the topology. It does not modify any object, it only changes + * the sets returned by hwloc_topology_get_allowed_cpuset() and + * hwloc_topology_get_allowed_nodeset(). + * + * It is notably useful when importing a topology from another process + * running in a different Linux Cgroup. + * + * \p flags must be set to one flag among ::hwloc_allow_flags_e. + * + * \note Removing objects from a topology should rather be performed with + * hwloc_topology_restrict(). + */ +HWLOC_DECLSPEC int hwloc_topology_allow(hwloc_topology_t __hwloc_restrict topology, hwloc_const_cpuset_t cpuset, hwloc_const_nodeset_t nodeset, unsigned long flags); + +/** \brief Add a MISC object as a leaf of the topology + * + * A new MISC object will be created and inserted into the topology at the + * position given by parent. It is appended to the list of existing Misc children, + * without ever adding any intermediate hierarchy level. This is useful for + * annotating the topology without actually changing the hierarchy. + * + * \p name is supposed to be unique across all Misc objects in the topology. + * It will be duplicated to setup the new object attributes. + * + * The new leaf object will not have any \p cpuset. + * + * \return the newly-created object + * + * \return \c NULL on error. + * + * \return \c NULL if Misc objects are filtered-out of the topology (::HWLOC_TYPE_FILTER_KEEP_NONE). + * + * \note If \p name contains some non-printable characters, they will + * be dropped when exporting to XML, see hwloc_topology_export_xml() in hwloc/export.h. + */ +HWLOC_DECLSPEC hwloc_obj_t hwloc_topology_insert_misc_object(hwloc_topology_t topology, hwloc_obj_t parent, const char *name); + +/** \brief Allocate a Group object to insert later with hwloc_topology_insert_group_object(). + * + * This function returns a new Group object. + * + * The caller should (at least) initialize its sets before inserting + * the object in the topology. See hwloc_topology_insert_group_object(). + */ +HWLOC_DECLSPEC hwloc_obj_t hwloc_topology_alloc_group_object(hwloc_topology_t topology); + +/** \brief Add more structure to the topology by adding an intermediate Group + * + * The caller should first allocate a new Group object with hwloc_topology_alloc_group_object(). + * Then it must setup at least one of its CPU or node sets to specify + * the final location of the Group in the topology. + * Then the object can be passed to this function for actual insertion in the topology. + * + * Either the cpuset or nodeset field (or both, if compatible) must be set + * to a non-empty bitmap. The complete_cpuset or complete_nodeset may be set + * instead if inserting with respect to the complete topology + * (including disallowed, offline or unknown objects). + * If grouping several objects, hwloc_obj_add_other_obj_sets() is an easy way + * to build the Group sets iteratively. + * These sets cannot be larger than the current topology, or they would get + * restricted silently. + * The core will setup the other sets after actual insertion. + * + * The \p subtype object attribute may be defined (to a dynamically + * allocated string) to display something else than "Group" as the + * type name for this object in lstopo. + * Custom name/value info pairs may be added with hwloc_obj_add_info() after + * insertion. + * + * The group \p dont_merge attribute may be set to \c 1 to prevent + * the hwloc core from ever merging this object with another + * hierarchically-identical object. + * This is useful when the Group itself describes an important feature + * that cannot be exposed anywhere else in the hierarchy. + * + * The group \p kind attribute may be set to a high value such + * as \c 0xffffffff to tell hwloc that this new Group should always + * be discarded in favor of any existing Group with the same locality. + * + * \return The inserted object if it was properly inserted. + * + * \return An existing object if the Group was merged or discarded + * because the topology already contained an object at the same + * location (the Group did not add any hierarchy information). + * + * \return \c NULL if the insertion failed because of conflicting sets in topology tree. + * + * \return \c NULL if Group objects are filtered-out of the topology (::HWLOC_TYPE_FILTER_KEEP_NONE). + * + * \return \c NULL if the object was discarded because no set was + * initialized in the Group before insert, or all of them were empty. + */ +HWLOC_DECLSPEC hwloc_obj_t hwloc_topology_insert_group_object(hwloc_topology_t topology, hwloc_obj_t group); + +/** \brief Setup object cpusets/nodesets by OR'ing another object's sets. + * + * For each defined cpuset or nodeset in \p src, allocate the corresponding set + * in \p dst and add \p src to it by OR'ing sets. + * + * This function is convenient between hwloc_topology_alloc_group_object() + * and hwloc_topology_insert_group_object(). It builds the sets of the new Group + * that will be inserted as a new intermediate parent of several objects. + */ +HWLOC_DECLSPEC int hwloc_obj_add_other_obj_sets(hwloc_obj_t dst, hwloc_obj_t src); + +/** \brief Refresh internal structures after topology modification. + * + * Modifying the topology (by restricting, adding objects, modifying structures + * such as distances or memory attributes, etc.) may cause some internal caches + * to become invalid. These caches are automatically refreshed when accessed + * but this refreshing is not thread-safe. + * + * This function is not thread-safe either, but it is a good way to end a + * non-thread-safe phase of topology modification. Once this refresh is done, + * multiple threads may concurrently consult the topology, objects, distances, + * attributes, etc. + * + * See also \ref threadsafety + */ +HWLOC_DECLSPEC int hwloc_topology_refresh(hwloc_topology_t topology); + +/** @} */ + + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +/* high-level helpers */ +#include "hwloc/helper.h" + +/* inline code of some functions above */ +#include "hwloc/inlines.h" + +/* memory attributes */ +#include "hwloc/memattrs.h" + +/* kinds of CPU cores */ +#include "hwloc/cpukinds.h" + +/* exporting to XML or synthetic */ +#include "hwloc/export.h" + +/* distances */ +#include "hwloc/distances.h" + +/* topology diffs */ +#include "hwloc/diff.h" + +/* deprecated headers */ +#include "hwloc/deprecated.h" + +#endif /* HWLOC_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/autogen/config.h b/deps/exla/cache/xla_extension/include/include/hwloc/autogen/config.h new file mode 100644 index 0000000000000000000000000000000000000000..2c673fd60bd6a11704d1551c39d5b0e2c1d2bddd --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/autogen/config.h @@ -0,0 +1,241 @@ +/* -*- c -*- + * Copyright © 2009 CNRS + * Copyright © 2009-2022 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/* The configuration file */ + +#ifndef HWLOC_CONFIG_H +#define HWLOC_CONFIG_H + +#define HWLOC_VERSION "2.0.3" +#define HWLOC_VERSION_MAJOR 2 +#define HWLOC_VERSION_MINOR 0 +#define HWLOC_VERSION_RELEASE 3 +#define HWLOC_VERSION_GREEK "" + +#undef HWLOC_PCI_COMPONENT_BUILTIN +#undef HWLOC_OPENCL_COMPONENT_BUILTIN +#undef HWLOC_CUDA_COMPONENT_BUILTIN +#undef HWLOC_NVML_COMPONENT_BUILTIN +#undef HWLOC_RSMI_COMPONENT_BUILTIN +#undef HWLOC_LEVELZERO_COMPONENT_BUILTIN +#undef HWLOC_GL_COMPONENT_BUILTIN +#undef HWLOC_XML_LIBXML_COMPONENT_BUILTIN + +#if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)) +# define __hwloc_restrict __restrict +#else +# if __STDC_VERSION__ >= 199901L +# define __hwloc_restrict restrict +# else +# define __hwloc_restrict +# endif +#endif + +/* Note that if we're compiling C++, then just use the "inline" + keyword, since it's part of C++ */ +#if defined(c_plusplus) || defined(__cplusplus) +# define __hwloc_inline inline +#elif defined(_MSC_VER) || defined(__HP_cc) +# define __hwloc_inline __inline +#else +# define __hwloc_inline __inline__ +#endif + +/* + * Note: this is public. We can not assume anything from the compiler used + * by the application and thus the HWLOC_HAVE_* macros below are not + * fetched from the autoconf result here. We only automatically use a few + * well-known easy cases. + */ + +/* Some handy constants to make the logic below a little more readable */ +#if defined(__cplusplus) && \ + (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR >= 4)) +#define GXX_ABOVE_3_4 1 +#else +#define GXX_ABOVE_3_4 0 +#endif + +#if !defined(__cplusplus) && \ + (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 95)) +#define GCC_ABOVE_2_95 1 +#else +#define GCC_ABOVE_2_95 0 +#endif + +#if !defined(__cplusplus) && \ + (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) +#define GCC_ABOVE_2_96 1 +#else +#define GCC_ABOVE_2_96 0 +#endif + +#if !defined(__cplusplus) && \ + (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) +#define GCC_ABOVE_3_3 1 +#else +#define GCC_ABOVE_3_3 0 +#endif + +#if !defined(__cplusplus) && \ + (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +#define GCC_ABOVE_3_4 1 +#else +#define GCC_ABOVE_3_4 0 +#endif + +/* Maybe before gcc 2.95 too */ +#ifdef HWLOC_HAVE_ATTRIBUTE_UNUSED +#define __HWLOC_HAVE_ATTRIBUTE_UNUSED HWLOC_HAVE_ATTRIBUTE_UNUSED +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_UNUSED (GXX_ABOVE_3_4 || GCC_ABOVE_2_95) +#else +# define __HWLOC_HAVE_ATTRIBUTE_UNUSED 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_UNUSED +# define __hwloc_attribute_unused __attribute__((__unused__)) +#else +# define __hwloc_attribute_unused +#endif + +#ifdef HWLOC_HAVE_ATTRIBUTE_MALLOC +#define __HWLOC_HAVE_ATTRIBUTE_MALLOC HWLOC_HAVE_ATTRIBUTE_MALLOC +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_MALLOC (GXX_ABOVE_3_4 || GCC_ABOVE_2_96) +#else +# define __HWLOC_HAVE_ATTRIBUTE_MALLOC 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_MALLOC +# define __hwloc_attribute_malloc __attribute__((__malloc__)) +#else +# define __hwloc_attribute_malloc +#endif + +#ifdef HWLOC_HAVE_ATTRIBUTE_CONST +#define __HWLOC_HAVE_ATTRIBUTE_CONST HWLOC_HAVE_ATTRIBUTE_CONST +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_CONST (GXX_ABOVE_3_4 || GCC_ABOVE_2_95) +#else +# define __HWLOC_HAVE_ATTRIBUTE_CONST 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_CONST +# define __hwloc_attribute_const __attribute__((__const__)) +#else +# define __hwloc_attribute_const +#endif + +#ifdef HWLOC_HAVE_ATTRIBUTE_PURE +#define __HWLOC_HAVE_ATTRIBUTE_PURE HWLOC_HAVE_ATTRIBUTE_PURE +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_PURE (GXX_ABOVE_3_4 || GCC_ABOVE_2_96) +#else +# define __HWLOC_HAVE_ATTRIBUTE_PURE 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_PURE +# define __hwloc_attribute_pure __attribute__((__pure__)) +#else +# define __hwloc_attribute_pure +#endif + +#ifndef __hwloc_attribute_deprecated /* allow the user to disable these warnings by defining this macro to nothing */ +#ifdef HWLOC_HAVE_ATTRIBUTE_DEPRECATED +#define __HWLOC_HAVE_ATTRIBUTE_DEPRECATED HWLOC_HAVE_ATTRIBUTE_DEPRECATED +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_DEPRECATED (GXX_ABOVE_3_4 || GCC_ABOVE_3_3) +#else +# define __HWLOC_HAVE_ATTRIBUTE_DEPRECATED 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_DEPRECATED +# define __hwloc_attribute_deprecated __attribute__((__deprecated__)) +#else +# define __hwloc_attribute_deprecated +#endif +#endif + +#ifdef HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS +#define __HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS (GXX_ABOVE_3_4 || GCC_ABOVE_3_3) +#else +# define __HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS +# define __hwloc_attribute_may_alias __attribute__((__may_alias__)) +#else +# define __hwloc_attribute_may_alias +#endif + +#ifdef HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT +#define __HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT +#elif defined(__GNUC__) +# define __HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT (GXX_ABOVE_3_4 || GCC_ABOVE_3_4) +#else +# define __HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT 0 +#endif +#if __HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT +# define __hwloc_attribute_warn_unused_result __attribute__((__warn_unused_result__)) +#else +# define __hwloc_attribute_warn_unused_result +#endif + +#ifdef HWLOC_C_HAVE_VISIBILITY +# if HWLOC_C_HAVE_VISIBILITY +# define HWLOC_DECLSPEC __attribute__((__visibility__("default"))) +# else +# define HWLOC_DECLSPEC +# endif +#else +# define HWLOC_DECLSPEC +#endif + +/* Defined to 1 on Linux */ +#define HWLOC_LINUX_SYS 1 + +/* Defined to 1 if the CPU_SET macro works */ +#undef HWLOC_HAVE_CPU_SET + +/* Defined to 1 if you have the `windows.h' header. */ +#undef HWLOC_HAVE_WINDOWS_H +#define hwloc_pid_t pid_t +#define hwloc_thread_t pthread_t + +#ifdef HWLOC_HAVE_WINDOWS_H + +# include +typedef DWORDLONG hwloc_uint64_t; + +#else /* HWLOC_HAVE_WINDOWS_H */ + +# ifdef hwloc_thread_t +# include +# endif /* hwloc_thread_t */ + +/* Defined to 1 if you have the header file. */ +# define HWLOC_HAVE_STDINT_H 1 + +# include +# ifdef HWLOC_HAVE_STDINT_H +# include +# endif +typedef uint64_t hwloc_uint64_t; + +#endif /* HWLOC_HAVE_WINDOWS_H */ + +/* Define to 1 if --enable-32bits-pci-domain is called. */ +#undef HWLOC_HAVE_32BITS_PCI_DOMAIN + +/* Whether we need to re-define all the hwloc public symbols or not */ +#define HWLOC_SYM_TRANSFORM 0 + +/* The hwloc symbol prefix */ +#define HWLOC_SYM_PREFIX hwloc_ + +/* The hwloc symbol prefix in all caps */ +#define HWLOC_SYM_PREFIX_CAPS HWLOC_ + +#endif /* HWLOC_CONFIG_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/bitmap.h b/deps/exla/cache/xla_extension/include/include/hwloc/bitmap.h new file mode 100644 index 0000000000000000000000000000000000000000..8d9bb9c8805efea35075a766d5e55a2505c51b78 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/bitmap.h @@ -0,0 +1,494 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2020 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief The bitmap API, for use in hwloc itself. + */ + +#ifndef HWLOC_BITMAP_H +#define HWLOC_BITMAP_H + +#include "hwloc/autogen/config.h" + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \defgroup hwlocality_bitmap The bitmap API + * + * The ::hwloc_bitmap_t type represents a set of integers (positive or null). + * A bitmap may be of infinite size (all bits are set after some point). + * A bitmap may even be full if all bits are set. + * + * Bitmaps are used by hwloc for sets of OS processors + * (which may actually be hardware threads) as by ::hwloc_cpuset_t + * (a typedef for ::hwloc_bitmap_t), or sets of NUMA memory nodes + * as ::hwloc_nodeset_t (also a typedef for ::hwloc_bitmap_t). + * Those are used for cpuset and nodeset fields in the ::hwloc_obj structure, + * see \ref hwlocality_object_sets. + * + * Both CPU and node sets are always indexed by OS physical number. + * However users should usually not build CPU and node sets manually + * (e.g. with hwloc_bitmap_set()). + * One should rather use existing object sets and combine them with + * hwloc_bitmap_or(), etc. + * For instance, binding the current thread on a pair of cores may be performed with: + * \code + * hwloc_obj_t core1 = ... , core2 = ... ; + * hwloc_bitmap_t set = hwloc_bitmap_alloc(); + * hwloc_bitmap_or(set, core1->cpuset, core2->cpuset); + * hwloc_set_cpubind(topology, set, HWLOC_CPUBIND_THREAD); + * hwloc_bitmap_free(set); + * \endcode + * + * \note Most functions below return an int that may be negative in case of + * error. The usual error case would be an internal failure to realloc/extend + * the storage of the bitmap (\p errno would be set to \c ENOMEM). + * + * \note Several examples of using the bitmap API are available under the + * doc/examples/ directory in the source tree. + * Regression tests such as tests/hwloc/hwloc_bitmap*.c also make intensive use + * of this API. + * @{ + */ + + +/** \brief + * Set of bits represented as an opaque pointer to an internal bitmap. + */ +typedef struct hwloc_bitmap_s * hwloc_bitmap_t; +/** \brief a non-modifiable ::hwloc_bitmap_t */ +typedef const struct hwloc_bitmap_s * hwloc_const_bitmap_t; + + +/* + * Bitmap allocation, freeing and copying. + */ + +/** \brief Allocate a new empty bitmap. + * + * \returns A valid bitmap or \c NULL. + * + * The bitmap should be freed by a corresponding call to + * hwloc_bitmap_free(). + */ +HWLOC_DECLSPEC hwloc_bitmap_t hwloc_bitmap_alloc(void) __hwloc_attribute_malloc; + +/** \brief Allocate a new full bitmap. */ +HWLOC_DECLSPEC hwloc_bitmap_t hwloc_bitmap_alloc_full(void) __hwloc_attribute_malloc; + +/** \brief Free bitmap \p bitmap. + * + * If \p bitmap is \c NULL, no operation is performed. + */ +HWLOC_DECLSPEC void hwloc_bitmap_free(hwloc_bitmap_t bitmap); + +/** \brief Duplicate bitmap \p bitmap by allocating a new bitmap and copying \p bitmap contents. + * + * If \p bitmap is \c NULL, \c NULL is returned. + */ +HWLOC_DECLSPEC hwloc_bitmap_t hwloc_bitmap_dup(hwloc_const_bitmap_t bitmap) __hwloc_attribute_malloc; + +/** \brief Copy the contents of bitmap \p src into the already allocated bitmap \p dst */ +HWLOC_DECLSPEC int hwloc_bitmap_copy(hwloc_bitmap_t dst, hwloc_const_bitmap_t src); + + +/* + * Bitmap/String Conversion + */ + +/** \brief Stringify a bitmap. + * + * Up to \p buflen characters may be written in buffer \p buf. + * + * If \p buflen is 0, \p buf may safely be \c NULL. + * + * \return the number of character that were actually written if not truncating, + * or that would have been written (not including the ending \\0). + */ +HWLOC_DECLSPEC int hwloc_bitmap_snprintf(char * __hwloc_restrict buf, size_t buflen, hwloc_const_bitmap_t bitmap); + +/** \brief Stringify a bitmap into a newly allocated string. + * + * \return -1 on error. + */ +HWLOC_DECLSPEC int hwloc_bitmap_asprintf(char ** strp, hwloc_const_bitmap_t bitmap); + +/** \brief Parse a bitmap string and stores it in bitmap \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_sscanf(hwloc_bitmap_t bitmap, const char * __hwloc_restrict string); + +/** \brief Stringify a bitmap in the list format. + * + * Lists are comma-separated indexes or ranges. + * Ranges are dash separated indexes. + * The last range may not have an ending indexes if the bitmap is infinitely set. + * + * Up to \p buflen characters may be written in buffer \p buf. + * + * If \p buflen is 0, \p buf may safely be \c NULL. + * + * \return the number of character that were actually written if not truncating, + * or that would have been written (not including the ending \\0). + */ +HWLOC_DECLSPEC int hwloc_bitmap_list_snprintf(char * __hwloc_restrict buf, size_t buflen, hwloc_const_bitmap_t bitmap); + +/** \brief Stringify a bitmap into a newly allocated list string. + * + * \return -1 on error. + */ +HWLOC_DECLSPEC int hwloc_bitmap_list_asprintf(char ** strp, hwloc_const_bitmap_t bitmap); + +/** \brief Parse a list string and stores it in bitmap \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_list_sscanf(hwloc_bitmap_t bitmap, const char * __hwloc_restrict string); + +/** \brief Stringify a bitmap in the taskset-specific format. + * + * The taskset command manipulates bitmap strings that contain a single + * (possible very long) hexadecimal number starting with 0x. + * + * Up to \p buflen characters may be written in buffer \p buf. + * + * If \p buflen is 0, \p buf may safely be \c NULL. + * + * \return the number of character that were actually written if not truncating, + * or that would have been written (not including the ending \\0). + */ +HWLOC_DECLSPEC int hwloc_bitmap_taskset_snprintf(char * __hwloc_restrict buf, size_t buflen, hwloc_const_bitmap_t bitmap); + +/** \brief Stringify a bitmap into a newly allocated taskset-specific string. + * + * \return -1 on error. + */ +HWLOC_DECLSPEC int hwloc_bitmap_taskset_asprintf(char ** strp, hwloc_const_bitmap_t bitmap); + +/** \brief Parse a taskset-specific bitmap string and stores it in bitmap \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_taskset_sscanf(hwloc_bitmap_t bitmap, const char * __hwloc_restrict string); + + +/* + * Building bitmaps. + */ + +/** \brief Empty the bitmap \p bitmap */ +HWLOC_DECLSPEC void hwloc_bitmap_zero(hwloc_bitmap_t bitmap); + +/** \brief Fill bitmap \p bitmap with all possible indexes (even if those objects don't exist or are otherwise unavailable) */ +HWLOC_DECLSPEC void hwloc_bitmap_fill(hwloc_bitmap_t bitmap); + +/** \brief Empty the bitmap \p bitmap and add bit \p id */ +HWLOC_DECLSPEC int hwloc_bitmap_only(hwloc_bitmap_t bitmap, unsigned id); + +/** \brief Fill the bitmap \p and clear the index \p id */ +HWLOC_DECLSPEC int hwloc_bitmap_allbut(hwloc_bitmap_t bitmap, unsigned id); + +/** \brief Setup bitmap \p bitmap from unsigned long \p mask */ +HWLOC_DECLSPEC int hwloc_bitmap_from_ulong(hwloc_bitmap_t bitmap, unsigned long mask); + +/** \brief Setup bitmap \p bitmap from unsigned long \p mask used as \p i -th subset */ +HWLOC_DECLSPEC int hwloc_bitmap_from_ith_ulong(hwloc_bitmap_t bitmap, unsigned i, unsigned long mask); + +/** \brief Setup bitmap \p bitmap from unsigned longs \p masks used as first \p nr subsets */ +HWLOC_DECLSPEC int hwloc_bitmap_from_ulongs(hwloc_bitmap_t bitmap, unsigned nr, const unsigned long *masks); + + +/* + * Modifying bitmaps. + */ + +/** \brief Add index \p id in bitmap \p bitmap */ +HWLOC_DECLSPEC int hwloc_bitmap_set(hwloc_bitmap_t bitmap, unsigned id); + +/** \brief Add indexes from \p begin to \p end in bitmap \p bitmap. + * + * If \p end is \c -1, the range is infinite. + */ +HWLOC_DECLSPEC int hwloc_bitmap_set_range(hwloc_bitmap_t bitmap, unsigned begin, int end); + +/** \brief Replace \p i -th subset of bitmap \p bitmap with unsigned long \p mask */ +HWLOC_DECLSPEC int hwloc_bitmap_set_ith_ulong(hwloc_bitmap_t bitmap, unsigned i, unsigned long mask); + +/** \brief Remove index \p id from bitmap \p bitmap */ +HWLOC_DECLSPEC int hwloc_bitmap_clr(hwloc_bitmap_t bitmap, unsigned id); + +/** \brief Remove indexes from \p begin to \p end in bitmap \p bitmap. + * + * If \p end is \c -1, the range is infinite. + */ +HWLOC_DECLSPEC int hwloc_bitmap_clr_range(hwloc_bitmap_t bitmap, unsigned begin, int end); + +/** \brief Keep a single index among those set in bitmap \p bitmap + * + * May be useful before binding so that the process does not + * have a chance of migrating between multiple processors + * in the original mask. + * Instead of running the task on any PU inside the given CPU set, + * the operating system scheduler will be forced to run it on a single + * of these PUs. + * It avoids a migration overhead and cache-line ping-pongs between PUs. + * + * \note This function is NOT meant to distribute multiple processes + * within a single CPU set. It always return the same single bit when + * called multiple times on the same input set. hwloc_distrib() may + * be used for generating CPU sets to distribute multiple tasks below + * a single multi-PU object. + * + * \note This function cannot be applied to an object set directly. It + * should be applied to a copy (which may be obtained with hwloc_bitmap_dup()). + */ +HWLOC_DECLSPEC int hwloc_bitmap_singlify(hwloc_bitmap_t bitmap); + + +/* + * Consulting bitmaps. + */ + +/** \brief Convert the beginning part of bitmap \p bitmap into unsigned long \p mask */ +HWLOC_DECLSPEC unsigned long hwloc_bitmap_to_ulong(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Convert the \p i -th subset of bitmap \p bitmap into unsigned long mask */ +HWLOC_DECLSPEC unsigned long hwloc_bitmap_to_ith_ulong(hwloc_const_bitmap_t bitmap, unsigned i) __hwloc_attribute_pure; + +/** \brief Convert the first \p nr subsets of bitmap \p bitmap into the array of \p nr unsigned long \p masks + * + * \p nr may be determined earlier with hwloc_bitmap_nr_ulongs(). + * + * \return 0 + */ +HWLOC_DECLSPEC int hwloc_bitmap_to_ulongs(hwloc_const_bitmap_t bitmap, unsigned nr, unsigned long *masks); + +/** \brief Return the number of unsigned longs required for storing bitmap \p bitmap entirely + * + * This is the number of contiguous unsigned longs from the very first bit of the bitmap + * (even if unset) up to the last set bit. + * This is useful for knowing the \p nr parameter to pass to hwloc_bitmap_to_ulongs() + * (or which calls to hwloc_bitmap_to_ith_ulong() are needed) + * to entirely convert a bitmap into multiple unsigned longs. + * + * When called on the output of hwloc_topology_get_topology_cpuset(), + * the returned number is large enough for all cpusets of the topology. + * + * \return -1 if \p bitmap is infinite. + */ +HWLOC_DECLSPEC int hwloc_bitmap_nr_ulongs(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Test whether index \p id is part of bitmap \p bitmap. + * + * \return 1 if the bit at index \p id is set in bitmap \p bitmap, 0 otherwise. + */ +HWLOC_DECLSPEC int hwloc_bitmap_isset(hwloc_const_bitmap_t bitmap, unsigned id) __hwloc_attribute_pure; + +/** \brief Test whether bitmap \p bitmap is empty + * + * \return 1 if bitmap is empty, 0 otherwise. + */ +HWLOC_DECLSPEC int hwloc_bitmap_iszero(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Test whether bitmap \p bitmap is completely full + * + * \return 1 if bitmap is full, 0 otherwise. + * + * \note A full bitmap is always infinitely set. + */ +HWLOC_DECLSPEC int hwloc_bitmap_isfull(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Compute the first index (least significant bit) in bitmap \p bitmap + * + * \return -1 if no index is set in \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_first(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Compute the next index in bitmap \p bitmap which is after index \p prev + * + * If \p prev is -1, the first index is returned. + * + * \return -1 if no index with higher index is set in \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_next(hwloc_const_bitmap_t bitmap, int prev) __hwloc_attribute_pure; + +/** \brief Compute the last index (most significant bit) in bitmap \p bitmap + * + * \return -1 if no index is set in \p bitmap, or if \p bitmap is infinitely set. + */ +HWLOC_DECLSPEC int hwloc_bitmap_last(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Compute the "weight" of bitmap \p bitmap (i.e., number of + * indexes that are in the bitmap). + * + * \return the number of indexes that are in the bitmap. + * + * \return -1 if \p bitmap is infinitely set. + */ +HWLOC_DECLSPEC int hwloc_bitmap_weight(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Compute the first unset index (least significant bit) in bitmap \p bitmap + * + * \return -1 if no index is unset in \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_first_unset(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Compute the next unset index in bitmap \p bitmap which is after index \p prev + * + * If \p prev is -1, the first unset index is returned. + * + * \return -1 if no index with higher index is unset in \p bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_next_unset(hwloc_const_bitmap_t bitmap, int prev) __hwloc_attribute_pure; + +/** \brief Compute the last unset index (most significant bit) in bitmap \p bitmap + * + * \return -1 if no index is unset in \p bitmap, or if \p bitmap is infinitely set. + */ +HWLOC_DECLSPEC int hwloc_bitmap_last_unset(hwloc_const_bitmap_t bitmap) __hwloc_attribute_pure; + +/** \brief Loop macro iterating on bitmap \p bitmap + * + * The loop must start with hwloc_bitmap_foreach_begin() and end + * with hwloc_bitmap_foreach_end() followed by a terminating ';'. + * + * \p index is the loop variable; it should be an unsigned int. The + * first iteration will set \p index to the lowest index in the bitmap. + * Successive iterations will iterate through, in order, all remaining + * indexes set in the bitmap. To be specific: each iteration will return a + * value for \p index such that hwloc_bitmap_isset(bitmap, index) is true. + * + * The assert prevents the loop from being infinite if the bitmap is infinitely set. + * + * \hideinitializer + */ +#define hwloc_bitmap_foreach_begin(id, bitmap) \ +do { \ + assert(hwloc_bitmap_weight(bitmap) != -1); \ + for (id = hwloc_bitmap_first(bitmap); \ + (unsigned) id != (unsigned) -1; \ + id = hwloc_bitmap_next(bitmap, id)) { + +/** \brief End of loop macro iterating on a bitmap. + * + * Needs a terminating ';'. + * + * \sa hwloc_bitmap_foreach_begin() + * \hideinitializer + */ +#define hwloc_bitmap_foreach_end() \ + } \ +} while (0) + + +/* + * Combining bitmaps. + */ + +/** \brief Or bitmaps \p bitmap1 and \p bitmap2 and store the result in bitmap \p res + * + * \p res can be the same as \p bitmap1 or \p bitmap2 + */ +HWLOC_DECLSPEC int hwloc_bitmap_or (hwloc_bitmap_t res, hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2); + +/** \brief And bitmaps \p bitmap1 and \p bitmap2 and store the result in bitmap \p res + * + * \p res can be the same as \p bitmap1 or \p bitmap2 + */ +HWLOC_DECLSPEC int hwloc_bitmap_and (hwloc_bitmap_t res, hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2); + +/** \brief And bitmap \p bitmap1 and the negation of \p bitmap2 and store the result in bitmap \p res + * + * \p res can be the same as \p bitmap1 or \p bitmap2 + */ +HWLOC_DECLSPEC int hwloc_bitmap_andnot (hwloc_bitmap_t res, hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2); + +/** \brief Xor bitmaps \p bitmap1 and \p bitmap2 and store the result in bitmap \p res + * + * \p res can be the same as \p bitmap1 or \p bitmap2 + */ +HWLOC_DECLSPEC int hwloc_bitmap_xor (hwloc_bitmap_t res, hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2); + +/** \brief Negate bitmap \p bitmap and store the result in bitmap \p res + * + * \p res can be the same as \p bitmap + */ +HWLOC_DECLSPEC int hwloc_bitmap_not (hwloc_bitmap_t res, hwloc_const_bitmap_t bitmap); + + +/* + * Comparing bitmaps. + */ + +/** \brief Test whether bitmaps \p bitmap1 and \p bitmap2 intersects. + * + * \return 1 if bitmaps intersect, 0 otherwise. + */ +HWLOC_DECLSPEC int hwloc_bitmap_intersects (hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2) __hwloc_attribute_pure; + +/** \brief Test whether bitmap \p sub_bitmap is part of bitmap \p super_bitmap. + * + * \return 1 if \p sub_bitmap is included in \p super_bitmap, 0 otherwise. + * + * \note The empty bitmap is considered included in any other bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_isincluded (hwloc_const_bitmap_t sub_bitmap, hwloc_const_bitmap_t super_bitmap) __hwloc_attribute_pure; + +/** \brief Test whether bitmap \p bitmap1 is equal to bitmap \p bitmap2. + * + * \return 1 if bitmaps are equal, 0 otherwise. + */ +HWLOC_DECLSPEC int hwloc_bitmap_isequal (hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2) __hwloc_attribute_pure; + +/** \brief Compare bitmaps \p bitmap1 and \p bitmap2 using their lowest index. + * + * A bitmap is considered smaller if its least significant bit is smaller. + * The empty bitmap is considered higher than anything (because its least significant bit does not exist). + * + * \return -1 if \p bitmap1 is considered smaller than \p bitmap2. + * \return 1 if \p bitmap1 is considered larger than \p bitmap2. + * + * For instance comparing binary bitmaps 0011 and 0110 returns -1 + * (hence 0011 is considered smaller than 0110) + * because least significant bit of 0011 (0001) is smaller than least significant bit of 0110 (0010). + * Comparing 01001 and 00110 would also return -1 for the same reason. + * + * \return 0 if bitmaps are considered equal, even if they are not strictly equal. + * They just need to have the same least significant bit. + * For instance, comparing binary bitmaps 0010 and 0110 returns 0 because they have the same least significant bit. + */ +HWLOC_DECLSPEC int hwloc_bitmap_compare_first(hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2) __hwloc_attribute_pure; + +/** \brief Compare bitmaps \p bitmap1 and \p bitmap2 in lexicographic order. + * + * Lexicographic comparison of bitmaps, starting for their highest indexes. + * Compare last indexes first, then second, etc. + * The empty bitmap is considered lower than anything. + * + * \return -1 if \p bitmap1 is considered smaller than \p bitmap2. + * \return 1 if \p bitmap1 is considered larger than \p bitmap2. + * \return 0 if bitmaps are equal (contrary to hwloc_bitmap_compare_first()). + * + * For instance comparing binary bitmaps 0011 and 0110 returns -1 + * (hence 0011 is considered smaller than 0110). + * Comparing 00101 and 01010 returns -1 too. + * + * \note This is different from the non-existing hwloc_bitmap_compare_last() + * which would only compare the highest index of each bitmap. + */ +HWLOC_DECLSPEC int hwloc_bitmap_compare(hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2) __hwloc_attribute_pure; + +/** @} */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_BITMAP_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/cpukinds.h b/deps/exla/cache/xla_extension/include/include/hwloc/cpukinds.h new file mode 100644 index 0000000000000000000000000000000000000000..524a05afe8c0b81bd7af8d1a8916eb6db04c2f33 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/cpukinds.h @@ -0,0 +1,193 @@ +/* + * Copyright © 2020-2021 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief Kinds of CPU cores. + */ + +#ifndef HWLOC_CPUKINDS_H +#define HWLOC_CPUKINDS_H + +#include "hwloc.h" + +#ifdef __cplusplus +extern "C" { +#elif 0 +} +#endif + +/** \defgroup hwlocality_cpukinds Kinds of CPU cores + * + * Platforms with heterogeneous CPUs may have some cores with + * different features or frequencies. + * This API exposes identical PUs in sets called CPU kinds. + * Each PU of the topology may only be in a single kind. + * + * The number of kinds may be obtained with hwloc_cpukinds_get_nr(). + * If the platform is homogeneous, there may be a single kind + * with all PUs. + * If the platform or operating system does not expose any + * information about CPU cores, there may be no kind at all. + * + * The index of the kind that describes a given CPU set + * (if any, and not partially) + * may be obtained with hwloc_cpukinds_get_by_cpuset(). + * + * From the index of a kind, it is possible to retrieve information + * with hwloc_cpukinds_get_info(): + * an abstracted efficiency value, + * and an array of info attributes + * (for instance the "CoreType" and "FrequencyMaxMHz", + * see \ref topoattrs_cpukinds). + * + * A higher efficiency value means greater intrinsic performance + * (and possibly less performance/power efficiency). + * Kinds with lower efficiency values are ranked first: + * Passing 0 as \p kind_index to hwloc_cpukinds_get_info() will + * return information about the CPU kind with lower performance + * but higher energy-efficiency. + * Higher \p kind_index values would rather return information + * about power-hungry high-performance cores. + * + * When available, efficiency values are gathered from the operating system. + * If so, \p cpukind_efficiency is set in the struct hwloc_topology_discovery_support array. + * This is currently available on Windows 10, Mac OS X (Darwin), + * and on some Linux platforms where core "capacity" is exposed in sysfs. + * + * If the operating system does not expose core efficiencies natively, + * hwloc tries to compute efficiencies by comparing CPU kinds using + * frequencies (on ARM), or core types and frequencies (on other architectures). + * The environment variable HWLOC_CPUKINDS_RANKING may be used + * to change this heuristics, see \ref envvar. + * + * If hwloc fails to rank any kind, for instance because the operating + * system does not expose efficiencies and core frequencies, + * all kinds will have an unknown efficiency (\c -1), + * and they are not indexed/ordered in any specific way. + * + * @{ + */ + +/** \brief Get the number of different kinds of CPU cores in the topology. + * + * \p flags must be \c 0 for now. + * + * \return The number of CPU kinds (positive integer) on success. + * \return \c 0 if no information about kinds was found. + * \return \c -1 with \p errno set to \c EINVAL if \p flags is invalid. + */ +HWLOC_DECLSPEC int +hwloc_cpukinds_get_nr(hwloc_topology_t topology, + unsigned long flags); + +/** \brief Get the index of the CPU kind that contains CPUs listed in \p cpuset. + * + * \p flags must be \c 0 for now. + * + * \return The index of the CPU kind (positive integer or 0) on success. + * \return \c -1 with \p errno set to \c EXDEV if \p cpuset is + * only partially included in the some kind. + * \return \c -1 with \p errno set to \c ENOENT if \p cpuset is + * not included in any kind, even partially. + * \return \c -1 with \p errno set to \c EINVAL if parameters are invalid. + */ +HWLOC_DECLSPEC int +hwloc_cpukinds_get_by_cpuset(hwloc_topology_t topology, + hwloc_const_bitmap_t cpuset, + unsigned long flags); + +/** \brief Get the CPU set and infos about a CPU kind in the topology. + * + * \p kind_index identifies one kind of CPU between 0 and the number + * of kinds returned by hwloc_cpukinds_get_nr() minus 1. + * + * If not \c NULL, the bitmap \p cpuset will be filled with + * the set of PUs of this kind. + * + * The integer pointed by \p efficiency, if not \c NULL will, be filled + * with the ranking of this kind of CPU in term of efficiency (see above). + * It ranges from \c 0 to the number of kinds + * (as reported by hwloc_cpukinds_get_nr()) minus 1. + * + * Kinds with lower efficiency are reported first. + * + * If there is a single kind in the topology, its efficiency \c 0. + * If the efficiency of some kinds of cores is unknown, + * the efficiency of all kinds is set to \c -1, + * and kinds are reported in no specific order. + * + * The array of info attributes (for instance the "CoreType", + * "FrequencyMaxMHz" or "FrequencyBaseMHz", see \ref topoattrs_cpukinds) + * and its length are returned in \p infos or \p nr_infos. + * The array belongs to the topology, it should not be freed or modified. + * + * If \p nr_infos or \p infos is \c NULL, no info is returned. + * + * \p flags must be \c 0 for now. + * + * \return \c 0 on success. + * \return \c -1 with \p errno set to \c ENOENT if \p kind_index does not match any CPU kind. + * \return \c -1 with \p errno set to \c EINVAL if parameters are invalid. + */ +HWLOC_DECLSPEC int +hwloc_cpukinds_get_info(hwloc_topology_t topology, + unsigned kind_index, + hwloc_bitmap_t cpuset, + int *efficiency, + unsigned *nr_infos, struct hwloc_info_s **infos, + unsigned long flags); + +/** \brief Register a kind of CPU in the topology. + * + * Mark the PUs listed in \p cpuset as being of the same kind + * with respect to the given attributes. + * + * \p forced_efficiency should be \c -1 if unknown. + * Otherwise it is an abstracted efficiency value to enforce + * the ranking of all kinds if all of them have valid (and + * different) efficiencies. + * + * The array \p infos of size \p nr_infos may be used to provide + * info names and values describing this kind of PUs. + * + * \p flags must be \c 0 for now. + * + * Parameters \p cpuset and \p infos will be duplicated internally, + * the caller is responsible for freeing them. + * + * If \p cpuset overlaps with some existing kinds, those might get + * modified or split. For instance if existing kind A contains + * PUs 0 and 1, and one registers another kind for PU 1 and 2, + * there will be 3 resulting kinds: + * existing kind A is restricted to only PU 0; + * new kind B contains only PU 1 and combines information from A + * and from the newly-registered kind; + * new kind C contains only PU 2 and only gets information from + * the newly-registered kind. + * + * \note The efficiency \p forced_efficiency provided to this function + * may be different from the one reported later by hwloc_cpukinds_get_info() + * because hwloc will scale efficiency values down to + * between 0 and the number of kinds minus 1. + * + * \return \c 0 on success. + * \return \c -1 with \p errno set to \c EINVAL if some parameters are invalid, + * for instance if \p cpuset is \c NULL or empty. + */ +HWLOC_DECLSPEC int +hwloc_cpukinds_register(hwloc_topology_t topology, + hwloc_bitmap_t cpuset, + int forced_efficiency, + unsigned nr_infos, struct hwloc_info_s *infos, + unsigned long flags); + +/** @} */ + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_CPUKINDS_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/deprecated.h b/deps/exla/cache/xla_extension/include/include/hwloc/deprecated.h new file mode 100644 index 0000000000000000000000000000000000000000..f2419dd4825b5772d3caf64af3947530d9270d6f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/deprecated.h @@ -0,0 +1,217 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2021 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2010 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/** + * This file contains the inline code of functions declared in hwloc.h + */ + +#ifndef HWLOC_DEPRECATED_H +#define HWLOC_DEPRECATED_H + +#ifndef HWLOC_H +#error Please include the main hwloc.h instead +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* backward compat with v2.0 before WHOLE_SYSTEM renaming */ +#define HWLOC_TOPOLOGY_FLAG_WHOLE_SYSTEM HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED +/* backward compat with v1.11 before System removal */ +#define HWLOC_OBJ_SYSTEM HWLOC_OBJ_MACHINE +/* backward compat with v1.10 before Socket->Package renaming */ +#define HWLOC_OBJ_SOCKET HWLOC_OBJ_PACKAGE +/* backward compat with v1.10 before Node->NUMANode clarification */ +#define HWLOC_OBJ_NODE HWLOC_OBJ_NUMANODE + +/** \brief Add a distances structure. + * + * Superseded by hwloc_distances_add_create()+hwloc_distances_add_values()+hwloc_distances_add_commit() + * in v2.5. + */ +HWLOC_DECLSPEC int hwloc_distances_add(hwloc_topology_t topology, + unsigned nbobjs, hwloc_obj_t *objs, hwloc_uint64_t *values, + unsigned long kind, unsigned long flags) __hwloc_attribute_deprecated; + +/** \brief Insert a misc object by parent. + * + * Identical to hwloc_topology_insert_misc_object(). + */ +static __hwloc_inline hwloc_obj_t +hwloc_topology_insert_misc_object_by_parent(hwloc_topology_t topology, hwloc_obj_t parent, const char *name) __hwloc_attribute_deprecated; +static __hwloc_inline hwloc_obj_t +hwloc_topology_insert_misc_object_by_parent(hwloc_topology_t topology, hwloc_obj_t parent, const char *name) +{ + return hwloc_topology_insert_misc_object(topology, parent, name); +} + +/** \brief Stringify the cpuset containing a set of objects. + * + * If \p size is 0, \p string may safely be \c NULL. + * + * \return the number of character that were actually written if not truncating, + * or that would have been written (not including the ending \\0). + */ +static __hwloc_inline int +hwloc_obj_cpuset_snprintf(char *str, size_t size, size_t nobj, struct hwloc_obj * const *objs) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_obj_cpuset_snprintf(char *str, size_t size, size_t nobj, struct hwloc_obj * const *objs) +{ + hwloc_bitmap_t set = hwloc_bitmap_alloc(); + int res; + unsigned i; + + hwloc_bitmap_zero(set); + for(i=0; icpuset) + hwloc_bitmap_or(set, set, objs[i]->cpuset); + + res = hwloc_bitmap_snprintf(str, size, set); + hwloc_bitmap_free(set); + return res; +} + +/** \brief Convert a type string into a type and some attributes. + * + * Deprecated by hwloc_type_sscanf() + */ +static __hwloc_inline int +hwloc_obj_type_sscanf(const char *string, hwloc_obj_type_t *typep, int *depthattrp, void *typeattrp, size_t typeattrsize) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_obj_type_sscanf(const char *string, hwloc_obj_type_t *typep, int *depthattrp, void *typeattrp, size_t typeattrsize) +{ + union hwloc_obj_attr_u attr; + int err = hwloc_type_sscanf(string, typep, &attr, sizeof(attr)); + if (err < 0) + return err; + if (hwloc_obj_type_is_cache(*typep)) { + if (depthattrp) + *depthattrp = (int) attr.cache.depth; + if (typeattrp && typeattrsize >= sizeof(hwloc_obj_cache_type_t)) + memcpy(typeattrp, &attr.cache.type, sizeof(hwloc_obj_cache_type_t)); + } else if (*typep == HWLOC_OBJ_GROUP) { + if (depthattrp) + *depthattrp = (int) attr.group.depth; + } + return 0; +} + +/** \brief Set the default memory binding policy of the current + * process or thread to prefer the NUMA node(s) specified by physical \p nodeset + */ +static __hwloc_inline int +hwloc_set_membind_nodeset(hwloc_topology_t topology, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_set_membind_nodeset(hwloc_topology_t topology, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) +{ + return hwloc_set_membind(topology, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Query the default memory binding policy and physical locality of the + * current process or thread. + */ +static __hwloc_inline int +hwloc_get_membind_nodeset(hwloc_topology_t topology, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_get_membind_nodeset(hwloc_topology_t topology, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags) +{ + return hwloc_get_membind(topology, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Set the default memory binding policy of the specified + * process to prefer the NUMA node(s) specified by physical \p nodeset + */ +static __hwloc_inline int +hwloc_set_proc_membind_nodeset(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_set_proc_membind_nodeset(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) +{ + return hwloc_set_proc_membind(topology, pid, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Query the default memory binding policy and physical locality of the + * specified process. + */ +static __hwloc_inline int +hwloc_get_proc_membind_nodeset(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_get_proc_membind_nodeset(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags) +{ + return hwloc_get_proc_membind(topology, pid, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Bind the already-allocated memory identified by (addr, len) + * to the NUMA node(s) in physical \p nodeset. + */ +static __hwloc_inline int +hwloc_set_area_membind_nodeset(hwloc_topology_t topology, const void *addr, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_set_area_membind_nodeset(hwloc_topology_t topology, const void *addr, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) +{ + return hwloc_set_area_membind(topology, addr, len, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Query the physical NUMA node(s) and binding policy of the memory + * identified by (\p addr, \p len ). + */ +static __hwloc_inline int +hwloc_get_area_membind_nodeset(hwloc_topology_t topology, const void *addr, size_t len, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags) __hwloc_attribute_deprecated; +static __hwloc_inline int +hwloc_get_area_membind_nodeset(hwloc_topology_t topology, const void *addr, size_t len, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags) +{ + return hwloc_get_area_membind(topology, addr, len, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Allocate some memory on the given physical nodeset \p nodeset + */ +static __hwloc_inline void * +hwloc_alloc_membind_nodeset(hwloc_topology_t topology, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_malloc __hwloc_attribute_deprecated; +static __hwloc_inline void * +hwloc_alloc_membind_nodeset(hwloc_topology_t topology, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) +{ + return hwloc_alloc_membind(topology, len, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Allocate some memory on the given nodeset \p nodeset. + */ +static __hwloc_inline void * +hwloc_alloc_membind_policy_nodeset(hwloc_topology_t topology, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) __hwloc_attribute_malloc __hwloc_attribute_deprecated; +static __hwloc_inline void * +hwloc_alloc_membind_policy_nodeset(hwloc_topology_t topology, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags) +{ + return hwloc_alloc_membind_policy(topology, len, nodeset, policy, flags | HWLOC_MEMBIND_BYNODESET); +} + +/** \brief Convert a CPU set into a NUMA node set and handle non-NUMA cases + */ +static __hwloc_inline void +hwloc_cpuset_to_nodeset_strict(hwloc_topology_t topology, hwloc_const_cpuset_t _cpuset, hwloc_nodeset_t nodeset) __hwloc_attribute_deprecated; +static __hwloc_inline void +hwloc_cpuset_to_nodeset_strict(hwloc_topology_t topology, hwloc_const_cpuset_t _cpuset, hwloc_nodeset_t nodeset) +{ + hwloc_cpuset_to_nodeset(topology, _cpuset, nodeset); +} + +/** \brief Convert a NUMA node set into a CPU set and handle non-NUMA cases + */ +static __hwloc_inline void +hwloc_cpuset_from_nodeset_strict(hwloc_topology_t topology, hwloc_cpuset_t _cpuset, hwloc_const_nodeset_t nodeset) __hwloc_attribute_deprecated; +static __hwloc_inline void +hwloc_cpuset_from_nodeset_strict(hwloc_topology_t topology, hwloc_cpuset_t _cpuset, hwloc_const_nodeset_t nodeset) +{ + hwloc_cpuset_from_nodeset(topology, _cpuset, nodeset); +} + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_DEPRECATED_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/diff.h b/deps/exla/cache/xla_extension/include/include/hwloc/diff.h new file mode 100644 index 0000000000000000000000000000000000000000..0ad0486beabf40380a8b666261df775c8f8da9b8 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/diff.h @@ -0,0 +1,289 @@ +/* + * Copyright © 2013-2020 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief Topology differences. + */ + +#ifndef HWLOC_DIFF_H +#define HWLOC_DIFF_H + +#ifndef HWLOC_H +#error Please include the main hwloc.h instead +#endif + + +#ifdef __cplusplus +extern "C" { +#elif 0 +} +#endif + + +/** \defgroup hwlocality_diff Topology differences + * + * Applications that manipulate many similar topologies, for instance + * one for each node of a homogeneous cluster, may want to compress + * topologies to reduce the memory footprint. + * + * This file offers a way to manipulate the difference between topologies + * and export/import it to/from XML. + * Compression may therefore be achieved by storing one topology + * entirely while the others are only described by their differences + * with the former. + * The actual topology can be reconstructed when actually needed by + * applying the precomputed difference to the reference topology. + * + * This interface targets very similar nodes. + * Only very simple differences between topologies are actually + * supported, for instance a change in the memory size, the name + * of the object, or some info attribute. + * More complex differences such as adding or removing objects cannot + * be represented in the difference structures and therefore return + * errors. + * Differences between object sets or topology-wide allowed sets, + * cannot be represented either. + * + * It means that there is no need to apply the difference when + * looking at the tree organization (how many levels, how many + * objects per level, what kind of objects, CPU and node sets, etc) + * and when binding to objects. + * However the difference must be applied when looking at object + * attributes such as the name, the memory size or info attributes. + * + * @{ + */ + + +/** \brief Type of one object attribute difference. + */ +typedef enum hwloc_topology_diff_obj_attr_type_e { + /** \brief The object local memory is modified. + * The union is a hwloc_topology_diff_obj_attr_u::hwloc_topology_diff_obj_attr_uint64_s + * (and the index field is ignored). + */ + HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_SIZE, + + /** \brief The object name is modified. + * The union is a hwloc_topology_diff_obj_attr_u::hwloc_topology_diff_obj_attr_string_s + * (and the name field is ignored). + */ + + HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_NAME, + /** \brief the value of an info attribute is modified. + * The union is a hwloc_topology_diff_obj_attr_u::hwloc_topology_diff_obj_attr_string_s. + */ + HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_INFO +} hwloc_topology_diff_obj_attr_type_t; + +/** \brief One object attribute difference. + */ +union hwloc_topology_diff_obj_attr_u { + struct hwloc_topology_diff_obj_attr_generic_s { + /* each part of the union must start with these */ + hwloc_topology_diff_obj_attr_type_t type; + } generic; + + /** \brief Integer attribute modification with an optional index. */ + struct hwloc_topology_diff_obj_attr_uint64_s { + /* used for storing integer attributes */ + hwloc_topology_diff_obj_attr_type_t type; + hwloc_uint64_t index; /* not used for SIZE */ + hwloc_uint64_t oldvalue; + hwloc_uint64_t newvalue; + } uint64; + + /** \brief String attribute modification with an optional name */ + struct hwloc_topology_diff_obj_attr_string_s { + /* used for storing name and info pairs */ + hwloc_topology_diff_obj_attr_type_t type; + char *name; /* not used for NAME */ + char *oldvalue; + char *newvalue; + } string; +}; + + +/** \brief Type of one element of a difference list. + */ +typedef enum hwloc_topology_diff_type_e { + /** \brief An object attribute was changed. + * The union is a hwloc_topology_diff_u::hwloc_topology_diff_obj_attr_s. + */ + HWLOC_TOPOLOGY_DIFF_OBJ_ATTR, + + /** \brief The difference is too complex, + * it cannot be represented. The difference below + * this object has not been checked. + * hwloc_topology_diff_build() will return 1. + * + * The union is a hwloc_topology_diff_u::hwloc_topology_diff_too_complex_s. + */ + HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX +} hwloc_topology_diff_type_t; + +/** \brief One element of a difference list between two topologies. + */ +typedef union hwloc_topology_diff_u { + struct hwloc_topology_diff_generic_s { + /* each part of the union must start with these */ + hwloc_topology_diff_type_t type; + union hwloc_topology_diff_u * next; /* pointer to the next element of the list, or NULL */ + } generic; + + /* A difference in an object attribute. */ + struct hwloc_topology_diff_obj_attr_s { + hwloc_topology_diff_type_t type; /* must be ::HWLOC_TOPOLOGY_DIFF_OBJ_ATTR */ + union hwloc_topology_diff_u * next; + /* List of attribute differences for a single object */ + int obj_depth; + unsigned obj_index; + union hwloc_topology_diff_obj_attr_u diff; + } obj_attr; + + /* A difference that is too complex. */ + struct hwloc_topology_diff_too_complex_s { + hwloc_topology_diff_type_t type; /* must be ::HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX */ + union hwloc_topology_diff_u * next; + /* Where we had to stop computing the diff in the first topology */ + int obj_depth; + unsigned obj_index; + } too_complex; +} * hwloc_topology_diff_t; + + +/** \brief Compute the difference between 2 topologies. + * + * The difference is stored as a list of ::hwloc_topology_diff_t entries + * starting at \p diff. + * It is computed by doing a depth-first traversal of both topology trees + * simultaneously. + * + * If the difference between 2 objects is too complex to be represented + * (for instance if some objects have different types, or different numbers + * of children), a special diff entry of type ::HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX + * is queued. + * The computation of the diff does not continue below these objects. + * So each such diff entry means that the difference between two subtrees + * could not be computed. + * + * \return 0 if the difference can be represented properly. + * + * \return 0 with \p diff pointing to NULL if there is no difference + * between the topologies. + * + * \return 1 if the difference is too complex (see above). Some entries in + * the list will be of type ::HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX. + * + * \return -1 on any other error. + * + * \note \p flags is currently not used. It should be 0. + * + * \note The output diff has to be freed with hwloc_topology_diff_destroy(). + * + * \note The output diff can only be exported to XML or passed to + * hwloc_topology_diff_apply() if 0 was returned, i.e. if no entry of type + * ::HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX is listed. + * + * \note The output diff may be modified by removing some entries from + * the list. The removed entries should be freed by passing them to + * to hwloc_topology_diff_destroy() (possible as another list). +*/ +HWLOC_DECLSPEC int hwloc_topology_diff_build(hwloc_topology_t topology, hwloc_topology_t newtopology, unsigned long flags, hwloc_topology_diff_t *diff); + +/** \brief Flags to be given to hwloc_topology_diff_apply(). + */ +enum hwloc_topology_diff_apply_flags_e { + /** \brief Apply topology diff in reverse direction. + * \hideinitializer + */ + HWLOC_TOPOLOGY_DIFF_APPLY_REVERSE = (1UL<<0) +}; + +/** \brief Apply a topology diff to an existing topology. + * + * \p flags is an OR'ed set of ::hwloc_topology_diff_apply_flags_e. + * + * The new topology is modified in place. hwloc_topology_dup() + * may be used to duplicate it before patching. + * + * If the difference cannot be applied entirely, all previous applied + * elements are unapplied before returning. + * + * \return 0 on success. + * + * \return -N if applying the difference failed while trying + * to apply the N-th part of the difference. For instance -1 + * is returned if the very first difference element could not + * be applied. + */ +HWLOC_DECLSPEC int hwloc_topology_diff_apply(hwloc_topology_t topology, hwloc_topology_diff_t diff, unsigned long flags); + +/** \brief Destroy a list of topology differences. + */ +HWLOC_DECLSPEC int hwloc_topology_diff_destroy(hwloc_topology_diff_t diff); + +/** \brief Load a list of topology differences from a XML file. + * + * If not \c NULL, \p refname will be filled with the identifier + * string of the reference topology for the difference file, + * if any was specified in the XML file. + * This identifier is usually the name of the other XML file + * that contains the reference topology. + * + * \note the pointer returned in refname should later be freed + * by the caller. + */ +HWLOC_DECLSPEC int hwloc_topology_diff_load_xml(const char *xmlpath, hwloc_topology_diff_t *diff, char **refname); + +/** \brief Export a list of topology differences to a XML file. + * + * If not \c NULL, \p refname defines an identifier string + * for the reference topology which was used as a base when + * computing this difference. + * This identifier is usually the name of the other XML file + * that contains the reference topology. + * This attribute is given back when reading the diff from XML. + */ +HWLOC_DECLSPEC int hwloc_topology_diff_export_xml(hwloc_topology_diff_t diff, const char *refname, const char *xmlpath); + +/** \brief Load a list of topology differences from a XML buffer. + * + * If not \c NULL, \p refname will be filled with the identifier + * string of the reference topology for the difference file, + * if any was specified in the XML file. + * This identifier is usually the name of the other XML file + * that contains the reference topology. + * + * \note the pointer returned in refname should later be freed + * by the caller. + */ +HWLOC_DECLSPEC int hwloc_topology_diff_load_xmlbuffer(const char *xmlbuffer, int buflen, hwloc_topology_diff_t *diff, char **refname); + +/** \brief Export a list of topology differences to a XML buffer. + * + * If not \c NULL, \p refname defines an identifier string + * for the reference topology which was used as a base when + * computing this difference. + * This identifier is usually the name of the other XML file + * that contains the reference topology. + * This attribute is given back when reading the diff from XML. + * + * The returned buffer ends with a \0 that is included in the returned + * length. + * + * \note The XML buffer should later be freed with hwloc_free_xmlbuffer(). + */ +HWLOC_DECLSPEC int hwloc_topology_diff_export_xmlbuffer(hwloc_topology_diff_t diff, const char *refname, char **xmlbuffer, int *buflen); + +/** @} */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_DIFF_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/distances.h b/deps/exla/cache/xla_extension/include/include/hwloc/distances.h new file mode 100644 index 0000000000000000000000000000000000000000..44cd7ea1fa2a2582d2ec585c4b6b987b63317d22 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/distances.h @@ -0,0 +1,471 @@ +/* + * Copyright © 2010-2021 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief Object distances. + */ + +#ifndef HWLOC_DISTANCES_H +#define HWLOC_DISTANCES_H + +#ifndef HWLOC_H +#error Please include the main hwloc.h instead +#endif + + +#ifdef __cplusplus +extern "C" { +#elif 0 +} +#endif + + +/** \defgroup hwlocality_distances_get Retrieve distances between objects + * @{ + */ + +/** \brief Matrix of distances between a set of objects. + * + * This matrix often contains latencies between NUMA nodes + * (as reported in the System Locality Distance Information Table (SLIT) + * in the ACPI specification), which may or may not be physically accurate. + * It corresponds to the latency for accessing the memory of one node + * from a core in another node. + * The corresponding kind is ::HWLOC_DISTANCES_KIND_FROM_OS | ::HWLOC_DISTANCES_KIND_FROM_USER. + * The name of this distances structure is "NUMALatency". + * Others distance structures include and "XGMIBandwidth", "XGMIHops" + * and "NVLinkBandwidth". + * + * The matrix may also contain bandwidths between random sets of objects, + * possibly provided by the user, as specified in the \p kind attribute. + * + * Pointers \p objs and \p values should not be replaced, reallocated, freed, etc. + * However callers are allowed to modify \p kind as well as the contents + * of \p objs and \p values arrays. + * For instance, if there is a single NUMA node per Package, + * hwloc_get_obj_with_same_locality() may be used to convert between them + * and replace NUMA nodes in the \p objs array with the corresponding Packages. + * See also hwloc_distances_transform() for applying some transformations + * to the structure. + */ +struct hwloc_distances_s { + unsigned nbobjs; /**< \brief Number of objects described by the distance matrix. */ + hwloc_obj_t *objs; /**< \brief Array of objects described by the distance matrix. + * These objects are not in any particular order, + * see hwloc_distances_obj_index() and hwloc_distances_obj_pair_values() + * for easy ways to find objects in this array and their corresponding values. + */ + unsigned long kind; /**< \brief OR'ed set of ::hwloc_distances_kind_e. */ + hwloc_uint64_t *values; /**< \brief Matrix of distances between objects, stored as a one-dimension array. + * + * Distance from i-th to j-th object is stored in slot i*nbobjs+j. + * The meaning of the value depends on the \p kind attribute. + */ +}; + +/** \brief Kinds of distance matrices. + * + * The \p kind attribute of struct hwloc_distances_s is a OR'ed set + * of kinds. + * + * A kind of format HWLOC_DISTANCES_KIND_FROM_* specifies where the + * distance information comes from, if known. + * + * A kind of format HWLOC_DISTANCES_KIND_MEANS_* specifies whether + * values are latencies or bandwidths, if applicable. + */ +enum hwloc_distances_kind_e { + /** \brief These distances were obtained from the operating system or hardware. + * \hideinitializer + */ + HWLOC_DISTANCES_KIND_FROM_OS = (1UL<<0), + /** \brief These distances were provided by the user. + * \hideinitializer + */ + HWLOC_DISTANCES_KIND_FROM_USER = (1UL<<1), + + /** \brief Distance values are similar to latencies between objects. + * Values are smaller for closer objects, hence minimal on the diagonal + * of the matrix (distance between an object and itself). + * It could also be the number of network hops between objects, etc. + * \hideinitializer + */ + HWLOC_DISTANCES_KIND_MEANS_LATENCY = (1UL<<2), + /** \brief Distance values are similar to bandwidths between objects. + * Values are higher for closer objects, hence maximal on the diagonal + * of the matrix (distance between an object and itself). + * Such values are currently ignored for distance-based grouping. + * \hideinitializer + */ + HWLOC_DISTANCES_KIND_MEANS_BANDWIDTH = (1UL<<3), + + /** \brief This distances structure covers objects of different types. + * This may apply to the "NVLinkBandwidth" structure in presence + * of a NVSwitch or POWER processor NVLink port. + * \hideinitializer + */ + HWLOC_DISTANCES_KIND_HETEROGENEOUS_TYPES = (1UL<<4) +}; + +/** \brief Retrieve distance matrices. + * + * Retrieve distance matrices from the topology into the \p distances array. + * + * \p flags is currently unused, should be \c 0. + * + * \p kind serves as a filter. If \c 0, all distance matrices are returned. + * If it contains some HWLOC_DISTANCES_KIND_FROM_*, only distance matrices + * whose kind matches one of these are returned. + * If it contains some HWLOC_DISTANCES_KIND_MEANS_*, only distance matrices + * whose kind matches one of these are returned. + * + * On input, \p nr points to the number of distance matrices that may be stored + * in \p distances. + * On output, \p nr points to the number of distance matrices that were actually + * found, even if some of them couldn't be stored in \p distances. + * Distance matrices that couldn't be stored are ignored, but the function still + * returns success (\c 0). The caller may find out by comparing the value pointed + * by \p nr before and after the function call. + * + * Each distance matrix returned in the \p distances array should be released + * by the caller using hwloc_distances_release(). + */ +HWLOC_DECLSPEC int +hwloc_distances_get(hwloc_topology_t topology, + unsigned *nr, struct hwloc_distances_s **distances, + unsigned long kind, unsigned long flags); + +/** \brief Retrieve distance matrices for object at a specific depth in the topology. + * + * Identical to hwloc_distances_get() with the additional \p depth filter. + */ +HWLOC_DECLSPEC int +hwloc_distances_get_by_depth(hwloc_topology_t topology, int depth, + unsigned *nr, struct hwloc_distances_s **distances, + unsigned long kind, unsigned long flags); + +/** \brief Retrieve distance matrices for object of a specific type. + * + * Identical to hwloc_distances_get() with the additional \p type filter. + */ +HWLOC_DECLSPEC int +hwloc_distances_get_by_type(hwloc_topology_t topology, hwloc_obj_type_t type, + unsigned *nr, struct hwloc_distances_s **distances, + unsigned long kind, unsigned long flags); + +/** \brief Retrieve a distance matrix with the given name. + * + * Usually only one distances structure may match a given name. + * + * The name of the most common structure is "NUMALatency". + * Others include "XGMIBandwidth", "XGMIHops" and "NVLinkBandwidth". + */ +HWLOC_DECLSPEC int +hwloc_distances_get_by_name(hwloc_topology_t topology, const char *name, + unsigned *nr, struct hwloc_distances_s **distances, + unsigned long flags); + +/** \brief Get a description of what a distances structure contains. + * + * For instance "NUMALatency" for hardware-provided NUMA distances (ACPI SLIT), + * or NULL if unknown. + */ +HWLOC_DECLSPEC const char * +hwloc_distances_get_name(hwloc_topology_t topology, struct hwloc_distances_s *distances); + +/** \brief Release a distance matrix structure previously returned by hwloc_distances_get(). + * + * \note This function is not required if the structure is removed with hwloc_distances_release_remove(). + */ +HWLOC_DECLSPEC void +hwloc_distances_release(hwloc_topology_t topology, struct hwloc_distances_s *distances); + +/** \brief Transformations of distances structures. */ +enum hwloc_distances_transform_e { + /** \brief Remove \c NULL objects from the distances structure. + * + * Every object that was replaced with \c NULL in the \p objs array + * is removed and the \p values array is updated accordingly. + * + * At least \c 2 objects must remain, otherwise hwloc_distances_transform() + * will return \c -1 with \p errno set to \c EINVAL. + * + * \p kind will be updated with or without ::HWLOC_DISTANCES_KIND_HETEROGENEOUS_TYPES + * according to the remaining objects. + * + * \hideinitializer + */ + HWLOC_DISTANCES_TRANSFORM_REMOVE_NULL = 0, + + /** \brief Replace bandwidth values with a number of links. + * + * Usually all values will be either \c 0 (no link) or \c 1 (one link). + * However some matrices could get larger values if some pairs of + * peers are connected by different numbers of links. + * + * Values on the diagonal are set to \c 0. + * + * This transformation only applies to bandwidth matrices. + * + * \hideinitializer + */ + HWLOC_DISTANCES_TRANSFORM_LINKS = 1, + + /** \brief Merge switches with multiple ports into a single object. + * This currently only applies to NVSwitches where GPUs seem connected to different + * separate switch ports in the NVLinkBandwidth matrix. This transformation will + * replace all of them with the same port connected to all GPUs. + * Other ports are removed by applying ::HWLOC_DISTANCES_TRANSFORM_REMOVE_NULL internally. + * \hideinitializer + */ + HWLOC_DISTANCES_TRANSFORM_MERGE_SWITCH_PORTS = 2, + + /** \brief Apply a transitive closure to the matrix to connect objects across switches. + * This currently only applies to GPUs and NVSwitches in the NVLinkBandwidth matrix. + * All pairs of GPUs will be reported as directly connected. + * \hideinitializer + */ + HWLOC_DISTANCES_TRANSFORM_TRANSITIVE_CLOSURE = 3 +}; + +/** \brief Apply a transformation to a distances structure. + * + * Modify a distances structure that was previously obtained with + * hwloc_distances_get() or one of its variants. + * + * This modifies the local copy of the distances structures but does + * not modify the distances information stored inside the topology + * (retrieved by another call to hwloc_distances_get() or exported to XML). + * To do so, one should add a new distances structure with same + * name, kind, objects and values (see \ref hwlocality_distances_add) + * and then remove this old one with hwloc_distances_release_remove(). + * + * \p transform must be one of the transformations listed + * in ::hwloc_distances_transform_e. + * + * These transformations may modify the contents of the \p objs or \p values arrays. + * + * \p transform_attr must be \c NULL for now. + * + * \p flags must be \c 0 for now. + * + * \note Objects in distances array \p objs may be directly modified + * in place without using hwloc_distances_transform(). + * One may use hwloc_get_obj_with_same_locality() to easily convert + * between similar objects of different types. + */ +HWLOC_DECLSPEC int hwloc_distances_transform(hwloc_topology_t topology, struct hwloc_distances_s *distances, + enum hwloc_distances_transform_e transform, + void *transform_attr, + unsigned long flags); + +/** @} */ + + + +/** \defgroup hwlocality_distances_consult Helpers for consulting distance matrices + * @{ + */ + +/** \brief Find the index of an object in a distances structure. + * + * \return -1 if object \p obj is not involved in structure \p distances. + */ +static __hwloc_inline int +hwloc_distances_obj_index(struct hwloc_distances_s *distances, hwloc_obj_t obj) +{ + unsigned i; + for(i=0; inbobjs; i++) + if (distances->objs[i] == obj) + return (int)i; + return -1; +} + +/** \brief Find the values between two objects in a distance matrices. + * + * The distance from \p obj1 to \p obj2 is stored in the value pointed by + * \p value1to2 and reciprocally. + * + * \return -1 if object \p obj1 or \p obj2 is not involved in structure \p distances. + */ +static __hwloc_inline int +hwloc_distances_obj_pair_values(struct hwloc_distances_s *distances, + hwloc_obj_t obj1, hwloc_obj_t obj2, + hwloc_uint64_t *value1to2, hwloc_uint64_t *value2to1) +{ + int i1 = hwloc_distances_obj_index(distances, obj1); + int i2 = hwloc_distances_obj_index(distances, obj2); + if (i1 < 0 || i2 < 0) + return -1; + *value1to2 = distances->values[i1 * distances->nbobjs + i2]; + *value2to1 = distances->values[i2 * distances->nbobjs + i1]; + return 0; +} + +/** @} */ + + + +/** \defgroup hwlocality_distances_add Add distances between objects + * + * The usual way to add distances is: + * \code + * hwloc_distances_add_handle_t handle; + * int err = -1; + * handle = hwloc_distances_add_create(topology, "name", kind, 0); + * if (handle) { + * err = hwloc_distances_add_values(topology, handle, nbobjs, objs, values, 0); + * if (!err) + * err = hwloc_distances_add_commit(topology, handle, flags); + * } + * \endcode + * If \p err is \c 0 at the end, then addition was successful. + * + * @{ + */ + +/** \brief Handle to a new distances structure during its addition to the topology. */ +typedef void * hwloc_distances_add_handle_t; + +/** \brief Create a new empty distances structure. + * + * Create an empty distances structure + * to be filled with hwloc_distances_add_values() + * and then committed with hwloc_distances_add_commit(). + * + * Parameter \p name is optional, it may be \c NULL. + * Otherwise, it will be copied internally and may later be freed by the caller. + * + * \p kind specifies the kind of distance as a OR'ed set of ::hwloc_distances_kind_e. + * Kind ::HWLOC_DISTANCES_KIND_HETEROGENEOUS_TYPES will be automatically set + * according to objects having different types in hwloc_distances_add_values(). + * + * \p flags must be \c 0 for now. + * + * \return A hwloc_distances_add_handle_t that should then be passed + * to hwloc_distances_add_values() and hwloc_distances_add_commit(). + * + * \return \c NULL on error. + */ +HWLOC_DECLSPEC hwloc_distances_add_handle_t +hwloc_distances_add_create(hwloc_topology_t topology, + const char *name, unsigned long kind, + unsigned long flags); + +/** \brief Specify the objects and values in a new empty distances structure. + * + * Specify the objects and values for a new distances structure + * that was returned as a handle by hwloc_distances_add_create(). + * The structure must then be committed with hwloc_distances_add_commit(). + * + * The number of objects is \p nbobjs and the array of objects is \p objs. + * Distance values are stored as a one-dimension array in \p values. + * The distance from object i to object j is in slot i*nbobjs+j. + * + * \p nbobjs must be at least 2. + * + * Arrays \p objs and \p values will be copied internally, + * they may later be freed by the caller. + * + * On error, the temporary distances structure and its content are destroyed. + * + * \p flags must be \c 0 for now. + * + * \return \c 0 on success. + * \return \c -1 on error. + */ +HWLOC_DECLSPEC int hwloc_distances_add_values(hwloc_topology_t topology, + hwloc_distances_add_handle_t handle, + unsigned nbobjs, hwloc_obj_t *objs, + hwloc_uint64_t *values, + unsigned long flags); + +/** \brief Flags for adding a new distances to a topology. */ +enum hwloc_distances_add_flag_e { + /** \brief Try to group objects based on the newly provided distance information. + * This is ignored for distances between objects of different types. + * \hideinitializer + */ + HWLOC_DISTANCES_ADD_FLAG_GROUP = (1UL<<0), + /** \brief If grouping, consider the distance values as inaccurate and relax the + * comparisons during the grouping algorithms. The actual accuracy may be modified + * through the HWLOC_GROUPING_ACCURACY environment variable (see \ref envvar). + * \hideinitializer + */ + HWLOC_DISTANCES_ADD_FLAG_GROUP_INACCURATE = (1UL<<1) +}; + +/** \brief Commit a new distances structure. + * + * This function finalizes the distances structure and inserts in it the topology. + * + * Parameter \p handle was previously returned by hwloc_distances_add_create(). + * Then objects and values were specified with hwloc_distances_add_values(). + * + * \p flags configures the behavior of the function using an optional OR'ed set of + * ::hwloc_distances_add_flag_e. + * It may be used to request the grouping of existing objects based on distances. + * + * On error, the temporary distances structure and its content are destroyed. + * + * \return \c 0 on success. + * \return \c -1 on error. + */ +HWLOC_DECLSPEC int hwloc_distances_add_commit(hwloc_topology_t topology, + hwloc_distances_add_handle_t handle, + unsigned long flags); + +/** @} */ + + + +/** \defgroup hwlocality_distances_remove Remove distances between objects + * @{ + */ + +/** \brief Remove all distance matrices from a topology. + * + * Remove all distance matrices, either provided by the user or + * gathered through the OS. + * + * If these distances were used to group objects, these additional + * Group objects are not removed from the topology. + */ +HWLOC_DECLSPEC int hwloc_distances_remove(hwloc_topology_t topology); + +/** \brief Remove distance matrices for objects at a specific depth in the topology. + * + * Identical to hwloc_distances_remove() but only applies to one level of the topology. + */ +HWLOC_DECLSPEC int hwloc_distances_remove_by_depth(hwloc_topology_t topology, int depth); + +/** \brief Remove distance matrices for objects of a specific type in the topology. + * + * Identical to hwloc_distances_remove() but only applies to one level of the topology. + */ +static __hwloc_inline int +hwloc_distances_remove_by_type(hwloc_topology_t topology, hwloc_obj_type_t type) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN || depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return 0; + return hwloc_distances_remove_by_depth(topology, depth); +} + +/** \brief Release and remove the given distance matrice from the topology. + * + * This function includes a call to hwloc_distances_release(). + */ +HWLOC_DECLSPEC int hwloc_distances_release_remove(hwloc_topology_t topology, struct hwloc_distances_s *distances); + +/** @} */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_DISTANCES_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/export.h b/deps/exla/cache/xla_extension/include/include/hwloc/export.h new file mode 100644 index 0000000000000000000000000000000000000000..b178b77e52488c27c0431ce21ebd5094403e57e5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/export.h @@ -0,0 +1,278 @@ +/* + * Copyright © 2009-2018 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief Exporting Topologies to XML or to Synthetic strings. + */ + +#ifndef HWLOC_EXPORT_H +#define HWLOC_EXPORT_H + +#ifndef HWLOC_H +#error Please include the main hwloc.h instead +#endif + + +#ifdef __cplusplus +extern "C" { +#elif 0 +} +#endif + + +/** \defgroup hwlocality_xmlexport Exporting Topologies to XML + * @{ + */ + +/** \brief Flags for exporting XML topologies. + * + * Flags to be given as a OR'ed set to hwloc_topology_export_xml(). + */ +enum hwloc_topology_export_xml_flags_e { + /** \brief Export XML that is loadable by hwloc v1.x. + * However, the export may miss some details about the topology. + * \hideinitializer + */ + HWLOC_TOPOLOGY_EXPORT_XML_FLAG_V1 = (1UL<<0) +}; + +/** \brief Export the topology into an XML file. + * + * This file may be loaded later through hwloc_topology_set_xml(). + * + * By default, the latest export format is used, which means older hwloc + * releases (e.g. v1.x) will not be able to import it. + * Exporting to v1.x specific XML format is possible using flag + * ::HWLOC_TOPOLOGY_EXPORT_XML_FLAG_V1 but it may miss some details + * about the topology. + * If there is any chance that the exported file may ever be imported + * back by a process using hwloc 1.x, one should consider detecting + * it at runtime and using the corresponding export format. + * + * \p flags is a OR'ed set of ::hwloc_topology_export_xml_flags_e. + * + * \return -1 if a failure occured. + * + * \note See also hwloc_topology_set_userdata_export_callback() + * for exporting application-specific object userdata. + * + * \note The topology-specific userdata pointer is ignored when exporting to XML. + * + * \note Only printable characters may be exported to XML string attributes. + * Any other character, especially any non-ASCII character, will be silently + * dropped. + * + * \note If \p name is "-", the XML output is sent to the standard output. + */ +HWLOC_DECLSPEC int hwloc_topology_export_xml(hwloc_topology_t topology, const char *xmlpath, unsigned long flags); + +/** \brief Export the topology into a newly-allocated XML memory buffer. + * + * \p xmlbuffer is allocated by the callee and should be freed with + * hwloc_free_xmlbuffer() later in the caller. + * + * This memory buffer may be loaded later through hwloc_topology_set_xmlbuffer(). + * + * By default, the latest export format is used, which means older hwloc + * releases (e.g. v1.x) will not be able to import it. + * Exporting to v1.x specific XML format is possible using flag + * ::HWLOC_TOPOLOGY_EXPORT_XML_FLAG_V1 but it may miss some details + * about the topology. + * If there is any chance that the exported buffer may ever be imported + * back by a process using hwloc 1.x, one should consider detecting + * it at runtime and using the corresponding export format. + * + * The returned buffer ends with a \0 that is included in the returned + * length. + * + * \p flags is a OR'ed set of ::hwloc_topology_export_xml_flags_e. + * + * \return -1 if a failure occured. + * + * \note See also hwloc_topology_set_userdata_export_callback() + * for exporting application-specific object userdata. + * + * \note The topology-specific userdata pointer is ignored when exporting to XML. + * + * \note Only printable characters may be exported to XML string attributes. + * Any other character, especially any non-ASCII character, will be silently + * dropped. + */ +HWLOC_DECLSPEC int hwloc_topology_export_xmlbuffer(hwloc_topology_t topology, char **xmlbuffer, int *buflen, unsigned long flags); + +/** \brief Free a buffer allocated by hwloc_topology_export_xmlbuffer() */ +HWLOC_DECLSPEC void hwloc_free_xmlbuffer(hwloc_topology_t topology, char *xmlbuffer); + +/** \brief Set the application-specific callback for exporting object userdata + * + * The object userdata pointer is not exported to XML by default because hwloc + * does not know what it contains. + * + * This function lets applications set \p export_cb to a callback function + * that converts this opaque userdata into an exportable string. + * + * \p export_cb is invoked during XML export for each object whose + * \p userdata pointer is not \c NULL. + * The callback should use hwloc_export_obj_userdata() or + * hwloc_export_obj_userdata_base64() to actually export + * something to XML (possibly multiple times per object). + * + * \p export_cb may be set to \c NULL if userdata should not be exported to XML. + * + * \note The topology-specific userdata pointer is ignored when exporting to XML. + */ +HWLOC_DECLSPEC void hwloc_topology_set_userdata_export_callback(hwloc_topology_t topology, + void (*export_cb)(void *reserved, hwloc_topology_t topology, hwloc_obj_t obj)); + +/** \brief Export some object userdata to XML + * + * This function may only be called from within the export() callback passed + * to hwloc_topology_set_userdata_export_callback(). + * It may be invoked one of multiple times to export some userdata to XML. + * The \p buffer content of length \p length is stored with optional name + * \p name. + * + * When importing this XML file, the import() callback (if set) will be + * called exactly as many times as hwloc_export_obj_userdata() was called + * during export(). It will receive the corresponding \p name, \p buffer + * and \p length arguments. + * + * \p reserved, \p topology and \p obj must be the first three parameters + * that were given to the export callback. + * + * Only printable characters may be exported to XML string attributes. + * If a non-printable character is passed in \p name or \p buffer, + * the function returns -1 with errno set to EINVAL. + * + * If exporting binary data, the application should first encode into + * printable characters only (or use hwloc_export_obj_userdata_base64()). + * It should also take care of portability issues if the export may + * be reimported on a different architecture. + */ +HWLOC_DECLSPEC int hwloc_export_obj_userdata(void *reserved, hwloc_topology_t topology, hwloc_obj_t obj, const char *name, const void *buffer, size_t length); + +/** \brief Encode and export some object userdata to XML + * + * This function is similar to hwloc_export_obj_userdata() but it encodes + * the input buffer into printable characters before exporting. + * On import, decoding is automatically performed before the data is given + * to the import() callback if any. + * + * This function may only be called from within the export() callback passed + * to hwloc_topology_set_userdata_export_callback(). + * + * The function does not take care of portability issues if the export + * may be reimported on a different architecture. + */ +HWLOC_DECLSPEC int hwloc_export_obj_userdata_base64(void *reserved, hwloc_topology_t topology, hwloc_obj_t obj, const char *name, const void *buffer, size_t length); + +/** \brief Set the application-specific callback for importing userdata + * + * On XML import, userdata is ignored by default because hwloc does not know + * how to store it in memory. + * + * This function lets applications set \p import_cb to a callback function + * that will get the XML-stored userdata and store it in the object as expected + * by the application. + * + * \p import_cb is called during hwloc_topology_load() as many times as + * hwloc_export_obj_userdata() was called during export. The topology + * is not entirely setup yet. Object attributes are ready to consult, + * but links between objects are not. + * + * \p import_cb may be \c NULL if userdata should be ignored during import. + * + * \note \p buffer contains \p length characters followed by a null byte ('\0'). + * + * \note This function should be called before hwloc_topology_load(). + * + * \note The topology-specific userdata pointer is ignored when importing from XML. + */ +HWLOC_DECLSPEC void hwloc_topology_set_userdata_import_callback(hwloc_topology_t topology, + void (*import_cb)(hwloc_topology_t topology, hwloc_obj_t obj, const char *name, const void *buffer, size_t length)); + +/** @} */ + + +/** \defgroup hwlocality_syntheticexport Exporting Topologies to Synthetic + * @{ + */ + +/** \brief Flags for exporting synthetic topologies. + * + * Flags to be given as a OR'ed set to hwloc_topology_export_synthetic(). + */ +enum hwloc_topology_export_synthetic_flags_e { + /** \brief Export extended types such as L2dcache as basic types such as Cache. + * + * This is required if loading the synthetic description with hwloc < 1.9. + * \hideinitializer + */ + HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_NO_EXTENDED_TYPES = (1UL<<0), + + /** \brief Do not export level attributes. + * + * Ignore level attributes such as memory/cache sizes or PU indexes. + * This is required if loading the synthetic description with hwloc < 1.10. + * \hideinitializer + */ + HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_NO_ATTRS = (1UL<<1), + + /** \brief Export the memory hierarchy as expected in hwloc 1.x. + * + * Instead of attaching memory children to levels, export single NUMA node child + * as normal intermediate levels, when possible. + * This is required if loading the synthetic description with hwloc 1.x. + * However this may fail if some objects have multiple local NUMA nodes. + * \hideinitializer + */ + HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_V1 = (1UL<<2), + + /** \brief Do not export memory information. + * + * Only export the actual hierarchy of normal CPU-side objects and ignore + * where memory is attached. + * This is useful for when the hierarchy of CPUs is what really matters, + * but it behaves as if there was a single machine-wide NUMA node. + * \hideinitializer + */ + HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_IGNORE_MEMORY = (1UL<<3) +}; + +/** \brief Export the topology as a synthetic string. + * + * At most \p buflen characters will be written in \p buffer, + * including the terminating \0. + * + * This exported string may be given back to hwloc_topology_set_synthetic(). + * + * \p flags is a OR'ed set of ::hwloc_topology_export_synthetic_flags_e. + * + * \return The number of characters that were written, + * not including the terminating \0. + * + * \return -1 if the topology could not be exported, + * for instance if it is not symmetric. + * + * \note I/O and Misc children are ignored, the synthetic string only + * describes normal children. + * + * \note A 1024-byte buffer should be large enough for exporting + * topologies in the vast majority of cases. + */ + HWLOC_DECLSPEC int hwloc_topology_export_synthetic(hwloc_topology_t topology, char *buffer, size_t buflen, unsigned long flags); + +/** @} */ + + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_EXPORT_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/helper.h b/deps/exla/cache/xla_extension/include/include/hwloc/helper.h new file mode 100644 index 0000000000000000000000000000000000000000..f918d8163dd3629714033d5ee0101e8baba93709 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/helper.h @@ -0,0 +1,1231 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2021 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2010 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief High-level hwloc traversal helpers. + */ + +#ifndef HWLOC_HELPER_H +#define HWLOC_HELPER_H + +#ifndef HWLOC_H +#error Please include the main hwloc.h instead +#endif + +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \defgroup hwlocality_helper_find_inside Finding Objects inside a CPU set + * @{ + */ + +/** \brief Get the first largest object included in the given cpuset \p set. + * + * \return the first object that is included in \p set and whose parent is not. + * + * This is convenient for iterating over all largest objects within a CPU set + * by doing a loop getting the first largest object and clearing its CPU set + * from the remaining CPU set. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_first_largest_obj_inside_cpuset(hwloc_topology_t topology, hwloc_const_cpuset_t set) +{ + hwloc_obj_t obj = hwloc_get_root_obj(topology); + if (!hwloc_bitmap_intersects(obj->cpuset, set)) + return NULL; + while (!hwloc_bitmap_isincluded(obj->cpuset, set)) { + /* while the object intersects without being included, look at its children */ + hwloc_obj_t child = obj->first_child; + while (child) { + if (hwloc_bitmap_intersects(child->cpuset, set)) + break; + child = child->next_sibling; + } + if (!child) + /* no child intersects, return their father */ + return obj; + /* found one intersecting child, look at its children */ + obj = child; + } + /* obj is included, return it */ + return obj; +} + +/** \brief Get the set of largest objects covering exactly a given cpuset \p set + * + * \return the number of objects returned in \p objs. + */ +HWLOC_DECLSPEC int hwloc_get_largest_objs_inside_cpuset (hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_t * __hwloc_restrict objs, int max); + +/** \brief Return the next object at depth \p depth included in CPU set \p set. + * + * If \p prev is \c NULL, return the first object at depth \p depth + * included in \p set. The next invokation should pass the previous + * return value in \p prev so as to obtain the next object in \p set. + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if objects at the given depth do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_inside_cpuset_by_depth (hwloc_topology_t topology, hwloc_const_cpuset_t set, + int depth, hwloc_obj_t prev) +{ + hwloc_obj_t next = hwloc_get_next_obj_by_depth(topology, depth, prev); + if (!next) + return NULL; + while (next && (hwloc_bitmap_iszero(next->cpuset) || !hwloc_bitmap_isincluded(next->cpuset, set))) + next = next->next_cousin; + return next; +} + +/** \brief Return the next object of type \p type included in CPU set \p set. + * + * If there are multiple or no depth for given type, return \c NULL + * and let the caller fallback to + * hwloc_get_next_obj_inside_cpuset_by_depth(). + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if objects of the given type do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_inside_cpuset_by_type (hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_type_t type, hwloc_obj_t prev) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN || depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return NULL; + return hwloc_get_next_obj_inside_cpuset_by_depth(topology, set, depth, prev); +} + +/** \brief Return the (logically) \p idx -th object at depth \p depth included in CPU set \p set. + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if objects at the given depth do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_inside_cpuset_by_depth (hwloc_topology_t topology, hwloc_const_cpuset_t set, + int depth, unsigned idx) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_inside_cpuset_by_depth (hwloc_topology_t topology, hwloc_const_cpuset_t set, + int depth, unsigned idx) +{ + hwloc_obj_t obj = hwloc_get_obj_by_depth (topology, depth, 0); + unsigned count = 0; + if (!obj) + return NULL; + while (obj) { + if (!hwloc_bitmap_iszero(obj->cpuset) && hwloc_bitmap_isincluded(obj->cpuset, set)) { + if (count == idx) + return obj; + count++; + } + obj = obj->next_cousin; + } + return NULL; +} + +/** \brief Return the \p idx -th object of type \p type included in CPU set \p set. + * + * If there are multiple or no depth for given type, return \c NULL + * and let the caller fallback to + * hwloc_get_obj_inside_cpuset_by_depth(). + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if objects of the given type do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_inside_cpuset_by_type (hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_type_t type, unsigned idx) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_inside_cpuset_by_type (hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_type_t type, unsigned idx) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN || depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return NULL; + return hwloc_get_obj_inside_cpuset_by_depth(topology, set, depth, idx); +} + +/** \brief Return the number of objects at depth \p depth included in CPU set \p set. + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if objects at the given depth do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline unsigned +hwloc_get_nbobjs_inside_cpuset_by_depth (hwloc_topology_t topology, hwloc_const_cpuset_t set, + int depth) __hwloc_attribute_pure; +static __hwloc_inline unsigned +hwloc_get_nbobjs_inside_cpuset_by_depth (hwloc_topology_t topology, hwloc_const_cpuset_t set, + int depth) +{ + hwloc_obj_t obj = hwloc_get_obj_by_depth (topology, depth, 0); + unsigned count = 0; + if (!obj) + return 0; + while (obj) { + if (!hwloc_bitmap_iszero(obj->cpuset) && hwloc_bitmap_isincluded(obj->cpuset, set)) + count++; + obj = obj->next_cousin; + } + return count; +} + +/** \brief Return the number of objects of type \p type included in CPU set \p set. + * + * If no object for that type exists inside CPU set \p set, 0 is + * returned. If there are several levels with objects of that type + * inside CPU set \p set, -1 is returned. + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if objects of the given type do + * not have CPU sets (I/O objects). + */ +static __hwloc_inline int +hwloc_get_nbobjs_inside_cpuset_by_type (hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_type_t type) __hwloc_attribute_pure; +static __hwloc_inline int +hwloc_get_nbobjs_inside_cpuset_by_type (hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_type_t type) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN) + return 0; + if (depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return -1; /* FIXME: agregate nbobjs from different levels? */ + return (int) hwloc_get_nbobjs_inside_cpuset_by_depth(topology, set, depth); +} + +/** \brief Return the logical index among the objects included in CPU set \p set. + * + * Consult all objects in the same level as \p obj and inside CPU set \p set + * in the logical order, and return the index of \p obj within them. + * If \p set covers the entire topology, this is the logical index of \p obj. + * Otherwise, this is similar to a logical index within the part of the topology + * defined by CPU set \p set. + * + * \note Objects with empty CPU sets are ignored + * (otherwise they would be considered included in any given set). + * + * \note This function cannot work if obj does not have CPU sets (I/O objects). + */ +static __hwloc_inline int +hwloc_get_obj_index_inside_cpuset (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_const_cpuset_t set, + hwloc_obj_t obj) __hwloc_attribute_pure; +static __hwloc_inline int +hwloc_get_obj_index_inside_cpuset (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_const_cpuset_t set, + hwloc_obj_t obj) +{ + int idx = 0; + if (!hwloc_bitmap_isincluded(obj->cpuset, set)) + return -1; + /* count how many objects are inside the cpuset on the way from us to the beginning of the level */ + while ((obj = obj->prev_cousin) != NULL) + if (!hwloc_bitmap_iszero(obj->cpuset) && hwloc_bitmap_isincluded(obj->cpuset, set)) + idx++; + return idx; +} + +/** @} */ + + + +/** \defgroup hwlocality_helper_find_covering Finding Objects covering at least CPU set + * @{ + */ + +/** \brief Get the child covering at least CPU set \p set. + * + * \return \c NULL if no child matches or if \p set is empty. + * + * \note This function cannot work if parent does not have a CPU set (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_child_covering_cpuset (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_const_cpuset_t set, + hwloc_obj_t parent) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_child_covering_cpuset (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_const_cpuset_t set, + hwloc_obj_t parent) +{ + hwloc_obj_t child; + if (hwloc_bitmap_iszero(set)) + return NULL; + child = parent->first_child; + while (child) { + if (child->cpuset && hwloc_bitmap_isincluded(set, child->cpuset)) + return child; + child = child->next_sibling; + } + return NULL; +} + +/** \brief Get the lowest object covering at least CPU set \p set + * + * \return \c NULL if no object matches or if \p set is empty. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_covering_cpuset (hwloc_topology_t topology, hwloc_const_cpuset_t set) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_covering_cpuset (hwloc_topology_t topology, hwloc_const_cpuset_t set) +{ + struct hwloc_obj *current = hwloc_get_root_obj(topology); + if (hwloc_bitmap_iszero(set) || !hwloc_bitmap_isincluded(set, current->cpuset)) + return NULL; + while (1) { + hwloc_obj_t child = hwloc_get_child_covering_cpuset(topology, set, current); + if (!child) + return current; + current = child; + } +} + +/** \brief Iterate through same-depth objects covering at least CPU set \p set + * + * If object \p prev is \c NULL, return the first object at depth \p + * depth covering at least part of CPU set \p set. The next + * invokation should pass the previous return value in \p prev so as + * to obtain the next object covering at least another part of \p set. + * + * \note This function cannot work if objects at the given depth do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_covering_cpuset_by_depth(hwloc_topology_t topology, hwloc_const_cpuset_t set, + int depth, hwloc_obj_t prev) +{ + hwloc_obj_t next = hwloc_get_next_obj_by_depth(topology, depth, prev); + if (!next) + return NULL; + while (next && !hwloc_bitmap_intersects(set, next->cpuset)) + next = next->next_cousin; + return next; +} + +/** \brief Iterate through same-type objects covering at least CPU set \p set + * + * If object \p prev is \c NULL, return the first object of type \p + * type covering at least part of CPU set \p set. The next invokation + * should pass the previous return value in \p prev so as to obtain + * the next object of type \p type covering at least another part of + * \p set. + * + * If there are no or multiple depths for type \p type, \c NULL is returned. + * The caller may fallback to hwloc_get_next_obj_covering_cpuset_by_depth() + * for each depth. + * + * \note This function cannot work if objects of the given type do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_covering_cpuset_by_type(hwloc_topology_t topology, hwloc_const_cpuset_t set, + hwloc_obj_type_t type, hwloc_obj_t prev) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN || depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return NULL; + return hwloc_get_next_obj_covering_cpuset_by_depth(topology, set, depth, prev); +} + +/** @} */ + + + +/** \defgroup hwlocality_helper_ancestors Looking at Ancestor and Child Objects + * @{ + * + * Be sure to see the figure in \ref termsanddefs that shows a + * complete topology tree, including depths, child/sibling/cousin + * relationships, and an example of an asymmetric topology where one + * package has fewer caches than its peers. + */ + +/** \brief Returns the ancestor object of \p obj at depth \p depth. + * + * \note \p depth should not be the depth of PU or NUMA objects + * since they are ancestors of no objects (except Misc or I/O). + * This function rather expects an intermediate level depth, + * such as the depth of Packages, Cores, or Caches. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_ancestor_obj_by_depth (hwloc_topology_t topology __hwloc_attribute_unused, int depth, hwloc_obj_t obj) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_ancestor_obj_by_depth (hwloc_topology_t topology __hwloc_attribute_unused, int depth, hwloc_obj_t obj) +{ + hwloc_obj_t ancestor = obj; + if (obj->depth < depth) + return NULL; + while (ancestor && ancestor->depth > depth) + ancestor = ancestor->parent; + return ancestor; +} + +/** \brief Returns the ancestor object of \p obj with type \p type. + * + * \note \p type should not be ::HWLOC_OBJ_PU or ::HWLOC_OBJ_NUMANODE + * since these objects are ancestors of no objects (except Misc or I/O). + * This function rather expects an intermediate object type, + * such as ::HWLOC_OBJ_PACKAGE, ::HWLOC_OBJ_CORE, etc. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_ancestor_obj_by_type (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_type_t type, hwloc_obj_t obj) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_ancestor_obj_by_type (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_type_t type, hwloc_obj_t obj) +{ + hwloc_obj_t ancestor = obj->parent; + while (ancestor && ancestor->type != type) + ancestor = ancestor->parent; + return ancestor; +} + +/** \brief Returns the common parent object to objects \p obj1 and \p obj2 */ +static __hwloc_inline hwloc_obj_t +hwloc_get_common_ancestor_obj (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t obj1, hwloc_obj_t obj2) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_common_ancestor_obj (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t obj1, hwloc_obj_t obj2) +{ + /* the loop isn't so easy since intermediate ancestors may have + * different depth, causing us to alternate between using obj1->parent + * and obj2->parent. Also, even if at some point we find ancestors of + * of the same depth, their ancestors may have different depth again. + */ + while (obj1 != obj2) { + while (obj1->depth > obj2->depth) + obj1 = obj1->parent; + while (obj2->depth > obj1->depth) + obj2 = obj2->parent; + if (obj1 != obj2 && obj1->depth == obj2->depth) { + obj1 = obj1->parent; + obj2 = obj2->parent; + } + } + return obj1; +} + +/** \brief Returns true if \p obj is inside the subtree beginning with ancestor object \p subtree_root. + * + * \note This function cannot work if \p obj and \p subtree_root objects do + * not have CPU sets (I/O or Misc objects). + */ +static __hwloc_inline int +hwloc_obj_is_in_subtree (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t obj, hwloc_obj_t subtree_root) __hwloc_attribute_pure; +static __hwloc_inline int +hwloc_obj_is_in_subtree (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t obj, hwloc_obj_t subtree_root) +{ + return obj->cpuset && subtree_root->cpuset && hwloc_bitmap_isincluded(obj->cpuset, subtree_root->cpuset); +} + +/** \brief Return the next child. + * + * Return the next child among the normal children list, + * then among the memory children list, then among the I/O + * children list, then among the Misc children list. + * + * If \p prev is \c NULL, return the first child. + * + * Return \c NULL when there is no next child. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_child (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t parent, hwloc_obj_t prev) +{ + hwloc_obj_t obj; + int state = 0; + if (prev) { + if (prev->type == HWLOC_OBJ_MISC) + state = 3; + else if (prev->type == HWLOC_OBJ_BRIDGE || prev->type == HWLOC_OBJ_PCI_DEVICE || prev->type == HWLOC_OBJ_OS_DEVICE) + state = 2; + else if (prev->type == HWLOC_OBJ_NUMANODE) + state = 1; + obj = prev->next_sibling; + } else { + obj = parent->first_child; + } + if (!obj && state == 0) { + obj = parent->memory_first_child; + state = 1; + } + if (!obj && state == 1) { + obj = parent->io_first_child; + state = 2; + } + if (!obj && state == 2) { + obj = parent->misc_first_child; + state = 3; + } + return obj; +} + +/** @} */ + + + +/** \defgroup hwlocality_helper_types Kinds of object Type + * @{ + * + * Each object type is + * either Normal (i.e. hwloc_obj_type_is_normal() returns 1), + * or Memory (i.e. hwloc_obj_type_is_memory() returns 1) + * or I/O (i.e. hwloc_obj_type_is_io() returns 1) + * or Misc (i.e. equal to ::HWLOC_OBJ_MISC). + * It cannot be of more than one of these kinds. + */ + +/** \brief Check whether an object type is Normal. + * + * Normal objects are objects of the main CPU hierarchy + * (Machine, Package, Core, PU, CPU caches, etc.), + * but they are not NUMA nodes, I/O devices or Misc objects. + * + * They are attached to parent as Normal children, + * not as Memory, I/O or Misc children. + * + * \return 1 if an object of type \p type is a Normal object, 0 otherwise. + */ +HWLOC_DECLSPEC int +hwloc_obj_type_is_normal(hwloc_obj_type_t type); + +/** \brief Check whether an object type is I/O. + * + * I/O objects are objects attached to their parents + * in the I/O children list. + * This current includes Bridges, PCI and OS devices. + * + * \return 1 if an object of type \p type is a I/O object, 0 otherwise. + */ +HWLOC_DECLSPEC int +hwloc_obj_type_is_io(hwloc_obj_type_t type); + +/** \brief Check whether an object type is Memory. + * + * Memory objects are objects attached to their parents + * in the Memory children list. + * This current includes NUMA nodes and Memory-side caches. + * + * \return 1 if an object of type \p type is a Memory object, 0 otherwise. + */ +HWLOC_DECLSPEC int +hwloc_obj_type_is_memory(hwloc_obj_type_t type); + +/** \brief Check whether an object type is a CPU Cache (Data, Unified or Instruction). + * + * Memory-side caches are not CPU caches. + * + * \return 1 if an object of type \p type is a Cache, 0 otherwise. + */ +HWLOC_DECLSPEC int +hwloc_obj_type_is_cache(hwloc_obj_type_t type); + +/** \brief Check whether an object type is a CPU Data or Unified Cache. + * + * Memory-side caches are not CPU caches. + * + * \return 1 if an object of type \p type is a CPU Data or Unified Cache, 0 otherwise. + */ +HWLOC_DECLSPEC int +hwloc_obj_type_is_dcache(hwloc_obj_type_t type); + +/** \brief Check whether an object type is a CPU Instruction Cache, + * + * Memory-side caches are not CPU caches. + * + * \return 1 if an object of type \p type is a CPU Instruction Cache, 0 otherwise. + */ +HWLOC_DECLSPEC int +hwloc_obj_type_is_icache(hwloc_obj_type_t type); + +/** @} */ + + + +/** \defgroup hwlocality_helper_find_cache Looking at Cache Objects + * @{ + */ + +/** \brief Find the depth of cache objects matching cache level and type. + * + * Return the depth of the topology level that contains cache objects + * whose attributes match \p cachelevel and \p cachetype. + + * This function is identical to calling hwloc_get_type_depth() with the + * corresponding type such as ::HWLOC_OBJ_L1ICACHE, except that it may + * also return a Unified cache when looking for an instruction cache. + * + * If no cache level matches, ::HWLOC_TYPE_DEPTH_UNKNOWN is returned. + * + * If \p cachetype is ::HWLOC_OBJ_CACHE_UNIFIED, the depth of the + * unique matching unified cache level is returned. + * + * If \p cachetype is ::HWLOC_OBJ_CACHE_DATA or ::HWLOC_OBJ_CACHE_INSTRUCTION, + * either a matching cache, or a unified cache is returned. + * + * If \p cachetype is \c -1, it is ignored and multiple levels may + * match. The function returns either the depth of a uniquely matching + * level or ::HWLOC_TYPE_DEPTH_MULTIPLE. + */ +static __hwloc_inline int +hwloc_get_cache_type_depth (hwloc_topology_t topology, + unsigned cachelevel, hwloc_obj_cache_type_t cachetype) +{ + int depth; + int found = HWLOC_TYPE_DEPTH_UNKNOWN; + for (depth=0; ; depth++) { + hwloc_obj_t obj = hwloc_get_obj_by_depth(topology, depth, 0); + if (!obj) + break; + if (!hwloc_obj_type_is_dcache(obj->type) || obj->attr->cache.depth != cachelevel) + /* doesn't match, try next depth */ + continue; + if (cachetype == (hwloc_obj_cache_type_t) -1) { + if (found != HWLOC_TYPE_DEPTH_UNKNOWN) { + /* second match, return MULTIPLE */ + return HWLOC_TYPE_DEPTH_MULTIPLE; + } + /* first match, mark it as found */ + found = depth; + continue; + } + if (obj->attr->cache.type == cachetype || obj->attr->cache.type == HWLOC_OBJ_CACHE_UNIFIED) + /* exact match (either unified is alone, or we match instruction or data), return immediately */ + return depth; + } + /* went to the bottom, return what we found */ + return found; +} + +/** \brief Get the first data (or unified) cache covering a cpuset \p set + * + * \return \c NULL if no cache matches. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_cache_covering_cpuset (hwloc_topology_t topology, hwloc_const_cpuset_t set) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_cache_covering_cpuset (hwloc_topology_t topology, hwloc_const_cpuset_t set) +{ + hwloc_obj_t current = hwloc_get_obj_covering_cpuset(topology, set); + while (current) { + if (hwloc_obj_type_is_dcache(current->type)) + return current; + current = current->parent; + } + return NULL; +} + +/** \brief Get the first data (or unified) cache shared between an object and somebody else. + * + * \return \c NULL if no cache matches or if an invalid object is given. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_shared_cache_covering_obj (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t obj) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_shared_cache_covering_obj (hwloc_topology_t topology __hwloc_attribute_unused, hwloc_obj_t obj) +{ + hwloc_obj_t current = obj->parent; + if (!obj->cpuset) + return NULL; + while (current) { + if (!hwloc_bitmap_isequal(current->cpuset, obj->cpuset) + && hwloc_obj_type_is_dcache(current->type)) + return current; + current = current->parent; + } + return NULL; +} + +/** @} */ + + + +/** \defgroup hwlocality_helper_find_misc Finding objects, miscellaneous helpers + * @{ + * + * Be sure to see the figure in \ref termsanddefs that shows a + * complete topology tree, including depths, child/sibling/cousin + * relationships, and an example of an asymmetric topology where one + * package has fewer caches than its peers. + */ + +/** \brief Remove simultaneous multithreading PUs from a CPU set. + * + * For each core in \p topology, if \p cpuset contains some PUs of that core, + * modify \p cpuset to only keep a single PU for that core. + * + * \p which specifies which PU will be kept. + * PU are considered in physical index order. + * If 0, for each core, the function keeps the first PU that was originally set in \p cpuset. + * + * If \p which is larger than the number of PUs in a core there were originally set in \p cpuset, + * no PU is kept for that core. + * + * \note PUs that are not below a Core object are ignored + * (for instance if the topology does not contain any Core object). + * None of them is removed from \p cpuset. + */ +HWLOC_DECLSPEC int hwloc_bitmap_singlify_per_core(hwloc_topology_t topology, hwloc_bitmap_t cpuset, unsigned which); + +/** \brief Returns the object of type ::HWLOC_OBJ_PU with \p os_index. + * + * This function is useful for converting a CPU set into the PU + * objects it contains. + * When retrieving the current binding (e.g. with hwloc_get_cpubind()), + * one may iterate over the bits of the resulting CPU set with + * hwloc_bitmap_foreach_begin(), and find the corresponding PUs + * with this function. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_pu_obj_by_os_index(hwloc_topology_t topology, unsigned os_index) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_pu_obj_by_os_index(hwloc_topology_t topology, unsigned os_index) +{ + hwloc_obj_t obj = NULL; + while ((obj = hwloc_get_next_obj_by_type(topology, HWLOC_OBJ_PU, obj)) != NULL) + if (obj->os_index == os_index) + return obj; + return NULL; +} + +/** \brief Returns the object of type ::HWLOC_OBJ_NUMANODE with \p os_index. + * + * This function is useful for converting a nodeset into the NUMA node + * objects it contains. + * When retrieving the current binding (e.g. with hwloc_get_membind() with HWLOC_MEMBIND_BYNODESET), + * one may iterate over the bits of the resulting nodeset with + * hwloc_bitmap_foreach_begin(), and find the corresponding NUMA nodes + * with this function. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_numanode_obj_by_os_index(hwloc_topology_t topology, unsigned os_index) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_numanode_obj_by_os_index(hwloc_topology_t topology, unsigned os_index) +{ + hwloc_obj_t obj = NULL; + while ((obj = hwloc_get_next_obj_by_type(topology, HWLOC_OBJ_NUMANODE, obj)) != NULL) + if (obj->os_index == os_index) + return obj; + return NULL; +} + +/** \brief Do a depth-first traversal of the topology to find and sort + * + * all objects that are at the same depth than \p src. + * Report in \p objs up to \p max physically closest ones to \p src. + * + * \return the number of objects returned in \p objs. + * + * \return 0 if \p src is an I/O object. + * + * \note This function requires the \p src object to have a CPU set. + */ +/* TODO: rather provide an iterator? Provide a way to know how much should be allocated? By returning the total number of objects instead? */ +HWLOC_DECLSPEC unsigned hwloc_get_closest_objs (hwloc_topology_t topology, hwloc_obj_t src, hwloc_obj_t * __hwloc_restrict objs, unsigned max); + +/** \brief Find an object below another object, both specified by types and indexes. + * + * Start from the top system object and find object of type \p type1 + * and logical index \p idx1. Then look below this object and find another + * object of type \p type2 and logical index \p idx2. Indexes are specified + * within the parent, not withing the entire system. + * + * For instance, if type1 is PACKAGE, idx1 is 2, type2 is CORE and idx2 + * is 3, return the fourth core object below the third package. + * + * \note This function requires these objects to have a CPU set. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_below_by_type (hwloc_topology_t topology, + hwloc_obj_type_t type1, unsigned idx1, + hwloc_obj_type_t type2, unsigned idx2) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_below_by_type (hwloc_topology_t topology, + hwloc_obj_type_t type1, unsigned idx1, + hwloc_obj_type_t type2, unsigned idx2) +{ + hwloc_obj_t obj; + obj = hwloc_get_obj_by_type (topology, type1, idx1); + if (!obj) + return NULL; + return hwloc_get_obj_inside_cpuset_by_type(topology, obj->cpuset, type2, idx2); +} + +/** \brief Find an object below a chain of objects specified by types and indexes. + * + * This is a generalized version of hwloc_get_obj_below_by_type(). + * + * Arrays \p typev and \p idxv must contain \p nr types and indexes. + * + * Start from the top system object and walk the arrays \p typev and \p idxv. + * For each type and logical index couple in the arrays, look under the previously found + * object to find the index-th object of the given type. + * Indexes are specified within the parent, not withing the entire system. + * + * For instance, if nr is 3, typev contains NODE, PACKAGE and CORE, + * and idxv contains 0, 1 and 2, return the third core object below + * the second package below the first NUMA node. + * + * \note This function requires all these objects and the root object + * to have a CPU set. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_below_array_by_type (hwloc_topology_t topology, int nr, hwloc_obj_type_t *typev, unsigned *idxv) __hwloc_attribute_pure; +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_below_array_by_type (hwloc_topology_t topology, int nr, hwloc_obj_type_t *typev, unsigned *idxv) +{ + hwloc_obj_t obj = hwloc_get_root_obj(topology); + int i; + for(i=0; icpuset, typev[i], idxv[i]); + } + return obj; +} + +/** \brief Return an object of a different type with same locality. + * + * If the source object \p src is a normal or memory type, + * this function returns an object of type \p type with same + * CPU and node sets, either below or above in the hierarchy. + * + * If the source object \p src is a PCI or an OS device within a PCI + * device, the function may either return that PCI device, or another + * OS device in the same PCI parent. + * This may for instance be useful for converting between OS devices + * such as "nvml0" or "rsmi1" used in distance structures into the + * the PCI device, or the CUDA or OpenCL OS device that correspond + * to the same physical card. + * + * If not \c NULL, parameter \p subtype only select objects whose + * subtype attribute exists and is \p subtype (case-insensitively), + * for instance "OpenCL" or "CUDA". + * + * If not \c NULL, parameter \p nameprefix only selects objects whose + * name attribute exists and starts with \p nameprefix (case-insensitively), + * for instance "rsmi" for matching "rsmi0". + * + * If multiple objects match, the first one is returned. + * + * This function will not walk the hierarchy across bridges since + * the PCI locality may become different. + * This function cannot also convert between normal/memory objects + * and I/O or Misc objects. + * + * \p flags must be \c 0 for now. + * + * \return An object with identical locality, + * matching \p subtype and \p nameprefix if any. + * + * \return \c NULL if no matching object could be found, + * or if the source object and target type are incompatible, + * for instance if converting between CPU and I/O objects. + */ +HWLOC_DECLSPEC hwloc_obj_t +hwloc_get_obj_with_same_locality(hwloc_topology_t topology, hwloc_obj_t src, + hwloc_obj_type_t type, const char *subtype, const char *nameprefix, + unsigned long flags); + +/** @} */ + + + +/** \defgroup hwlocality_helper_distribute Distributing items over a topology + * @{ + */ + +/** \brief Flags to be given to hwloc_distrib(). + */ +enum hwloc_distrib_flags_e { + /** \brief Distrib in reverse order, starting from the last objects. + * \hideinitializer + */ + HWLOC_DISTRIB_FLAG_REVERSE = (1UL<<0) +}; + +/** \brief Distribute \p n items over the topology under \p roots + * + * Array \p set will be filled with \p n cpusets recursively distributed + * linearly over the topology under objects \p roots, down to depth \p until + * (which can be INT_MAX to distribute down to the finest level). + * + * \p n_roots is usually 1 and \p roots only contains the topology root object + * so as to distribute over the entire topology. + * + * This is typically useful when an application wants to distribute \p n + * threads over a machine, giving each of them as much private cache as + * possible and keeping them locally in number order. + * + * The caller may typically want to also call hwloc_bitmap_singlify() + * before binding a thread so that it does not move at all. + * + * \p flags should be 0 or a OR'ed set of ::hwloc_distrib_flags_e. + * + * \note This function requires the \p roots objects to have a CPU set. + * + * \note This function replaces the now deprecated hwloc_distribute() + * and hwloc_distributev() functions. + */ +static __hwloc_inline int +hwloc_distrib(hwloc_topology_t topology, + hwloc_obj_t *roots, unsigned n_roots, + hwloc_cpuset_t *set, + unsigned n, + int until, unsigned long flags) +{ + unsigned i; + unsigned tot_weight; + unsigned given, givenweight; + hwloc_cpuset_t *cpusetp = set; + + if (flags & ~HWLOC_DISTRIB_FLAG_REVERSE) { + errno = EINVAL; + return -1; + } + + tot_weight = 0; + for (i = 0; i < n_roots; i++) + tot_weight += (unsigned) hwloc_bitmap_weight(roots[i]->cpuset); + + for (i = 0, given = 0, givenweight = 0; i < n_roots; i++) { + unsigned chunk, weight; + hwloc_obj_t root = roots[flags & HWLOC_DISTRIB_FLAG_REVERSE ? n_roots-1-i : i]; + hwloc_cpuset_t cpuset = root->cpuset; + while (!hwloc_obj_type_is_normal(root->type)) + /* If memory/io/misc, walk up to normal parent */ + root = root->parent; + weight = (unsigned) hwloc_bitmap_weight(cpuset); + if (!weight) + continue; + /* Give to root a chunk proportional to its weight. + * If previous chunks got rounded-up, we may get a bit less. */ + chunk = (( (givenweight+weight) * n + tot_weight-1) / tot_weight) + - (( givenweight * n + tot_weight-1) / tot_weight); + if (!root->arity || chunk <= 1 || root->depth >= until) { + /* We can't split any more, put everything there. */ + if (chunk) { + /* Fill cpusets with ours */ + unsigned j; + for (j=0; j < chunk; j++) + cpusetp[j] = hwloc_bitmap_dup(cpuset); + } else { + /* We got no chunk, just merge our cpuset to a previous one + * (the first chunk cannot be empty) + * so that this root doesn't get ignored. + */ + assert(given); + hwloc_bitmap_or(cpusetp[-1], cpusetp[-1], cpuset); + } + } else { + /* Still more to distribute, recurse into children */ + hwloc_distrib(topology, root->children, root->arity, cpusetp, chunk, until, flags); + } + cpusetp += chunk; + given += chunk; + givenweight += weight; + } + + return 0; +} + +/** @} */ + + + +/** \defgroup hwlocality_helper_topology_sets CPU and node sets of entire topologies + * @{ + */ + +/** \brief Get complete CPU set + * + * \return the complete CPU set of processors of the system. + * + * \note The returned cpuset is not newly allocated and should thus not be + * changed or freed; hwloc_bitmap_dup() must be used to obtain a local copy. + * + * \note This is equivalent to retrieving the root object complete CPU-set. + */ +HWLOC_DECLSPEC hwloc_const_cpuset_t +hwloc_topology_get_complete_cpuset(hwloc_topology_t topology) __hwloc_attribute_pure; + +/** \brief Get topology CPU set + * + * \return the CPU set of processors of the system for which hwloc + * provides topology information. This is equivalent to the cpuset of the + * system object. + * + * \note The returned cpuset is not newly allocated and should thus not be + * changed or freed; hwloc_bitmap_dup() must be used to obtain a local copy. + * + * \note This is equivalent to retrieving the root object CPU-set. + */ +HWLOC_DECLSPEC hwloc_const_cpuset_t +hwloc_topology_get_topology_cpuset(hwloc_topology_t topology) __hwloc_attribute_pure; + +/** \brief Get allowed CPU set + * + * \return the CPU set of allowed processors of the system. + * + * \note If the topology flag ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED was not set, + * this is identical to hwloc_topology_get_topology_cpuset(), which means + * all PUs are allowed. + * + * \note If ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED was set, applying + * hwloc_bitmap_intersects() on the result of this function and on an object + * cpuset checks whether there are allowed PUs inside that object. + * Applying hwloc_bitmap_and() returns the list of these allowed PUs. + * + * \note The returned cpuset is not newly allocated and should thus not be + * changed or freed, hwloc_bitmap_dup() must be used to obtain a local copy. + */ +HWLOC_DECLSPEC hwloc_const_cpuset_t +hwloc_topology_get_allowed_cpuset(hwloc_topology_t topology) __hwloc_attribute_pure; + +/** \brief Get complete node set + * + * \return the complete node set of memory of the system. + * + * \note The returned nodeset is not newly allocated and should thus not be + * changed or freed; hwloc_bitmap_dup() must be used to obtain a local copy. + * + * \note This is equivalent to retrieving the root object complete nodeset. + */ +HWLOC_DECLSPEC hwloc_const_nodeset_t +hwloc_topology_get_complete_nodeset(hwloc_topology_t topology) __hwloc_attribute_pure; + +/** \brief Get topology node set + * + * \return the node set of memory of the system for which hwloc + * provides topology information. This is equivalent to the nodeset of the + * system object. + * + * \note The returned nodeset is not newly allocated and should thus not be + * changed or freed; hwloc_bitmap_dup() must be used to obtain a local copy. + * + * \note This is equivalent to retrieving the root object nodeset. + */ +HWLOC_DECLSPEC hwloc_const_nodeset_t +hwloc_topology_get_topology_nodeset(hwloc_topology_t topology) __hwloc_attribute_pure; + +/** \brief Get allowed node set + * + * \return the node set of allowed memory of the system. + * + * \note If the topology flag ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED was not set, + * this is identical to hwloc_topology_get_topology_nodeset(), which means + * all NUMA nodes are allowed. + * + * \note If ::HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED was set, applying + * hwloc_bitmap_intersects() on the result of this function and on an object + * nodeset checks whether there are allowed NUMA nodes inside that object. + * Applying hwloc_bitmap_and() returns the list of these allowed NUMA nodes. + * + * \note The returned nodeset is not newly allocated and should thus not be + * changed or freed, hwloc_bitmap_dup() must be used to obtain a local copy. + */ +HWLOC_DECLSPEC hwloc_const_nodeset_t +hwloc_topology_get_allowed_nodeset(hwloc_topology_t topology) __hwloc_attribute_pure; + +/** @} */ + + + +/** \defgroup hwlocality_helper_nodeset_convert Converting between CPU sets and node sets + * + * @{ + */ + +/** \brief Convert a CPU set into a NUMA node set + * + * For each PU included in the input \p _cpuset, set the corresponding + * local NUMA node(s) in the output \p nodeset. + * + * If some NUMA nodes have no CPUs at all, this function never sets their + * indexes in the output node set, even if a full CPU set is given in input. + * + * Hence the entire topology CPU set is converted into the set of all nodes + * that have some local CPUs. + */ +static __hwloc_inline int +hwloc_cpuset_to_nodeset(hwloc_topology_t topology, hwloc_const_cpuset_t _cpuset, hwloc_nodeset_t nodeset) +{ + int depth = hwloc_get_type_depth(topology, HWLOC_OBJ_NUMANODE); + hwloc_obj_t obj = NULL; + assert(depth != HWLOC_TYPE_DEPTH_UNKNOWN); + hwloc_bitmap_zero(nodeset); + while ((obj = hwloc_get_next_obj_covering_cpuset_by_depth(topology, _cpuset, depth, obj)) != NULL) + if (hwloc_bitmap_set(nodeset, obj->os_index) < 0) + return -1; + return 0; +} + +/** \brief Convert a NUMA node set into a CPU set + * + * For each NUMA node included in the input \p nodeset, set the corresponding + * local PUs in the output \p _cpuset. + * + * If some CPUs have no local NUMA nodes, this function never sets their + * indexes in the output CPU set, even if a full node set is given in input. + * + * Hence the entire topology node set is converted into the set of all CPUs + * that have some local NUMA nodes. + */ +static __hwloc_inline int +hwloc_cpuset_from_nodeset(hwloc_topology_t topology, hwloc_cpuset_t _cpuset, hwloc_const_nodeset_t nodeset) +{ + int depth = hwloc_get_type_depth(topology, HWLOC_OBJ_NUMANODE); + hwloc_obj_t obj = NULL; + assert(depth != HWLOC_TYPE_DEPTH_UNKNOWN); + hwloc_bitmap_zero(_cpuset); + while ((obj = hwloc_get_next_obj_by_depth(topology, depth, obj)) != NULL) { + if (hwloc_bitmap_isset(nodeset, obj->os_index)) + /* no need to check obj->cpuset because objects in levels always have a cpuset */ + if (hwloc_bitmap_or(_cpuset, _cpuset, obj->cpuset) < 0) + return -1; + } + return 0; +} + +/** @} */ + + + +/** \defgroup hwlocality_advanced_io Finding I/O objects + * @{ + */ + +/** \brief Get the first non-I/O ancestor object. + * + * Given the I/O object \p ioobj, find the smallest non-I/O ancestor + * object. This object (normal or memory) may then be used for binding + * because it has non-NULL CPU and node sets + * and because its locality is the same as \p ioobj. + * + * \note The resulting object is usually a normal object but it could also + * be a memory object (e.g. NUMA node) in future platforms if I/O objects + * ever get attached to memory instead of CPUs. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_non_io_ancestor_obj(hwloc_topology_t topology __hwloc_attribute_unused, + hwloc_obj_t ioobj) +{ + hwloc_obj_t obj = ioobj; + while (obj && !obj->cpuset) { + obj = obj->parent; + } + return obj; +} + +/** \brief Get the next PCI device in the system. + * + * \return the first PCI device if \p prev is \c NULL. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_pcidev(hwloc_topology_t topology, hwloc_obj_t prev) +{ + return hwloc_get_next_obj_by_type(topology, HWLOC_OBJ_PCI_DEVICE, prev); +} + +/** \brief Find the PCI device object matching the PCI bus id + * given domain, bus device and function PCI bus id. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_pcidev_by_busid(hwloc_topology_t topology, + unsigned domain, unsigned bus, unsigned dev, unsigned func) +{ + hwloc_obj_t obj = NULL; + while ((obj = hwloc_get_next_pcidev(topology, obj)) != NULL) { + if (obj->attr->pcidev.domain == domain + && obj->attr->pcidev.bus == bus + && obj->attr->pcidev.dev == dev + && obj->attr->pcidev.func == func) + return obj; + } + return NULL; +} + +/** \brief Find the PCI device object matching the PCI bus id + * given as a string xxxx:yy:zz.t or yy:zz.t. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_pcidev_by_busidstring(hwloc_topology_t topology, const char *busid) +{ + unsigned domain = 0; /* default */ + unsigned bus, dev, func; + + if (sscanf(busid, "%x:%x.%x", &bus, &dev, &func) != 3 + && sscanf(busid, "%x:%x:%x.%x", &domain, &bus, &dev, &func) != 4) { + errno = EINVAL; + return NULL; + } + + return hwloc_get_pcidev_by_busid(topology, domain, bus, dev, func); +} + +/** \brief Get the next OS device in the system. + * + * \return the first OS device if \p prev is \c NULL. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_osdev(hwloc_topology_t topology, hwloc_obj_t prev) +{ + return hwloc_get_next_obj_by_type(topology, HWLOC_OBJ_OS_DEVICE, prev); +} + +/** \brief Get the next bridge in the system. + * + * \return the first bridge if \p prev is \c NULL. + */ +static __hwloc_inline hwloc_obj_t +hwloc_get_next_bridge(hwloc_topology_t topology, hwloc_obj_t prev) +{ + return hwloc_get_next_obj_by_type(topology, HWLOC_OBJ_BRIDGE, prev); +} + +/* \brief Checks whether a given bridge covers a given PCI bus. + */ +static __hwloc_inline int +hwloc_bridge_covers_pcibus(hwloc_obj_t bridge, + unsigned domain, unsigned bus) +{ + return bridge->type == HWLOC_OBJ_BRIDGE + && bridge->attr->bridge.downstream_type == HWLOC_OBJ_BRIDGE_PCI + && bridge->attr->bridge.downstream.pci.domain == domain + && bridge->attr->bridge.downstream.pci.secondary_bus <= bus + && bridge->attr->bridge.downstream.pci.subordinate_bus >= bus; +} + +/** @} */ + + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_HELPER_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/inlines.h b/deps/exla/cache/xla_extension/include/include/hwloc/inlines.h new file mode 100644 index 0000000000000000000000000000000000000000..494209ea663467f3019e5a9e637daccefcdcd4b6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/inlines.h @@ -0,0 +1,146 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2018 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2009-2010 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/** + * This file contains the inline code of functions declared in hwloc.h + */ + +#ifndef HWLOC_INLINES_H +#define HWLOC_INLINES_H + +#ifndef HWLOC_H +#error Please include the main hwloc.h instead +#endif + +#include +#include + + +#ifdef __cplusplus +extern "C" { +#endif + +static __hwloc_inline int +hwloc_get_type_or_below_depth (hwloc_topology_t topology, hwloc_obj_type_t type) +{ + int depth = hwloc_get_type_depth(topology, type); + + if (depth != HWLOC_TYPE_DEPTH_UNKNOWN) + return depth; + + /* find the highest existing level with type order >= */ + for(depth = hwloc_get_type_depth(topology, HWLOC_OBJ_PU); ; depth--) + if (hwloc_compare_types(hwloc_get_depth_type(topology, depth), type) < 0) + return depth+1; + + /* Shouldn't ever happen, as there is always a Machine level with lower order and known depth. */ + /* abort(); */ +} + +static __hwloc_inline int +hwloc_get_type_or_above_depth (hwloc_topology_t topology, hwloc_obj_type_t type) +{ + int depth = hwloc_get_type_depth(topology, type); + + if (depth != HWLOC_TYPE_DEPTH_UNKNOWN) + return depth; + + /* find the lowest existing level with type order <= */ + for(depth = 0; ; depth++) + if (hwloc_compare_types(hwloc_get_depth_type(topology, depth), type) > 0) + return depth-1; + + /* Shouldn't ever happen, as there is always a PU level with higher order and known depth. */ + /* abort(); */ +} + +static __hwloc_inline int +hwloc_get_nbobjs_by_type (hwloc_topology_t topology, hwloc_obj_type_t type) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN) + return 0; + if (depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return -1; /* FIXME: agregate nbobjs from different levels? */ + return (int) hwloc_get_nbobjs_by_depth(topology, depth); +} + +static __hwloc_inline hwloc_obj_t +hwloc_get_obj_by_type (hwloc_topology_t topology, hwloc_obj_type_t type, unsigned idx) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN) + return NULL; + if (depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return NULL; + return hwloc_get_obj_by_depth(topology, depth, idx); +} + +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_by_depth (hwloc_topology_t topology, int depth, hwloc_obj_t prev) +{ + if (!prev) + return hwloc_get_obj_by_depth (topology, depth, 0); + if (prev->depth != depth) + return NULL; + return prev->next_cousin; +} + +static __hwloc_inline hwloc_obj_t +hwloc_get_next_obj_by_type (hwloc_topology_t topology, hwloc_obj_type_t type, + hwloc_obj_t prev) +{ + int depth = hwloc_get_type_depth(topology, type); + if (depth == HWLOC_TYPE_DEPTH_UNKNOWN || depth == HWLOC_TYPE_DEPTH_MULTIPLE) + return NULL; + return hwloc_get_next_obj_by_depth (topology, depth, prev); +} + +static __hwloc_inline hwloc_obj_t +hwloc_get_root_obj (hwloc_topology_t topology) +{ + return hwloc_get_obj_by_depth (topology, 0, 0); +} + +static __hwloc_inline const char * +hwloc_obj_get_info_by_name(hwloc_obj_t obj, const char *name) +{ + unsigned i; + for(i=0; iinfos_count; i++) { + struct hwloc_info_s *info = &obj->infos[i]; + if (!strcmp(info->name, name)) + return info->value; + } + return NULL; +} + +static __hwloc_inline void * +hwloc_alloc_membind_policy(hwloc_topology_t topology, size_t len, hwloc_const_cpuset_t set, hwloc_membind_policy_t policy, int flags) +{ + void *p = hwloc_alloc_membind(topology, len, set, policy, flags); + if (p) + return p; + + if (hwloc_set_membind(topology, set, policy, flags) < 0) + /* hwloc_set_membind() takes care of ignoring errors if non-STRICT */ + return NULL; + + p = hwloc_alloc(topology, len); + if (p && policy != HWLOC_MEMBIND_FIRSTTOUCH) + /* Enforce the binding by touching the data */ + memset(p, 0, len); + return p; +} + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_INLINES_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/linux.h b/deps/exla/cache/xla_extension/include/include/hwloc/linux.h new file mode 100644 index 0000000000000000000000000000000000000000..d76633b0f655c223e72177cc288fd0ae47d2dbdd --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/linux.h @@ -0,0 +1,87 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2021 Inria. All rights reserved. + * Copyright © 2009-2011 Université Bordeaux + * See COPYING in top-level directory. + */ + +/** \file + * \brief Macros to help interaction between hwloc and Linux. + * + * Applications that use hwloc on Linux may want to include this file + * if using some low-level Linux features. + */ + +#ifndef HWLOC_LINUX_H +#define HWLOC_LINUX_H + +#include "hwloc.h" + +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +/** \defgroup hwlocality_linux Linux-specific helpers + * + * This includes helpers for manipulating Linux kernel cpumap files, and hwloc + * equivalents of the Linux sched_setaffinity and sched_getaffinity system calls. + * + * @{ + */ + +/** \brief Bind a thread \p tid on cpus given in cpuset \p set + * + * The behavior is exactly the same as the Linux sched_setaffinity system call, + * but uses a hwloc cpuset. + * + * \note This is equivalent to calling hwloc_set_proc_cpubind() with + * HWLOC_CPUBIND_THREAD as flags. + */ +HWLOC_DECLSPEC int hwloc_linux_set_tid_cpubind(hwloc_topology_t topology, pid_t tid, hwloc_const_cpuset_t set); + +/** \brief Get the current binding of thread \p tid + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the list of PUs which the thread + * was last bound to. + * + * The behavior is exactly the same as the Linux sched_getaffinity system call, + * but uses a hwloc cpuset. + * + * \note This is equivalent to calling hwloc_get_proc_cpubind() with + * ::HWLOC_CPUBIND_THREAD as flags. + */ +HWLOC_DECLSPEC int hwloc_linux_get_tid_cpubind(hwloc_topology_t topology, pid_t tid, hwloc_cpuset_t set); + +/** \brief Get the last physical CPU where thread \p tid ran. + * + * The CPU-set \p set (previously allocated by the caller) + * is filled with the PU which the thread last ran on. + * + * \note This is equivalent to calling hwloc_get_proc_last_cpu_location() with + * ::HWLOC_CPUBIND_THREAD as flags. + */ +HWLOC_DECLSPEC int hwloc_linux_get_tid_last_cpu_location(hwloc_topology_t topology, pid_t tid, hwloc_bitmap_t set); + +/** \brief Convert a linux kernel cpumask file \p path into a hwloc bitmap \p set. + * + * Might be used when reading CPU set from sysfs attributes such as topology + * and caches for processors, or local_cpus for devices. + * + * \note This function ignores the HWLOC_FSROOT environment variable. + */ +HWLOC_DECLSPEC int hwloc_linux_read_path_as_cpumask(const char *path, hwloc_bitmap_t set); + +/** @} */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_LINUX_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/memattrs.h b/deps/exla/cache/xla_extension/include/include/hwloc/memattrs.h new file mode 100644 index 0000000000000000000000000000000000000000..02ffa83267a85d92f63029f3d8d1fa97c306744f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/memattrs.h @@ -0,0 +1,455 @@ +/* + * Copyright © 2019-2022 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief Memory node attributes. + */ + +#ifndef HWLOC_MEMATTR_H +#define HWLOC_MEMATTR_H + +#include "hwloc.h" + +#ifdef __cplusplus +extern "C" { +#elif 0 +} +#endif + +/** \defgroup hwlocality_memattrs Comparing memory node attributes for finding where to allocate on + * + * Platforms with heterogeneous memory require ways to decide whether + * a buffer should be allocated on "fast" memory (such as HBM), + * "normal" memory (DDR) or even "slow" but large-capacity memory + * (non-volatile memory). + * These memory nodes are called "Targets" while the CPU accessing them + * is called the "Initiator". Access performance depends on their + * locality (NUMA platforms) as well as the intrinsic performance + * of the targets (heterogeneous platforms). + * + * The following attributes describe the performance of memory accesses + * from an Initiator to a memory Target, for instance their latency + * or bandwidth. + * Initiators performing these memory accesses are usually some PUs or Cores + * (described as a CPU set). + * Hence a Core may choose where to allocate a memory buffer by comparing + * the attributes of different target memory nodes nearby. + * + * There are also some attributes that are system-wide. + * Their value does not depend on a specific initiator performing + * an access. + * The memory node Capacity is an example of such attribute without + * initiator. + * + * One way to use this API is to start with a cpuset describing the Cores where + * a program is bound. The best target NUMA node for allocating memory in this + * program on these Cores may be obtained by passing this cpuset as an initiator + * to hwloc_memattr_get_best_target() with the relevant memory attribute. + * For instance, if the code is latency limited, use the Latency attribute. + * + * A more flexible approach consists in getting the list of local NUMA nodes + * by passing this cpuset to hwloc_get_local_numanode_objs(). + * Attribute values for these nodes, if any, may then be obtained with + * hwloc_memattr_get_value() and manually compared with the desired criteria. + * + * \note The API also supports specific objects as initiator, + * but it is currently not used internally by hwloc. + * Users may for instance use it to provide custom performance + * values for host memory accesses performed by GPUs. + * + * \note The interface actually also accepts targets that are not NUMA nodes. + * @{ + */ + +/** \brief Memory node attributes. */ +enum hwloc_memattr_id_e { + /** \brief "Capacity". + * The capacity is returned in bytes + * (local_memory attribute in objects). + * + * Best capacity nodes are nodes with higher capacity. + * + * No initiator is involved when looking at this attribute. + * The corresponding attribute flags are ::HWLOC_MEMATTR_FLAG_HIGHER_FIRST. + */ + HWLOC_MEMATTR_ID_CAPACITY = 0, + + /** \brief "Locality". + * The locality is returned as the number of PUs in that locality + * (e.g. the weight of its cpuset). + * + * Best locality nodes are nodes with smaller locality + * (nodes that are local to very few PUs). + * Poor locality nodes are nodes with larger locality + * (nodes that are local to the entire machine). + * + * No initiator is involved when looking at this attribute. + * The corresponding attribute flags are ::HWLOC_MEMATTR_FLAG_HIGHER_FIRST. + */ + HWLOC_MEMATTR_ID_LOCALITY = 1, + + /** \brief "Bandwidth". + * The bandwidth is returned in MiB/s, as seen from the given initiator location. + * Best bandwidth nodes are nodes with higher bandwidth. + * The corresponding attribute flags are ::HWLOC_MEMATTR_FLAG_HIGHER_FIRST + * and ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR. + */ + HWLOC_MEMATTR_ID_BANDWIDTH = 2, + + /** \brief "Latency". + * The latency is returned as nanoseconds, as seen from the given initiator location. + * Best latency nodes are nodes with smaller latency. + * The corresponding attribute flags are ::HWLOC_MEMATTR_FLAG_LOWER_FIRST + * and ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR. + */ + HWLOC_MEMATTR_ID_LATENCY = 3 + + /* TODO read vs write, persistence? */ +}; + +/** \brief A memory attribute identifier. + * May be either one of ::hwloc_memattr_id_e or a new id returned by hwloc_memattr_register(). + */ +typedef unsigned hwloc_memattr_id_t; + +/** \brief Return the identifier of the memory attribute with the given name. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_by_name(hwloc_topology_t topology, + const char *name, + hwloc_memattr_id_t *id); + + +/** \brief Type of location. */ +enum hwloc_location_type_e { + /** \brief Location is given as a cpuset, in the location cpuset union field. \hideinitializer */ + HWLOC_LOCATION_TYPE_CPUSET = 1, + /** \brief Location is given as an object, in the location object union field. \hideinitializer */ + HWLOC_LOCATION_TYPE_OBJECT = 0 +}; + +/** \brief Where to measure attributes from. */ +struct hwloc_location { + /** \brief Type of location. */ + enum hwloc_location_type_e type; + /** \brief Actual location. */ + union hwloc_location_u { + /** \brief Location as a cpuset, when the location type is ::HWLOC_LOCATION_TYPE_CPUSET. */ + hwloc_cpuset_t cpuset; + /** \brief Location as an object, when the location type is ::HWLOC_LOCATION_TYPE_OBJECT. */ + hwloc_obj_t object; + } location; +}; + + +/** \brief Flags for selecting target NUMA nodes. */ +enum hwloc_local_numanode_flag_e { + /** \brief Select NUMA nodes whose locality is larger than the given cpuset. + * For instance, if a single PU (or its cpuset) is given in \p initiator, + * select all nodes close to the package that contains this PU. + * \hideinitializer + */ + HWLOC_LOCAL_NUMANODE_FLAG_LARGER_LOCALITY = (1UL<<0), + + /** \brief Select NUMA nodes whose locality is smaller than the given cpuset. + * For instance, if a package (or its cpuset) is given in \p initiator, + * also select nodes that are attached to only a half of that package. + * \hideinitializer + */ + HWLOC_LOCAL_NUMANODE_FLAG_SMALLER_LOCALITY = (1UL<<1), + + /** \brief Select all NUMA nodes in the topology. + * The initiator \p initiator is ignored. + * \hideinitializer + */ + HWLOC_LOCAL_NUMANODE_FLAG_ALL = (1UL<<2) +}; + +/** \brief Return an array of local NUMA nodes. + * + * By default only select the NUMA nodes whose locality is exactly + * the given \p location. More nodes may be selected if additional flags + * are given as a OR'ed set of ::hwloc_local_numanode_flag_e. + * + * If \p location is given as an explicit object, its CPU set is used + * to find NUMA nodes with the corresponding locality. + * If the object does not have a CPU set (e.g. I/O object), the CPU + * parent (where the I/O object is attached) is used. + * + * On input, \p nr points to the number of nodes that may be stored + * in the \p nodes array. + * On output, \p nr will be changed to the number of stored nodes, + * or the number of nodes that would have been stored if there were + * enough room. + * + * \note Some of these NUMA nodes may not have any memory attribute + * values and hence not be reported as actual targets in other functions. + * + * \note The number of NUMA nodes in the topology (obtained by + * hwloc_bitmap_weight() on the root object nodeset) may be used + * to allocate the \p nodes array. + * + * \note When an object CPU set is given as locality, for instance a Package, + * and when flags contain both ::HWLOC_LOCAL_NUMANODE_FLAG_LARGER_LOCALITY + * and ::HWLOC_LOCAL_NUMANODE_FLAG_SMALLER_LOCALITY, + * the returned array corresponds to the nodeset of that object. + */ +HWLOC_DECLSPEC int +hwloc_get_local_numanode_objs(hwloc_topology_t topology, + struct hwloc_location *location, + unsigned *nr, + hwloc_obj_t *nodes, + unsigned long flags); + + + +/** \brief Return an attribute value for a specific target NUMA node. + * + * If the attribute does not relate to a specific initiator + * (it does not have the flag ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR), + * location \p initiator is ignored and may be \c NULL. + * + * \p flags must be \c 0 for now. + * + * \note The initiator \p initiator should be of type ::HWLOC_LOCATION_TYPE_CPUSET + * when refering to accesses performed by CPU cores. + * ::HWLOC_LOCATION_TYPE_OBJECT is currently unused internally by hwloc, + * but users may for instance use it to provide custom information about + * host memory accesses performed by GPUs. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_value(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + hwloc_obj_t target_node, + struct hwloc_location *initiator, + unsigned long flags, + hwloc_uint64_t *value); + +/** \brief Return the best target NUMA node for the given attribute and initiator. + * + * If the attribute does not relate to a specific initiator + * (it does not have the flag ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR), + * location \p initiator is ignored and may be \c NULL. + * + * If \p value is non \c NULL, the corresponding value is returned there. + * + * If multiple targets have the same attribute values, only one is + * returned (and there is no way to clarify how that one is chosen). + * Applications that want to detect targets with identical/similar + * values, or that want to look at values for multiple attributes, + * should rather get all values using hwloc_memattr_get_value() + * and manually select the target they consider the best. + * + * \p flags must be \c 0 for now. + * + * If there are no matching targets, \c -1 is returned with \p errno set to \c ENOENT; + * + * \note The initiator \p initiator should be of type ::HWLOC_LOCATION_TYPE_CPUSET + * when refering to accesses performed by CPU cores. + * ::HWLOC_LOCATION_TYPE_OBJECT is currently unused internally by hwloc, + * but users may for instance use it to provide custom information about + * host memory accesses performed by GPUs. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_best_target(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + struct hwloc_location *initiator, + unsigned long flags, + hwloc_obj_t *best_target, hwloc_uint64_t *value); + +/** \brief Return the best initiator for the given attribute and target NUMA node. + * + * If the attribute does not relate to a specific initiator + * (it does not have the flag ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR), + * \c -1 is returned and \p errno is set to \c EINVAL. + * + * If \p value is non \c NULL, the corresponding value is returned there. + * + * If multiple initiators have the same attribute values, only one is + * returned (and there is no way to clarify how that one is chosen). + * Applications that want to detect initiators with identical/similar + * values, or that want to look at values for multiple attributes, + * should rather get all values using hwloc_memattr_get_value() + * and manually select the initiator they consider the best. + * + * The returned initiator should not be modified or freed, + * it belongs to the topology. + * + * \p flags must be \c 0 for now. + * + * If there are no matching initiators, \c -1 is returned with \p errno set to \c ENOENT; + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_best_initiator(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + hwloc_obj_t target, + unsigned long flags, + struct hwloc_location *best_initiator, hwloc_uint64_t *value); + +/** @} */ + + +/** \defgroup hwlocality_memattrs_manage Managing memory attributes + * @{ + */ + +/** \brief Return the name of a memory attribute. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_name(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + const char **name); + +/** \brief Return the flags of the given attribute. + * + * Flags are a OR'ed set of ::hwloc_memattr_flag_e. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_flags(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + unsigned long *flags); + +/** \brief Memory attribute flags. + * Given to hwloc_memattr_register() and returned by hwloc_memattr_get_flags(). + */ +enum hwloc_memattr_flag_e { + /** \brief The best nodes for this memory attribute are those with the higher values. + * For instance Bandwidth. + */ + HWLOC_MEMATTR_FLAG_HIGHER_FIRST = (1UL<<0), + /** \brief The best nodes for this memory attribute are those with the lower values. + * For instance Latency. + */ + HWLOC_MEMATTR_FLAG_LOWER_FIRST = (1UL<<1), + /** \brief The value returned for this memory attribute depends on the given initiator. + * For instance Bandwidth and Latency, but not Capacity. + */ + HWLOC_MEMATTR_FLAG_NEED_INITIATOR = (1UL<<2) +}; + +/** \brief Register a new memory attribute. + * + * Add a specific memory attribute that is not defined in ::hwloc_memattr_id_e. + * Flags are a OR'ed set of ::hwloc_memattr_flag_e. It must contain at least + * one of ::HWLOC_MEMATTR_FLAG_HIGHER_FIRST or ::HWLOC_MEMATTR_FLAG_LOWER_FIRST. + */ +HWLOC_DECLSPEC int +hwloc_memattr_register(hwloc_topology_t topology, + const char *name, + unsigned long flags, + hwloc_memattr_id_t *id); + +/** \brief Set an attribute value for a specific target NUMA node. + * + * If the attribute does not relate to a specific initiator + * (it does not have the flag ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR), + * location \p initiator is ignored and may be \c NULL. + * + * The initiator will be copied into the topology, + * the caller should free anything allocated to store the initiator, + * for instance the cpuset. + * + * \p flags must be \c 0 for now. + * + * \note The initiator \p initiator should be of type ::HWLOC_LOCATION_TYPE_CPUSET + * when referring to accesses performed by CPU cores. + * ::HWLOC_LOCATION_TYPE_OBJECT is currently unused internally by hwloc, + * but users may for instance use it to provide custom information about + * host memory accesses performed by GPUs. + */ +HWLOC_DECLSPEC int +hwloc_memattr_set_value(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + hwloc_obj_t target_node, + struct hwloc_location *initiator, + unsigned long flags, + hwloc_uint64_t value); + +/** \brief Return the target NUMA nodes that have some values for a given attribute. + * + * Return targets for the given attribute in the \p targets array + * (for the given initiator if any). + * If \p values is not \c NULL, the corresponding attribute values + * are stored in the array it points to. + * + * On input, \p nr points to the number of targets that may be stored + * in the array \p targets (and \p values). + * On output, \p nr points to the number of targets (and values) that + * were actually found, even if some of them couldn't be stored in the array. + * Targets that couldn't be stored are ignored, but the function still + * returns success (\c 0). The caller may find out by comparing the value pointed + * by \p nr before and after the function call. + * + * The returned targets should not be modified or freed, + * they belong to the topology. + * + * Argument \p initiator is ignored if the attribute does not relate to a specific + * initiator (it does not have the flag ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR). + * Otherwise \p initiator may be non \c NULL to report only targets + * that have a value for that initiator. + * + * \p flags must be \c 0 for now. + * + * \note This function is meant for tools and debugging (listing internal information) + * rather than for application queries. Applications should rather select useful + * NUMA nodes with hwloc_get_local_numanode_objs() and then look at their attribute + * values. + * + * \note The initiator \p initiator should be of type ::HWLOC_LOCATION_TYPE_CPUSET + * when referring to accesses performed by CPU cores. + * ::HWLOC_LOCATION_TYPE_OBJECT is currently unused internally by hwloc, + * but users may for instance use it to provide custom information about + * host memory accesses performed by GPUs. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_targets(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + struct hwloc_location *initiator, + unsigned long flags, + unsigned *nr, hwloc_obj_t *targets, hwloc_uint64_t *values); + +/** \brief Return the initiators that have values for a given attribute for a specific target NUMA node. + * + * Return initiators for the given attribute and target node in the + * \p initiators array. + * If \p values is not \c NULL, the corresponding attribute values + * are stored in the array it points to. + * + * On input, \p nr points to the number of initiators that may be stored + * in the array \p initiators (and \p values). + * On output, \p nr points to the number of initiators (and values) that + * were actually found, even if some of them couldn't be stored in the array. + * Initiators that couldn't be stored are ignored, but the function still + * returns success (\c 0). The caller may find out by comparing the value pointed + * by \p nr before and after the function call. + * + * The returned initiators should not be modified or freed, + * they belong to the topology. + * + * \p flags must be \c 0 for now. + * + * If the attribute does not relate to a specific initiator + * (it does not have the flag ::HWLOC_MEMATTR_FLAG_NEED_INITIATOR), + * no initiator is returned. + * + * \note This function is meant for tools and debugging (listing internal information) + * rather than for application queries. Applications should rather select useful + * NUMA nodes with hwloc_get_local_numanode_objs() and then look at their attribute + * values for some relevant initiators. + */ +HWLOC_DECLSPEC int +hwloc_memattr_get_initiators(hwloc_topology_t topology, + hwloc_memattr_id_t attribute, + hwloc_obj_t target_node, + unsigned long flags, + unsigned *nr, struct hwloc_location *initiators, hwloc_uint64_t *values); +/** @} */ + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_MEMATTR_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/plugins.h b/deps/exla/cache/xla_extension/include/include/hwloc/plugins.h new file mode 100644 index 0000000000000000000000000000000000000000..ed4b833d84f62a55feece1948959da6576ccd3fb --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/plugins.h @@ -0,0 +1,689 @@ +/* + * Copyright © 2013-2021 Inria. All rights reserved. + * Copyright © 2016 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +#ifndef HWLOC_PLUGINS_H +#define HWLOC_PLUGINS_H + +/** \file + * \brief Public interface for building hwloc plugins. + */ + +struct hwloc_backend; + +#include "hwloc.h" + +#ifdef HWLOC_INSIDE_PLUGIN +/* needed for hwloc_plugin_check_namespace() */ +#ifdef HWLOC_HAVE_LTDL +#include +#else +#include +#endif +#endif + + + +/** \defgroup hwlocality_disc_components Components and Plugins: Discovery components + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Discovery component structure + * + * This is the major kind of components, taking care of the discovery. + * They are registered by generic components, either statically-built or as plugins. + */ +struct hwloc_disc_component { + /** \brief Name. + * If this component is built as a plugin, this name does not have to match the plugin filename. + */ + const char *name; + + /** \brief Discovery phases performed by this component. + * OR'ed set of ::hwloc_disc_phase_t + */ + unsigned phases; + + /** \brief Component phases to exclude, as an OR'ed set of ::hwloc_disc_phase_t. + * + * For a GLOBAL component, this usually includes all other phases (\c ~UL). + * + * Other components only exclude types that may bring conflicting + * topology information. MISC components should likely not be excluded + * since they usually bring non-primary additional information. + */ + unsigned excluded_phases; + + /** \brief Instantiate callback to create a backend from the component. + * Parameters data1, data2, data3 are NULL except for components + * that have special enabling routines such as hwloc_topology_set_xml(). */ + struct hwloc_backend * (*instantiate)(struct hwloc_topology *topology, struct hwloc_disc_component *component, unsigned excluded_phases, const void *data1, const void *data2, const void *data3); + + /** \brief Component priority. + * Used to sort topology->components, higher priority first. + * Also used to decide between two components with the same name. + * + * Usual values are + * 50 for native OS (or platform) components, + * 45 for x86, + * 40 for no-OS fallback, + * 30 for global components (xml, synthetic), + * 20 for pci, + * 10 for other misc components (opencl etc.). + */ + unsigned priority; + + /** \brief Enabled by default. + * If unset, if will be disabled unless explicitly requested. + */ + unsigned enabled_by_default; + + /** \private Used internally to list components by priority on topology->components + * (the component structure is usually read-only, + * the core copies it before using this field for queueing) + */ + struct hwloc_disc_component * next; +}; + +/** @} */ + + + + +/** \defgroup hwlocality_disc_backends Components and Plugins: Discovery backends + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Discovery phase */ +typedef enum hwloc_disc_phase_e { + /** \brief xml or synthetic, platform-specific components such as bgq. + * Discovers everything including CPU, memory, I/O and everything else. + * A component with a Global phase usually excludes all other phases. + * \hideinitializer */ + HWLOC_DISC_PHASE_GLOBAL = (1U<<0), + + /** \brief CPU discovery. + * \hideinitializer */ + HWLOC_DISC_PHASE_CPU = (1U<<1), + + /** \brief Attach memory to existing CPU objects. + * \hideinitializer */ + HWLOC_DISC_PHASE_MEMORY = (1U<<2), + + /** \brief Attach PCI devices and bridges to existing CPU objects. + * \hideinitializer */ + HWLOC_DISC_PHASE_PCI = (1U<<3), + + /** \brief I/O discovery that requires PCI devices (OS devices such as OpenCL, CUDA, etc.). + * \hideinitializer */ + HWLOC_DISC_PHASE_IO = (1U<<4), + + /** \brief Misc objects that gets added below anything else. + * \hideinitializer */ + HWLOC_DISC_PHASE_MISC = (1U<<5), + + /** \brief Annotating existing objects, adding distances, etc. + * \hideinitializer */ + HWLOC_DISC_PHASE_ANNOTATE = (1U<<6), + + /** \brief Final tweaks to a ready-to-use topology. + * This phase runs once the topology is loaded, before it is returned to the topology. + * Hence it may only use the main hwloc API for modifying the topology, + * for instance by restricting it, adding info attributes, etc. + * \hideinitializer */ + HWLOC_DISC_PHASE_TWEAK = (1U<<7) +} hwloc_disc_phase_t; + +/** \brief Discovery status flags */ +enum hwloc_disc_status_flag_e { + /** \brief The sets of allowed resources were already retrieved \hideinitializer */ + HWLOC_DISC_STATUS_FLAG_GOT_ALLOWED_RESOURCES = (1UL<<1) +}; + +/** \brief Discovery status structure + * + * Used by the core and backends to inform about what has been/is being done + * during the discovery process. + */ +struct hwloc_disc_status { + /** \brief The current discovery phase that is performed. + * Must match one of the phases in the component phases field. + */ + hwloc_disc_phase_t phase; + + /** \brief Dynamically excluded phases. + * If a component decides during discovery that some phases are no longer needed. + */ + unsigned excluded_phases; + + /** \brief OR'ed set of hwloc_disc_status_flag_e */ + unsigned long flags; +}; + +/** \brief Discovery backend structure + * + * A backend is the instantiation of a discovery component. + * When a component gets enabled for a topology, + * its instantiate() callback creates a backend. + * + * hwloc_backend_alloc() initializes all fields to default values + * that the component may change (except "component" and "next") + * before enabling the backend with hwloc_backend_enable(). + * + * Most backends assume that the topology is_thissystem flag is + * set because they talk to the underlying operating system. + * However they may still be used in topologies without the + * is_thissystem flag for debugging reasons. + * In practice, they are usually auto-disabled in such cases + * (excluded by xml or synthetic backends, or by environment + * variables when changing the Linux fsroot or the x86 cpuid path). + */ +struct hwloc_backend { + /** \private Reserved for the core, set by hwloc_backend_alloc() */ + struct hwloc_disc_component * component; + /** \private Reserved for the core, set by hwloc_backend_enable() */ + struct hwloc_topology * topology; + /** \private Reserved for the core. Set to 1 if forced through envvar, 0 otherwise. */ + int envvar_forced; + /** \private Reserved for the core. Used internally to list backends topology->backends. */ + struct hwloc_backend * next; + + /** \brief Discovery phases performed by this component, possibly without some of them if excluded by other components. + * OR'ed set of ::hwloc_disc_phase_t + */ + unsigned phases; + + /** \brief Backend flags, currently always 0. */ + unsigned long flags; + + /** \brief Backend-specific 'is_thissystem' property. + * Set to 0 if the backend disables the thissystem flag for this topology + * (e.g. loading from xml or synthetic string, + * or using a different fsroot on Linux, or a x86 CPUID dump). + * Set to -1 if the backend doesn't care (default). + */ + int is_thissystem; + + /** \brief Backend private data, or NULL if none. */ + void * private_data; + /** \brief Callback for freeing the private_data. + * May be NULL. + */ + void (*disable)(struct hwloc_backend *backend); + + /** \brief Main discovery callback. + * returns -1 on error, either because it couldn't add its objects ot the existing topology, + * or because of an actual discovery/gathering failure. + * May be NULL. + */ + int (*discover)(struct hwloc_backend *backend, struct hwloc_disc_status *status); + + /** \brief Callback to retrieve the locality of a PCI object. + * Called by the PCI core when attaching PCI hierarchy to CPU objects. + * May be NULL. + */ + int (*get_pci_busid_cpuset)(struct hwloc_backend *backend, struct hwloc_pcidev_attr_s *busid, hwloc_bitmap_t cpuset); +}; + +/** \brief Allocate a backend structure, set good default values, initialize backend->component and topology, etc. + * The caller will then modify whatever needed, and call hwloc_backend_enable(). + */ +HWLOC_DECLSPEC struct hwloc_backend * hwloc_backend_alloc(struct hwloc_topology *topology, struct hwloc_disc_component *component); + +/** \brief Enable a previously allocated and setup backend. */ +HWLOC_DECLSPEC int hwloc_backend_enable(struct hwloc_backend *backend); + +/** @} */ + + + + +/** \defgroup hwlocality_generic_components Components and Plugins: Generic components + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Generic component type */ +typedef enum hwloc_component_type_e { + /** \brief The data field must point to a struct hwloc_disc_component. */ + HWLOC_COMPONENT_TYPE_DISC, + + /** \brief The data field must point to a struct hwloc_xml_component. */ + HWLOC_COMPONENT_TYPE_XML +} hwloc_component_type_t; + +/** \brief Generic component structure + * + * Generic components structure, either statically listed by configure in static-components.h + * or dynamically loaded as a plugin. + */ +struct hwloc_component { + /** \brief Component ABI version, set to ::HWLOC_COMPONENT_ABI */ + unsigned abi; + + /** \brief Process-wide component initialization callback. + * + * This optional callback is called when the component is registered + * to the hwloc core (after loading the plugin). + * + * When the component is built as a plugin, this callback + * should call hwloc_check_plugin_namespace() + * and return an negative error code on error. + * + * \p flags is always 0 for now. + * + * \return 0 on success, or a negative code on error. + * + * \note If the component uses ltdl for loading its own plugins, + * it should load/unload them only in init() and finalize(), + * to avoid race conditions with hwloc's use of ltdl. + */ + int (*init)(unsigned long flags); + + /** \brief Process-wide component termination callback. + * + * This optional callback is called after unregistering the component + * from the hwloc core (before unloading the plugin). + * + * \p flags is always 0 for now. + * + * \note If the component uses ltdl for loading its own plugins, + * it should load/unload them only in init() and finalize(), + * to avoid race conditions with hwloc's use of ltdl. + */ + void (*finalize)(unsigned long flags); + + /** \brief Component type */ + hwloc_component_type_t type; + + /** \brief Component flags, unused for now */ + unsigned long flags; + + /** \brief Component data, pointing to a struct hwloc_disc_component or struct hwloc_xml_component. */ + void * data; +}; + +/** @} */ + + + + +/** \defgroup hwlocality_components_core_funcs Components and Plugins: Core functions to be used by components + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Check whether error messages are hidden. + * + * Callers should print critical error messages + * (e.g. invalid hw topo info, invalid config) + * only if this function returns strictly less than 2. + * + * Callers should print non-critical error messages + * (e.g. failure to initialize CUDA) + * if this function returns 0. + * + * This function return 1 by default (show critical only), + * 0 in lstopo (show all), + * or anything set in HWLOC_HIDE_ERRORS in the environment. + */ +HWLOC_DECLSPEC int hwloc_hide_errors(void); + +/** \brief Add an object to the topology. + * + * Insert new object \p obj in the topology starting under existing object \p root + * (if \c NULL, the topology root object is used). + * + * It is sorted along the tree of other objects according to the inclusion of + * cpusets, to eventually be added as a child of the smallest object including + * this object. + * + * If the cpuset is empty, the type of the object (and maybe some attributes) + * must be enough to find where to insert the object. This is especially true + * for NUMA nodes with memory and no CPUs. + * + * The given object should not have children. + * + * This shall only be called before levels are built. + * + * The caller should check whether the object type is filtered-out before calling this function. + * + * The topology cpuset/nodesets will be enlarged to include the object sets. + * + * \p reason is a unique string identifying where and why this insertion call was performed + * (it will be displayed in case of internal insertion error). + * + * Returns the object on success. + * Returns NULL and frees obj on error. + * Returns another object and frees obj if it was merged with an identical pre-existing object. + */ +HWLOC_DECLSPEC hwloc_obj_t +hwloc__insert_object_by_cpuset(struct hwloc_topology *topology, hwloc_obj_t root, + hwloc_obj_t obj, const char *reason); + +/** \brief Insert an object somewhere in the topology. + * + * It is added as the last child of the given parent. + * The cpuset is completely ignored, so strange objects such as I/O devices should + * preferably be inserted with this. + * + * When used for "normal" children with cpusets (when importing from XML + * when duplicating a topology), the caller should make sure that: + * - children are inserted in order, + * - children cpusets do not intersect. + * + * The given object may have normal, I/O or Misc children, as long as they are in order as well. + * These children must have valid parent and next_sibling pointers. + * + * The caller should check whether the object type is filtered-out before calling this function. + */ +HWLOC_DECLSPEC void hwloc_insert_object_by_parent(struct hwloc_topology *topology, hwloc_obj_t parent, hwloc_obj_t obj); + +/** \brief Allocate and initialize an object of the given type and physical index. + * + * If \p os_index is unknown or irrelevant, use \c HWLOC_UNKNOWN_INDEX. + */ +HWLOC_DECLSPEC hwloc_obj_t hwloc_alloc_setup_object(hwloc_topology_t topology, hwloc_obj_type_t type, unsigned os_index); + +/** \brief Setup object cpusets/nodesets by OR'ing its children. + * + * Used when adding an object late in the topology. + * Will update the new object by OR'ing all its new children sets. + * + * Used when PCI backend adds a hostbridge parent, when distances + * add a new Group, etc. + */ +HWLOC_DECLSPEC int hwloc_obj_add_children_sets(hwloc_obj_t obj); + +/** \brief Request a reconnection of children and levels in the topology. + * + * May be used by backends during discovery if they need arrays or lists + * of object within levels or children to be fully connected. + * + * \p flags is currently unused, must 0. + */ +HWLOC_DECLSPEC int hwloc_topology_reconnect(hwloc_topology_t topology, unsigned long flags __hwloc_attribute_unused); + +/** \brief Make sure that plugins can lookup core symbols. + * + * This is a sanity check to avoid lazy-lookup failures when libhwloc + * is loaded within a plugin, and later tries to load its own plugins. + * This may fail (and abort the program) if libhwloc symbols are in a + * private namespace. + * + * \return 0 on success. + * \return -1 if the plugin cannot be successfully loaded. The caller + * plugin init() callback should return a negative error code as well. + * + * Plugins should call this function in their init() callback to avoid + * later crashes if lazy symbol resolution is used by the upper layer that + * loaded hwloc (e.g. OpenCL implementations using dlopen with RTLD_LAZY). + * + * \note The build system must define HWLOC_INSIDE_PLUGIN if and only if + * building the caller as a plugin. + * + * \note This function should remain inline so plugins can call it even + * when they cannot find libhwloc symbols. + */ +static __hwloc_inline int +hwloc_plugin_check_namespace(const char *pluginname __hwloc_attribute_unused, const char *symbol __hwloc_attribute_unused) +{ +#ifdef HWLOC_INSIDE_PLUGIN + void *sym; +#ifdef HWLOC_HAVE_LTDL + lt_dlhandle handle = lt_dlopen(NULL); +#else + void *handle = dlopen(NULL, RTLD_NOW|RTLD_LOCAL); +#endif + if (!handle) + /* cannot check, assume things will work */ + return 0; +#ifdef HWLOC_HAVE_LTDL + sym = lt_dlsym(handle, symbol); + lt_dlclose(handle); +#else + sym = dlsym(handle, symbol); + dlclose(handle); +#endif + if (!sym) { + static int verboseenv_checked = 0; + static int verboseenv_value = 0; + if (!verboseenv_checked) { + const char *verboseenv = getenv("HWLOC_PLUGINS_VERBOSE"); + verboseenv_value = verboseenv ? atoi(verboseenv) : 0; + verboseenv_checked = 1; + } + if (verboseenv_value) + fprintf(stderr, "Plugin `%s' disabling itself because it cannot find the `%s' core symbol.\n", + pluginname, symbol); + return -1; + } +#endif /* HWLOC_INSIDE_PLUGIN */ + return 0; +} + +/** @} */ + + + + +/** \defgroup hwlocality_components_filtering Components and Plugins: Filtering objects + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Check whether the given PCI device classid is important. + * + * \return 1 if important, 0 otherwise. + */ +static __hwloc_inline int +hwloc_filter_check_pcidev_subtype_important(unsigned classid) +{ + unsigned baseclass = classid >> 8; + return (baseclass == 0x03 /* PCI_BASE_CLASS_DISPLAY */ + || baseclass == 0x02 /* PCI_BASE_CLASS_NETWORK */ + || baseclass == 0x01 /* PCI_BASE_CLASS_STORAGE */ + || baseclass == 0x00 /* Unclassified, for Atos/Bull BXI */ + || baseclass == 0x0b /* PCI_BASE_CLASS_PROCESSOR */ + || classid == 0x0c04 /* PCI_CLASS_SERIAL_FIBER */ + || classid == 0x0c06 /* PCI_CLASS_SERIAL_INFINIBAND */ + || baseclass == 0x06 /* PCI_BASE_CLASS_BRIDGE with non-PCI downstream. the core will drop the useless ones later */ + || baseclass == 0x12 /* Processing Accelerators */); +} + +/** \brief Check whether the given OS device subtype is important. + * + * \return 1 if important, 0 otherwise. + */ +static __hwloc_inline int +hwloc_filter_check_osdev_subtype_important(hwloc_obj_osdev_type_t subtype) +{ + return (subtype != HWLOC_OBJ_OSDEV_DMA); +} + +/** \brief Check whether a non-I/O object type should be filtered-out. + * + * Cannot be used for I/O objects. + * + * \return 1 if the object type should be kept, 0 otherwise. + */ +static __hwloc_inline int +hwloc_filter_check_keep_object_type(hwloc_topology_t topology, hwloc_obj_type_t type) +{ + enum hwloc_type_filter_e filter = HWLOC_TYPE_FILTER_KEEP_NONE; + hwloc_topology_get_type_filter(topology, type, &filter); + assert(filter != HWLOC_TYPE_FILTER_KEEP_IMPORTANT); /* IMPORTANT only used for I/O */ + return filter == HWLOC_TYPE_FILTER_KEEP_NONE ? 0 : 1; +} + +/** \brief Check whether the given object should be filtered-out. + * + * \return 1 if the object type should be kept, 0 otherwise. + */ +static __hwloc_inline int +hwloc_filter_check_keep_object(hwloc_topology_t topology, hwloc_obj_t obj) +{ + hwloc_obj_type_t type = obj->type; + enum hwloc_type_filter_e filter = HWLOC_TYPE_FILTER_KEEP_NONE; + hwloc_topology_get_type_filter(topology, type, &filter); + if (filter == HWLOC_TYPE_FILTER_KEEP_NONE) + return 0; + if (filter == HWLOC_TYPE_FILTER_KEEP_IMPORTANT) { + if (type == HWLOC_OBJ_PCI_DEVICE) + return hwloc_filter_check_pcidev_subtype_important(obj->attr->pcidev.class_id); + if (type == HWLOC_OBJ_OS_DEVICE) + return hwloc_filter_check_osdev_subtype_important(obj->attr->osdev.type); + } + return 1; +} + +/** @} */ + + + + +/** \defgroup hwlocality_components_pcidisc Components and Plugins: helpers for PCI discovery + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Return the offset of the given capability in the PCI config space buffer + * + * This function requires a 256-bytes config space. Unknown/unavailable bytes should be set to 0xff. + */ +HWLOC_DECLSPEC unsigned hwloc_pcidisc_find_cap(const unsigned char *config, unsigned cap); + +/** \brief Fill linkspeed by reading the PCI config space where PCI_CAP_ID_EXP is at position offset. + * + * Needs 20 bytes of EXP capability block starting at offset in the config space + * for registers up to link status. + */ +HWLOC_DECLSPEC int hwloc_pcidisc_find_linkspeed(const unsigned char *config, unsigned offset, float *linkspeed); + +/** \brief Return the hwloc object type (PCI device or Bridge) for the given class and configuration space. + * + * This function requires 16 bytes of common configuration header at the beginning of config. + */ +HWLOC_DECLSPEC hwloc_obj_type_t hwloc_pcidisc_check_bridge_type(unsigned device_class, const unsigned char *config); + +/** \brief Fills the attributes of the given PCI bridge using the given PCI config space. + * + * This function requires 32 bytes of common configuration header at the beginning of config. + * + * Returns -1 and destroys /p obj if bridge fields are invalid. + */ +HWLOC_DECLSPEC int hwloc_pcidisc_find_bridge_buses(unsigned domain, unsigned bus, unsigned dev, unsigned func, + unsigned *secondary_busp, unsigned *subordinate_busp, + const unsigned char *config); + +/** \brief Insert a PCI object in the given PCI tree by looking at PCI bus IDs. + * + * If \p treep points to \c NULL, the new object is inserted there. + */ +HWLOC_DECLSPEC void hwloc_pcidisc_tree_insert_by_busid(struct hwloc_obj **treep, struct hwloc_obj *obj); + +/** \brief Add some hostbridges on top of the given tree of PCI objects and attach them to the topology. + * + * Other backends may lookup PCI objects or localities (for instance to attach OS devices) + * by using hwloc_pcidisc_find_by_busid() or hwloc_pcidisc_find_busid_parent(). + */ +HWLOC_DECLSPEC int hwloc_pcidisc_tree_attach(struct hwloc_topology *topology, struct hwloc_obj *tree); + +/** @} */ + + + + +/** \defgroup hwlocality_components_pcifind Components and Plugins: finding PCI objects during other discoveries + * + * \note These structures and functions may change when ::HWLOC_COMPONENT_ABI is modified. + * + * @{ + */ + +/** \brief Find the object or a parent of a PCI bus ID. + * + * When attaching a new object (typically an OS device) whose locality + * is specified by PCI bus ID, this function returns the PCI object + * to use as a parent for attaching. + * + * If the exact PCI device with this bus ID exists, it is returned. + * Otherwise (for instance if it was filtered out), the function returns + * another object with similar locality (for instance a parent bridge, + * or the local CPU Package). + */ +HWLOC_DECLSPEC struct hwloc_obj * hwloc_pci_find_parent_by_busid(struct hwloc_topology *topology, unsigned domain, unsigned bus, unsigned dev, unsigned func); + +/** \brief Find the PCI device or bridge matching a PCI bus ID exactly. + * + * This is useful for adding specific information about some objects + * based on their PCI id. When it comes to attaching objects based on + * PCI locality, hwloc_pci_find_parent_by_busid() should be preferred. + */ +HWLOC_DECLSPEC struct hwloc_obj * hwloc_pci_find_by_busid(struct hwloc_topology *topology, unsigned domain, unsigned bus, unsigned dev, unsigned func); + +/** \brief Handle to a new distances structure during its addition to the topology. */ +typedef void * hwloc_backend_distances_add_handle_t; + +/** \brief Create a new empty distances structure. + * + * This is identical to hwloc_distances_add_create() + * but this variant is designed for backend inserting + * distances during topology discovery. + */ +HWLOC_DECLSPEC hwloc_backend_distances_add_handle_t +hwloc_backend_distances_add_create(hwloc_topology_t topology, + const char *name, unsigned long kind, + unsigned long flags); + +/** \brief Specify the objects and values in a new empty distances structure. + * + * This is similar to hwloc_distances_add_values() + * but this variant is designed for backend inserting + * distances during topology discovery. + * + * The only semantical difference is that \p objs and \p values + * are not duplicated, but directly attached to the topology. + * On success, these arrays are given to the core and should not + * ever be freed by the caller anymore. + */ +HWLOC_DECLSPEC int +hwloc_backend_distances_add_values(hwloc_topology_t topology, + hwloc_backend_distances_add_handle_t handle, + unsigned nbobjs, hwloc_obj_t *objs, + hwloc_uint64_t *values, + unsigned long flags); + +/** \brief Commit a new distances structure. + * + * This is similar to hwloc_distances_add_commit() + * but this variant is designed for backend inserting + * distances during topology discovery. + */ +HWLOC_DECLSPEC int +hwloc_backend_distances_add_commit(hwloc_topology_t topology, + hwloc_backend_distances_add_handle_t handle, + unsigned long flags); + +/** @} */ + + + + +#endif /* HWLOC_PLUGINS_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/rename.h b/deps/exla/cache/xla_extension/include/include/hwloc/rename.h new file mode 100644 index 0000000000000000000000000000000000000000..ae439b51c01a080b800204224498afe91de2c96f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/rename.h @@ -0,0 +1,901 @@ +/* + * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. + * Copyright © 2010-2021 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +#ifndef HWLOC_RENAME_H +#define HWLOC_RENAME_H + +#include "hwloc/autogen/config.h" + + +#ifdef __cplusplus +extern "C" { +#endif + + +/* Only enact these defines if we're actually renaming the symbols + (i.e., avoid trying to have no-op defines if we're *not* + renaming). */ + +#if HWLOC_SYM_TRANSFORM + +/* Use a preprocessor two-step in order to get the prefixing right. + Make 2 macros: HWLOC_NAME and HWLOC_NAME_CAPS for renaming + things. */ + +#define HWLOC_MUNGE_NAME(a, b) HWLOC_MUNGE_NAME2(a, b) +#define HWLOC_MUNGE_NAME2(a, b) a ## b +#define HWLOC_NAME(name) HWLOC_MUNGE_NAME(HWLOC_SYM_PREFIX, hwloc_ ## name) +/* FIXME: should be "HWLOC_ ## name" below, unchanged because it doesn't matter much and could break some embedders hacks */ +#define HWLOC_NAME_CAPS(name) HWLOC_MUNGE_NAME(HWLOC_SYM_PREFIX_CAPS, hwloc_ ## name) + +/* Now define all the "real" names to be the prefixed names. This + allows us to use the real names throughout the code base (i.e., + "hwloc_"); the preprocessor will adjust to have the prefixed + name under the covers. */ + +/* Names from hwloc.h */ + +#define hwloc_get_api_version HWLOC_NAME(get_api_version) + +#define hwloc_topology HWLOC_NAME(topology) +#define hwloc_topology_t HWLOC_NAME(topology_t) + +#define hwloc_cpuset_t HWLOC_NAME(cpuset_t) +#define hwloc_const_cpuset_t HWLOC_NAME(const_cpuset_t) +#define hwloc_nodeset_t HWLOC_NAME(nodeset_t) +#define hwloc_const_nodeset_t HWLOC_NAME(const_nodeset_t) + +#define HWLOC_OBJ_MACHINE HWLOC_NAME_CAPS(OBJ_MACHINE) +#define HWLOC_OBJ_NUMANODE HWLOC_NAME_CAPS(OBJ_NUMANODE) +#define HWLOC_OBJ_MEMCACHE HWLOC_NAME_CAPS(OBJ_MEMCACHE) +#define HWLOC_OBJ_PACKAGE HWLOC_NAME_CAPS(OBJ_PACKAGE) +#define HWLOC_OBJ_DIE HWLOC_NAME_CAPS(OBJ_DIE) +#define HWLOC_OBJ_CORE HWLOC_NAME_CAPS(OBJ_CORE) +#define HWLOC_OBJ_PU HWLOC_NAME_CAPS(OBJ_PU) +#define HWLOC_OBJ_L1CACHE HWLOC_NAME_CAPS(OBJ_L1CACHE) +#define HWLOC_OBJ_L2CACHE HWLOC_NAME_CAPS(OBJ_L2CACHE) +#define HWLOC_OBJ_L3CACHE HWLOC_NAME_CAPS(OBJ_L3CACHE) +#define HWLOC_OBJ_L4CACHE HWLOC_NAME_CAPS(OBJ_L4CACHE) +#define HWLOC_OBJ_L5CACHE HWLOC_NAME_CAPS(OBJ_L5CACHE) +#define HWLOC_OBJ_L1ICACHE HWLOC_NAME_CAPS(OBJ_L1ICACHE) +#define HWLOC_OBJ_L2ICACHE HWLOC_NAME_CAPS(OBJ_L2ICACHE) +#define HWLOC_OBJ_L3ICACHE HWLOC_NAME_CAPS(OBJ_L3ICACHE) +#define HWLOC_OBJ_MISC HWLOC_NAME_CAPS(OBJ_MISC) +#define HWLOC_OBJ_GROUP HWLOC_NAME_CAPS(OBJ_GROUP) +#define HWLOC_OBJ_BRIDGE HWLOC_NAME_CAPS(OBJ_BRIDGE) +#define HWLOC_OBJ_PCI_DEVICE HWLOC_NAME_CAPS(OBJ_PCI_DEVICE) +#define HWLOC_OBJ_OS_DEVICE HWLOC_NAME_CAPS(OBJ_OS_DEVICE) +#define HWLOC_OBJ_TYPE_MAX HWLOC_NAME_CAPS(OBJ_TYPE_MAX) +#define hwloc_obj_type_t HWLOC_NAME(obj_type_t) + +#define hwloc_obj_cache_type_e HWLOC_NAME(obj_cache_type_e) +#define hwloc_obj_cache_type_t HWLOC_NAME(obj_cache_type_t) +#define HWLOC_OBJ_CACHE_UNIFIED HWLOC_NAME_CAPS(OBJ_CACHE_UNIFIED) +#define HWLOC_OBJ_CACHE_DATA HWLOC_NAME_CAPS(OBJ_CACHE_DATA) +#define HWLOC_OBJ_CACHE_INSTRUCTION HWLOC_NAME_CAPS(OBJ_CACHE_INSTRUCTION) + +#define hwloc_obj_bridge_type_e HWLOC_NAME(obj_bridge_type_e) +#define hwloc_obj_bridge_type_t HWLOC_NAME(obj_bridge_type_t) +#define HWLOC_OBJ_BRIDGE_HOST HWLOC_NAME_CAPS(OBJ_BRIDGE_HOST) +#define HWLOC_OBJ_BRIDGE_PCI HWLOC_NAME_CAPS(OBJ_BRIDGE_PCI) + +#define hwloc_obj_osdev_type_e HWLOC_NAME(obj_osdev_type_e) +#define hwloc_obj_osdev_type_t HWLOC_NAME(obj_osdev_type_t) +#define HWLOC_OBJ_OSDEV_BLOCK HWLOC_NAME_CAPS(OBJ_OSDEV_BLOCK) +#define HWLOC_OBJ_OSDEV_GPU HWLOC_NAME_CAPS(OBJ_OSDEV_GPU) +#define HWLOC_OBJ_OSDEV_NETWORK HWLOC_NAME_CAPS(OBJ_OSDEV_NETWORK) +#define HWLOC_OBJ_OSDEV_OPENFABRICS HWLOC_NAME_CAPS(OBJ_OSDEV_OPENFABRICS) +#define HWLOC_OBJ_OSDEV_DMA HWLOC_NAME_CAPS(OBJ_OSDEV_DMA) +#define HWLOC_OBJ_OSDEV_COPROC HWLOC_NAME_CAPS(OBJ_OSDEV_COPROC) + +#define hwloc_compare_types HWLOC_NAME(compare_types) + +#define hwloc_obj HWLOC_NAME(obj) +#define hwloc_obj_t HWLOC_NAME(obj_t) + +#define hwloc_info_s HWLOC_NAME(info_s) + +#define hwloc_obj_attr_u HWLOC_NAME(obj_attr_u) +#define hwloc_numanode_attr_s HWLOC_NAME(numanode_attr_s) +#define hwloc_memory_page_type_s HWLOC_NAME(memory_page_type_s) +#define hwloc_cache_attr_s HWLOC_NAME(cache_attr_s) +#define hwloc_group_attr_s HWLOC_NAME(group_attr_s) +#define hwloc_pcidev_attr_s HWLOC_NAME(pcidev_attr_s) +#define hwloc_bridge_attr_s HWLOC_NAME(bridge_attr_s) +#define hwloc_osdev_attr_s HWLOC_NAME(osdev_attr_s) + +#define hwloc_topology_init HWLOC_NAME(topology_init) +#define hwloc_topology_load HWLOC_NAME(topology_load) +#define hwloc_topology_destroy HWLOC_NAME(topology_destroy) +#define hwloc_topology_dup HWLOC_NAME(topology_dup) +#define hwloc_topology_abi_check HWLOC_NAME(topology_abi_check) +#define hwloc_topology_check HWLOC_NAME(topology_check) + +#define hwloc_topology_flags_e HWLOC_NAME(topology_flags_e) + +#define HWLOC_TOPOLOGY_FLAG_INCLUDE_DISALLOWED HWLOC_NAME_CAPS(TOPOLOGY_FLAG_WITH_DISALLOWED) +#define HWLOC_TOPOLOGY_FLAG_IS_THISSYSTEM HWLOC_NAME_CAPS(TOPOLOGY_FLAG_IS_THISSYSTEM) +#define HWLOC_TOPOLOGY_FLAG_THISSYSTEM_ALLOWED_RESOURCES HWLOC_NAME_CAPS(TOPOLOGY_FLAG_THISSYSTEM_ALLOWED_RESOURCES) +#define HWLOC_TOPOLOGY_FLAG_IMPORT_SUPPORT HWLOC_NAME_CAPS(TOPOLOGY_FLAG_IMPORT_SUPPORT) +#define HWLOC_TOPOLOGY_FLAG_RESTRICT_TO_CPUBINDING HWLOC_NAME_CAPS(TOPOLOGY_FLAG_RESTRICT_TO_CPUBINDING) +#define HWLOC_TOPOLOGY_FLAG_RESTRICT_TO_MEMBINDING HWLOC_NAME_CAPS(TOPOLOGY_FLAG_RESTRICT_TO_MEMBINDING) +#define HWLOC_TOPOLOGY_FLAG_DONT_CHANGE_BINDING HWLOC_NAME_CAPS(TOPOLOGY_FLAG_DONT_CHANGE_BINDING) + +#define hwloc_topology_set_pid HWLOC_NAME(topology_set_pid) +#define hwloc_topology_set_synthetic HWLOC_NAME(topology_set_synthetic) +#define hwloc_topology_set_xml HWLOC_NAME(topology_set_xml) +#define hwloc_topology_set_xmlbuffer HWLOC_NAME(topology_set_xmlbuffer) +#define hwloc_topology_components_flag_e HWLOC_NAME(hwloc_topology_components_flag_e) +#define HWLOC_TOPOLOGY_COMPONENTS_FLAG_BLACKLIST HWLOC_NAME_CAPS(TOPOLOGY_COMPONENTS_FLAG_BLACKLIST) +#define hwloc_topology_set_components HWLOC_NAME(topology_set_components) + +#define hwloc_topology_set_flags HWLOC_NAME(topology_set_flags) +#define hwloc_topology_is_thissystem HWLOC_NAME(topology_is_thissystem) +#define hwloc_topology_get_flags HWLOC_NAME(topology_get_flags) +#define hwloc_topology_discovery_support HWLOC_NAME(topology_discovery_support) +#define hwloc_topology_cpubind_support HWLOC_NAME(topology_cpubind_support) +#define hwloc_topology_membind_support HWLOC_NAME(topology_membind_support) +#define hwloc_topology_misc_support HWLOC_NAME(topology_misc_support) +#define hwloc_topology_support HWLOC_NAME(topology_support) +#define hwloc_topology_get_support HWLOC_NAME(topology_get_support) + +#define hwloc_type_filter_e HWLOC_NAME(type_filter_e) +#define HWLOC_TYPE_FILTER_KEEP_ALL HWLOC_NAME_CAPS(TYPE_FILTER_KEEP_ALL) +#define HWLOC_TYPE_FILTER_KEEP_NONE HWLOC_NAME_CAPS(TYPE_FILTER_KEEP_NONE) +#define HWLOC_TYPE_FILTER_KEEP_STRUCTURE HWLOC_NAME_CAPS(TYPE_FILTER_KEEP_STRUCTURE) +#define HWLOC_TYPE_FILTER_KEEP_IMPORTANT HWLOC_NAME_CAPS(TYPE_FILTER_KEEP_IMPORTANT) +#define hwloc_topology_set_type_filter HWLOC_NAME(topology_set_type_filter) +#define hwloc_topology_get_type_filter HWLOC_NAME(topology_get_type_filter) +#define hwloc_topology_set_all_types_filter HWLOC_NAME(topology_set_all_types_filter) +#define hwloc_topology_set_cache_types_filter HWLOC_NAME(topology_set_cache_types_filter) +#define hwloc_topology_set_icache_types_filter HWLOC_NAME(topology_set_icache_types_filter) +#define hwloc_topology_set_io_types_filter HWLOC_NAME(topology_set_io_types_filter) + +#define hwloc_topology_set_userdata HWLOC_NAME(topology_set_userdata) +#define hwloc_topology_get_userdata HWLOC_NAME(topology_get_userdata) + +#define hwloc_restrict_flags_e HWLOC_NAME(restrict_flags_e) +#define HWLOC_RESTRICT_FLAG_REMOVE_CPULESS HWLOC_NAME_CAPS(RESTRICT_FLAG_REMOVE_CPULESS) +#define HWLOC_RESTRICT_FLAG_BYNODESET HWLOC_NAME_CAPS(RESTRICT_FLAG_BYNODESET) +#define HWLOC_RESTRICT_FLAG_REMOVE_MEMLESS HWLOC_NAME_CAPS(RESTRICT_FLAG_REMOVE_MEMLESS) +#define HWLOC_RESTRICT_FLAG_ADAPT_MISC HWLOC_NAME_CAPS(RESTRICT_FLAG_ADAPT_MISC) +#define HWLOC_RESTRICT_FLAG_ADAPT_IO HWLOC_NAME_CAPS(RESTRICT_FLAG_ADAPT_IO) +#define hwloc_topology_restrict HWLOC_NAME(topology_restrict) + +#define hwloc_allow_flags_e HWLOC_NAME(allow_flags_e) +#define HWLOC_ALLOW_FLAG_ALL HWLOC_NAME_CAPS(ALLOW_FLAG_ALL) +#define HWLOC_ALLOW_FLAG_LOCAL_RESTRICTIONS HWLOC_NAME_CAPS(ALLOW_FLAG_LOCAL_RESTRICTIONS) +#define HWLOC_ALLOW_FLAG_CUSTOM HWLOC_NAME_CAPS(ALLOW_FLAG_CUSTOM) +#define hwloc_topology_allow HWLOC_NAME(topology_allow) + +#define hwloc_topology_insert_misc_object HWLOC_NAME(topology_insert_misc_object) +#define hwloc_topology_alloc_group_object HWLOC_NAME(topology_alloc_group_object) +#define hwloc_topology_insert_group_object HWLOC_NAME(topology_insert_group_object) +#define hwloc_obj_add_other_obj_sets HWLOC_NAME(obj_add_other_obj_sets) +#define hwloc_topology_refresh HWLOC_NAME(topology_refresh) + +#define hwloc_topology_get_depth HWLOC_NAME(topology_get_depth) +#define hwloc_get_type_depth HWLOC_NAME(get_type_depth) +#define hwloc_get_memory_parents_depth HWLOC_NAME(get_memory_parents_depth) + +#define hwloc_get_type_depth_e HWLOC_NAME(get_type_depth_e) +#define HWLOC_TYPE_DEPTH_UNKNOWN HWLOC_NAME_CAPS(TYPE_DEPTH_UNKNOWN) +#define HWLOC_TYPE_DEPTH_MULTIPLE HWLOC_NAME_CAPS(TYPE_DEPTH_MULTIPLE) +#define HWLOC_TYPE_DEPTH_BRIDGE HWLOC_NAME_CAPS(TYPE_DEPTH_BRIDGE) +#define HWLOC_TYPE_DEPTH_PCI_DEVICE HWLOC_NAME_CAPS(TYPE_DEPTH_PCI_DEVICE) +#define HWLOC_TYPE_DEPTH_OS_DEVICE HWLOC_NAME_CAPS(TYPE_DEPTH_OS_DEVICE) +#define HWLOC_TYPE_DEPTH_MISC HWLOC_NAME_CAPS(TYPE_DEPTH_MISC) +#define HWLOC_TYPE_DEPTH_NUMANODE HWLOC_NAME_CAPS(TYPE_DEPTH_NUMANODE) +#define HWLOC_TYPE_DEPTH_MEMCACHE HWLOC_NAME_CAPS(TYPE_DEPTH_MEMCACHE) + +#define hwloc_get_depth_type HWLOC_NAME(get_depth_type) +#define hwloc_get_nbobjs_by_depth HWLOC_NAME(get_nbobjs_by_depth) +#define hwloc_get_nbobjs_by_type HWLOC_NAME(get_nbobjs_by_type) + +#define hwloc_get_obj_by_depth HWLOC_NAME(get_obj_by_depth ) +#define hwloc_get_obj_by_type HWLOC_NAME(get_obj_by_type ) + +#define hwloc_obj_type_string HWLOC_NAME(obj_type_string ) +#define hwloc_obj_type_snprintf HWLOC_NAME(obj_type_snprintf ) +#define hwloc_obj_attr_snprintf HWLOC_NAME(obj_attr_snprintf ) +#define hwloc_type_sscanf HWLOC_NAME(type_sscanf) +#define hwloc_type_sscanf_as_depth HWLOC_NAME(type_sscanf_as_depth) + +#define hwloc_obj_get_info_by_name HWLOC_NAME(obj_get_info_by_name) +#define hwloc_obj_add_info HWLOC_NAME(obj_add_info) + +#define HWLOC_CPUBIND_PROCESS HWLOC_NAME_CAPS(CPUBIND_PROCESS) +#define HWLOC_CPUBIND_THREAD HWLOC_NAME_CAPS(CPUBIND_THREAD) +#define HWLOC_CPUBIND_STRICT HWLOC_NAME_CAPS(CPUBIND_STRICT) +#define HWLOC_CPUBIND_NOMEMBIND HWLOC_NAME_CAPS(CPUBIND_NOMEMBIND) + +#define hwloc_cpubind_flags_t HWLOC_NAME(cpubind_flags_t) + +#define hwloc_set_cpubind HWLOC_NAME(set_cpubind) +#define hwloc_get_cpubind HWLOC_NAME(get_cpubind) +#define hwloc_set_proc_cpubind HWLOC_NAME(set_proc_cpubind) +#define hwloc_get_proc_cpubind HWLOC_NAME(get_proc_cpubind) +#define hwloc_set_thread_cpubind HWLOC_NAME(set_thread_cpubind) +#define hwloc_get_thread_cpubind HWLOC_NAME(get_thread_cpubind) + +#define hwloc_get_last_cpu_location HWLOC_NAME(get_last_cpu_location) +#define hwloc_get_proc_last_cpu_location HWLOC_NAME(get_proc_last_cpu_location) + +#define HWLOC_MEMBIND_DEFAULT HWLOC_NAME_CAPS(MEMBIND_DEFAULT) +#define HWLOC_MEMBIND_FIRSTTOUCH HWLOC_NAME_CAPS(MEMBIND_FIRSTTOUCH) +#define HWLOC_MEMBIND_BIND HWLOC_NAME_CAPS(MEMBIND_BIND) +#define HWLOC_MEMBIND_INTERLEAVE HWLOC_NAME_CAPS(MEMBIND_INTERLEAVE) +#define HWLOC_MEMBIND_NEXTTOUCH HWLOC_NAME_CAPS(MEMBIND_NEXTTOUCH) +#define HWLOC_MEMBIND_MIXED HWLOC_NAME_CAPS(MEMBIND_MIXED) + +#define hwloc_membind_policy_t HWLOC_NAME(membind_policy_t) + +#define HWLOC_MEMBIND_PROCESS HWLOC_NAME_CAPS(MEMBIND_PROCESS) +#define HWLOC_MEMBIND_THREAD HWLOC_NAME_CAPS(MEMBIND_THREAD) +#define HWLOC_MEMBIND_STRICT HWLOC_NAME_CAPS(MEMBIND_STRICT) +#define HWLOC_MEMBIND_MIGRATE HWLOC_NAME_CAPS(MEMBIND_MIGRATE) +#define HWLOC_MEMBIND_NOCPUBIND HWLOC_NAME_CAPS(MEMBIND_NOCPUBIND) +#define HWLOC_MEMBIND_BYNODESET HWLOC_NAME_CAPS(MEMBIND_BYNODESET) + +#define hwloc_membind_flags_t HWLOC_NAME(membind_flags_t) + +#define hwloc_set_membind HWLOC_NAME(set_membind) +#define hwloc_get_membind HWLOC_NAME(get_membind) +#define hwloc_set_proc_membind HWLOC_NAME(set_proc_membind) +#define hwloc_get_proc_membind HWLOC_NAME(get_proc_membind) +#define hwloc_set_area_membind HWLOC_NAME(set_area_membind) +#define hwloc_get_area_membind HWLOC_NAME(get_area_membind) +#define hwloc_get_area_memlocation HWLOC_NAME(get_area_memlocation) +#define hwloc_alloc_membind HWLOC_NAME(alloc_membind) +#define hwloc_alloc HWLOC_NAME(alloc) +#define hwloc_free HWLOC_NAME(free) + +#define hwloc_get_non_io_ancestor_obj HWLOC_NAME(get_non_io_ancestor_obj) +#define hwloc_get_next_pcidev HWLOC_NAME(get_next_pcidev) +#define hwloc_get_pcidev_by_busid HWLOC_NAME(get_pcidev_by_busid) +#define hwloc_get_pcidev_by_busidstring HWLOC_NAME(get_pcidev_by_busidstring) +#define hwloc_get_next_osdev HWLOC_NAME(get_next_osdev) +#define hwloc_get_next_bridge HWLOC_NAME(get_next_bridge) +#define hwloc_bridge_covers_pcibus HWLOC_NAME(bridge_covers_pcibus) + +/* hwloc/bitmap.h */ + +#define hwloc_bitmap_s HWLOC_NAME(bitmap_s) +#define hwloc_bitmap_t HWLOC_NAME(bitmap_t) +#define hwloc_const_bitmap_t HWLOC_NAME(const_bitmap_t) + +#define hwloc_bitmap_alloc HWLOC_NAME(bitmap_alloc) +#define hwloc_bitmap_alloc_full HWLOC_NAME(bitmap_alloc_full) +#define hwloc_bitmap_free HWLOC_NAME(bitmap_free) +#define hwloc_bitmap_dup HWLOC_NAME(bitmap_dup) +#define hwloc_bitmap_copy HWLOC_NAME(bitmap_copy) +#define hwloc_bitmap_snprintf HWLOC_NAME(bitmap_snprintf) +#define hwloc_bitmap_asprintf HWLOC_NAME(bitmap_asprintf) +#define hwloc_bitmap_sscanf HWLOC_NAME(bitmap_sscanf) +#define hwloc_bitmap_list_snprintf HWLOC_NAME(bitmap_list_snprintf) +#define hwloc_bitmap_list_asprintf HWLOC_NAME(bitmap_list_asprintf) +#define hwloc_bitmap_list_sscanf HWLOC_NAME(bitmap_list_sscanf) +#define hwloc_bitmap_taskset_snprintf HWLOC_NAME(bitmap_taskset_snprintf) +#define hwloc_bitmap_taskset_asprintf HWLOC_NAME(bitmap_taskset_asprintf) +#define hwloc_bitmap_taskset_sscanf HWLOC_NAME(bitmap_taskset_sscanf) +#define hwloc_bitmap_zero HWLOC_NAME(bitmap_zero) +#define hwloc_bitmap_fill HWLOC_NAME(bitmap_fill) +#define hwloc_bitmap_from_ulong HWLOC_NAME(bitmap_from_ulong) +#define hwloc_bitmap_from_ulongs HWLOC_NAME(bitmap_from_ulongs) +#define hwloc_bitmap_from_ith_ulong HWLOC_NAME(bitmap_from_ith_ulong) +#define hwloc_bitmap_to_ulong HWLOC_NAME(bitmap_to_ulong) +#define hwloc_bitmap_to_ith_ulong HWLOC_NAME(bitmap_to_ith_ulong) +#define hwloc_bitmap_to_ulongs HWLOC_NAME(bitmap_to_ulongs) +#define hwloc_bitmap_nr_ulongs HWLOC_NAME(bitmap_nr_ulongs) +#define hwloc_bitmap_only HWLOC_NAME(bitmap_only) +#define hwloc_bitmap_allbut HWLOC_NAME(bitmap_allbut) +#define hwloc_bitmap_set HWLOC_NAME(bitmap_set) +#define hwloc_bitmap_set_range HWLOC_NAME(bitmap_set_range) +#define hwloc_bitmap_set_ith_ulong HWLOC_NAME(bitmap_set_ith_ulong) +#define hwloc_bitmap_clr HWLOC_NAME(bitmap_clr) +#define hwloc_bitmap_clr_range HWLOC_NAME(bitmap_clr_range) +#define hwloc_bitmap_isset HWLOC_NAME(bitmap_isset) +#define hwloc_bitmap_iszero HWLOC_NAME(bitmap_iszero) +#define hwloc_bitmap_isfull HWLOC_NAME(bitmap_isfull) +#define hwloc_bitmap_isequal HWLOC_NAME(bitmap_isequal) +#define hwloc_bitmap_intersects HWLOC_NAME(bitmap_intersects) +#define hwloc_bitmap_isincluded HWLOC_NAME(bitmap_isincluded) +#define hwloc_bitmap_or HWLOC_NAME(bitmap_or) +#define hwloc_bitmap_and HWLOC_NAME(bitmap_and) +#define hwloc_bitmap_andnot HWLOC_NAME(bitmap_andnot) +#define hwloc_bitmap_xor HWLOC_NAME(bitmap_xor) +#define hwloc_bitmap_not HWLOC_NAME(bitmap_not) +#define hwloc_bitmap_first HWLOC_NAME(bitmap_first) +#define hwloc_bitmap_last HWLOC_NAME(bitmap_last) +#define hwloc_bitmap_next HWLOC_NAME(bitmap_next) +#define hwloc_bitmap_first_unset HWLOC_NAME(bitmap_first_unset) +#define hwloc_bitmap_last_unset HWLOC_NAME(bitmap_last_unset) +#define hwloc_bitmap_next_unset HWLOC_NAME(bitmap_next_unset) +#define hwloc_bitmap_singlify HWLOC_NAME(bitmap_singlify) +#define hwloc_bitmap_compare_first HWLOC_NAME(bitmap_compare_first) +#define hwloc_bitmap_compare HWLOC_NAME(bitmap_compare) +#define hwloc_bitmap_weight HWLOC_NAME(bitmap_weight) + +/* hwloc/helper.h */ + +#define hwloc_get_type_or_below_depth HWLOC_NAME(get_type_or_below_depth) +#define hwloc_get_type_or_above_depth HWLOC_NAME(get_type_or_above_depth) +#define hwloc_get_root_obj HWLOC_NAME(get_root_obj) +#define hwloc_get_ancestor_obj_by_depth HWLOC_NAME(get_ancestor_obj_by_depth) +#define hwloc_get_ancestor_obj_by_type HWLOC_NAME(get_ancestor_obj_by_type) +#define hwloc_get_next_obj_by_depth HWLOC_NAME(get_next_obj_by_depth) +#define hwloc_get_next_obj_by_type HWLOC_NAME(get_next_obj_by_type) +#define hwloc_bitmap_singlify_per_core HWLOC_NAME(bitmap_singlify_by_core) +#define hwloc_get_pu_obj_by_os_index HWLOC_NAME(get_pu_obj_by_os_index) +#define hwloc_get_numanode_obj_by_os_index HWLOC_NAME(get_numanode_obj_by_os_index) +#define hwloc_get_next_child HWLOC_NAME(get_next_child) +#define hwloc_get_common_ancestor_obj HWLOC_NAME(get_common_ancestor_obj) +#define hwloc_obj_is_in_subtree HWLOC_NAME(obj_is_in_subtree) +#define hwloc_get_first_largest_obj_inside_cpuset HWLOC_NAME(get_first_largest_obj_inside_cpuset) +#define hwloc_get_largest_objs_inside_cpuset HWLOC_NAME(get_largest_objs_inside_cpuset) +#define hwloc_get_next_obj_inside_cpuset_by_depth HWLOC_NAME(get_next_obj_inside_cpuset_by_depth) +#define hwloc_get_next_obj_inside_cpuset_by_type HWLOC_NAME(get_next_obj_inside_cpuset_by_type) +#define hwloc_get_obj_inside_cpuset_by_depth HWLOC_NAME(get_obj_inside_cpuset_by_depth) +#define hwloc_get_obj_inside_cpuset_by_type HWLOC_NAME(get_obj_inside_cpuset_by_type) +#define hwloc_get_nbobjs_inside_cpuset_by_depth HWLOC_NAME(get_nbobjs_inside_cpuset_by_depth) +#define hwloc_get_nbobjs_inside_cpuset_by_type HWLOC_NAME(get_nbobjs_inside_cpuset_by_type) +#define hwloc_get_obj_index_inside_cpuset HWLOC_NAME(get_obj_index_inside_cpuset) +#define hwloc_get_child_covering_cpuset HWLOC_NAME(get_child_covering_cpuset) +#define hwloc_get_obj_covering_cpuset HWLOC_NAME(get_obj_covering_cpuset) +#define hwloc_get_next_obj_covering_cpuset_by_depth HWLOC_NAME(get_next_obj_covering_cpuset_by_depth) +#define hwloc_get_next_obj_covering_cpuset_by_type HWLOC_NAME(get_next_obj_covering_cpuset_by_type) +#define hwloc_obj_type_is_normal HWLOC_NAME(obj_type_is_normal) +#define hwloc_obj_type_is_memory HWLOC_NAME(obj_type_is_memory) +#define hwloc_obj_type_is_io HWLOC_NAME(obj_type_is_io) +#define hwloc_obj_type_is_cache HWLOC_NAME(obj_type_is_cache) +#define hwloc_obj_type_is_dcache HWLOC_NAME(obj_type_is_dcache) +#define hwloc_obj_type_is_icache HWLOC_NAME(obj_type_is_icache) +#define hwloc_get_cache_type_depth HWLOC_NAME(get_cache_type_depth) +#define hwloc_get_cache_covering_cpuset HWLOC_NAME(get_cache_covering_cpuset) +#define hwloc_get_shared_cache_covering_obj HWLOC_NAME(get_shared_cache_covering_obj) +#define hwloc_get_closest_objs HWLOC_NAME(get_closest_objs) +#define hwloc_get_obj_below_by_type HWLOC_NAME(get_obj_below_by_type) +#define hwloc_get_obj_below_array_by_type HWLOC_NAME(get_obj_below_array_by_type) +#define hwloc_get_obj_with_same_locality HWLOC_NAME(get_obj_with_same_locality) +#define hwloc_distrib_flags_e HWLOC_NAME(distrib_flags_e) +#define HWLOC_DISTRIB_FLAG_REVERSE HWLOC_NAME_CAPS(DISTRIB_FLAG_REVERSE) +#define hwloc_distrib HWLOC_NAME(distrib) +#define hwloc_alloc_membind_policy HWLOC_NAME(alloc_membind_policy) +#define hwloc_alloc_membind_policy_nodeset HWLOC_NAME(alloc_membind_policy_nodeset) +#define hwloc_topology_get_complete_cpuset HWLOC_NAME(topology_get_complete_cpuset) +#define hwloc_topology_get_topology_cpuset HWLOC_NAME(topology_get_topology_cpuset) +#define hwloc_topology_get_allowed_cpuset HWLOC_NAME(topology_get_allowed_cpuset) +#define hwloc_topology_get_complete_nodeset HWLOC_NAME(topology_get_complete_nodeset) +#define hwloc_topology_get_topology_nodeset HWLOC_NAME(topology_get_topology_nodeset) +#define hwloc_topology_get_allowed_nodeset HWLOC_NAME(topology_get_allowed_nodeset) +#define hwloc_cpuset_to_nodeset HWLOC_NAME(cpuset_to_nodeset) +#define hwloc_cpuset_from_nodeset HWLOC_NAME(cpuset_from_nodeset) + +/* memattrs.h */ + +#define hwloc_memattr_id_e HWLOC_NAME(memattr_id_e) +#define HWLOC_MEMATTR_ID_CAPACITY HWLOC_NAME_CAPS(MEMATTR_ID_CAPACITY) +#define HWLOC_MEMATTR_ID_LOCALITY HWLOC_NAME_CAPS(MEMATTR_ID_LOCALITY) +#define HWLOC_MEMATTR_ID_BANDWIDTH HWLOC_NAME_CAPS(MEMATTR_ID_BANDWIDTH) +#define HWLOC_MEMATTR_ID_LATENCY HWLOC_NAME_CAPS(MEMATTR_ID_LATENCY) + +#define hwloc_memattr_id_t HWLOC_NAME(memattr_id_t) +#define hwloc_memattr_get_by_name HWLOC_NAME(memattr_get_by_name) + +#define hwloc_location HWLOC_NAME(location) +#define hwloc_location_type_e HWLOC_NAME(location_type_e) +#define HWLOC_LOCATION_TYPE_OBJECT HWLOC_NAME_CAPS(LOCATION_TYPE_OBJECT) +#define HWLOC_LOCATION_TYPE_CPUSET HWLOC_NAME_CAPS(LOCATION_TYPE_CPUSET) +#define hwloc_location_u HWLOC_NAME(location_u) + +#define hwloc_memattr_get_value HWLOC_NAME(memattr_get_value) +#define hwloc_memattr_get_best_target HWLOC_NAME(memattr_get_best_target) +#define hwloc_memattr_get_best_initiator HWLOC_NAME(memattr_get_best_initiator) + +#define hwloc_local_numanode_flag_e HWLOC_NAME(local_numanode_flag_e) +#define HWLOC_LOCAL_NUMANODE_FLAG_LARGER_LOCALITY HWLOC_NAME_CAPS(LOCAL_NUMANODE_FLAG_LARGER_LOCALITY) +#define HWLOC_LOCAL_NUMANODE_FLAG_SMALLER_LOCALITY HWLOC_NAME_CAPS(LOCAL_NUMANODE_FLAG_SMALLER_LOCALITY) +#define HWLOC_LOCAL_NUMANODE_FLAG_ALL HWLOC_NAME_CAPS(LOCAL_NUMANODE_FLAG_ALL) +#define hwloc_get_local_numanode_objs HWLOC_NAME(get_local_numanode_objs) + +#define hwloc_memattr_get_name HWLOC_NAME(memattr_get_name) +#define hwloc_memattr_get_flags HWLOC_NAME(memattr_get_flags) +#define hwloc_memattr_flag_e HWLOC_NAME(memattr_flag_e) +#define HWLOC_MEMATTR_FLAG_HIGHER_FIRST HWLOC_NAME_CAPS(MEMATTR_FLAG_HIGHER_FIRST) +#define HWLOC_MEMATTR_FLAG_LOWER_FIRST HWLOC_NAME_CAPS(MEMATTR_FLAG_LOWER_FIRST) +#define HWLOC_MEMATTR_FLAG_NEED_INITIATOR HWLOC_NAME_CAPS(MEMATTR_FLAG_NEED_INITIATOR) +#define hwloc_memattr_register HWLOC_NAME(memattr_register) +#define hwloc_memattr_set_value HWLOC_NAME(memattr_set_value) +#define hwloc_memattr_get_targets HWLOC_NAME(memattr_get_targets) +#define hwloc_memattr_get_initiators HWLOC_NAME(memattr_get_initiators) + +/* cpukinds.h */ + +#define hwloc_cpukinds_get_nr HWLOC_NAME(cpukinds_get_nr) +#define hwloc_cpukinds_get_by_cpuset HWLOC_NAME(cpukinds_get_by_cpuset) +#define hwloc_cpukinds_get_info HWLOC_NAME(cpukinds_get_info) +#define hwloc_cpukinds_register HWLOC_NAME(cpukinds_register) + +/* export.h */ + +#define hwloc_topology_export_xml_flags_e HWLOC_NAME(topology_export_xml_flags_e) +#define HWLOC_TOPOLOGY_EXPORT_XML_FLAG_V1 HWLOC_NAME_CAPS(TOPOLOGY_EXPORT_XML_FLAG_V1) +#define hwloc_topology_export_xml HWLOC_NAME(topology_export_xml) +#define hwloc_topology_export_xmlbuffer HWLOC_NAME(topology_export_xmlbuffer) +#define hwloc_free_xmlbuffer HWLOC_NAME(free_xmlbuffer) +#define hwloc_topology_set_userdata_export_callback HWLOC_NAME(topology_set_userdata_export_callback) +#define hwloc_export_obj_userdata HWLOC_NAME(export_obj_userdata) +#define hwloc_export_obj_userdata_base64 HWLOC_NAME(export_obj_userdata_base64) +#define hwloc_topology_set_userdata_import_callback HWLOC_NAME(topology_set_userdata_import_callback) + +#define hwloc_topology_export_synthetic_flags_e HWLOC_NAME(topology_export_synthetic_flags_e) +#define HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_NO_EXTENDED_TYPES HWLOC_NAME_CAPS(TOPOLOGY_EXPORT_SYNTHETIC_FLAG_NO_EXTENDED_TYPES) +#define HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_NO_ATTRS HWLOC_NAME_CAPS(TOPOLOGY_EXPORT_SYNTHETIC_FLAG_NO_ATTRS) +#define HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_V1 HWLOC_NAME_CAPS(TOPOLOGY_EXPORT_SYNTHETIC_FLAG_V1) +#define HWLOC_TOPOLOGY_EXPORT_SYNTHETIC_FLAG_IGNORE_MEMORY HWLOC_NAME_CAPS(TOPOLOGY_EXPORT_SYNTHETIC_FLAG_IGNORE_MEMORY) +#define hwloc_topology_export_synthetic HWLOC_NAME(topology_export_synthetic) + +/* distances.h */ + +#define hwloc_distances_s HWLOC_NAME(distances_s) + +#define hwloc_distances_kind_e HWLOC_NAME(distances_kind_e) +#define HWLOC_DISTANCES_KIND_FROM_OS HWLOC_NAME_CAPS(DISTANCES_KIND_FROM_OS) +#define HWLOC_DISTANCES_KIND_FROM_USER HWLOC_NAME_CAPS(DISTANCES_KIND_FROM_USER) +#define HWLOC_DISTANCES_KIND_MEANS_LATENCY HWLOC_NAME_CAPS(DISTANCES_KIND_MEANS_LATENCY) +#define HWLOC_DISTANCES_KIND_MEANS_BANDWIDTH HWLOC_NAME_CAPS(DISTANCES_KIND_MEANS_BANDWIDTH) +#define HWLOC_DISTANCES_KIND_HETEROGENEOUS_TYPES HWLOC_NAME_CAPS(DISTANCES_KIND_HETEROGENEOUS_TYPES) + +#define hwloc_distances_get HWLOC_NAME(distances_get) +#define hwloc_distances_get_by_depth HWLOC_NAME(distances_get_by_depth) +#define hwloc_distances_get_by_type HWLOC_NAME(distances_get_by_type) +#define hwloc_distances_get_by_name HWLOC_NAME(distances_get_by_name) +#define hwloc_distances_get_name HWLOC_NAME(distances_get_name) +#define hwloc_distances_release HWLOC_NAME(distances_release) +#define hwloc_distances_obj_index HWLOC_NAME(distances_obj_index) +#define hwloc_distances_obj_pair_values HWLOC_NAME(distances_pair_values) + +#define hwloc_distances_transform_e HWLOC_NAME(distances_transform_e) +#define HWLOC_DISTANCES_TRANSFORM_REMOVE_NULL HWLOC_NAME_CAPS(DISTANCES_TRANSFORM_REMOVE_NULL) +#define HWLOC_DISTANCES_TRANSFORM_LINKS HWLOC_NAME_CAPS(DISTANCES_TRANSFORM_LINKS) +#define HWLOC_DISTANCES_TRANSFORM_MERGE_SWITCH_PORTS HWLOC_NAME_CAPS(DISTANCES_TRANSFORM_MERGE_SWITCH_PORTS) +#define HWLOC_DISTANCES_TRANSFORM_TRANSITIVE_CLOSURE HWLOC_NAME_CAPS(DISTANCES_TRANSFORM_TRANSITIVE_CLOSURE) +#define hwloc_distances_transform HWLOC_NAME(distances_transform) + +#define hwloc_distances_add_flag_e HWLOC_NAME(distances_add_flag_e) +#define HWLOC_DISTANCES_ADD_FLAG_GROUP HWLOC_NAME_CAPS(DISTANCES_ADD_FLAG_GROUP) +#define HWLOC_DISTANCES_ADD_FLAG_GROUP_INACCURATE HWLOC_NAME_CAPS(DISTANCES_ADD_FLAG_GROUP_INACCURATE) + +#define hwloc_distances_add_handle_t HWLOC_NAME(distances_add_handle_t) +#define hwloc_distances_add_create HWLOC_NAME(distances_add_create) +#define hwloc_distances_add_values HWLOC_NAME(distances_add_values) +#define hwloc_distances_add_commit HWLOC_NAME(distances_add_commit) + +#define hwloc_distances_remove HWLOC_NAME(distances_remove) +#define hwloc_distances_remove_by_depth HWLOC_NAME(distances_remove_by_depth) +#define hwloc_distances_remove_by_type HWLOC_NAME(distances_remove_by_type) +#define hwloc_distances_release_remove HWLOC_NAME(distances_release_remove) + +/* diff.h */ + +#define hwloc_topology_diff_obj_attr_type_e HWLOC_NAME(topology_diff_obj_attr_type_e) +#define hwloc_topology_diff_obj_attr_type_t HWLOC_NAME(topology_diff_obj_attr_type_t) +#define HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_SIZE HWLOC_NAME_CAPS(TOPOLOGY_DIFF_OBJ_ATTR_SIZE) +#define HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_NAME HWLOC_NAME_CAPS(TOPOLOGY_DIFF_OBJ_ATTR_NAME) +#define HWLOC_TOPOLOGY_DIFF_OBJ_ATTR_INFO HWLOC_NAME_CAPS(TOPOLOGY_DIFF_OBJ_ATTR_INFO) +#define hwloc_topology_diff_obj_attr_u HWLOC_NAME(topology_diff_obj_attr_u) +#define hwloc_topology_diff_obj_attr_generic_s HWLOC_NAME(topology_diff_obj_attr_generic_s) +#define hwloc_topology_diff_obj_attr_uint64_s HWLOC_NAME(topology_diff_obj_attr_uint64_s) +#define hwloc_topology_diff_obj_attr_string_s HWLOC_NAME(topology_diff_obj_attr_string_s) +#define hwloc_topology_diff_type_e HWLOC_NAME(topology_diff_type_e) +#define hwloc_topology_diff_type_t HWLOC_NAME(topology_diff_type_t) +#define HWLOC_TOPOLOGY_DIFF_OBJ_ATTR HWLOC_NAME_CAPS(TOPOLOGY_DIFF_OBJ_ATTR) +#define HWLOC_TOPOLOGY_DIFF_TOO_COMPLEX HWLOC_NAME_CAPS(TOPOLOGY_DIFF_TOO_COMPLEX) +#define hwloc_topology_diff_u HWLOC_NAME(topology_diff_u) +#define hwloc_topology_diff_t HWLOC_NAME(topology_diff_t) +#define hwloc_topology_diff_generic_s HWLOC_NAME(topology_diff_generic_s) +#define hwloc_topology_diff_obj_attr_s HWLOC_NAME(topology_diff_obj_attr_s) +#define hwloc_topology_diff_too_complex_s HWLOC_NAME(topology_diff_too_complex_s) +#define hwloc_topology_diff_build HWLOC_NAME(topology_diff_build) +#define hwloc_topology_diff_apply_flags_e HWLOC_NAME(topology_diff_apply_flags_e) +#define HWLOC_TOPOLOGY_DIFF_APPLY_REVERSE HWLOC_NAME_CAPS(TOPOLOGY_DIFF_APPLY_REVERSE) +#define hwloc_topology_diff_apply HWLOC_NAME(topology_diff_apply) +#define hwloc_topology_diff_destroy HWLOC_NAME(topology_diff_destroy) +#define hwloc_topology_diff_load_xml HWLOC_NAME(topology_diff_load_xml) +#define hwloc_topology_diff_export_xml HWLOC_NAME(topology_diff_export_xml) +#define hwloc_topology_diff_load_xmlbuffer HWLOC_NAME(topology_diff_load_xmlbuffer) +#define hwloc_topology_diff_export_xmlbuffer HWLOC_NAME(topology_diff_export_xmlbuffer) + +/* shmem.h */ + +#define hwloc_shmem_topology_get_length HWLOC_NAME(shmem_topology_get_length) +#define hwloc_shmem_topology_write HWLOC_NAME(shmem_topology_write) +#define hwloc_shmem_topology_adopt HWLOC_NAME(shmem_topology_adopt) + +/* glibc-sched.h */ + +#define hwloc_cpuset_to_glibc_sched_affinity HWLOC_NAME(cpuset_to_glibc_sched_affinity) +#define hwloc_cpuset_from_glibc_sched_affinity HWLOC_NAME(cpuset_from_glibc_sched_affinity) + +/* linux-libnuma.h */ + +#define hwloc_cpuset_to_linux_libnuma_ulongs HWLOC_NAME(cpuset_to_linux_libnuma_ulongs) +#define hwloc_nodeset_to_linux_libnuma_ulongs HWLOC_NAME(nodeset_to_linux_libnuma_ulongs) +#define hwloc_cpuset_from_linux_libnuma_ulongs HWLOC_NAME(cpuset_from_linux_libnuma_ulongs) +#define hwloc_nodeset_from_linux_libnuma_ulongs HWLOC_NAME(nodeset_from_linux_libnuma_ulongs) +#define hwloc_cpuset_to_linux_libnuma_bitmask HWLOC_NAME(cpuset_to_linux_libnuma_bitmask) +#define hwloc_nodeset_to_linux_libnuma_bitmask HWLOC_NAME(nodeset_to_linux_libnuma_bitmask) +#define hwloc_cpuset_from_linux_libnuma_bitmask HWLOC_NAME(cpuset_from_linux_libnuma_bitmask) +#define hwloc_nodeset_from_linux_libnuma_bitmask HWLOC_NAME(nodeset_from_linux_libnuma_bitmask) + +/* linux.h */ + +#define hwloc_linux_set_tid_cpubind HWLOC_NAME(linux_set_tid_cpubind) +#define hwloc_linux_get_tid_cpubind HWLOC_NAME(linux_get_tid_cpubind) +#define hwloc_linux_get_tid_last_cpu_location HWLOC_NAME(linux_get_tid_last_cpu_location) +#define hwloc_linux_read_path_as_cpumask HWLOC_NAME(linux_read_file_cpumask) + +/* windows.h */ + +#define hwloc_windows_get_nr_processor_groups HWLOC_NAME(windows_get_nr_processor_groups) +#define hwloc_windows_get_processor_group_cpuset HWLOC_NAME(windows_get_processor_group_cpuset) + +/* openfabrics-verbs.h */ + +#define hwloc_ibv_get_device_cpuset HWLOC_NAME(ibv_get_device_cpuset) +#define hwloc_ibv_get_device_osdev HWLOC_NAME(ibv_get_device_osdev) +#define hwloc_ibv_get_device_osdev_by_name HWLOC_NAME(ibv_get_device_osdev_by_name) + +/* opencl.h */ + +#define hwloc_cl_device_topology_amd HWLOC_NAME(cl_device_topology_amd) +#define hwloc_opencl_get_device_pci_busid HWLOC_NAME(opencl_get_device_pci_ids) +#define hwloc_opencl_get_device_cpuset HWLOC_NAME(opencl_get_device_cpuset) +#define hwloc_opencl_get_device_osdev HWLOC_NAME(opencl_get_device_osdev) +#define hwloc_opencl_get_device_osdev_by_index HWLOC_NAME(opencl_get_device_osdev_by_index) + +/* cuda.h */ + +#define hwloc_cuda_get_device_pci_ids HWLOC_NAME(cuda_get_device_pci_ids) +#define hwloc_cuda_get_device_cpuset HWLOC_NAME(cuda_get_device_cpuset) +#define hwloc_cuda_get_device_pcidev HWLOC_NAME(cuda_get_device_pcidev) +#define hwloc_cuda_get_device_osdev HWLOC_NAME(cuda_get_device_osdev) +#define hwloc_cuda_get_device_osdev_by_index HWLOC_NAME(cuda_get_device_osdev_by_index) + +/* cudart.h */ + +#define hwloc_cudart_get_device_pci_ids HWLOC_NAME(cudart_get_device_pci_ids) +#define hwloc_cudart_get_device_cpuset HWLOC_NAME(cudart_get_device_cpuset) +#define hwloc_cudart_get_device_pcidev HWLOC_NAME(cudart_get_device_pcidev) +#define hwloc_cudart_get_device_osdev_by_index HWLOC_NAME(cudart_get_device_osdev_by_index) + +/* nvml.h */ + +#define hwloc_nvml_get_device_cpuset HWLOC_NAME(nvml_get_device_cpuset) +#define hwloc_nvml_get_device_osdev HWLOC_NAME(nvml_get_device_osdev) +#define hwloc_nvml_get_device_osdev_by_index HWLOC_NAME(nvml_get_device_osdev_by_index) + +/* rsmi.h */ + +#define hwloc_rsmi_get_device_cpuset HWLOC_NAME(rsmi_get_device_cpuset) +#define hwloc_rsmi_get_device_osdev HWLOC_NAME(rsmi_get_device_osdev) +#define hwloc_rsmi_get_device_osdev_by_index HWLOC_NAME(rsmi_get_device_osdev_by_index) + +/* levelzero.h */ + +#define hwloc_levelzero_get_device_cpuset HWLOC_NAME(levelzero_get_device_cpuset) +#define hwloc_levelzero_get_device_osdev HWLOC_NAME(levelzero_get_device_osdev) + +/* gl.h */ + +#define hwloc_gl_get_display_osdev_by_port_device HWLOC_NAME(gl_get_display_osdev_by_port_device) +#define hwloc_gl_get_display_osdev_by_name HWLOC_NAME(gl_get_display_osdev_by_name) +#define hwloc_gl_get_display_by_osdev HWLOC_NAME(gl_get_display_by_osdev) + +/* hwloc/plugins.h */ + +#define hwloc_disc_phase_e HWLOC_NAME(disc_phase_e) +#define HWLOC_DISC_PHASE_GLOBAL HWLOC_NAME_CAPS(DISC_PHASE_GLOBAL) +#define HWLOC_DISC_PHASE_CPU HWLOC_NAME_CAPS(DISC_PHASE_CPU) +#define HWLOC_DISC_PHASE_MEMORY HWLOC_NAME_CAPS(DISC_PHASE_MEMORY) +#define HWLOC_DISC_PHASE_PCI HWLOC_NAME_CAPS(DISC_PHASE_PCI) +#define HWLOC_DISC_PHASE_IO HWLOC_NAME_CAPS(DISC_PHASE_IO) +#define HWLOC_DISC_PHASE_MISC HWLOC_NAME_CAPS(DISC_PHASE_MISC) +#define HWLOC_DISC_PHASE_ANNOTATE HWLOC_NAME_CAPS(DISC_PHASE_ANNOTATE) +#define HWLOC_DISC_PHASE_TWEAK HWLOC_NAME_CAPS(DISC_PHASE_TWEAK) +#define hwloc_disc_phase_t HWLOC_NAME(disc_phase_t) +#define hwloc_disc_component HWLOC_NAME(disc_component) + +#define hwloc_disc_status_flag_e HWLOC_NAME(disc_status_flag_e) +#define HWLOC_DISC_STATUS_FLAG_GOT_ALLOWED_RESOURCES HWLOC_NAME_CAPS(DISC_STATUS_FLAG_GOT_ALLOWED_RESOURCES) +#define hwloc_disc_status HWLOC_NAME(disc_status) + +#define hwloc_backend HWLOC_NAME(backend) + +#define hwloc_backend_alloc HWLOC_NAME(backend_alloc) +#define hwloc_backend_enable HWLOC_NAME(backend_enable) + +#define hwloc_component_type_e HWLOC_NAME(component_type_e) +#define HWLOC_COMPONENT_TYPE_DISC HWLOC_NAME_CAPS(COMPONENT_TYPE_DISC) +#define HWLOC_COMPONENT_TYPE_XML HWLOC_NAME_CAPS(COMPONENT_TYPE_XML) +#define hwloc_component_type_t HWLOC_NAME(component_type_t) +#define hwloc_component HWLOC_NAME(component) + +#define hwloc_plugin_check_namespace HWLOC_NAME(plugin_check_namespace) + +#define hwloc_hide_errors HWLOC_NAME(hide_errors) +#define hwloc__insert_object_by_cpuset HWLOC_NAME(_insert_object_by_cpuset) +#define hwloc_insert_object_by_parent HWLOC_NAME(insert_object_by_parent) +#define hwloc_alloc_setup_object HWLOC_NAME(alloc_setup_object) +#define hwloc_obj_add_children_sets HWLOC_NAME(add_children_sets) +#define hwloc_topology_reconnect HWLOC_NAME(topology_reconnect) + +#define hwloc_filter_check_pcidev_subtype_important HWLOC_NAME(filter_check_pcidev_subtype_important) +#define hwloc_filter_check_osdev_subtype_important HWLOC_NAME(filter_check_osdev_subtype_important) +#define hwloc_filter_check_keep_object_type HWLOC_NAME(filter_check_keep_object_type) +#define hwloc_filter_check_keep_object HWLOC_NAME(filter_check_keep_object) + +#define hwloc_pcidisc_find_cap HWLOC_NAME(pcidisc_find_cap) +#define hwloc_pcidisc_find_linkspeed HWLOC_NAME(pcidisc_find_linkspeed) +#define hwloc_pcidisc_check_bridge_type HWLOC_NAME(pcidisc_check_bridge_type) +#define hwloc_pcidisc_find_bridge_buses HWLOC_NAME(pcidisc_find_bridge_buses) +#define hwloc_pcidisc_tree_insert_by_busid HWLOC_NAME(pcidisc_tree_insert_by_busid) +#define hwloc_pcidisc_tree_attach HWLOC_NAME(pcidisc_tree_attach) + +#define hwloc_pci_find_by_busid HWLOC_NAME(pcidisc_find_by_busid) +#define hwloc_pci_find_parent_by_busid HWLOC_NAME(pcidisc_find_busid_parent) + +#define hwloc_backend_distances_add_handle_t HWLOC_NAME(backend_distances_add_handle_t) +#define hwloc_backend_distances_add_create HWLOC_NAME(backend_distances_add_create) +#define hwloc_backend_distances_add_values HWLOC_NAME(backend_distances_add_values) +#define hwloc_backend_distances_add_commit HWLOC_NAME(backend_distances_add_commit) + +/* hwloc/deprecated.h */ + +#define hwloc_distances_add HWLOC_NAME(distances_add) + +#define hwloc_topology_insert_misc_object_by_parent HWLOC_NAME(topology_insert_misc_object_by_parent) +#define hwloc_obj_cpuset_snprintf HWLOC_NAME(obj_cpuset_snprintf) +#define hwloc_obj_type_sscanf HWLOC_NAME(obj_type_sscanf) + +#define hwloc_set_membind_nodeset HWLOC_NAME(set_membind_nodeset) +#define hwloc_get_membind_nodeset HWLOC_NAME(get_membind_nodeset) +#define hwloc_set_proc_membind_nodeset HWLOC_NAME(set_proc_membind_nodeset) +#define hwloc_get_proc_membind_nodeset HWLOC_NAME(get_proc_membind_nodeset) +#define hwloc_set_area_membind_nodeset HWLOC_NAME(set_area_membind_nodeset) +#define hwloc_get_area_membind_nodeset HWLOC_NAME(get_area_membind_nodeset) +#define hwloc_alloc_membind_nodeset HWLOC_NAME(alloc_membind_nodeset) + +#define hwloc_cpuset_to_nodeset_strict HWLOC_NAME(cpuset_to_nodeset_strict) +#define hwloc_cpuset_from_nodeset_strict HWLOC_NAME(cpuset_from_nodeset_strict) + +/* private/debug.h */ + +#define hwloc_debug_enabled HWLOC_NAME(debug_enabled) +#define hwloc_debug HWLOC_NAME(debug) + +/* private/misc.h */ + +#ifndef HWLOC_HAVE_CORRECT_SNPRINTF +#define hwloc_snprintf HWLOC_NAME(snprintf) +#endif +#define hwloc_ffsl_manual HWLOC_NAME(ffsl_manual) +#define hwloc_ffs32 HWLOC_NAME(ffs32) +#define hwloc_ffsl_from_ffs32 HWLOC_NAME(ffsl_from_ffs32) +#define hwloc_flsl_manual HWLOC_NAME(flsl_manual) +#define hwloc_fls32 HWLOC_NAME(fls32) +#define hwloc_flsl_from_fls32 HWLOC_NAME(flsl_from_fls32) +#define hwloc_weight_long HWLOC_NAME(weight_long) +#define hwloc_strncasecmp HWLOC_NAME(strncasecmp) + +#define hwloc_bitmap_compare_inclusion HWLOC_NAME(bitmap_compare_inclusion) + +#define hwloc_pci_class_string HWLOC_NAME(pci_class_string) +#define hwloc_linux_pci_link_speed_from_string HWLOC_NAME(linux_pci_link_speed_from_string) + +#define hwloc_cache_type_by_depth_type HWLOC_NAME(cache_type_by_depth_type) +#define hwloc__obj_type_is_normal HWLOC_NAME(_obj_type_is_normal) +#define hwloc__obj_type_is_memory HWLOC_NAME(_obj_type_is_memory) +#define hwloc__obj_type_is_io HWLOC_NAME(_obj_type_is_io) +#define hwloc__obj_type_is_special HWLOC_NAME(_obj_type_is_special) + +#define hwloc__obj_type_is_cache HWLOC_NAME(_obj_type_is_cache) +#define hwloc__obj_type_is_dcache HWLOC_NAME(_obj_type_is_dcache) +#define hwloc__obj_type_is_icache HWLOC_NAME(_obj_type_is_icache) + +/* private/cpuid-x86.h */ + +#define hwloc_have_x86_cpuid HWLOC_NAME(have_x86_cpuid) +#define hwloc_x86_cpuid HWLOC_NAME(x86_cpuid) + +/* private/xml.h */ + +#define hwloc__xml_verbose HWLOC_NAME(_xml_verbose) + +#define hwloc__xml_import_state_s HWLOC_NAME(_xml_import_state_s) +#define hwloc__xml_import_state_t HWLOC_NAME(_xml_import_state_t) +#define hwloc__xml_import_diff HWLOC_NAME(_xml_import_diff) +#define hwloc_xml_backend_data_s HWLOC_NAME(xml_backend_data_s) +#define hwloc__xml_export_state_s HWLOC_NAME(_xml_export_state_s) +#define hwloc__xml_export_state_t HWLOC_NAME(_xml_export_state_t) +#define hwloc__xml_export_data_s HWLOC_NAME(_xml_export_data_s) +#define hwloc__xml_export_topology HWLOC_NAME(_xml_export_topology) +#define hwloc__xml_export_diff HWLOC_NAME(_xml_export_diff) + +#define hwloc_xml_callbacks HWLOC_NAME(xml_callbacks) +#define hwloc_xml_component HWLOC_NAME(xml_component) +#define hwloc_xml_callbacks_register HWLOC_NAME(xml_callbacks_register) +#define hwloc_xml_callbacks_reset HWLOC_NAME(xml_callbacks_reset) + +#define hwloc__xml_imported_v1distances_s HWLOC_NAME(_xml_imported_v1distances_s) + +/* private/components.h */ + +#define hwloc_disc_component_force_enable HWLOC_NAME(disc_component_force_enable) +#define hwloc_disc_components_enable_others HWLOC_NAME(disc_components_instantiate_others) + +#define hwloc_backends_is_thissystem HWLOC_NAME(backends_is_thissystem) +#define hwloc_backends_find_callbacks HWLOC_NAME(backends_find_callbacks) + +#define hwloc_topology_components_init HWLOC_NAME(topology_components_init) +#define hwloc_backends_disable_all HWLOC_NAME(backends_disable_all) +#define hwloc_topology_components_fini HWLOC_NAME(topology_components_fini) + +#define hwloc_components_init HWLOC_NAME(components_init) +#define hwloc_components_fini HWLOC_NAME(components_fini) + +/* private/internal-private.h */ + +#define hwloc_xml_component HWLOC_NAME(xml_component) +#define hwloc_synthetic_component HWLOC_NAME(synthetic_component) + +#define hwloc_aix_component HWLOC_NAME(aix_component) +#define hwloc_bgq_component HWLOC_NAME(bgq_component) +#define hwloc_darwin_component HWLOC_NAME(darwin_component) +#define hwloc_freebsd_component HWLOC_NAME(freebsd_component) +#define hwloc_hpux_component HWLOC_NAME(hpux_component) +#define hwloc_linux_component HWLOC_NAME(linux_component) +#define hwloc_netbsd_component HWLOC_NAME(netbsd_component) +#define hwloc_noos_component HWLOC_NAME(noos_component) +#define hwloc_solaris_component HWLOC_NAME(solaris_component) +#define hwloc_windows_component HWLOC_NAME(windows_component) +#define hwloc_x86_component HWLOC_NAME(x86_component) + +#define hwloc_cuda_component HWLOC_NAME(cuda_component) +#define hwloc_gl_component HWLOC_NAME(gl_component) +#define hwloc_levelzero_component HWLOC_NAME(levelzero_component) +#define hwloc_nvml_component HWLOC_NAME(nvml_component) +#define hwloc_rsmi_component HWLOC_NAME(rsmi_component) +#define hwloc_opencl_component HWLOC_NAME(opencl_component) +#define hwloc_pci_component HWLOC_NAME(pci_component) + +#define hwloc_xml_libxml_component HWLOC_NAME(xml_libxml_component) +#define hwloc_xml_nolibxml_component HWLOC_NAME(xml_nolibxml_component) + +/* private/private.h */ + +#define hwloc_internal_location_s HWLOC_NAME(internal_location_s) + +#define hwloc_special_level_s HWLOC_NAME(special_level_s) + +#define hwloc_pci_forced_locality_s HWLOC_NAME(pci_forced_locality_s) +#define hwloc_pci_locality_s HWLOC_NAME(pci_locality_s) + +#define hwloc_topology_forced_component_s HWLOC_NAME(topology_forced_component) + +#define hwloc_alloc_root_sets HWLOC_NAME(alloc_root_sets) +#define hwloc_setup_pu_level HWLOC_NAME(setup_pu_level) +#define hwloc_get_sysctlbyname HWLOC_NAME(get_sysctlbyname) +#define hwloc_get_sysctl HWLOC_NAME(get_sysctl) +#define hwloc_fallback_nbprocessors HWLOC_NAME(fallback_nbprocessors) +#define hwloc_fallback_memsize HWLOC_NAME(fallback_memsize) + +#define hwloc__object_cpusets_compare_first HWLOC_NAME(_object_cpusets_compare_first) +#define hwloc__reorder_children HWLOC_NAME(_reorder_children) + +#define hwloc_topology_setup_defaults HWLOC_NAME(topology_setup_defaults) +#define hwloc_topology_clear HWLOC_NAME(topology_clear) + +#define hwloc__attach_memory_object HWLOC_NAME(insert_memory_object) + +#define hwloc_get_obj_by_type_and_gp_index HWLOC_NAME(get_obj_by_type_and_gp_index) + +#define hwloc_pci_discovery_init HWLOC_NAME(pci_discovery_init) +#define hwloc_pci_discovery_prepare HWLOC_NAME(pci_discovery_prepare) +#define hwloc_pci_discovery_exit HWLOC_NAME(pci_discovery_exit) +#define hwloc_find_insert_io_parent_by_complete_cpuset HWLOC_NAME(hwloc_find_insert_io_parent_by_complete_cpuset) + +#define hwloc__add_info HWLOC_NAME(_add_info) +#define hwloc__add_info_nodup HWLOC_NAME(_add_info_nodup) +#define hwloc__move_infos HWLOC_NAME(_move_infos) +#define hwloc__free_infos HWLOC_NAME(_free_infos) +#define hwloc__tma_dup_infos HWLOC_NAME(_tma_dup_infos) + +#define hwloc_binding_hooks HWLOC_NAME(binding_hooks) +#define hwloc_set_native_binding_hooks HWLOC_NAME(set_native_binding_hooks) +#define hwloc_set_binding_hooks HWLOC_NAME(set_binding_hooks) + +#define hwloc_set_linuxfs_hooks HWLOC_NAME(set_linuxfs_hooks) +#define hwloc_set_bgq_hooks HWLOC_NAME(set_bgq_hooks) +#define hwloc_set_solaris_hooks HWLOC_NAME(set_solaris_hooks) +#define hwloc_set_aix_hooks HWLOC_NAME(set_aix_hooks) +#define hwloc_set_windows_hooks HWLOC_NAME(set_windows_hooks) +#define hwloc_set_darwin_hooks HWLOC_NAME(set_darwin_hooks) +#define hwloc_set_freebsd_hooks HWLOC_NAME(set_freebsd_hooks) +#define hwloc_set_netbsd_hooks HWLOC_NAME(set_netbsd_hooks) +#define hwloc_set_hpux_hooks HWLOC_NAME(set_hpux_hooks) + +#define hwloc_look_hardwired_fujitsu_k HWLOC_NAME(look_hardwired_fujitsu_k) +#define hwloc_look_hardwired_fujitsu_fx10 HWLOC_NAME(look_hardwired_fujitsu_fx10) +#define hwloc_look_hardwired_fujitsu_fx100 HWLOC_NAME(look_hardwired_fujitsu_fx100) + +#define hwloc_add_uname_info HWLOC_NAME(add_uname_info) +#define hwloc_free_unlinked_object HWLOC_NAME(free_unlinked_object) +#define hwloc_free_object_and_children HWLOC_NAME(free_object_and_children) +#define hwloc_free_object_siblings_and_children HWLOC_NAME(free_object_siblings_and_children) + +#define hwloc_alloc_heap HWLOC_NAME(alloc_heap) +#define hwloc_alloc_mmap HWLOC_NAME(alloc_mmap) +#define hwloc_free_heap HWLOC_NAME(free_heap) +#define hwloc_free_mmap HWLOC_NAME(free_mmap) +#define hwloc_alloc_or_fail HWLOC_NAME(alloc_or_fail) + +#define hwloc_internal_distances_s HWLOC_NAME(internal_distances_s) +#define hwloc_internal_distances_init HWLOC_NAME(internal_distances_init) +#define hwloc_internal_distances_prepare HWLOC_NAME(internal_distances_prepare) +#define hwloc_internal_distances_dup HWLOC_NAME(internal_distances_dup) +#define hwloc_internal_distances_refresh HWLOC_NAME(internal_distances_refresh) +#define hwloc_internal_distances_destroy HWLOC_NAME(internal_distances_destroy) +#define hwloc_internal_distances_add HWLOC_NAME(internal_distances_add) +#define hwloc_internal_distances_add_by_index HWLOC_NAME(internal_distances_add_by_index) +#define hwloc_internal_distances_invalidate_cached_objs HWLOC_NAME(hwloc_internal_distances_invalidate_cached_objs) + +#define hwloc_internal_memattr_s HWLOC_NAME(internal_memattr_s) +#define hwloc_internal_memattr_target_s HWLOC_NAME(internal_memattr_target_s) +#define hwloc_internal_memattr_initiator_s HWLOC_NAME(internal_memattr_initiator_s) +#define hwloc_internal_memattrs_init HWLOC_NAME(internal_memattrs_init) +#define hwloc_internal_memattrs_prepare HWLOC_NAME(internal_memattrs_prepare) +#define hwloc_internal_memattrs_dup HWLOC_NAME(internal_memattrs_dup) +#define hwloc_internal_memattrs_destroy HWLOC_NAME(internal_memattrs_destroy) +#define hwloc_internal_memattrs_need_refresh HWLOC_NAME(internal_memattrs_need_refresh) +#define hwloc_internal_memattrs_refresh HWLOC_NAME(internal_memattrs_refresh) + +#define hwloc_internal_cpukind_s HWLOC_NAME(internal_cpukind_s) +#define hwloc_internal_cpukinds_init HWLOC_NAME(internal_cpukinds_init) +#define hwloc_internal_cpukinds_destroy HWLOC_NAME(internal_cpukinds_destroy) +#define hwloc_internal_cpukinds_dup HWLOC_NAME(internal_cpukinds_dup) +#define hwloc_internal_cpukinds_register HWLOC_NAME(internal_cpukinds_register) +#define hwloc_internal_cpukinds_rank HWLOC_NAME(internal_cpukinds_rank) +#define hwloc_internal_cpukinds_restrict HWLOC_NAME(internal_cpukinds_restrict) + +#define hwloc_encode_to_base64 HWLOC_NAME(encode_to_base64) +#define hwloc_decode_from_base64 HWLOC_NAME(decode_from_base64) + +#define hwloc_progname HWLOC_NAME(progname) + +#define hwloc__topology_disadopt HWLOC_NAME(_topology_disadopt) +#define hwloc__topology_dup HWLOC_NAME(_topology_dup) + +#define hwloc_tma HWLOC_NAME(tma) +#define hwloc_tma_malloc HWLOC_NAME(tma_malloc) +#define hwloc_tma_calloc HWLOC_NAME(tma_calloc) +#define hwloc_tma_strdup HWLOC_NAME(tma_strdup) +#define hwloc_bitmap_tma_dup HWLOC_NAME(bitmap_tma_dup) + +/* private/solaris-chiptype.h */ + +#define hwloc_solaris_chip_info_s HWLOC_NAME(solaris_chip_info_s) +#define hwloc_solaris_get_chip_info HWLOC_NAME(solaris_get_chip_info) + +#endif /* HWLOC_SYM_TRANSFORM */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_RENAME_H */ diff --git a/deps/exla/cache/xla_extension/include/include/hwloc/shmem.h b/deps/exla/cache/xla_extension/include/include/hwloc/shmem.h new file mode 100644 index 0000000000000000000000000000000000000000..86f57b4f6826c9352245df1a9889553d6fd7c5bd --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/hwloc/shmem.h @@ -0,0 +1,137 @@ +/* + * Copyright © 2013-2018 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +/** \file + * \brief Sharing topologies between processes + */ + +#ifndef HWLOC_SHMEM_H +#define HWLOC_SHMEM_H + +#include "hwloc.h" + +#ifdef __cplusplus +extern "C" { +#elif 0 +} +#endif + + +/** \defgroup hwlocality_shmem Sharing topologies between processes + * + * These functions are used to share a topology between processes by + * duplicating it into a file-backed shared-memory buffer. + * + * The master process must first get the required shared-memory size + * for storing this topology with hwloc_shmem_topology_get_length(). + * + * Then it must find a virtual memory area of that size that is available + * in all processes (identical virtual addresses in all processes). + * On Linux, this can be done by comparing holes found in /proc/\/maps + * for each process. + * + * Once found, it must open a destination file for storing the buffer, + * and pass it to hwloc_shmem_topology_write() together with + * virtual memory address and length obtained above. + * + * Other processes may then adopt this shared topology by opening the + * same file and passing it to hwloc_shmem_topology_adopt() with the + * exact same virtual memory address and length. + * + * @{ + */ + +/** \brief Get the required shared memory length for storing a topology. + * + * This length (in bytes) must be used in hwloc_shmem_topology_write() + * and hwloc_shmem_topology_adopt() later. + * + * \note Flags \p flags are currently unused, must be 0. + */ +HWLOC_DECLSPEC int hwloc_shmem_topology_get_length(hwloc_topology_t topology, + size_t *lengthp, + unsigned long flags); + +/** \brief Duplicate a topology to a shared memory file. + * + * Temporarily map a file in virtual memory and duplicate the + * topology \p topology by allocating duplicates in there. + * + * The segment of the file pointed by descriptor \p fd, + * starting at offset \p fileoffset, and of length \p length (in bytes), + * will be temporarily mapped at virtual address \p mmap_address + * during the duplication. + * + * The mapping length \p length must have been previously obtained with + * hwloc_shmem_topology_get_length() + * and the topology must not have been modified in the meantime. + * + * \note Flags \p flags are currently unused, must be 0. + * + * \note The object userdata pointer is duplicated but the pointed buffer + * is not. However the caller may also allocate it manually in shared memory + * to share it as well. + * + * \return -1 with errno set to EBUSY if the virtual memory mapping defined + * by \p mmap_address and \p length isn't available in the process. + * \return -1 with errno set to EINVAL if \p fileoffset, \p mmap_address + * or \p length aren't page-aligned. + */ +HWLOC_DECLSPEC int hwloc_shmem_topology_write(hwloc_topology_t topology, + int fd, hwloc_uint64_t fileoffset, + void *mmap_address, size_t length, + unsigned long flags); + +/** \brief Adopt a shared memory topology stored in a file. + * + * Map a file in virtual memory and adopt the topology that was previously + * stored there with hwloc_shmem_topology_write(). + * + * The returned adopted topology in \p topologyp can be used just like any + * topology. And it must be destroyed with hwloc_topology_destroy() as usual. + * + * However the topology is read-only. + * For instance, it cannot be modified with hwloc_topology_restrict() + * and object userdata pointers cannot be changed. + * + * The segment of the file pointed by descriptor \p fd, + * starting at offset \p fileoffset, and of length \p length (in bytes), + * will be mapped at virtual address \p mmap_address. + * + * The file pointed by descriptor \p fd, the offset \p fileoffset, + * the requested mapping virtual address \p mmap_address and the length \p length + * must be identical to what was given to hwloc_shmem_topology_write() earlier. + * + * \note Flags \p flags are currently unused, must be 0. + * + * \note The object userdata pointer should not be used unless the process + * that created the shared topology also placed userdata-pointed buffers + * in shared memory. + * + * \note This function takes care of calling hwloc_topology_abi_check(). + * + * \return -1 with errno set to EBUSY if the virtual memory mapping defined + * by \p mmap_address and \p length isn't available in the process. + * + * \return -1 with errno set to EINVAL if \p fileoffset, \p mmap_address + * or \p length aren't page-aligned, or do not match what was given to + * hwloc_shmem_topology_write() earlier. + * + * \return -1 with errno set to EINVAL if the layout of the topology structure + * is different between the writer process and the adopter process. + */ +HWLOC_DECLSPEC int hwloc_shmem_topology_adopt(hwloc_topology_t *topologyp, + int fd, hwloc_uint64_t fileoffset, + void *mmap_address, size_t length, + unsigned long flags); +/** @} */ + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + + +#endif /* HWLOC_SHMEM_H */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl.h new file mode 100644 index 0000000000000000000000000000000000000000..73bf67a893006741b8caaccd7fb7e26a0eff5f2d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl.h @@ -0,0 +1,3895 @@ +/******************************************************************************* +* Copyright 2016-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C API + +#ifndef ONEAPI_DNNL_DNNL_H +#define ONEAPI_DNNL_DNNL_H + +#include "oneapi/dnnl/dnnl_common.h" +#include "oneapi/dnnl/dnnl_config.h" +#include "oneapi/dnnl/dnnl_types.h" +#include "oneapi/dnnl/dnnl_version.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_primitives +/// @{ + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// Changes the primitive descriptor to point to the next available +/// implementation. +/// +/// @param primitive_desc A primitive descriptor to change. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +/// @returns #dnnl_last_impl_reached if no more implementations available, +/// in which case the primitive descriptor itself is kept unchanged. +dnnl_status_t DNNL_API dnnl_primitive_desc_next_impl( + dnnl_primitive_desc_t primitive_desc); + +/// Clones a primitive descriptor. The resulting primitive descriptor must be +/// destroyed separately. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param existing_primitive_desc Primitive descriptor to clone. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_desc_clone( + dnnl_primitive_desc_t *primitive_desc, + const_dnnl_primitive_desc_t existing_primitive_desc); + +/// Returns a constant reference to the attributes of a primitive descriptor. +/// +/// @warning +/// It is an error to destroy the resulting @p attr. +/// +/// @warning +/// The lifetime of an @p attr is the same as that of a @p +/// primitive_desc, so it is an error to use the @p attr once the @p +/// primitive_desc has been destroyed. +/// +/// @param primitive_desc Primitive descriptor. +/// @param attr Output primitive attributes. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_desc_get_attr( + const_dnnl_primitive_desc_t primitive_desc, + const_dnnl_primitive_attr_t *attr); + +/// Destroys a primitive descriptor. +/// +/// @param primitive_desc Primitive descriptor to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_desc_destroy( + dnnl_primitive_desc_t primitive_desc); + +/// Queries a primitive descriptor for various pieces of information. +/// +/// The most common use case is to query a primitive descriptor, created with +/// source, weights, and destination memory descriptors with format tags set +/// to #dnnl_format_tag_any, for the corresponding memory descriptors (in this +/// case the @p what is set to #dnnl_query_src_md, #dnnl_query_weights_md, and +/// #dnnl_query_dst_md respectively) so that it is possible to create memory +/// objects and reorder primitives if necessary. +/// +/// Another typical use case is to query a primitive descriptor for workspace +/// memory descriptor (with @p what set to #dnnl_query_workspace_md). If this +/// query returns #dnnl_not_required status, then workspace memory is not +/// required. +/// +/// @note +/// When querying for a memory descriptor for a scratchpad, a workspace, +/// or an optional parameter, the query will return a pointer to a zero +/// memory descriptor if the parameter is not needed. +/// +/// A few other use cases: +/// - query a primitive descriptor for the implementation information string +/// (#dnnl_query_impl_info_str) +/// - query a primitive descriptor for the number of inputs and outputs +/// (#dnnl_query_num_of_inputs_s32 and #dnnl_query_num_of_outputs_s32 +/// respectively) +/// +/// @sa dnnl_query_t for more options +/// +/// @param primitive_desc Primitive descriptor. +/// @param what Parameter to query. +/// @param index Index of the parameter to query for. +/// @param result Output result. The type depends on the query. For example, +/// it must be a @c dnnl_memory_desc_t* if querying for a memory +/// descriptor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_desc_query( + const_dnnl_primitive_desc_t primitive_desc, dnnl_query_t what, + int index, void *result); + +/// Queries primitive descriptor for a memory descriptor. +/// +/// @note +/// This function is a convenience version of +/// #dnnl_primitive_desc_query(). +/// +/// @param primitive_desc Primitive descriptor. +/// @param what Kind of memory descriptor parameter to query for. +/// @param index Index of the parameter to query. +/// @returns A pointer to the requested memory descriptor. +/// @returns A pointer to a zero memory descriptor if the parameter is not +/// needed. +/// @returns NULL in case of any error. +/// +const_dnnl_memory_desc_t DNNL_API dnnl_primitive_desc_query_md( + const_dnnl_primitive_desc_t primitive_desc, dnnl_query_t what, + int index); + +/// Queries primitive descriptor for a signed 32bit int. +/// +/// @note +/// This function is a convenience version of +/// #dnnl_primitive_desc_query(). +/// +/// @param primitive_desc Primitive descriptor. +/// @param what Kind of the value to query for. +/// @param index Index of the parameter to query. +/// @returns The requested value. +/// @returns 0 in case of any error (in particular if the queried entity is +/// not of type int32_t). Note that 0 may also be the actual returned +/// value. +int DNNL_API dnnl_primitive_desc_query_s32( + const_dnnl_primitive_desc_t primitive_desc, dnnl_query_t what, + int index); + +/// Creates a primitive. +/// +/// @param primitive Output primitive. +/// @param primitive_desc Primitive descriptor used to create the primitive. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_create(dnnl_primitive_t *primitive, + const_dnnl_primitive_desc_t primitive_desc); + +/// Creates a primitive from a cache blob. +/// +/// @param primitive Output primitive. +/// @param primitive_desc Primitive descriptor used to create the primitive. +/// @param size Size of the cache blob in bytes. +/// @param cache_blob Cache blob of size @p size. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_create_from_cache_blob( + dnnl_primitive_t *primitive, const_dnnl_primitive_desc_t primitive_desc, + size_t size, const uint8_t *cache_blob); + +/// Executes a primitive. +/// +/// @param primitive Primitive to execute. +/// @param stream Stream to use. +/// @param nargs Number of arguments. +/// @param args Array of arguments. Each argument is an +/// pair. The index is one of the `DNNL_ARG_*` +/// values such as `DNNL_ARG_SRC`. Unless runtime shapes are used (see +/// #DNNL_RUNTIME_DIM_VAL), the memory object must have the same memory +/// descriptor as that returned by +/// #dnnl_primitive_desc_query_md(#dnnl_query_exec_arg_md, index). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. + +/// @note If any argument in @p args is padded (padded_dims > +/// dims), the primitive execution will assume properly zero-padded +/// input arguments, and produce zero-padded output arguments. +dnnl_status_t DNNL_API dnnl_primitive_execute(const_dnnl_primitive_t primitive, + dnnl_stream_t stream, int nargs, const dnnl_exec_arg_t *args); + +/// Retrieves a constant reference to the primitive descriptor of a given +/// primitive. +/// +/// @warning +/// It is an error to destroy the returned object. It is owned by the +/// primitive. The @c const qualifier of the returned object prevents +/// such attempts. +/// +/// @param primitive Primitive to query for the primitive descriptor. +/// @param primitive_desc Output primitive descriptor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_get_primitive_desc( + const_dnnl_primitive_t primitive, + const_dnnl_primitive_desc_t *primitive_desc); + +/// Retrieves a cache blob associated with the given primitive. +/// +/// @param primitive Primitive to query for the cache blob. +/// @param size Size of the cache blob in bytes. +/// @param cache_blob Cache blob of size @p size. If the @p cache_blob is +/// nullptr then the size of the cache blob is returned in @p size. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +/// +/// @note The cache blob can be empty. It's the user's responsibility to check +/// whether it's empty prior to passing it to +/// #dnnl_primitive_create_from_cache_blob(). +dnnl_status_t DNNL_API dnnl_primitive_get_cache_blob( + const_dnnl_primitive_t primitive, size_t *size, uint8_t *cache_blob); + +/// Destroys a primitive. +/// +/// @param primitive The primitive to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_destroy(dnnl_primitive_t primitive); + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_attributes +/// @{ + +/// Creates an empty (default) primitive attributes with all the parameters +/// set to their default values. +/// +/// Empty attributes are implied whenever the respective argument is NULL. +/// +/// @param attr Output primitive attributes. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_create(dnnl_primitive_attr_t *attr); + +/// Clones primitive attributes. +/// +/// @param attr Output primitive attributes. +/// @param existing_attr Primitive attributes to clone. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_clone( + dnnl_primitive_attr_t *attr, const_dnnl_primitive_attr_t existing_attr); + +/// Destroys primitive attributes. +/// +/// @param attr Primitive attributes to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_destroy(dnnl_primitive_attr_t attr); + +/// Returns the floating-point math mode primitive attribute. +/// +/// @param attr Primitive attributes. +/// @param mode Output FP math mode. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_fpmath_mode( + const_dnnl_primitive_attr_t attr, dnnl_fpmath_mode_t *mode); + +/// Sets the floating-point math mode primitive attributes. +/// +/// @param attr Primitive attributes. +/// @param mode FP math mode. The possible values are: +/// #dnnl_fpmath_mode_strict (default), +/// #dnnl_fpmath_mode_bf16, +/// #dnnl_fpmath_mode_f16, +/// #dnnl_fpmath_mode_tf32, +/// #dnnl_fpmath_mode_any. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_fpmath_mode( + dnnl_primitive_attr_t attr, dnnl_fpmath_mode_t mode); + +/// Returns the floating-point math mode primitive attribute. +/// +/// @param attr Primitive attributes. +/// @param mode Output FP math mode. +/// @param apply_to_int Output use floating-point arithmetic for integer primitives. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_fpmath_mode_v2( + const_dnnl_primitive_attr_t attr, dnnl_fpmath_mode_t *mode, + int *apply_to_int); + +/// Sets the floating-point math mode primitive attributes. +/// +/// @param attr Primitive attributes. +/// @param mode FP math mode. The possible values are: +/// #dnnl_fpmath_mode_strict (default), +/// #dnnl_fpmath_mode_bf16, +/// #dnnl_fpmath_mode_f16, +/// #dnnl_fpmath_mode_tf32, +/// #dnnl_fpmath_mode_any. +/// @param apply_to_int Boolean. Use of floating-point arithmetic for integer primitives. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_fpmath_mode_v2( + dnnl_primitive_attr_t attr, dnnl_fpmath_mode_t mode, int apply_to_int); + +/// Returns the deterministic primitive attribute value. +/// +/// @param attr Primitive attributes. +/// @param value Output deterministic attribute value +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_deterministic( + const_dnnl_primitive_attr_t attr, int *value); + +/// Sets the deterministic primitive attribute value. +/// +/// @param attr Primitive attributes. +/// @param value Boolean value to set deterministic attribute. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_deterministic( + dnnl_primitive_attr_t attr, int value); + +/// Returns the accumulation mode primitive attribute. +/// +/// @param attr Primitive attributes. +/// @param mode Output accumulation mode. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_accumulation_mode( + const_dnnl_primitive_attr_t attr, dnnl_accumulation_mode_t *mode); + +/// Sets the accumulation mode primitive attribute. +/// +/// @param attr Primitive attributes. +/// @param mode Accumulation mode. The possible values are: +/// #dnnl_accumulation_mode_strict (default), which is s32 for quantized primitives, f32/f64 otherwise +/// #dnnl_accumulation_mode_relaxed, which is same as strict but allows intermediate accumulators to be in src/dst datatype +/// #dnnl_accumulation_mode_any, which allows accumulators to be src/dst datatype or any wider type. +/// #dnnl_accumulation_mode_f32, +/// #dnnl_accumulation_mode_s32, +/// #dnnl_accumulation_mode_f16. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_accumulation_mode( + dnnl_primitive_attr_t attr, dnnl_accumulation_mode_t mode); + +/// Returns the primitive attributes scratchpad mode. +/// +/// @param attr Primitive attributes. +/// @param mode Output scratchpad mode. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_scratchpad_mode( + const_dnnl_primitive_attr_t attr, dnnl_scratchpad_mode_t *mode); + +/// Sets primitive attributes scratchpad mode. +/// +/// @param attr Primitive attributes. +/// @param mode Scratchpad mode. The possible values are: +/// #dnnl_scratchpad_mode_library (default) and +/// #dnnl_scratchpad_mode_user. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_scratchpad_mode( + dnnl_primitive_attr_t attr, dnnl_scratchpad_mode_t mode); + +/// Sets primitive attributes scaling factors for primitive operations for a +/// given memory argument. The scaling factors must be passed at execution time +/// as an argument with index #DNNL_ARG_ATTR_SCALES | arg. +/// +/// @sa dnnl_primitive_attr_set_scales_mask +/// +/// +/// @param attr Primitive attributes. +/// @param arg Parameter argument index as passed to the +/// dnnl_primitive_execute() call. +/// @param mask Scaling factors correspondence mask that defines the +/// correspondence between the tensor dimensions and the @p scales array. +/// The set i-th bit indicates that a dedicated scaling factor is used for +/// each index along that dimension. Set the mask to 0 to use a common +/// scaling factor for the whole output tensor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_scales_mask( + dnnl_primitive_attr_t attr, int arg, int mask); + +/// Sets primitive attributes scaling factors for primitive operations for a +/// given memory argument. The scaling factors must be passed at execution time +/// as an argument with index #DNNL_ARG_ATTR_SCALES | arg. +/// +/// @sa dnnl_primitive_attr_set_scales +/// +/// +/// @param attr Primitive attributes. +/// @param arg Parameter argument index as passed to the +/// dnnl_primitive_execute() call. +/// @param mask Scaling factors correspondence mask that defines the +/// correspondence between the tensor dimensions and the @p scales array. +/// The set i-th bit indicates that a dedicated scaling factor is used for +/// each index along that dimension. Set the mask to 0 to use a common +/// scaling factor for the whole output tensor. +/// @param ndims Number of group dimensions. +/// @param group_dims Scaling factors correspondence groups that define the +/// correspondence between the tensor dimensions and the scales array. +/// The group dimensions should only be provided for each logical dimension +/// that has correspondence mask @p mask set. +/// @param data_type Scaling factors data_type. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_scales( + dnnl_primitive_attr_t attr, int arg, int mask, int ndims, + const dnnl_dims_t group_dims, dnnl_data_type_t data_type); + +/// Sets primitive attributes zero points for primitive operations for a given +/// memory argument. The zero points must be passed at execution time +/// as an argument with index #DNNL_ARG_ATTR_ZERO_POINTS | arg. +/// +/// @sa dnnl_primitive_attr_set_zero_points_mask +/// +/// +/// @param attr Primitive attributes. +/// @param arg Parameter argument index as passed to the +/// dnnl_primitive_execute() call. +/// @param mask Zero point correspondence mask that defines the +/// correspondence between the tensor dimensions and the @p +/// zero_points array. The set i-th bit indicates that a dedicated +/// zero point is used for each index along that dimension. Set the +/// mask to 0 to use a common zero point for the whole output tensor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_zero_points_mask( + dnnl_primitive_attr_t attr, int arg, int mask); + +/// Sets primitive attributes zero points for primitive operations for a given +/// memory argument. The zero points must be passed at execution time +/// as an argument with index #DNNL_ARG_ATTR_ZERO_POINTS | arg. +/// +/// @sa dnnl_primitive_attr_set_zero_points +/// +/// +/// @param attr Primitive attributes. +/// @param arg Parameter argument index as passed to the +/// dnnl_primitive_execute() call. +/// @param mask Zero point correspondence mask that defines the +/// correspondence between the tensor dimensions and the @p +/// zero_points array. The set i-th bit indicates that a dedicated +/// zero point is used for each index along that dimension. Set the +/// mask to 0 to use a common zero point for the whole output tensor. +/// @param ndims Number of group dimensions. +/// @param group_dims Zero point factors correspondence groups that define the +/// correspondence between the tensor dimensions and the zero_points array. +/// The group dimensions should be only provided for each logical dimension +/// that has the bit set correspondence mask @p mask set. +/// @param data_type Zero points factors data_type. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_zero_points( + dnnl_primitive_attr_t attr, int arg, int mask, int ndims, + const dnnl_dims_t group_dims, dnnl_data_type_t data_type); + +/// Returns primitive attributes post-ops. +/// +/// @warning +/// The output @p post_ops points to the internal @p attr field, so it is +/// an error to modify or destroy them. The lifetime of @p post_ops is +/// the same as that of the @p attr it belongs to, so it is an error to +/// use @p post_ops after @p attr has been destroyed. +/// +/// @param attr Primitive attributes. +/// @param post_ops Output post-ops. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_post_ops( + const_dnnl_primitive_attr_t attr, const_dnnl_post_ops_t *post_ops); + +/// Sets primitive attributes post-ops. +/// +/// @note +/// There is no way to check whether the post-ops would be supported by +/// the target primitive. Any error will be reported by the +/// dnnl__[propagation kind]_primitive_desc_create() function call. +/// +/// @param attr Primitive attributes. +/// @param post_ops Post-ops to set. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_post_ops( + dnnl_primitive_attr_t attr, const_dnnl_post_ops_t post_ops); + +/// Creates empty post-ops sequence. +/// +/// @param post_ops Output post-ops. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_create(dnnl_post_ops_t *post_ops); + +/// Clones post-ops primitive attribute. +/// +/// @param post_ops Output post-ops primitive attribute. +/// @param existing_post_ops Post-ops primitive attribute to clone. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_clone( + dnnl_post_ops_t *post_ops, const_dnnl_post_ops_t existing_post_ops); + +/// Destroys post-ops. +/// +/// @param post_ops Post-ops to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_destroy(dnnl_post_ops_t post_ops); + +/// Returns the length of post-ops. +/// +/// @param post_ops Post-ops. +/// @returns The number of post-ops entries. +int DNNL_API dnnl_post_ops_len(const_dnnl_post_ops_t post_ops); + +/// Returns the kind of a post-op entry. +/// +/// @param post_ops Post-ops. +/// @param index Post-op entry index. +/// @returns The kind of the post-op with the specified index. +/// @returns #dnnl_undefined_primitive if there is no post-op at the specified +/// index. +dnnl_primitive_kind_t DNNL_API dnnl_post_ops_get_kind( + const_dnnl_post_ops_t post_ops, int index); + +/// Appends an accumulation v3 (sum) to post-ops. Prior to accumulating the +/// result, a zero point is subtracted from the previous value and is +/// multiplied by the scale. +/// +/// The kind of this post-op is #dnnl_sum. +/// +/// This feature may improve performance for cases like dequantize the +/// asymmetrically quantized sum's src1 tensor to f32 domain before performing +/// the sum operation by subtracting the @p zero_point before the scaling. +/// +/// In the simplest case where accumulation is the only post-op, the +/// computations will be: +/// +/// dst[:] <- scale * (dst[:] - zero_point) + op(...) +/// // instead of dst[:] <- op(...) +/// +/// If @p data_type is specified, original dst tensor will be reinterpreted +/// as a tensor with provided data type. Since it is reinterpretation, +/// data_type and dst data type should have the same size. +/// As a result, computations will be: +/// +/// dst[:] <- scale * (as_data_type(dst[:]) - zero_point) + op(...) +/// // instead of dst[:] <- op(...) +/// @note +/// This post-op executes in-place and does not change the +/// destination layout. +/// +/// @param post_ops Post-ops. +/// @param scale Accumulation scaling factor. +/// @param zero_point Single scalar int32_t value of zero point. +/// @param data_type Accumulation data_type. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_append_sum(dnnl_post_ops_t post_ops, + float scale, int32_t zero_point, dnnl_data_type_t data_type); + +/// Returns the parameters of an accumulation (sum) post-op with +/// zero point and data type parameter. +/// +/// @param post_ops Post-ops. +/// @param index Index of the sum post-op. +/// @param scale Output accumulation scaling factor. +/// @param zero_point Zero point. +/// @param data_type Data type for accumulation. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_get_params_sum( + const_dnnl_post_ops_t post_ops, int index, float *scale, + int32_t *zero_point, dnnl_data_type_t *data_type); + +/// Appends an elementwise post-op. +/// +/// The kind of this post operation is #dnnl_eltwise. +/// +/// In the simplest case when the elementwise is the only post operation, the +/// computations would be: +/// +/// dst[:] <- eltwise_op (op(...)) // instead of dst[:] <- op(...) +/// +/// where eltwise_op is configured with the given parameters. +/// +/// @param post_ops Post-ops. +/// @param alg_kind Elementwise algorithm for the post-op. +/// @param alpha Alpha parameter for the elementwise algorithm. +/// @param beta Beta parameter for the elementwise algorithm. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_append_eltwise(dnnl_post_ops_t post_ops, + dnnl_alg_kind_t alg_kind, float alpha, float beta); + +/// Returns the parameters of an elementwise post-op. +/// +/// @param post_ops Post-ops. +/// @param index Index of the elementwise post-op. +/// @param alg_kind Output elementwise algorithm kind. +/// @param alpha Output alpha parameter for the elementwise algorithm. +/// @param beta Output beta parameter for the elementwise algorithm. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +/// @returns #dnnl_invalid_arguments if @p index does not refer to an +/// elementwise post-op. +dnnl_status_t DNNL_API dnnl_post_ops_get_params_eltwise( + const_dnnl_post_ops_t post_ops, int index, dnnl_alg_kind_t *alg_kind, + float *alpha, float *beta); + +/// Appends a depthwise post-op convolution. +/// +/// This post-op can only be fused with a 2D 1x1 convolution (convolution with +/// weights spatial dimensions equal to 1 i.e., kh=kw=1). +/// +/// The kind of this post-op is #dnnl_convolution. +/// +/// The number of outputs for primitive with fusion is one. The output spatial +/// size can be derived as below: +/// +/// output_height = ceil(output_height_1x1_convolution, stride) +/// output_width = ceil(output_width_1x1_convolution, stride) +/// +/// See @ref dev_guide_attributes_post_ops_depthwise and +/// @ref dev_guide_attributes_post_ops_depthwise_fusion for more info. +/// +/// @param post_ops Post-ops. +/// @param weights_data_type Weights data type of depthwise post-op +/// @param bias_data_type Bias data type of depthwise post-op +/// @param dst_data_type Output data type of depthwise post-op +/// @param kernel_size Size of kernel of depthwise post-op +/// @param stride_size Size of stride of depthwise post-op +/// @param padding_l_size Size of left and top paddings of depthwise post-op +/// @returns #dnnl_success on success and a status describing the error +/// otherwise +dnnl_status_t DNNL_API dnnl_post_ops_append_dw(dnnl_post_ops_t post_ops, + dnnl_data_type_t weights_data_type, dnnl_data_type_t bias_data_type, + dnnl_data_type_t dst_data_type, dnnl_dim_t kernel_size, + dnnl_dim_t stride_size, dnnl_dim_t padding_l_size); + +/// Returns the parameters of an depthwise post-op. +/// +/// @param post_ops Post-ops. +/// @param index Index of the elementwise post-op. +/// @param weights_data_type Weights data type of depthwise post-op +/// @param bias_data_type Bias data type of depthwise post-op +/// @param dst_data_type Output data type of depthwise post-op +/// @param kernel_size Size of kernel of depthwise post-op +/// @param stride_size Size of stride of depthwise post-op +/// @param padding_l_size Size of left and top paddings of depthwise post-op +/// @returns #dnnl_success on success and a status describing the error +/// otherwise +dnnl_status_t DNNL_API dnnl_post_ops_get_params_dw( + const_dnnl_post_ops_t post_ops, int index, + dnnl_data_type_t *weights_data_type, dnnl_data_type_t *bias_data_type, + dnnl_data_type_t *dst_data_type, dnnl_dim_t *kernel_size, + dnnl_dim_t *stride_size, dnnl_dim_t *padding_l_size); + +/// Appends a binary post-op. +/// +/// The kind of this post operation is #dnnl_binary. +/// +/// In the simplest case when the binary is the only post operation, the +/// computations would be: +/// +/// dst[:] <- binary_op (dst[:], another_input[:]) +/// +/// where binary_op is configured with the given parameters. binary_op supports +/// broadcast semantics for a second operand. +/// +/// @param post_ops Post-ops. +/// @param alg_kind Binary algorithm for the post-op. +/// @param src1_desc Memory descriptor of a second operand. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_append_binary(dnnl_post_ops_t post_ops, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t src1_desc); + +/// Returns the parameters of a binary post-op. +/// +/// @param post_ops Post-ops. +/// @param index Index of the binary post-op. +/// @param alg_kind Output binary algorithm kind. +/// @param src1_desc Output memory descriptor of a second operand. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +/// @returns #dnnl_invalid_arguments if @p index does not refer to a binary +/// post-op. +dnnl_status_t DNNL_API dnnl_post_ops_get_params_binary( + const_dnnl_post_ops_t post_ops, int index, dnnl_alg_kind_t *alg_kind, + const_dnnl_memory_desc_t *src1_desc); + +/// Appends a prelu forward post-op. +/// +/// The kind of this post-op is #dnnl::primitive::kind::prelu. +/// +/// The post-op can be defined as: +/// +/// dst[:] <- prelu(dst[:], weights[:]) +/// prelu: +/// dst[:] <- dst[:] if dst[:] > 0 +/// dst[:] <- dst[:] * weights[:] if dst[:] <= 0 +/// +/// +/// @note +/// The order of dimensions does not depend on how elements are laid +/// out in memory. For example: +/// - for a 2D CNN activations tensor the order is always (n, c) +/// - for a 4D CNN activations tensor the order is always (n, c, h, w) +/// - for a 5D CNN weights tensor the order is always +/// (g, oc, ic, kh, kw) +/// +/// Prelu weights tensor is passed in runtime execution phase. Prelu +/// weights tensor data type is implicitly assumed as f32 using plain +/// layout (a, ab, acb, acdb, acdeb) +/// +/// @param post_ops Post-ops. +/// @param mask Defines the correspondence between the output tensor +/// dimensions and the prelu weights tensor. The set i-th bit indicates +/// that a dedicated weights value is used for each index along that +/// dimension. Set the mask to 0 to use a common weights value +/// for the whole output tensor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_append_prelu( + dnnl_post_ops_t post_ops, int mask); + +/// Returns the parameters of a prelu post-op. +/// +/// @param post_ops Post-ops. +/// @param index Index of the prelu post-op. +/// @param mask Mask of the prelu post-op. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_post_ops_get_params_prelu( + const_dnnl_post_ops_t post_ops, int index, int *mask); + +/// @} dnnl_api_attributes + +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_memory +/// @{ + +/// Destroys a memory descriptor. +/// +/// @param memory_desc Memory descriptor to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_destroy(dnnl_memory_desc_t memory_desc); + +/// Clones a memory descriptor. The resulting memory descriptor must be +/// destroyed separately. +/// +/// @param memory_desc Output memory descriptor. +/// @param existing_memory_desc Memory descriptor to clone. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_clone(dnnl_memory_desc_t *memory_desc, + const_dnnl_memory_desc_t existing_memory_desc); + +/// Retrieves a binary blob associated with the given memory descriptor +/// +/// @param blob Output pointer to binary blob. +/// If not nullptr, size bytes of the memory descriptor blob are written. +/// @param size Output pointer to the size of the binary blob in bytes. +/// Size is written if blob is nullptr. +/// @param memory_desc input memory descriptor to serialize +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_get_blob( + uint8_t *blob, size_t *size, const_dnnl_memory_desc_t memory_desc); + +/// Creates a memory descriptor from a memory descriptor binary blob. +/// +/// @param memory_desc Output pointer to a newly allocated memory descriptor. +/// @param blob Pointer to a memory descriptor binary blob. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_create_with_blob( + dnnl_memory_desc_t *memory_desc, const uint8_t *blob); + +/// Creates a memory descriptor using dimensions and strides. +/// +/// @note +/// As always, the logical order of dimensions corresponds to the `abc...` +/// format tag, and the physical meaning of the dimensions depends on both +/// the primitive that consumes the memory and the context of that +/// consumption. +/// +/// @param memory_desc Output memory descriptor. +/// @param ndims Number of dimensions +/// @param dims Array of dimensions. +/// @param data_type Elements data type. +/// @param strides Strides in each dimension. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_create_with_strides( + dnnl_memory_desc_t *memory_desc, int ndims, const dnnl_dims_t dims, + dnnl_data_type_t data_type, const dnnl_dims_t strides); + +/// Creates a memory descriptor using dimensions and memory format tag. +/// +/// @note +/// As always, the logical order of dimensions corresponds to the `abc...` +/// format tag, and the physical meaning of the dimensions depends on both +/// the primitive that consumes the memory and the context of that +/// consumption. +/// +/// @param memory_desc Output memory descriptor. +/// @param ndims Number of dimensions +/// @param dims Array of dimensions. +/// @param data_type Elements data type. +/// @param tag Memory format tag. Can be #dnnl_format_tag_any which would +/// allow a primitive to chose the final memory format. In this case the +/// format_kind field of the memory descriptor would be set to +/// #dnnl_format_kind_any. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_create_with_tag( + dnnl_memory_desc_t *memory_desc, int ndims, const dnnl_dims_t dims, + dnnl_data_type_t data_type, dnnl_format_tag_t tag); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Creates a memory descriptor for CSR encoding. +/// +/// @param memory_desc Output memory descriptor. +/// @param ndims Number of dimensions +/// @param dims Array of dimensions. +/// @param data_type Elements data type. +/// @param nnz Number of non-zero entries. +/// @param indices_dt Data type of indices. +/// @param pointers_dt Data type of pointers. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_create_with_csr_encoding( + dnnl_memory_desc_t *memory_desc, int ndims, const dnnl_dims_t dims, + dnnl_data_type_t data_type, dnnl_dim_t nnz, dnnl_data_type_t indices_dt, + dnnl_data_type_t pointers_dt); + +/// Creates a memory descriptor for packed sparse encoding. +/// +/// The created memory descriptor cannot be used to create a memory +/// object. It can only be used to create a primitive descriptor to +/// query the actual memory descriptor (similar to the format tag +/// `any`). +/// +/// @warning +/// The meaning and content of the handles of the memory object that +/// is created using the queried memory descriptor are unspecified +/// therefore using the content is an undefined behavior. +/// +/// @param memory_desc Output memory descriptor. +/// @param ndims Number of dimensions +/// @param dims Array of dimensions. +/// @param data_type Elements data type. +/// @param nnz Number of non-zero entries. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_create_with_packed_encoding( + dnnl_memory_desc_t *memory_desc, int ndims, const dnnl_dims_t dims, + dnnl_data_type_t data_type, dnnl_dim_t nnz); +#endif + +/// Creates a memory descriptor for a region inside an area +/// described by an existing memory descriptor. +/// +/// @warning +/// Some combinations of physical memory layout and/or offsets or dims may +/// result in a failure to create a submemory. +// +/// @param memory_desc Output memory descriptor. +/// @param parent_memory_desc An existing memory descriptor. +/// @param dims Sizes of the region. +/// @param offsets Offsets to the region from the encompassing +/// memory object in each dimension +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_create_submemory( + dnnl_memory_desc_t *memory_desc, + const_dnnl_memory_desc_t parent_memory_desc, const dnnl_dims_t dims, + const dnnl_dims_t offsets); + +/// Creates a memory descriptor by reshaping an existing one. The new +/// memory descriptor inherits the data type. This operation is valid only for +/// memory descriptors that have format_kind #dnnl_blocked or +/// #dnnl_format_kind_any. +/// +/// The resulting memory descriptor must be destroyed separately. +/// +/// The operation ensures the transformation of the physical memory format +/// corresponds to the transformation of the logical dimensions. If such +/// transformation is impossible, the function returns #dnnl_invalid_arguments. +/// +/// The reshape operation can be described as a combination of the following +/// basic operations: +/// 1. Add a dimension of size `1`. This is always possible. +/// 2. Remove a dimension of size `1`. This is possible only if the dimension +/// has no padding (i.e. `padded_dims[dim] == dims[dim] && dims[dim] == 1`). +/// 3. Split a dimension into multiple ones. This is possible only if the size +/// of the dimension is exactly equal to the product of the split ones and +/// the dimension does not have padding (i.e. +/// `padded_dims[dim] = dims[dim]`). +/// 4. Joining multiple consecutive dimensions into a single one. As in the +/// cases above, this requires that the dimensions do not have padding and +/// that the memory format is such that in physical memory these dimensions +/// are dense and have the same order as their logical counterparts. This +/// also assumes that these dimensions are not blocked. +/// - Here, dense means: +/// `stride for dim[i] == (stride for dim[i + 1]) * dim[i + 1]`; +/// - And same order means: +/// `i < j` if and only if `stride for dim[j] <= stride for dim[i]`. +/// +/// @warning +/// Some combinations of physical memory layout and/or offsets or +/// dimensions may result in a failure to make a reshape. +/// +/// @param out_memory_desc Output memory descriptor. +/// @param in_memory_desc An existing memory descriptor. Must have format_kind +/// set to #dnnl_blocked or #dnnl_format_kind_any. +/// @param ndims Number of dimensions for the output memory descriptor. +/// @param dims Dimensions for the output memory descriptor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_reshape( + dnnl_memory_desc_t *out_memory_desc, + const_dnnl_memory_desc_t in_memory_desc, int ndims, + const dnnl_dims_t dims); + +/// Creates a memory descriptor by permuting axes in an existing one. +/// +/// The physical memory layout representation is adjusted accordingly to +/// maintain the consistency between the logical and physical parts of the +/// memory descriptor. +/// +/// The resulting memory descriptor must be destroyed separately. +/// +/// The new memory descriptor inherits the data type. This operation is valid +/// only for memory descriptors that have format_kind set to #dnnl_blocked or +/// #dnnl_format_kind_any. +/// +/// The logical axes will be permuted in the following manner: +/// ``` +/// for (i: 0 .. in_memory_desc->ndims) +/// out_memory_desc->dims[permutation[i]] = in_memory_desc->dims[i]; +/// ``` +/// +/// Example: +/// @code +/// dnnl_memory_desc_t in_md, out_md, expect_out_md; +/// +/// const int permutation[] = {1, 0}; // swap the first and the second axes +/// +/// dnnl_dims_t in_dims = {2, 3}, out_dims = {3, 2}; +/// dnnl_format_tag_t in_tag = dnnl_ab, out_tag = dnnl_ba; +/// +/// dnnl_memory_desc_create_with_tag( +/// &in_md, 2, in_dims, data_type, in_tag); +/// dnnl_memory_desc_create_with_tag( +/// &expect_out_md, 2, out_dims, data_type, out_tag); +/// +/// dnnl_memory_desc_permute_axes(&out_md, in_md, permutation); +/// assert(dnnl_memory_desc_equal(out_md, expect_out_md)); +/// +/// dnnl_memory_desc_destroy(in_md); +/// dnnl_memory_desc_destroy(out_md); +/// dnnl_memory_desc_destroy(expect_out_md); +/// @endcode +/// +/// @param out_memory_desc Output memory descriptor. +/// @param in_memory_desc An existing memory descriptor. Must have format_kind +/// set to #dnnl_blocked or #dnnl_format_kind_any. +/// @param permutation Axes permutation (of size `in_memory_desc->ndims`). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_permute_axes( + dnnl_memory_desc_t *out_memory_desc, + const_dnnl_memory_desc_t in_memory_desc, const int *permutation); + +/// Queries a memory descriptor for various pieces of information. +/// +/// The following information can be queried: +/// - Number of dimensions (#dnnl_query_ndims_s32) +/// - Dimensions (#dnnl_query_dims) in the following order: +/// - CNN data tensors: mini-batch, channel, spatial +/// ({N, C, [[D,] H,] W}) +/// - CNN weight tensors: group (optional), output channel, input channel, +/// spatial ({[G,] O, I, [[D,] H,] W}) +/// - RNN data tensors: time, mini-batch, channels ({T, N, C}) +/// or layers, directions, states, mini-batch, channels +/// ({L, D, S, N, C}) +/// - RNN weight tensor: layers, directions, input channel, gates, output +/// channels ({L, D, I, G, O}) +/// - Data type of the tensor elements (#dnnl_query_data_type) +/// - Padded dimensions (#dnnl_query_padded_dims) - size of the data including +/// padding in each dimension +/// - Padded offsets (#dnnl_query_padded_offsets) - per-dimension offset from +/// the padding to actual data, the top-level tensor with offsets applied +/// must lie within the padding area. +/// - Submemory offset (#dnnl_query_submemory_offset_s64) - offset from memory +/// origin to the current block, non-zero only in a description of a memory +/// sub-block. +/// - Format kind (#dnnl_query_format_kind) - memory format kind +/// +/// @note +/// The order of dimensions does not depend on the memory format, so +/// whether the data is laid out in #dnnl_nchw or #dnnl_nhwc +/// the dims for 4D CN data tensor would be {N, C, H, W}. +/// +/// The following queries are applicable only to format kind #dnnl_blocked. +/// - Strides (#dnnl_query_strides) between the outermost blocks or in case +/// of plain (non-blocked) formats the strides between dimensions +/// - Number of innermost blocks (#dnnl_query_inner_nblks_s32), e.g. +/// `{4, 16, 4}` in case of `OIhw_4i16o4i` +/// - Size of the innermost blocks (#dnnl_query_inner_blks), e.g. 3 in case +/// of `OIhw_4i16o4i_` +/// - Logical indices of the blocks (#dnnl_query_inner_idxs), e.g. `{1, 0, 1}` +/// in case of `4i16o4i`, because `i` is the 1st dim and `o` is the 0st dim +/// +/// @param memory_desc Memory descriptor. +/// @param what Parameter to query. +/// @param result Output result. The type depends on the query. For example, +/// it must be a @c dnnl_dims_t** if querying for a strides. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_query( + const_dnnl_memory_desc_t memory_desc, dnnl_query_t what, void *result); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Queries a memory descriptor for various pieces of information. This version +/// support additional queries #dnnl_query_sparse_encoding, #dnnl_query_nnz_s64 +/// #dnnl_query_num_handles_s32 and #dnnl_query_data_type for a particular +/// buffer. +/// +/// The following information can be queried: +/// - Number of dimensions (#dnnl_query_ndims_s32) +/// - Dimensions (#dnnl_query_dims) in the following order: +/// - CNN data tensors: mini-batch, channel, spatial +/// ({N, C, [[D,] H,] W}) +/// - CNN weight tensors: group (optional), output channel, input channel, +/// spatial ({[G,] O, I, [[D,] H,] W}) +/// - RNN data tensors: time, mini-batch, channels ({T, N, C}) +/// or layers, directions, states, mini-batch, channels +/// ({L, D, S, N, C}) +/// - RNN weight tensor: layers, directions, input channel, gates, output +/// channels ({L, D, I, G, O}) +/// - Data type of the tensor elements (#dnnl_query_data_type) +/// - Padded dimensions (#dnnl_query_padded_dims) - size of the data including +/// padding in each dimension +/// - Padded offsets (#dnnl_query_padded_offsets) - per-dimension offset from +/// the padding to actual data, the top-level tensor with offsets applied +/// must lie within the padding area. +/// - Submemory offset (#dnnl_query_submemory_offset_s64) - offset from memory +/// origin to the current block, non-zero only in a description of a memory +/// sub-block. +/// - Format kind (#dnnl_query_format_kind) - memory format kind +/// +/// @note +/// The order of dimensions does not depend on the memory format, so +/// whether the data is laid out in #dnnl_nchw or #dnnl_nhwc +/// the dims for 4D CN data tensor would be {N, C, H, W}. +/// +/// The following queries are applicable only to format kind #dnnl_blocked. +/// - Strides (#dnnl_query_strides) between the outermost blocks or in case +/// of plain (non-blocked) formats the strides between dimensions +/// - Number of innermost blocks (#dnnl_query_inner_nblks_s32), e.g. +/// `{4, 16, 4}` in case of `OIhw_4i16o4i` +/// - Size of the innermost blocks (#dnnl_query_inner_blks), e.g. 3 in case +/// of `OIhw_4i16o4i_` +/// - Logical indices of the blocks (#dnnl_query_inner_idxs), e.g. `{1, 0, 1}` +/// in case of `4i16o4i`, because `i` is the 1st dim and `o` is the 0st dim +/// +/// @param memory_desc Memory descriptor. +/// @param what Parameter to query. +/// @param index Index of the parameter to query for. It is mostly used with +/// #dnnl_query_data_type to specify which data type is being queried. +/// The main data type (data type of values) has always index 0. For other +/// indices please refer to the API for creating a memory descriptor for +/// sparse encoding. +/// @param result Output result. The type depends on the query. For example, +/// it must be a @c dnnl_dims_t** if querying for a strides. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_desc_query_v2( + const_dnnl_memory_desc_t memory_desc, dnnl_query_t what, int index, + void *result); +#endif + +/// Compares two memory descriptors. +/// +/// Use this function to identify whether a reorder is required between the +/// two memories +/// +/// @param lhs Left-hand side of the comparison. +/// @param rhs Right-hand side of the comparison. +/// @returns 1 if the descriptors are the same. +/// @returns 0 if the descriptors are different. +int DNNL_API dnnl_memory_desc_equal( + const_dnnl_memory_desc_t lhs, const_dnnl_memory_desc_t rhs); + +/// Returns the size of a memory descriptor. +/// +/// @param memory_desc Memory descriptor. +/// @returns The number of bytes required for memory described by a memory +/// descriptor. +size_t DNNL_API dnnl_memory_desc_get_size(const_dnnl_memory_desc_t memory_desc); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Returns the size of the data that corresponds to the given index. +/// +/// @param memory_desc Memory descriptor. +/// @param index Index of the buffer. +/// +/// @returns The number of bytes required for the requested data. +size_t DNNL_API dnnl_memory_desc_get_size_v2( + const_dnnl_memory_desc_t memory_desc, int index); +#endif + +/// Returns the size of data type. +/// +/// @param data_type Data type. +/// @returns The number of bytes occupied by data type. +size_t DNNL_API dnnl_data_type_size(dnnl_data_type_t data_type); + +/// Creates a memory object. +/// +/// Unless @p handle is equal to DNNL_MEMORY_NONE, the constructed memory +/// object will have the underlying buffer set. In this case, the buffer will +/// be initialized as if dnnl_memory_set_data_handle() had been called. +/// +/// @sa dnnl_memory_set_data_handle() +/// +/// @param memory Output memory object. +/// @param memory_desc Memory descriptor. +/// @param engine Engine to use. +/// @param handle Handle of the memory buffer to use as an underlying storage. +/// - A pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer for the memory object. In this case the library +/// owns the buffer. +/// - DNNL_MEMORY_NONE to create dnnl_memory without an underlying buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_create(dnnl_memory_t *memory, + const_dnnl_memory_desc_t memory_desc, dnnl_engine_t engine, + void *handle); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Creates a memory object with multiple handles. +/// +/// @param memory Output memory object. +/// @param memory_desc Memory descriptor. +/// @param engine Engine to use. +/// @param nhandles Number of handles. +/// @param handles Handles of the memory buffers to use as underlying storages. +/// For each element of the @p handles array the following applies: +/// - A pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer for the memory object. In this case the library +/// owns the buffer. +/// - DNNL_MEMORY_NONE Instructs the library to skip allocation of the +/// memory buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_create_v2(dnnl_memory_t *memory, + const_dnnl_memory_desc_t memory_desc, dnnl_engine_t engine, + int nhandles, void **handles); +#endif + +/// Returns the memory descriptor for a memory object. +/// +/// @param memory Memory object. +/// @param memory_desc Output memory descriptor (a copy). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_get_memory_desc( + const_dnnl_memory_t memory, const_dnnl_memory_desc_t *memory_desc); + +/// Returns the engine of a memory object. +/// +/// @param memory Memory object. +/// @param engine Output engine on which the memory is located. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_get_engine( + const_dnnl_memory_t memory, dnnl_engine_t *engine); + +/// Maps a memory object and returns a host-side pointer to a memory buffer +/// with a copy of its contents. +/// +/// Mapping enables explicit direct access to memory contents for the engines +/// that do not support it implicitly. +/// +/// Mapping is an exclusive operation - a memory object cannot be used in +/// other operations until this memory object is unmapped. +/// +/// @note +/// Any primitives working with @p memory should be completed before +/// the memory is mapped. Use dnnl_stream_wait to synchronize the +/// corresponding execution stream. +/// +/// @note +/// The dnnl_memory_map_data() and dnnl_memory_unmap_data() functions are +/// mainly provided for debug and testing purposes, and their performance +/// may be suboptimal. +/// +/// @param memory Memory object. +/// @param mapped_ptr Output pointer to the mapped buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_map_data( + const_dnnl_memory_t memory, void **mapped_ptr); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Maps a memory object and returns a host-side pointer to a memory buffer +/// with a copy of its contents. The memory buffer corresponds to the given +/// index. +/// +/// Mapping enables explicit direct access to memory contents for the engines +/// that do not support it implicitly. +/// +/// Mapping is an exclusive operation - a memory object cannot be used in +/// other operations until this memory object is unmapped. +/// +/// @note +/// Any primitives working with @p memory should be completed before +/// the memory is mapped. Use dnnl_stream_wait to synchronize the +/// corresponding execution stream. +/// +/// @note +/// The dnnl_memory_map_data() and dnnl_memory_unmap_data() functions are +/// mainly provided for debug and testing purposes, and their performance +/// may be suboptimal. +/// +/// @param memory Memory object. +/// @param mapped_ptr Output pointer to the mapped buffer. +/// @param index Index of the buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_map_data_v2( + const_dnnl_memory_t memory, void **mapped_ptr, int index); +#endif + +/// Unmaps a memory object and writes back any changes made to the previously +/// mapped memory buffer. The pointer to the mapped buffer must be obtained +/// via the dnnl_memory_map_data() call. +/// +/// @note +/// The dnnl_memory_map_data() and dnnl_memory_unmap_data() functions are +/// mainly provided for debug and testing purposes, and their performance +/// may be suboptimal. +/// +/// @param memory Memory object. +/// @param mapped_ptr Pointer to the mapped buffer that must have been +/// obtained using the dnnl_memory_map_data() function. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_unmap_data( + const_dnnl_memory_t memory, void *mapped_ptr); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Unmaps a memory object and writes back any changes made to the previously +/// mapped memory buffer. The pointer to the mapped buffer must be obtained +/// via the dnnl_memory_map_data() call. The buffer corresponds to the given +/// index. +/// +/// @note +/// The dnnl_memory_map_data() and dnnl_memory_unmap_data() functions are +/// mainly provided for debug and testing purposes, and their performance +/// may be suboptimal. +/// +/// @param memory Memory object. +/// @param mapped_ptr Pointer to the mapped buffer that must have been +/// obtained using the dnnl_memory_map_data() function. +/// @param index Index of the buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_unmap_data_v2( + const_dnnl_memory_t memory, void *mapped_ptr, int index); +#endif + +/// Returns memory object's data handle. +/// +/// @param memory Memory object. +/// @param handle Output data handle. For the CPU engine, the data handle is a +/// pointer to the actual data. For OpenCL it is a cl_mem. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_get_data_handle( + const_dnnl_memory_t memory, void **handle); + +/// Sets the underlying memory buffer. +/// +/// @param memory Memory object. +/// @param handle Data handle. For the CPU engine or when USM is used, the +/// memory buffer is a pointer to the actual data. For OpenCL it is a +/// `cl_mem`. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_set_data_handle( + dnnl_memory_t memory, void *handle); + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Returns an underlying memory buffer that corresponds to the given index. +/// +/// @param memory Memory object. +/// @param handle Data handle. For the CPU engine or when USM is used, the +/// memory buffer is a pointer to the actual data. For OpenCL it is a +/// `cl_mem`. +/// @param index Index of the buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_get_data_handle_v2( + const_dnnl_memory_t memory, void **handle, int index); + +/// Sets an underlying memory buffer that corresponds to the given index. +/// +/// @param memory Memory object. +/// @param handle Data handle. For the CPU engine or when USM is used, the +/// memory buffer is a pointer to the actual data. For OpenCL it is a +/// `cl_mem`. +/// @param index Index of the buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_set_data_handle_v2( + dnnl_memory_t memory, void *handle, int index); +#endif + +/// Destroys a memory object. +/// +/// @param memory Memory object to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_memory_destroy(dnnl_memory_t memory); + +/// @} dnnl_api_memory + +/// @addtogroup dnnl_api_primitives +/// @{ + +/// @addtogroup dnnl_api_reorder +/// @{ + +/// Creates a primitive descriptor for a reorder primitive. +/// +/// @param reorder_primitive_desc Output primitive descriptor. +/// @param src_desc Source memory descriptor. +/// @param src_engine Engine on which the source memory object will be +/// located. +/// @param dst_desc Destination memory descriptor. +/// @param dst_engine Engine on which the destination memory object +/// will be located. +/// @param attr Primitive attributes to use (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_reorder_primitive_desc_create( + dnnl_primitive_desc_t *reorder_primitive_desc, + const_dnnl_memory_desc_t src_desc, dnnl_engine_t src_engine, + const_dnnl_memory_desc_t dst_desc, dnnl_engine_t dst_engine, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_reorder + +/// @addtogroup dnnl_api_concat +/// @{ + +/// Creates a primitive descriptor for an out-of-place concatenation +/// primitive. +/// +/// @param concat_primitive_desc Output primitive descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param n Number of source parameters. +/// @param concat_dimension Source tensors will be concatenated over +/// dimension with this index. Note that order of dimensions does +/// not depend on memory format. +/// @param src_descs Array of source memory descriptors with @p n elements. +/// @param attr Primitive attributes to use (can be NULL). +/// @param engine Engine to use. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_concat_primitive_desc_create( + dnnl_primitive_desc_t *concat_primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t dst_desc, int n, int concat_dimension, + const_dnnl_memory_desc_t const *src_descs, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_concat + +/// @addtogroup dnnl_api_sum +/// @{ + +/// Creates a primitive descriptor for an (out-of-place) sum primitive. +/// +/// @param sum_primitive_desc Output primitive descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param n Number of source parameters. +/// @param scales Vector of scales to multiply data in each source +/// memory by. +/// @param src_descs Array of source memory descriptors having @p n elements. +/// @param attr Primitive attributes to use (can be NULL). +/// @param engine Engine to use. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sum_primitive_desc_create( + dnnl_primitive_desc_t *sum_primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t dst_desc, int n, const float *scales, + const_dnnl_memory_desc_t const *src_descs, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_sum + +/// @addtogroup dnnl_api_binary +/// @{ + +/// Creates a primitive descriptor for a binary primitive. +/// +/// @note +/// Memory descriptors @p src1_desc and @p dst_desc are alloweded to be +/// initialized with #dnnl_format_tag_any or with format_kind set to +/// #dnnl_format_kind_any. +/// +/// @note +/// Both memory descriptors must have the same number of dimensions. +/// Element broadcasting is supported for memory descriptor @p src1_desc +/// and are applied to @p src1_desc dimensions that have size equal to 1. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Algorithm kind. Valid values are #dnnl_binary_add, +/// #dnnl_binary_mul, #dnnl_binary_max, #dnnl_binary_min, #dnnl_binary_div, +/// #dnnl_binary_sub, #dnnl_binary_ge, #dnnl_binary_gt, #dnnl_binary_le, +/// #dnnl_binary_lt, #dnnl_binary_eq and #dnnl_binary_ne. +/// @param src0_desc Source 0 memory descriptor. +/// @param src1_desc Source 1 memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_binary_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t src0_desc, + const_dnnl_memory_desc_t src1_desc, const_dnnl_memory_desc_t dst_desc, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_binary + +/// @addtogroup dnnl_api_convolution +/// @{ + +/// Creates a primitive descriptor for a convolution forward propagation +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r contain +/// values for spatial dimensions only and hence must have the same number of +/// elements as there are spatial dimensions. The order of values is the same +/// as in the tensor: depth (for 3D tensors), height (for 3D and 2D tensors), +/// and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind Convolution algorithm. Possible values are +/// #dnnl_convolution_direct, #dnnl_convolution_winograd, +/// #dnnl_convolution_auto. +/// @param src_desc Source memory descriptor. +/// @param weights_desc Weights memory descriptor. +/// @param bias_desc Bias memory descriptor. Passing NULL, a zero memory +/// descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param dst_desc Destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param dilates Array of dilations for spatial dimension. A zero value +/// means no dilation in the corresponding dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_convolution_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t bias_desc, const_dnnl_memory_desc_t dst_desc, + const dnnl_dims_t strides, const dnnl_dims_t dilates, + const dnnl_dims_t padding_l, const dnnl_dims_t padding_r, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a convolution backward propagation +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r contain +/// values for spatial dimensions only and hence must have the same number of +/// elements as there are spatial dimensions. The order of values is the same +/// as in the tensor: depth (for 3D tensors), height (for 3D and 2D tensors), +/// and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Convolution algorithm. Possible values are +/// #dnnl_convolution_direct, #dnnl_convolution_winograd, +/// #dnnl_convolution_auto. +/// @param diff_src_desc Diff source memory descriptor. +/// @param weights_desc Weights memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param dilates Array of dilations for spatial dimension. A zero value +/// means no dilation in the corresponding dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_convolution_backward_data_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t diff_dst_desc, const dnnl_dims_t strides, + const dnnl_dims_t dilates, const dnnl_dims_t padding_l, + const dnnl_dims_t padding_r, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a convolution weights gradient primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r contain +/// values for spatial dimensions only and hence must have the same number of +/// elements as there are spatial dimensions. The order of values is the same +/// as in the tensor: depth (for 3D tensors), height (for 3D and 2D tensors), +/// and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Convolution algorithm. Possible values are +/// #dnnl_convolution_direct, #dnnl_convolution_winograd, +/// #dnnl_convolution_auto. +/// @param src_desc Source memory descriptor. +/// @param diff_weights_desc Diff weights memory descriptor. +/// @param diff_bias_desc Diff bias memory descriptor. Passing NULL, a zero +/// memory descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param dilates Array of dilations for spatial dimension. A zero value +/// means no dilation in the corresponding dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_convolution_backward_weights_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t diff_weights_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_desc, const dnnl_dims_t strides, + const dnnl_dims_t dilates, const dnnl_dims_t padding_l, + const dnnl_dims_t padding_r, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_convolution + +/// @addtogroup dnnl_api_deconvolution +/// @{ + +/// Creates a primitive descriptor for a deconvolution forward propagation +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r contain +/// values for spatial dimensions only and hence must have the same number of +/// elements as there are spatial dimensions. The order of values is the same +/// as in the tensor: depth (for 3D tensors), height (for 3D and 2D tensors), +/// and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind Deconvolution algorithm. Possible values are +/// #dnnl_deconvolution_direct, #dnnl_deconvolution_winograd. +/// @param src_desc Source memory descriptor. +/// @param weights_desc Weights memory descriptor. +/// @param bias_desc Bias memory descriptor. Passing NULL, a zero memory +/// descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param dst_desc Destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param dilates Array of dilations for spatial dimension. A zero value +/// means no dilation in the corresponding dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_deconvolution_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t bias_desc, const_dnnl_memory_desc_t dst_desc, + const dnnl_dims_t strides, const dnnl_dims_t dilates, + const dnnl_dims_t padding_l, const dnnl_dims_t padding_r, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a deconvolution backward propagation +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r contain +/// values for spatial dimensions only and hence must have the same number of +/// elements as there are spatial dimensions. The order of values is the same +/// as in the tensor: depth (for 3D tensors), height (for 3D and 2D tensors), +/// and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Deconvolution algorithm. Possible values are +/// #dnnl_deconvolution_direct, #dnnl_deconvolution_winograd. +/// @param diff_src_desc Diff source memory descriptor. +/// @param weights_desc Weights memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param dilates Array of dilations for spatial dimension. A zero value +/// means no dilation in the corresponding dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_deconvolution_backward_data_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t diff_dst_desc, const dnnl_dims_t strides, + const dnnl_dims_t dilates, const dnnl_dims_t padding_l, + const dnnl_dims_t padding_r, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a deconvolution weights gradient +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r contain +/// values for spatial dimensions only and hence must have the same number of +/// elements as there are spatial dimensions. The order of values is the same +/// as in the tensor: depth (for 3D tensors), height (for 3D and 2D tensors), +/// and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Deconvolution algorithm. Possible values are +/// #dnnl_deconvolution_direct, #dnnl_deconvolution_winograd. +/// @param src_desc Source memory descriptor. +/// @param diff_weights_desc Diff weights memory descriptor. +/// @param diff_bias_desc Diff bias memory descriptor. Passing NULL, a zero +/// memory descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param dilates Array of dilations for spatial dimension. A zero value +/// means no dilation in the corresponding dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API +dnnl_deconvolution_backward_weights_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t diff_weights_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_desc, const dnnl_dims_t strides, + const dnnl_dims_t dilates, const dnnl_dims_t padding_l, + const dnnl_dims_t padding_r, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_deconvolution + +/// @addtogroup dnnl_api_shuffle +/// @{ + +/// Creates a primitive descriptor for a shuffle forward propagation primitive +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param axis The axis along which the data is shuffled. +/// @param group_size Shuffle group size. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_shuffle_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, int axis, dnnl_dim_t group_size, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a shuffle backward propagation primitive +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param axis The axis along which the data is shuffled. +/// @param group_size Shuffle group size. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_shuffle_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, int axis, dnnl_dim_t group_size, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_shuffle + +/// @addtogroup dnnl_api_eltwise +/// @{ + +/// Creates a primitive descriptor for an eltwise forward propagation primitive. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind Elementwise algorithm kind. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param alpha The alpha parameter for the elementwise operation. Specific +/// meaning depends on the algorithm. +/// @param beta The beta parameter for the elementwise operation. Specific +/// meaning depends on the algorithm. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_eltwise_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const_dnnl_memory_desc_t src_desc, const_dnnl_memory_desc_t dst_desc, + float alpha, float beta, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for an eltwise backward propagation +/// primitive. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Elementwise algorithm kind. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param data_desc Destination memory descriptor if one of the +/// "use_dst_for_bwd" algorithms are used (such as +/// #dnnl_eltwise_relu_use_dst_for_bwd), source memory descriptor otherwise. +/// @param alpha The alpha parameter for the elementwise operation. Specific +/// meaning depends on the algorithm. +/// @param beta The beta parameter for the elementwise operation. Specific +/// meaning depends on the algorithm. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_eltwise_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t data_desc, float alpha, float beta, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_eltwise + +/// @addtogroup dnnl_api_softmax +/// @{ + +/// Creates a primitive descriptor for a softmax forward propagation primitive. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind Softmax algorithm kind: either #dnnl_softmax_accurate, or +/// #dnnl_softmax_log. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param softmax_axis Axis over which softmax is computed. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_softmax_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const_dnnl_memory_desc_t src_desc, const_dnnl_memory_desc_t dst_desc, + int softmax_axis, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a softmax backward propagation primitive. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Softmax algorithm kind: either #dnnl_softmax_accurate, or +/// #dnnl_softmax_log. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param softmax_axis Axis over which softmax is computed. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_softmax_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t dst_desc, int softmax_axis, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_softmax + +/// @addtogroup dnnl_api_pooling +/// @{ + +/// Creates a primitive descriptor for a pooling forward propagation +/// primitive. +/// +/// Arrays @p strides, @p kernel, @p dilation, @p padding_l and @p padding_r +/// contain values for spatial dimensions only and hence must have the same +/// number of elements as there are spatial dimensions. The order of values +/// is the same as in the tensor: depth (for 3D tensors), +/// height (for 3D and 2D tensors), and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind Pooling algorithm kind: either #dnnl_pooling_max, +/// #dnnl_pooling_avg_include_padding, or #dnnl_pooling_avg_exclude_padding. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param kernel Array of kernel spatial dimensions. +/// @param dilation Array of dilations for spatial dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_pooling_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const_dnnl_memory_desc_t src_desc, const_dnnl_memory_desc_t dst_desc, + const dnnl_dims_t strides, const dnnl_dims_t kernel, + const dnnl_dims_t dilation, const dnnl_dims_t padding_l, + const dnnl_dims_t padding_r, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a pooling backward propagation +/// primitive. +/// +/// Arrays @p strides, @p kernel, @p dilation, @p padding_l and @p padding_r +/// contain values for spatial dimensions only and hence must have the same +/// number of elements as there are spatial dimensions. The order of values +/// is the same as in the tensor: depth (for 3D tensors), +/// height (for 3D and 2D tensors), and width. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind Pooling algorithm kind: either #dnnl_pooling_max, +/// #dnnl_pooling_avg_include_padding, or #dnnl_pooling_avg_exclude_padding. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param strides Array of strides for spatial dimension. +/// @param kernel Array of kernel spatial dimensions. +/// @param dilation Array of dilations for spatial dimension. +/// @param padding_l Array of padding values for low indices for each spatial +/// dimension `([[front,] top,] left)`. +/// @param padding_r Array of padding values for high indices for each spatial +/// dimension `([[back,] bottom,] right)`. Can be NULL in which case +/// padding is considered to be symmetrical. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_pooling_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, const dnnl_dims_t strides, + const dnnl_dims_t kernel, const dnnl_dims_t dilation, + const dnnl_dims_t padding_l, const dnnl_dims_t padding_r, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_pooling + +/// @addtogroup dnnl_api_prelu +/// @{ + +/// Creates a primitive descriptor for a PReLU (leaky ReLU with trainable +/// alpha parameter) forward propagation primitive. +/// +/// @note +/// weights descriptor is allowed to be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param weights_desc Alpha parameters memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_prelu_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t dst_desc, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a PReLU (leaky ReLU with trainable +/// alpha parameter) backward propagation primitive. +/// +/// @note +/// weights descriptor and diff_weights descriptor are allowed +/// to be initialized with #dnnl_format_tag_any or with format_kind +/// set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param src_desc Source memory descriptor. +/// @param weights_desc Alpha parameters memory descriptor. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_weights_desc Diff alpha parameters memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_prelu_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_weights_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_prelu + +/// @addtogroup dnnl_api_lrn +/// @{ + +/// Creates a primitive descriptor for an LRN forward propagation primitive. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind LRN algorithm kind: either #dnnl_lrn_across_channels or +/// #dnnl_lrn_within_channel. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param local_size Regularization local size. +/// @param alpha The alpha regularization parameter. +/// @param beta The beta regularization parameter. +/// @param k The k regularization parameter. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lrn_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const_dnnl_memory_desc_t src_desc, const_dnnl_memory_desc_t dst_desc, + dnnl_dim_t local_size, float alpha, float beta, float k, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for an LRN backward propagation primitive. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param alg_kind LRN algorithm kind: either #dnnl_lrn_across_channels or +/// #dnnl_lrn_within_channel. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param src_desc Source memory descriptor. +/// @param local_size Regularization local size. +/// @param alpha The alpha regularization parameter. +/// @param beta The beta regularization parameter. +/// @param k The k regularization parameter. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lrn_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t src_desc, dnnl_dim_t local_size, float alpha, + float beta, float k, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_lrn + +/// @addtogroup dnnl_api_batch_normalization +/// @{ + +/// Creates a primitive descriptor for a batch normalization forward propagation +/// primitive. +/// +/// @note +/// In-place operation is supported: the dst can refer to the same memory +/// as the src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param epsilon Batch normalization epsilon parameter. +/// @param flags Batch normalization flags (@ref dnnl_normalization_flags_t). +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_batch_normalization_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, float epsilon, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a batch normalization backward +/// propagation primitive. +/// +/// @note +/// In-place operation is supported: the diff_dst can refer to the same +/// memory as the diff_src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_backward_data and #dnnl_backward (diffs for all parameters are +/// computed in this case). +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param src_desc Source memory descriptor. +/// @param epsilon Batch normalization epsilon parameter. +/// @param flags Batch normalization flags (@ref dnnl_normalization_flags_t). +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_batch_normalization_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t src_desc, float epsilon, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_batch_normalization + +/// @addtogroup dnnl_api_group_normalization +/// @{ + +/// Creates a primitive descriptor for a group normalization forward propagation +/// primitive. +/// +/// @note +/// In-place operation is supported: the dst can refer to the same memory +/// as the src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param groups Group normalization groups parameter. +/// @param epsilon Group normalization epsilon parameter. +/// @param flags Group normalization flags (@ref dnnl_normalization_flags_t). +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_group_normalization_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, dnnl_dim_t groups, float epsilon, + unsigned flags, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a group normalization backward +/// propagation primitive. +/// +/// @note +/// In-place operation is supported: the diff_dst can refer to the same +/// memory as the diff_src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_backward_data and #dnnl_backward (diffs for all parameters are +/// computed in this case). +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param src_desc Source memory descriptor. +/// @param groups Group normalization groups parameter. +/// @param epsilon Group normalization epsilon parameter. +/// @param flags Group normalization flags (@ref dnnl_normalization_flags_t). +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_group_normalization_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t src_desc, dnnl_dim_t groups, float epsilon, + unsigned flags, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_group_normalization + +/// @addtogroup dnnl_api_layer_normalization +/// @{ + +/// Creates a primitive descriptor for a layer normalization forward propagation +/// primitive. +/// +/// @note +/// In-place operation is supported: the dst can refer to the same memory +/// as the src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param stat_desc Memory descriptor for mean and variance. If this +/// parameter is NULL, a zero memory descriptor, or a memory descriptor +/// with format_kind set to #dnnl_format_kind_undef, then the memory +/// descriptor for stats is derived from @p src_desc by removing the last +/// dimension. +/// @param epsilon Layer normalization epsilon parameter. +/// @param flags Layer normalization flags (@ref dnnl_normalization_flags_t). +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_layer_normalization_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, const_dnnl_memory_desc_t stat_desc, + float epsilon, unsigned flags, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a layer normalization backward +/// propagation primitive. +/// +/// @note +/// In-place operation is supported: the diff_dst can refer to the same +/// memory as the diff_src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_backward_data and #dnnl_backward (diffs for all parameters are +/// computed in this case). +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param src_desc Source memory descriptor. +/// @param stat_desc Memory descriptor for mean and variance. If this +/// parameter is NULL, a zero memory descriptor, or a memory descriptor +/// with format_kind set to #dnnl_format_kind_undef, then the memory +/// descriptor for stats is derived from @p src_desc by removing the last +/// dimension. +/// @param epsilon Layer normalization epsilon parameter. +/// @param flags Layer normalization flags (@ref dnnl_normalization_flags_t). +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_layer_normalization_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t src_desc, const_dnnl_memory_desc_t stat_desc, + float epsilon, unsigned flags, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a layer normalization forward propagation +/// primitive with a user-provided data type for the scale and shift +/// memory objects. +/// +/// @note +/// In-place operation is supported: the dst can refer to the same memory +/// as the src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param stat_desc Memory descriptor for mean and variance. If this +/// parameter is NULL, a zero memory descriptor, or a memory descriptor +/// with format_kind set to #dnnl_format_kind_undef, then the memory +/// descriptor for stats is derived from @p src_desc by removing the last +/// dimension. +/// @param scale_shift_data_type Data type of scale and shift memory. If neither scale +/// nor shift flag are specified the parameter is ignored. +/// @param epsilon Layer normalization epsilon parameter. +/// @param flags Layer normalization flags (@ref dnnl_normalization_flags_t). +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API +dnnl_layer_normalization_forward_primitive_desc_create_v2( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, const_dnnl_memory_desc_t stat_desc, + dnnl_data_type_t scale_shift_data_type, float epsilon, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a layer normalization backward +/// propagation primitive with a user-provided data type for the +/// scale and shift memory objects. +/// +/// @note +/// In-place operation is supported: the diff_dst can refer to the same +/// memory as the diff_src. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_backward_data and #dnnl_backward (diffs for all parameters are +/// computed in this case). +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param src_desc Source memory descriptor. +/// @param stat_desc Memory descriptor for mean and variance. If this +/// parameter is NULL, a zero memory descriptor, or a memory descriptor +/// with format_kind set to #dnnl_format_kind_undef, then the memory +/// descriptor for stats is derived from @p src_desc by removing the last +/// dimension. +/// @param diff_scale_shift_data_type Data type of diff scale and shift memory. If neither scale +/// nor shift flag are specified the parameter is ignored. +/// @param scale_shift_data_type Data type of scale and shift memory. If neither scale +/// nor shift flag are specified the parameter is ignored. +/// @param epsilon Layer normalization epsilon parameter. +/// @param flags Layer normalization flags (@ref dnnl_normalization_flags_t). +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API +dnnl_layer_normalization_backward_primitive_desc_create_v2( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_memory_desc_t src_desc, const_dnnl_memory_desc_t stat_desc, + dnnl_data_type_t diff_scale_shift_data_type, + dnnl_data_type_t scale_shift_data_type, float epsilon, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_layer_normalization + +/// @addtogroup dnnl_api_inner_product +/// @{ + +/// Creates a primitive descriptor for an inner product forward propagation +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param src_desc Source memory descriptor. +/// @param weights_desc Weights memory descriptor. +/// @param bias_desc Bias memory descriptor. Passing NULL, a zero memory +/// descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param dst_desc Destination memory descriptor. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_inner_product_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t bias_desc, const_dnnl_memory_desc_t dst_desc, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for an inner product backward propagation +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param diff_src_desc Diff source memory descriptor. +/// @param weights_desc Weights memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_inner_product_backward_data_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for an inner product weights gradient +/// primitive. +/// +/// @note +/// Memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive_descriptor. +/// @param engine Engine to use. +/// @param src_desc Source memory descriptor. +/// @param diff_weights_desc Diff weights memory descriptor. +/// @param diff_bias_desc Diff bias memory descriptor. Passing NULL, a zero +/// memory descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API +dnnl_inner_product_backward_weights_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t diff_weights_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_inner_product + +/// @addtogroup dnnl_api_attributes +/// @{ + +/// Set quantization scale and shift parameters for RNN data tensors. +/// +/// For performance reasons, the low-precision configuration of the RNN +/// primitives expects input activations to have the unsigned 8-bit integer +/// data type. The scale and shift parameters are used to quantize +/// floating-point data to unsigned integer and must be passed to the RNN +/// primitive using attributes. +/// +/// The quantization formula is `scale * data + shift`. +/// +/// @note +/// Quantization scale and shift are common for src_layer, src_iter, +/// dst_iter, and dst_layer. +/// +/// Example usage: +/// @code +/// // RNN parameters +/// int l = 2, t = 2, mb = 32, sic = 32, slc = 32, dic = 32, dlc = 32; +/// // Activations quantization parameters +/// float scale = 63.f, shift = 64.f; +/// +/// dnnl_primitive_attr_t rnn_attr; +/// // Create default attributes +/// dnnl_primitive_attr_create(&rnn_attr); +/// +/// // Set scale and shift for int8 quantization of activation +/// dnnl_primitive_attr_set_rnn_data_qparams(rnn_attr, scale, shift); +/// +/// // Create an RNN primitive descriptor. +/// dnnl_primitive_desc_t rnn_pd; +/// dnnl_vanilla_rnn_forward_primitive_desc_create(&rnn_pd, +/// engine, /* arguments */, attr); +/// @endcode +/// +/// @param attr Primitive attributes. +/// @param scale The value to scale the data by. +/// @param shift The value to shift the data by. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_rnn_data_qparams( + dnnl_primitive_attr_t attr, const float scale, const float shift); + +/// Returns the quantization scale and shift parameters for RNN data tensors. +/// +/// @note +/// Quantization scale and shift are common for src_layer, src_iter, +/// dst_iter, and dst_layer. +/// +/// @param attr Primitive attributes. +/// @param scale The value to scale the data by. +/// @param shift The value to shift the data by. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_rnn_data_qparams( + const_dnnl_primitive_attr_t attr, float *scale, float *shift); + +/// Sets quantization scaling factors for RNN weights tensors. The +/// low-precision configuration of the RNN primitives expects input weights to +/// use the signed 8-bit integer data type. The scaling factors are used to +/// quantize floating-point data to signed integer and must be passed to RNN +/// primitives using attributes. +/// +/// @note +/// The dimension order is always native and does not depend on the actual +/// layout used. For example, five-dimensional weights always have (l, d, +/// i, g, o) logical dimension ordering. +/// +/// @note +/// Quantization scales are common for weights_layer and weights_iteration +/// +/// @param attr Primitive attributes. +/// @param count Number of elements in the @p scales array. +/// @param mask Scaling factors correspondence mask that defines the +/// correspondence between the output tensor dimensions and the @p +/// scales vector. The set i-th bit indicates that a dedicated scaling +/// factor should be used for each index along that dimension. Set the +/// mask to 0 to use a common scaling factor for the whole output +/// tensor. +/// @param scales Array of output scaling factors that must contain @p count +/// values and the following equality must hold: +/// \f[count = \prod\limits_{d \in mask} weights.dims[d].\f] +/// Violations can only be detected when the attributes are used to create +/// a primitive descriptor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_rnn_weights_qparams( + dnnl_primitive_attr_t attr, dnnl_dim_t count, int mask, + const float *scales); + +/// Returns the quantization scaling factors for RNN weights tensors. +/// +/// @param attr Primitive attributes. +/// @param count Number of elements in the @p scales array. +/// @param mask Scaling factors correspondence mask that defines the +/// correspondence between the output tensor dimensions and the @p +/// scales vector. The set i-th bit indicates that a dedicated scaling +/// factor should be used for each index along that dimension. Set the +/// mask to 0 to use a common scaling factor for the whole output +/// tensor. +/// @param scales Array of output scaling factors that contain @p count +/// values and the following equality must hold: +/// \f[count = \prod\limits_{d \in mask} weights.dims[d].\f] +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_rnn_weights_qparams( + const_dnnl_primitive_attr_t attr, dnnl_dim_t *count, int *mask, + const float **scales); + +/// Sets quantization scaling factors for RNN projection weights tensors. The +/// low-precision configuration of the RNN primitives expects input weights to +/// use the signed 8-bit integer data type. The scaling factors are used to +/// quantize floating-point data to signed integer and must be passed to RNN +/// primitives using attributes. +/// +/// @note +/// The dimension order is always native and does not depend on the actual +/// layout used. For example, five-dimensional weights always have (l, d, +/// i, g, o) logical dimension ordering. +/// +/// @param attr Primitive attributes. +/// @param count Number of elements in the @p scales array. +/// @param mask Scaling factors correspondence mask that defines the +/// correspondence between the output tensor dimensions and the @p +/// scales vector. The set i-th bit indicates that a dedicated scaling +/// factor should be used for each index along that dimension. Set the +/// mask to 0 to use a common scaling factor for the whole output +/// tensor. +/// @param scales Array of output scaling factors that must contain @p count +/// values and the following equality must hold: +/// \f[count = \prod\limits_{d \in mask} weights.dims[d].\f] +/// Violations can only be detected when the attributes are used to create +/// a primitive descriptor. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_set_rnn_weights_projection_qparams( + dnnl_primitive_attr_t attr, dnnl_dim_t count, int mask, + const float *scales); + +/// Returns the quantization scaling factors for RNN projection weights tensors. +/// +/// @param attr Primitive attributes. +/// @param count Number of elements in the @p scales array. +/// @param mask Scaling factors correspondence mask that defines the +/// correspondence between the output tensor dimensions and the @p +/// scales vector. The set i-th bit indicates that a dedicated scaling +/// factor should be used for each index along that dimension. Set the +/// mask to 0 to use a common scaling factor for the whole output +/// tensor. +/// @param scales Array of output scaling factors that contain @p count +/// values and the following equality must hold: +/// \f[count = \prod\limits_{d \in mask} weights.dims[d].\f] +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_primitive_attr_get_rnn_weights_projection_qparams( + const_dnnl_primitive_attr_t attr, dnnl_dim_t *count, int *mask, + const float **scales); + +/// @} dnnl_api_attributes + +/// @addtogroup dnnl_api_rnn +/// @{ + +/// Creates a primitive descriptor for vanilla RNN forward propagation +/// primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc, +/// - @p bias_desc, +/// - @p dst_iter_desc. +/// +/// This would then indicate that the RNN forward propagation primitive should +/// not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param activation Activation kind. Possible values are #dnnl_eltwise_relu, +/// #dnnl_eltwise_tanh or #dnnl_eltwise_logistic. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param flags Unused. +/// @param alpha Negative slope if activation is #dnnl_eltwise_relu. +/// @param beta Unused. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_vanilla_rnn_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const dnnl_alg_kind_t activation, + const dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, unsigned flags, float alpha, + float beta, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for vanilla RNN backward propagation +/// primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p diff_src_iter_desc, +/// - @p bias_desc together with @p diff_bias_desc, +/// - @p dst_iter_desc together with @p diff_dst_iter_desc. +/// +/// This would then indicate that the RNN backward propagation primitive should +/// not use the respective data and should use zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Must be #dnnl_backward. +/// @param activation Activation kind. Possible values are #dnnl_eltwise_relu, +/// #dnnl_eltwise_tanh or #dnnl_eltwise_logistic. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param diff_src_layer_desc Memory descriptor for the diff of input vector. +/// @param diff_src_iter_desc Memory descriptor for the diff of input recurrent +/// hidden state vector. +/// @param diff_weights_layer_desc Memory descriptor for the diff of weights +/// applied to the layer input. +/// @param diff_weights_iter_desc Memory descriptor for the diff of weights +/// applied to the recurrent input. +/// @param diff_bias_desc Diff bias memory descriptor. +/// @param diff_dst_layer_desc Memory descriptor for the diff of output +/// vector. +/// @param diff_dst_iter_desc Memory descriptor for the diff of output +/// recurrent hidden state vector. +/// @param flags Unused. +/// @param alpha Negative slope if activation is #dnnl_eltwise_relu. +/// @param beta Unused. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_vanilla_rnn_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, const dnnl_alg_kind_t activation, + const dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t diff_src_layer_desc, + const_dnnl_memory_desc_t diff_src_iter_desc, + const_dnnl_memory_desc_t diff_weights_layer_desc, + const_dnnl_memory_desc_t diff_weights_iter_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_layer_desc, + const_dnnl_memory_desc_t diff_dst_iter_desc, unsigned flags, + float alpha, float beta, const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for an LSTM forward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p src_iter_c_desc, +/// - @p weights_peephole_desc, +/// - @p bias_desc, +/// - @p dst_iter_desc together with @p dst_iter_c_desc. +/// +/// This would then indicate that the LSTM forward propagation primitive should +/// not use them and should default to zero values instead. +/// +/// The @p weights_projection_desc could either be @c NULL or point to a zero +/// memory descriptor. This would then indicate that the LSTM doesn't have +/// recurrent projection layer. +/// +/// @note +/// All memory descriptors can be initialized with #dnnl_format_tag_any or +/// with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param src_iter_c_desc Memory descriptor for the input recurrent cell +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param weights_peephole_desc Memory descriptor for the weights applied to +/// the cell states (according to the Peephole LSTM formula). +/// @param weights_projection_desc Memory descriptor for the weights applied to +/// the hidden states to get the recurrent projection (according to the +/// Projection LSTM formula). +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param dst_iter_c_desc Memory descriptor for the output recurrent cell +/// state vector. +/// @param flags Unused. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lstm_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t src_iter_c_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t weights_peephole_desc, + const_dnnl_memory_desc_t weights_projection_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t dst_iter_c_desc, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for an LSTM backward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p src_iter_c_desc, @p diff_src_iter_desc, +/// and @p diff_src_iter_c_desc, +/// - @p weights_peephole_desc together with @p diff_weights_peephole_desc, +/// - @p bias_desc together with @p diff_bias_desc, +/// - @p dst_iter_desc together with @p dst_iter_c_desc, @p diff_dst_iter_desc, +/// and @p diff_dst_iter_c_desc. +/// +/// This would then indicate that the LSTM backward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// The @p weights_projection_desc together with @p +/// diff_weights_projection_desc could either be @c NULL or point to a zero +/// memory descriptor. This would then indicate that the LSTM doesn't have +/// recurrent projection layer. +/// +/// @note +/// All memory descriptors can be initialized with #dnnl_format_tag_any or +/// with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Must be #dnnl_backward. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param src_iter_c_desc Memory descriptor for the input recurrent cell +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param weights_peephole_desc Memory descriptor for the weights applied to +/// the cell states (according to the Peephole LSTM formula). +/// @param weights_projection_desc Memory descriptor for the weights applied to +/// the hidden states to get the recurrent projection (according to the +/// Projection LSTM formula). +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param dst_iter_c_desc Memory descriptor for the output recurrent cell +/// state vector. +/// @param diff_src_layer_desc Memory descriptor for the diff of input vector. +/// @param diff_src_iter_desc Memory descriptor for the diff of input recurrent +/// hidden state vector. +/// @param diff_src_iter_c_desc Memory descriptor for the diff of input +/// recurrent cell state vector. +/// @param diff_weights_layer_desc Memory descriptor for the diff of weights +/// applied to the layer input. +/// @param diff_weights_iter_desc Memory descriptor for the diff of weights +/// applied to the recurrent input. +/// @param diff_weights_peephole_desc Memory descriptor for the diff of weights +/// applied to the cell states (according to the Peephole LSTM formula). +/// @param diff_weights_projection_desc Memory descriptor for the diff of +/// weights applied to the hidden states to get the recurrent projection +/// (according to the Projection LSTM formula). +/// @param diff_bias_desc Diff bias memory descriptor. +/// @param diff_dst_layer_desc Memory descriptor for the diff of output +/// vector. +/// @param diff_dst_iter_desc Memory descriptor for the diff of output +/// recurrent hidden state vector. +/// @param diff_dst_iter_c_desc Memory descriptor for the diff of output +/// recurrent cell state vector. +/// @param flags Unused. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lstm_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t src_iter_c_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t weights_peephole_desc, + const_dnnl_memory_desc_t weights_projection_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t dst_iter_c_desc, + const_dnnl_memory_desc_t diff_src_layer_desc, + const_dnnl_memory_desc_t diff_src_iter_desc, + const_dnnl_memory_desc_t diff_src_iter_c_desc, + const_dnnl_memory_desc_t diff_weights_layer_desc, + const_dnnl_memory_desc_t diff_weights_iter_desc, + const_dnnl_memory_desc_t diff_weights_peephole_desc, + const_dnnl_memory_desc_t diff_weights_projection_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_layer_desc, + const_dnnl_memory_desc_t diff_dst_iter_desc, + const_dnnl_memory_desc_t diff_dst_iter_c_desc, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for GRU forward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc, +/// - @p bias_desc, +/// - @p dst_iter_desc. +/// +/// This would then indicate that the GRU forward propagation primitive should +/// not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param flags Unused. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_gru_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for GRU backward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p diff_src_iter_desc, +/// - @p bias_desc together with @p diff_bias_desc, +/// - @p dst_iter_desc together with @p diff_dst_iter_desc. +/// +/// This would then indicate that the GRU backward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Must be #dnnl_backward. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param diff_src_layer_desc Memory descriptor for the diff of input vector. +/// @param diff_src_iter_desc Memory descriptor for the diff of input recurrent +/// hidden state vector. +/// @param diff_weights_layer_desc Memory descriptor for the diff of weights +/// applied to the layer input. +/// @param diff_weights_iter_desc Memory descriptor for the diff of weights +/// applied to the recurrent input. +/// @param diff_bias_desc Diff bias memory descriptor. +/// @param diff_dst_layer_desc Memory descriptor for the diff of output +/// vector. +/// @param diff_dst_iter_desc Memory descriptor for the diff of output +/// recurrent hidden state vector. +/// @param flags Unused. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_gru_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t diff_src_layer_desc, + const_dnnl_memory_desc_t diff_src_iter_desc, + const_dnnl_memory_desc_t diff_weights_layer_desc, + const_dnnl_memory_desc_t diff_weights_iter_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_layer_desc, + const_dnnl_memory_desc_t diff_dst_iter_desc, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a descriptor for LBR GRU forward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc, +/// - @p bias_desc, +/// - @p dst_iter_desc. +/// +/// This would then indicate that the LBR GRU forward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param flags Unused. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lbr_gru_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for LBR GRU backward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p diff_src_iter_desc, +/// - @p bias_desc together with @p diff_bias_desc, +/// - @p dst_iter_desc together with @p diff_dst_iter_desc. +/// +/// This would then indicate that the LBR GRU backward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Must be #dnnl_backward. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param diff_src_layer_desc Memory descriptor for the diff of input vector. +/// @param diff_src_iter_desc Memory descriptor for the diff of input recurrent +/// hidden state vector. +/// @param diff_weights_layer_desc Memory descriptor for the diff of weights +/// applied to the layer input. +/// @param diff_weights_iter_desc Memory descriptor for the diff of weights +/// applied to the recurrent input. +/// @param diff_bias_desc Diff bias memory descriptor. +/// @param diff_dst_layer_desc Memory descriptor for the diff of output +/// vector. +/// @param diff_dst_iter_desc Memory descriptor for the diff of output +/// recurrent hidden state vector. +/// @param flags Unused. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lbr_gru_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t diff_src_layer_desc, + const_dnnl_memory_desc_t diff_src_iter_desc, + const_dnnl_memory_desc_t diff_weights_layer_desc, + const_dnnl_memory_desc_t diff_weights_iter_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_layer_desc, + const_dnnl_memory_desc_t diff_dst_iter_desc, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for AUGRU forward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc, +/// - @p bias_desc, +/// - @p dst_iter_desc. +/// +/// This would then indicate that the AUGRU forward propagation primitive should +/// not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param attention_desc Memory descriptor for the attention vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param flags Unused. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_augru_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t attention_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for AUGRU backward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p diff_src_iter_desc, +/// - @p bias_desc together with @p diff_bias_desc, +/// - @p dst_iter_desc together with @p diff_dst_iter_desc. +/// +/// This would then indicate that the AUGRU backward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Must be #dnnl_backward. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param attention_desc Memory descriptor for the attention vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param diff_src_layer_desc Memory descriptor for the diff of input vector. +/// @param diff_src_iter_desc Memory descriptor for the diff of input recurrent +/// hidden state vector. +/// @param diff_attention_desc Memory descriptor for the diff of attention vector. +/// @param diff_weights_layer_desc Memory descriptor for the diff of weights +/// applied to the layer input. +/// @param diff_weights_iter_desc Memory descriptor for the diff of weights +/// applied to the recurrent input. +/// @param diff_bias_desc Diff bias memory descriptor. +/// @param diff_dst_layer_desc Memory descriptor for the diff of output +/// vector. +/// @param diff_dst_iter_desc Memory descriptor for the diff of output +/// recurrent hidden state vector. +/// @param flags Unused. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_augru_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t attention_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t diff_src_layer_desc, + const_dnnl_memory_desc_t diff_src_iter_desc, + const_dnnl_memory_desc_t diff_attention_desc, + const_dnnl_memory_desc_t diff_weights_layer_desc, + const_dnnl_memory_desc_t diff_weights_iter_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_layer_desc, + const_dnnl_memory_desc_t diff_dst_iter_desc, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for LBR AUGRU forward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc, +/// - @p bias_desc, +/// - @p dst_iter_desc. +/// +/// This would then indicate that the LBR AUGRU forward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param attention_desc Memory descriptor for the attention vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param flags Unused. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lbr_augru_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t attention_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, unsigned flags, + const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for LBR AUGRU backward propagation primitive. +/// +/// The following arguments may either be @c NULL or point to a zero memory +/// descriptor: +/// - @p src_iter_desc together with @p diff_src_iter_desc, +/// - @p bias_desc together with @p diff_bias_desc, +/// - @p dst_iter_desc together with @p diff_dst_iter_desc. +/// +/// This would then indicate that the LBR AUGRU backward propagation primitive +/// should not use them and should default to zero values instead. +/// +/// @note +/// All memory descriptors can be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Must be #dnnl_backward. +/// @param direction RNN direction. See @ref dnnl_rnn_direction_t for more +/// info. +/// @param src_layer_desc Memory descriptor for the input vector. +/// @param src_iter_desc Memory descriptor for the input recurrent hidden +/// state vector. +/// @param attention_desc Memory descriptor for the attention vector. +/// @param weights_layer_desc Memory descriptor for the weights applied to the +/// layer input. +/// @param weights_iter_desc Memory descriptor for the weights applied to the +/// recurrent input. +/// @param bias_desc Bias memory descriptor. +/// @param dst_layer_desc Memory descriptor for the output vector. +/// @param dst_iter_desc Memory descriptor for the output recurrent hidden +/// state vector. +/// @param diff_src_layer_desc Memory descriptor for the diff of input vector. +/// @param diff_src_iter_desc Memory descriptor for the diff of input recurrent +/// hidden state vector. +/// @param diff_attention_desc Memory descriptor for the diff of attention vector. +/// @param diff_weights_layer_desc Memory descriptor for the diff of weights +/// applied to the layer input. +/// @param diff_weights_iter_desc Memory descriptor for the diff of weights +/// applied to the recurrent input. +/// @param diff_bias_desc Diff bias memory descriptor. +/// @param diff_dst_layer_desc Memory descriptor for the diff of output +/// vector. +/// @param diff_dst_iter_desc Memory descriptor for the diff of output +/// recurrent hidden state vector. +/// @param flags Unused. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_lbr_augru_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_rnn_direction_t direction, + const_dnnl_memory_desc_t src_layer_desc, + const_dnnl_memory_desc_t src_iter_desc, + const_dnnl_memory_desc_t attention_desc, + const_dnnl_memory_desc_t weights_layer_desc, + const_dnnl_memory_desc_t weights_iter_desc, + const_dnnl_memory_desc_t bias_desc, + const_dnnl_memory_desc_t dst_layer_desc, + const_dnnl_memory_desc_t dst_iter_desc, + const_dnnl_memory_desc_t diff_src_layer_desc, + const_dnnl_memory_desc_t diff_src_iter_desc, + const_dnnl_memory_desc_t diff_attention_desc, + const_dnnl_memory_desc_t diff_weights_layer_desc, + const_dnnl_memory_desc_t diff_weights_iter_desc, + const_dnnl_memory_desc_t diff_bias_desc, + const_dnnl_memory_desc_t diff_dst_layer_desc, + const_dnnl_memory_desc_t diff_dst_iter_desc, unsigned flags, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_rnn + +/// @addtogroup dnnl_api_matmul +/// @{ + +/// Creates a primitive descriptor for a matrix multiplication primitive. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param src_desc Source memory descriptor (matrix A) +/// @param weights_desc Weights memory descriptor (matrix B) +/// @param bias_desc Bias memory descriptor. Passing NULL, a zero memory +/// descriptor, or a memory descriptor with format_kind set to +/// #dnnl_format_kind_undef disables the bias term. +/// @param dst_desc Destination memory descriptor (matrix C). +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_matmul_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t weights_desc, + const_dnnl_memory_desc_t bias_desc, const_dnnl_memory_desc_t dst_desc, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_matmul + +/// @addtogroup dnnl_api_resampling Resampling +/// @{ + +/// Creates a primitive descriptor for a resampling forward propagation +/// primitive. +/// +/// @note +/// Destination memory descriptor is allowed to be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param prop_kind Propagation kind. Possible values are +/// #dnnl_forward_training and #dnnl_forward_inference. +/// @param alg_kind resampling algorithm kind: either #dnnl_resampling_nearest, +/// or #dnnl_resampling_linear. +/// @param factors Array of scaling factors for spatial dimension. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_resampling_forward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_prop_kind_t prop_kind, dnnl_alg_kind_t alg_kind, + const float *factors, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, const_dnnl_primitive_attr_t attr); + +/// Creates a primitive descriptor for a resampling backward propagation +/// primitive. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind resamplinging algorithm kind: either +/// #dnnl_resampling_nearest, or #dnnl_resampling_linear. +/// @param diff_src_desc Diff source memory descriptor. +/// @param diff_dst_desc Diff destination memory descriptor. +/// @param factors Array of scaling factors for spatial dimension. +/// @param hint_fwd_pd Primitive descriptor for a respective forward propagation +/// primitive. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +/// +dnnl_status_t DNNL_API dnnl_resampling_backward_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const float *factors, + const_dnnl_memory_desc_t diff_src_desc, + const_dnnl_memory_desc_t diff_dst_desc, + const_dnnl_primitive_desc_t hint_fwd_pd, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_resampling + +/// @addtogroup dnnl_api_reduction Reduction +/// @{ + +/// Creates a primitive descriptor for a reduction primitive. +/// +/// @note +/// Destination memory descriptor is allowed to be initialized with +/// #dnnl_format_tag_any or with format_kind set to #dnnl_format_kind_any. +/// +/// @param primitive_desc Output primitive descriptor. +/// @param engine Engine to use. +/// @param alg_kind reduction algorithm kind. Possible values: +/// #dnnl_reduction_max, #dnnl_reduction_min, #dnnl_reduction_sum, +/// #dnnl_reduction_mul, #dnnl_reduction_mean, #dnnl_reduction_norm_lp_max, +/// #dnnl_reduction_norm_lp_sum, #dnnl_reduction_norm_lp_power_p_max, +/// #dnnl_reduction_norm_lp_power_p_sum. +/// @param p Algorithm specific parameter. +/// @param eps Algorithm specific parameter. +/// @param src_desc Source memory descriptor. +/// @param dst_desc Destination memory descriptor. +/// @param attr Primitive attributes (can be NULL). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_reduction_primitive_desc_create( + dnnl_primitive_desc_t *primitive_desc, dnnl_engine_t engine, + dnnl_alg_kind_t alg_kind, const_dnnl_memory_desc_t src_desc, + const_dnnl_memory_desc_t dst_desc, float p, float eps, + const_dnnl_primitive_attr_t attr); + +/// @} dnnl_api_reduction + +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_primitive_cache +/// @{ + +/// Returns the number of primitives that can be held in the primitive cache +/// at the same time. +/// +/// @param capacity Primitive cache capacity to query. Concurrently +/// accessing @p capacity is safe. +/// @returns #dnnl_invalid_arguments/#dnnl::status::invalid_arguments if the +/// @p capacity value is invalid, and #dnnl_success/#dnnl::status::success on +/// success. +dnnl_status_t DNNL_API dnnl_get_primitive_cache_capacity(int *capacity); + +/// Sets a number of primitives that can be held in the primitive cache +/// at a time. +/// +/// @param capacity Primitive cache capacity to set. If a new @p capacity is +/// less than a number of primitives that the primitive cache already has +/// then the excess entries will be evicted. Setting the @p capacity to 0 +/// clears the primitive cache and disables it. Concurrently modifying +/// @p capacity is safe. +/// @returns #dnnl_invalid_arguments/#dnnl::status::invalid_arguments if the +/// @p capacity value is invalid, and #dnnl_success/#dnnl::status::success on +/// success. +dnnl_status_t DNNL_API dnnl_set_primitive_cache_capacity(int capacity); + +/// @} dnnl_api_primitive_cache + +/// @addtogroup dnnl_api_service +/// @{ + +/// Configures dumping of JIT-generated code. +/// +/// @note +/// This setting overrides the DNNL_JIT_DUMP environment variable. +/// +/// @param enable Flag value. Set to 0 to disable and set to 1 to enable. +/// @returns #dnnl_invalid_arguments/#dnnl::status::invalid_arguments if the +/// @p flag value is invalid, and #dnnl_success/#dnnl::status::success on +/// success. +dnnl_status_t DNNL_API dnnl_set_jit_dump(int enable); + +/// Sets library profiling flags. The flags define which profilers are +/// supported. +/// +/// @note +/// This setting overrides DNNL_JIT_PROFILE environment variable. +/// +/// @sa @ref dev_guide_profilers +/// +/// @param flags Profiling flags that can contain the following bits: +/// - @ref DNNL_JIT_PROFILE_VTUNE -- integration with VTune Profiler +/// (on by default) +/// - @ref DNNL_JIT_PROFILE_LINUX_JITDUMP -- produce Linux-specific +/// jit-pid.dump output (off by default). The location of the output +/// is controlled via JITDUMPDIR environment variable or via +/// dnnl_set_jit_profiling_jitdumpdir() function. +/// - @ref DNNL_JIT_PROFILE_LINUX_PERFMAP -- produce Linux-specific +/// perf-pid.map output (off by default). The output is always placed +/// into /tmp. +/// +/// Passing @ref DNNL_JIT_PROFILE_NONE disables profiling completely. +/// +/// @returns #dnnl_invalid_arguments/#dnnl::status::invalid_arguments if the +/// @p flags value is invalid, and #dnnl_success/#dnnl::status::success on +/// success. +dnnl_status_t DNNL_API dnnl_set_jit_profiling_flags(unsigned flags); + +/// Sets JIT dump output path. Only applicable to Linux and is only +/// used when profiling flags have DNNL_JIT_PROFILE_LINUX_PERF bit set. +/// +/// After the first JIT kernel is generated, the jitdump output will be placed +/// into temporary directory created using the mkdtemp template +/// 'dir/.debug/jit/dnnl.XXXXXX'. +/// +/// @sa @ref dev_guide_profilers +/// +/// @note +/// This setting overrides JITDUMPDIR environment variable. If +/// JITDUMPDIR is not set, and this function is never called, the path +/// defaults to HOME. Passing NULL reverts the value to default. +/// +/// @note +/// The directory is accessed only when the first JIT kernel is being +/// created. JIT profiling will be disabled in case of any errors +/// accessing or creating this directory. +/// +/// @param dir JIT dump output path. +/// @returns #dnnl_success/#dnnl::status::success if the +/// output directory was set correctly and an error status otherwise. +/// @returns #dnnl_unimplemented/#dnnl::status::unimplemented on Windows. +dnnl_status_t DNNL_API dnnl_set_jit_profiling_jitdumpdir(const char *dir); + +/// Sets the maximal ISA the library can dispatch to on the CPU. See +/// #dnnl_cpu_isa_t and #dnnl::cpu_isa for the list of the values accepted by +/// the C and C++ API functions respectively. +/// +/// This function has effect only once, and returns an error on subsequent +/// calls. It should also be invoked before any other oneDNN API call, otherwise +/// it may return an error. +/// +/// This function overrides the DNNL_MAX_CPU_ISA environment variable. The +/// environment variable can be set to the desired maximal ISA name in upper +/// case and with dnnl_cpu_isa prefix removed. For example: +/// `DNNL_MAX_CPU_ISA=AVX2`. +/// +/// @note +/// The ISAs are only partially ordered: +/// - SSE41 < AVX < AVX2 < AVX2_VNNI < AVX2_VNNI_2, +/// - AVX2 < AVX512_CORE < AVX512_CORE_VNNI < AVX512_CORE_BF16 +/// < AVX10_1_512 < AVX10_1_512_AMX < AVX10_1_512_AMX_FP16, +/// - AVX2_VNNI < AVX10_1_512. +/// Aliases: +/// - AVX512_CORE_FP16 = AVX10_1_512 +/// - AVX512_CORE_AMX = AVX10_1_512_AMX +/// - AVX512_CORE_AMX_FP16 = AVX10_1_512_AMX_FP16 +/// +/// @sa @ref dev_guide_cpu_dispatcher_control for more details +/// +/// @param isa Maximal ISA the library should dispatch to. Pass +/// #dnnl_cpu_isa_default/#dnnl::cpu_isa::isa_default to remove ISA restrictions +/// (except for ISAs with initial support in the library). +/// @returns #dnnl_success/#dnnl::status::success on success and a +/// #dnnl_invalid_arguments/#dnnl::status::invalid_arguments if the @p isa +/// parameter is invalid or the ISA cannot be changed at this time. +/// @returns #dnnl_unimplemented/#dnnl::status::unimplemented if the feature +/// was disabled at build time (see @ref dev_guide_build_options for more +/// details). +dnnl_status_t DNNL_API dnnl_set_max_cpu_isa(dnnl_cpu_isa_t isa); + +/// Gets the maximal ISA the library can dispatch to on the CPU. See +/// #dnnl_cpu_isa_t and #dnnl::cpu_isa for the list of the values returned by +/// the C and C++ API functions respectively. +/// +/// @sa @ref dev_guide_cpu_dispatcher_control for more details +/// +/// @returns #dnnl_cpu_isa_t value reflecting the maximal ISA the library may +/// dispatch to. +dnnl_cpu_isa_t DNNL_API dnnl_get_effective_cpu_isa(void); + +/// Sets the hints flag for the CPU ISA. See #dnnl_cpu_isa_hints_t and +/// #dnnl::cpu_isa_hints for the list of the values accepted by the C and C++ +/// API functions respectively. +/// +/// This function has effect only once, and returns an error on subsequent +/// calls. It should also be invoked before any other oneDNN API call, otherwise +/// it may return an error. +/// +/// This function overrides the DNNL_CPU_ISA_HINTS environment variable. +/// @sa @ref dev_guide_cpu_isa_hints for more details +/// +/// @param isa_hints CPU ISA hints to be passed over to the implementation. +/// Pass #dnnl_cpu_isa_no_hints/#dnnl::cpu_isa_hints::no_hints to use +/// default features i.e. no hints. +/// @returns #dnnl_success/#dnnl::status::success on success and a +/// #dnnl_runtime_error/#dnnl::status::runtime_error if the ISA hints cannot +/// be specified at the current time. +/// @returns #dnnl_unimplemented/#dnnl::status::unimplemented if the feature +/// was disabled at build time (see @ref dev_guide_build_options for more +/// details). +dnnl_status_t DNNL_API dnnl_set_cpu_isa_hints(dnnl_cpu_isa_hints_t isa_hints); + +/// Gets the ISA specific hints that library can follow. See +/// #dnnl_cpu_isa_hints_t and #dnnl::cpu_isa_hints for the list of the values +/// returned by the C and C++ API functions respectively. +/// +/// @sa @ref dev_guide_cpu_isa_hints for more details +/// +/// @returns #dnnl_cpu_isa_hints_t value reflecting the ISA specific hints the +/// library can follow. +dnnl_cpu_isa_hints_t DNNL_API dnnl_get_cpu_isa_hints(void); + +/// @} dnnl_api_service + +#ifdef DNNL_EXPERIMENTAL_PROFILING + +/// @addtogroup dnnl_api_profiling Profiling +/// @{ + +/// Resets a profiler's state. +/// +/// @param stream Stream associated with the profiler. +/// +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_reset_profiling(dnnl_stream_t stream); + +/// Queries profiling data. The profiling data accumulates for each primitive +/// execution. The @p num_entries will be equal to the number of executions +/// since the last `dnnl_reset_profiling` call. In order to query the +/// @p num_entries the @p data parameter should be NULL. When @p data is NULL +/// then the @p data_kind parameter is ignored. +/// +/// The profiling data can be reset by calling #dnnl_reset_profiling. +/// +/// @note +/// It is required to wait for all submitted primitives to complete +/// using #dnnl_stream_wait prior to querying profiling data. +/// +/// @param stream Stream that was used for executing a primitive that +/// is being profiled. +/// @param data_kind Profiling data kind to query. +/// @param num_entries Number of profiling data entries. +/// @param data Profiling data. +/// +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_query_profiling_data(dnnl_stream_t stream, + dnnl_profiling_data_kind_t data_kind, int *num_entries, uint64_t *data); + +/// @} dnnl_api_profiling +#endif + +/// @addtogroup dnnl_api_blas +/// @{ + +/// Performs single-precision matrix-matrix multiply. +/// +/// The operation is defined as: +/// +/// `C := alpha * op( A ) * op( B ) + beta * C` +/// +/// where +/// - `op( X ) = X` or `op( X ) = X**T`, +/// - `alpha` and `beta` are scalars, and +/// - `A`, `B`, and `C` are matrices: +/// - `op( A )` is an `MxK` matrix, +/// - `op( B )` is an `KxN` matrix, +/// - `C` is an `MxN` matrix. +/// +/// The matrices are assumed to be stored in row-major order (the elements in +/// each of the matrix rows are contiguous in memory). +/// +/// @note +/// This API does not support XERBLA. Instead, unlike the standard BLAS +/// functions, this one returns a dnnl_status_t value to allow error +/// handling. +/// +/// @param transa Transposition flag for matrix A: 'N' or 'n' means A is not +/// transposed, and 'T' or 't' means that A is transposed. +/// @param transb Transposition flag for matrix B: 'N' or 'n' means B is not +/// transposed, and 'T' or 't' means that B is transposed. +/// @param M The M dimension. +/// @param N The N dimension. +/// @param K The K dimension. +/// @param alpha The alpha parameter that is used to scale the product of +/// matrices A and B. +/// @param A A pointer to the A matrix data. +/// @param lda The leading dimension for the matrix A. +/// @param B A pointer to the B matrix data. +/// @param ldb The leading dimension for the matrix B. +/// @param beta The beta parameter that is used to scale the matrix C. +/// @param C A pointer to the C matrix data. +/// @param ldc The leading dimension for the matrix C. +/// @returns #dnnl_success/#dnnl::status::success on success and a status +/// describing the error otherwise. +dnnl_status_t DNNL_API dnnl_sgemm(char transa, char transb, dnnl_dim_t M, + dnnl_dim_t N, dnnl_dim_t K, float alpha, const float *A, dnnl_dim_t lda, + const float *B, dnnl_dim_t ldb, float beta, float *C, dnnl_dim_t ldc); + +/// Performs integer matrix-matrix multiply on 8-bit unsigned matrix A, 8-bit +/// signed matrix B, and 32-bit signed resulting matrix C. +/// +/// The operation is defined as: +/// +/// `C := alpha * (op(A) - A_offset) * (op(B) - B_offset) + beta * C + C_offset` +/// +/// where +/// - `op( X ) = X` or `op( X ) = X**T`, +/// - `alpha` and `beta` are scalars, and +/// - `A`, `B`, and `C` are matrices: +/// - `op( A )` is an `MxK` matrix, +/// - `op( B )` is an `KxN` matrix, +/// - `C` is an `MxN` matrix. +/// - `A_offset` is an `MxK` matrix with every element equal the `ao` value, +/// - `B_offset` is an `KxN` matrix with every element equal the `bo` value, +/// - `C_offset` is an `MxN` matrix which is defined by the `co` array of size `len`: +/// - if `offsetc = F`: the `len` must be at least `1`, +/// - if `offsetc = C`: the `len` must be at least `max(1, m)`, +/// - if `offsetc = R`: the `len` must be at least `max(1, n)`, +/// +/// The matrices are assumed to be stored in row-major order (the elements in +/// each of the matrix rows are contiguous in memory). +/// +/// @note +/// This API does not support XERBLA. Instead, unlike the standard BLAS +/// functions, this one returns a dnnl_status_t value to allow error +/// handling. +/// +/// @warning +/// On some architectures saturation may happen during intermediate +/// computations, which would lead to unexpected results. For more +/// details, refer to @ref dev_guide_int8_computations. +/// +/// @param transa Transposition flag for matrix A: 'N' or 'n' means A is not +/// transposed, and 'T' or 't' means that A is transposed. +/// @param transb Transposition flag for matrix B: 'N' or 'n' means B is not +/// transposed, and 'T' or 't' means that B is transposed. +/// @param offsetc Flag specifying how offsets should be applied to matrix C: +/// - 'F' means that the same offset will be applied to each element of +/// the matrix C, +/// - 'C' means that individual offset will be applied to each element +/// within each column, +/// - 'R' means that individual offset will be applied to each element +/// within each row. +/// @param M The M dimension. +/// @param N The N dimension. +/// @param K The K dimension. +/// @param alpha The alpha parameter that is used to scale the product of +/// matrices A and B. +/// @param A A pointer to the A matrix data. +/// @param lda The leading dimension for the matrix A. +/// @param ao The offset value for the matrix A. +/// @param B A pointer to the B matrix data. +/// @param ldb The leading dimension for the matrix B. +/// @param bo The offset value for the matrix B. +/// @param beta The beta parameter that is used to scale the matrix C. +/// @param C A pointer to the C matrix data. +/// @param ldc The leading dimension for the matrix C. +/// @param co An array of offset values for the matrix C. The number of +/// elements in the array depends on the value of @p offsetc. +/// @returns #dnnl_success/#dnnl::status::success on success and a status +/// describing the error otherwise. +dnnl_status_t DNNL_API dnnl_gemm_u8s8s32(char transa, char transb, char offsetc, + dnnl_dim_t M, dnnl_dim_t N, dnnl_dim_t K, float alpha, const uint8_t *A, + dnnl_dim_t lda, uint8_t ao, const int8_t *B, dnnl_dim_t ldb, int8_t bo, + float beta, int32_t *C, dnnl_dim_t ldc, const int32_t *co); + +/// Performs integer matrix-matrix multiply on 8-bit signed matrix A, 8-bit +/// signed matrix B, and 32-bit signed resulting matrix C. +/// +/// The operation is defined as: +/// +/// `C := alpha * (op(A) - A_offset) * (op(B) - B_offset) + beta * C + C_offset` +/// +/// where +/// - `op( X ) = X` or `op( X ) = X**T`, +/// - `alpha` and `beta` are scalars, and +/// - `A`, `B`, and `C` are matrices: +/// - `op( A )` is an `MxK` matrix, +/// - `op( B )` is an `KxN` matrix, +/// - `C` is an `MxN` matrix. +/// - `A_offset` is an `MxK` matrix with every element equal the `ao` value, +/// - `B_offset` is an `KxN` matrix with every element equal the `bo` value, +/// - `C_offset` is an `MxN` matrix which is defined by the `co` array of size `len`: +/// - if `offsetc = F`: the `len` must be at least `1`, +/// - if `offsetc = C`: the `len` must be at least `max(1, m)`, +/// - if `offsetc = R`: the `len` must be at least `max(1, n)`, +/// +/// The matrices are assumed to be stored in row-major order (the elements in +/// each of the matrix rows are contiguous in memory). +/// +/// @note +/// This API does not support XERBLA. Instead, unlike the standard BLAS +/// functions, this one returns a dnnl_status_t value to allow error +/// handling. +/// +/// @warning +/// On some architectures saturation may happen during intermediate +/// computations, which would lead to unexpected results. For more +/// details, refer to @ref dev_guide_int8_computations. +/// +/// @param transa Transposition flag for matrix A: 'N' or 'n' means A is not +/// transposed, and 'T' or 't' means that A is transposed. +/// @param transb Transposition flag for matrix B: 'N' or 'n' means B is not +/// transposed, and 'T' or 't' means that B is transposed. +/// @param offsetc Flag specifying how offsets should be applied to matrix C: +/// - 'F' means that the same offset will be applied to each element of +/// the matrix C, +/// - 'C' means that individual offset will be applied to each element +/// within each column, +/// - 'R' means that individual offset will be applied to each element +/// within each row. +/// @param M The M dimension. +/// @param N The N dimension. +/// @param K The K dimension. +/// @param alpha The alpha parameter that is used to scale the product of +/// matrices A and B. +/// @param A A pointer to the A matrix data. +/// @param lda The leading dimension for the matrix A. +/// @param ao The offset value for the matrix A. +/// @param B A pointer to the B matrix data. +/// @param ldb The leading dimension for the matrix B. +/// @param bo The offset value for the matrix B. +/// @param beta The beta parameter that is used to scale the matrix C. +/// @param C A pointer to the C matrix data. +/// @param ldc The leading dimension for the matrix C. +/// @param co An array of offset values for the matrix C. The number of +/// elements in the array depends on the value of @p offsetc. +/// @returns #dnnl_success/#dnnl::status::success on success and a status +/// describing the error otherwise. +dnnl_status_t DNNL_API dnnl_gemm_s8s8s32(char transa, char transb, char offsetc, + dnnl_dim_t M, dnnl_dim_t N, dnnl_dim_t K, float alpha, const int8_t *A, + dnnl_dim_t lda, int8_t ao, const int8_t *B, dnnl_dim_t ldb, int8_t bo, + float beta, int32_t *C, dnnl_dim_t ldc, const int32_t *co); + +/// @} dnnl_api_blas + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif /* ONEAPI_DNNL_DNNL_H */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0874fe2a26109d716a65bf608447552cdd4aabc9 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl.hpp @@ -0,0 +1,13805 @@ +/******************************************************************************* +* Copyright 2016-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C++ API + +#ifndef ONEAPI_DNNL_DNNL_HPP +#define ONEAPI_DNNL_DNNL_HPP + +#include "oneapi/dnnl/dnnl_config.h" + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include +#include +#include +#include +#include +#include + +#include "oneapi/dnnl/dnnl.h" +#include "oneapi/dnnl/dnnl_common.hpp" + +/// @endcond + +/// @addtogroup dnnl_api oneDNN API +/// @{ + +/// oneDNN namespace +namespace dnnl { + +/// @addtogroup dnnl_api_utils Utilities +/// Utility types and definitions. +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS +template +void validate_container_size(const T &v, const char *error_message, + int min_size = 1, int max_size = -1) { + const int size = (int)v.size(); + if (size < min_size || (max_size >= 0 && size > max_size)) + DNNL_THROW_ERROR(dnnl_invalid_arguments, error_message); +} +/// @endcond + +/// @cond DO_NOT_DOCUMENT_THIS +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_memory_desc_t p) { + return dnnl_memory_desc_destroy(p); + } +}; + +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_memory_t p) { + return dnnl_memory_destroy(p); + } +}; + +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_primitive_desc_t p) { + return dnnl_primitive_desc_destroy(p); + } +}; + +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_primitive_t p) { + return dnnl_primitive_destroy(p); + } +}; + +/// @endcond + +/// @} dnnl_api_utils + +struct stream; +struct memory; +struct primitive_desc; + +/// @addtogroup dnnl_api_primitives Primitives +/// Compute primitives +/// @sa @ref dev_guide_basic_concepts +/// @{ + +/// @addtogroup dnnl_api_primitives_common Common +/// Common operations to create, destroy and inspect primitives +/// @{ + +/// Base class for all computational primitives. +struct primitive : public handle { + /// Kinds of primitives supported by the library. + enum class kind { + /// Undefined primitive + undef = dnnl_undefined_primitive, + /// A reorder primitive. + reorder = dnnl_reorder, + /// A shuffle primitive. + shuffle = dnnl_shuffle, + /// A (out-of-place) tensor concatenation primitive. + concat = dnnl_concat, + /// A summation primitive. + sum = dnnl_sum, + /// A convolution primitive. + convolution = dnnl_convolution, + /// A deconvolution primitive. + deconvolution = dnnl_deconvolution, + /// An element-wise primitive. + eltwise = dnnl_eltwise, + /// An LRN primitive. + lrn = dnnl_lrn, + /// A batch normalization primitive. + batch_normalization = dnnl_batch_normalization, + /// An inner product primitive. + inner_product = dnnl_inner_product, + /// An RNN primitive. + rnn = dnnl_rnn, + /// A binary primitive. + binary = dnnl_binary, + /// A matmul (matrix multiplication) primitive. + matmul = dnnl_matmul, + /// A resampling primitive. + resampling = dnnl_resampling, + /// A pooling primitive. + pooling = dnnl_pooling, + /// A reduction primitive. + reduction = dnnl_reduction, + /// A PReLU primitive. + prelu = dnnl_prelu, + /// A softmax primitive. + softmax = dnnl_softmax, + /// A layer normalization primitive. + layer_normalization = dnnl_layer_normalization, + /// A group normalization primitive + group_normalization = dnnl_group_normalization, + }; + + using handle::handle; + + /// Default constructor. Constructs an empty object. + primitive() = default; + + /// Constructs a primitive from a C API primitive descriptor. + /// + /// @param c_pd C API primitive descriptor. + primitive(const_dnnl_primitive_desc_t c_pd); + + /// Constructs a primitive from a C API primitive descriptor and a cache blob. + /// + /// @param c_pd C API primitive descriptor. + /// @param cache_blob Cache blob. + primitive(const_dnnl_primitive_desc_t c_pd, + const std::vector &cache_blob); + + /// Constructs a primitive from a primitive descriptor. + /// + /// @param pd Primitive descriptor. + primitive(const primitive_desc &pd); + + /// Constructs a primitive from a primitive descriptor and a cache blob. + /// + /// @param pd Primitive descriptor. + /// @param cache_blob Cache blob. + primitive(const primitive_desc &pd, const std::vector &cache_blob); + + /// Returns the C API primitive descriptor of the underlying C API + /// primitive. + /// + /// @returns The underlying C API primitive descriptor. + inline const_dnnl_primitive_desc_t get_primitive_desc() const; + + /// Returns the kind of the primitive. + /// + /// @returns The primitive kind. + inline kind get_kind() const; + + /// Returns a cache blob for the primitive. + /// + /// @returns Vector containing the cache blob. + /// + /// @note The cache blob can be empty. It's the user's responsibility to + /// check whether it's empty prior to passing it to the primitive + /// constructor. + inline std::vector get_cache_blob() const; + + /// Executes computations specified by the primitive in a specified stream. + /// + /// Arguments are passed via an arguments map containing pairs. The index must be one of the `DNNL_ARG_*` values + /// such as `DNNL_ARG_SRC`, and the memory must have a memory descriptor + /// matching the one returned by + /// primitive_desc::query_md(#query::exec_arg_md, index) unless using + /// dynamic shapes (see #DNNL_RUNTIME_DIM_VAL). + /// + /// @param astream Stream object. The stream must belong to the same engine + /// as the primitive. + /// @param args Arguments map. + void execute(const stream &astream, + const std::unordered_map &args) const; +}; + +/// Converts primitive kind enum value from C++ API to C API type. +/// +/// @param akind C++ API primitive kind enum value. +/// @returns Corresponding C API primitive kind enum value. +inline dnnl_primitive_kind_t convert_to_c(primitive::kind akind) { + return static_cast(akind); +} + +const_dnnl_primitive_desc_t primitive::get_primitive_desc() const { + const_dnnl_primitive_desc_t pd; + error::wrap_c_api(dnnl_primitive_get_primitive_desc(get(), &pd), + "could not get a primitive descriptor from a primitive"); + return pd; +} + +dnnl::primitive::kind primitive::get_kind() const { + const_dnnl_primitive_desc_t pd = get_primitive_desc(); + // TODO (Roma): the code below is only needed because get_primitive_desc + // returns a C type. + dnnl_primitive_kind_t kind; + error::wrap_c_api(dnnl_primitive_desc_query( + pd, dnnl_query_primitive_kind, 0, (void *)&kind), + "could not get a primitive kind from a primitive descriptor"); + return static_cast(kind); +} + +std::vector primitive::get_cache_blob() const { + size_t size; + error::wrap_c_api(dnnl_primitive_get_cache_blob(get(), &size, nullptr), + "could not get cache blob size from a primitive"); + + std::vector cache_blob(size); + error::wrap_c_api( + dnnl_primitive_get_cache_blob(get(), &size, cache_blob.data()), + "could not get a cache blob from a primitive"); + return cache_blob; +} + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_attributes +/// +/// A container for parameters that extend primitives behavior. +/// +/// Attributes can also contain Post-ops, which are computations executed +/// after the primitive. +/// +/// @sa @ref dev_guide_attributes +/// @sa @ref dev_guide_attributes_post_ops +/// +/// @{ + +/// Scratchpad mode +enum class scratchpad_mode { + /// The library manages the scratchpad allocation according to the policy + /// specified by the `DNNL_ENABLE_CONCURRENT_EXEC` + /// [build option](@ref dev_guide_build_options) (default). + /// + /// When `DNNL_ENABLE_CONCURRENT_EXEC=OFF` (default), the library + /// scratchpad is common to all primitives to reduce the memory footprint. + /// This configuration comes with limited thread-safety properties, namely + /// primitives can be created and executed in parallel but cannot migrate + /// between threads (in other words, each primitive should be executed in + /// the same thread it was created in). + /// + /// When `DNNL_ENABLE_CONCURRENT_EXEC=ON`, the library scratchpad is + /// private to each primitive. The memory footprint is larger than when + /// using `DNNL_ENABLE_CONCURRENT_EXEC=OFF` but different primitives can be + /// created and run concurrently (the same primitive cannot be run + /// concurrently from two different threads though). + library = dnnl_scratchpad_mode_library, + /// The user manages the scratchpad allocation by querying and providing + /// the scratchpad memory to primitives. This mode is thread-safe as long + /// as the scratchpad buffers are not used concurrently by two primitive + /// executions. + user = dnnl_scratchpad_mode_user, +}; + +/// Converts a scratchpad mode enum value from C++ API to C API type. +/// +/// @param mode C++ API scratchpad mode enum value. +/// @returns Corresponding C API scratchpad mode enum value. +inline dnnl_scratchpad_mode_t convert_to_c(scratchpad_mode mode) { + return static_cast(mode); +} + +/// Propagation kind. +enum class prop_kind { + /// Undefined propagation kind. + undef = dnnl_prop_kind_undef, + /// Forward data propagation (training mode). In this mode, primitives + /// perform computations necessary for subsequent backward propagation. + forward_training = dnnl_forward_training, + /// Forward data propagation (inference mode). In this mode, primitives + /// perform only computations that are necessary for inference and omit + /// computations that are necessary only for backward propagation. + forward_inference = dnnl_forward_inference, + /// Forward data propagation, + /// alias for #dnnl::prop_kind::forward_training. + forward = dnnl_forward, + /// Backward propagation (with respect to all parameters). + backward = dnnl_backward, + /// Backward data propagation. + backward_data = dnnl_backward_data, + /// Backward weights propagation. + backward_weights = dnnl_backward_weights, + /// Backward bias propagation. + backward_bias = dnnl_backward_bias +}; + +/// Converts propagation kind enum value from C++ API to C API type. +/// +/// @param akind C++ API propagation kind enum value. +/// @returns Corresponding C API propagation kind enum value. +inline dnnl_prop_kind_t convert_to_c(prop_kind akind) { + return static_cast(akind); +} + +/// Kinds of algorithms. +enum class algorithm { + /// Undefined algorithm + undef = dnnl_alg_kind_undef, + /// Convolution algorithm that is chosen to be either direct or Winograd + /// automatically + convolution_auto = dnnl_convolution_auto, + /// Direct convolution + convolution_direct = dnnl_convolution_direct, + /// Winograd convolution + convolution_winograd = dnnl_convolution_winograd, + /// Direct deconvolution + deconvolution_direct = dnnl_deconvolution_direct, + /// Winograd deconvolution + deconvolution_winograd = dnnl_deconvolution_winograd, + /// Elementwise: rectified linear unit (ReLU) + eltwise_relu = dnnl_eltwise_relu, + /// Elementwise: hyperbolic tangent non-linearity (tanh) + eltwise_tanh = dnnl_eltwise_tanh, + /// Elementwise: exponential linear unit (ELU) + eltwise_elu = dnnl_eltwise_elu, + /// Elementwise: square + eltwise_square = dnnl_eltwise_square, + /// Elementwise: abs + eltwise_abs = dnnl_eltwise_abs, + /// Elementwise: square root + eltwise_sqrt = dnnl_eltwise_sqrt, + /// Elementwise: swish (\f$x \cdot sigmoid(a \cdot x)\f$) + eltwise_swish = dnnl_eltwise_swish, + /// Elementwise: linear + eltwise_linear = dnnl_eltwise_linear, + /// Elementwise: soft_relu + eltwise_soft_relu = dnnl_eltwise_soft_relu, + /// Elementwise: mish + eltwise_mish = dnnl_eltwise_mish, + /// Elementwise: logistic + eltwise_logistic = dnnl_eltwise_logistic, + /// Elementwise: exponent + eltwise_exp = dnnl_eltwise_exp, + /// Elementwise: tanh-based gelu + eltwise_gelu_tanh = dnnl_eltwise_gelu_tanh, + /// Elementwise: erf-based gelu + eltwise_gelu_erf = dnnl_eltwise_gelu_erf, + /// Elementwise: natural logarithm + eltwise_log = dnnl_eltwise_log, + /// Elementwise: clip + eltwise_clip = dnnl_eltwise_clip, + /// Eltwise: clip version 2 + eltwise_clip_v2 = dnnl_eltwise_clip_v2, + /// Elementwise: pow + eltwise_pow = dnnl_eltwise_pow, + /// Elementwise: round + eltwise_round = dnnl_eltwise_round, + /// Elementwise: hardswish + eltwise_hardswish = dnnl_eltwise_hardswish, + /// Elementwise: hardsigmoid + eltwise_hardsigmoid = dnnl_eltwise_hardsigmoid, + /// Elementwise: rectified linar unit (ReLU) (dst for backward) + eltwise_relu_use_dst_for_bwd = dnnl_eltwise_relu_use_dst_for_bwd, + /// Elementwise: hyperbolic tangent non-linearity (tanh) (dst for backward) + eltwise_tanh_use_dst_for_bwd = dnnl_eltwise_tanh_use_dst_for_bwd, + /// Elementwise: exponential linear unit (ELU) (dst for backward) + eltwise_elu_use_dst_for_bwd = dnnl_eltwise_elu_use_dst_for_bwd, + /// Elementwise: square root (dst for backward) + eltwise_sqrt_use_dst_for_bwd = dnnl_eltwise_sqrt_use_dst_for_bwd, + /// Elementwise: logistic (dst for backward) + eltwise_logistic_use_dst_for_bwd = dnnl_eltwise_logistic_use_dst_for_bwd, + /// Elementwise: exponent (dst for backward) + eltwise_exp_use_dst_for_bwd = dnnl_eltwise_exp_use_dst_for_bwd, + /// Elementwise: clip version 2 (dst for backward) + eltwise_clip_v2_use_dst_for_bwd = dnnl_eltwise_clip_v2_use_dst_for_bwd, + /// Local response normalization (LRN) across multiple channels + lrn_across_channels = dnnl_lrn_across_channels, + /// LRN within a single channel + lrn_within_channel = dnnl_lrn_within_channel, + /// Max pooling + pooling_max = dnnl_pooling_max, + /// Average pooling include padding + pooling_avg_include_padding = dnnl_pooling_avg_include_padding, + /// Average pooling exclude padding + pooling_avg_exclude_padding = dnnl_pooling_avg_exclude_padding, + /// RNN cell + vanilla_rnn = dnnl_vanilla_rnn, + /// LSTM cell + vanilla_lstm = dnnl_vanilla_lstm, + /// GRU cell + vanilla_gru = dnnl_vanilla_gru, + /// GRU cell with linear before reset. Differs from the vanilla GRU + /// in how the new memory gate is calculated: + /// \f$c_t = tanh(W_c*x_t + b_{c_x} + r_t*(U_c*h_{t-1}+b_{c_h})) \f$ + /// LRB GRU expects 4 bias tensors on input: + /// \f$[b_{u}, b_{r}, b_{c_x}, b_{c_h}]\f$ + lbr_gru = dnnl_lbr_gru, + /// AUGRU cell + vanilla_augru = dnnl_vanilla_augru, + /// AUGRU cell with linear before reset + lbr_augru = dnnl_lbr_augru, + /// Binary add + binary_add = dnnl_binary_add, + /// Binary mul + binary_mul = dnnl_binary_mul, + /// Binary max + binary_max = dnnl_binary_max, + /// Binary min + binary_min = dnnl_binary_min, + /// Binary div + binary_div = dnnl_binary_div, + /// Binary sub + binary_sub = dnnl_binary_sub, + /// Binary greater than or equal + binary_ge = dnnl_binary_ge, + /// Binary greater than + binary_gt = dnnl_binary_gt, + /// Binary less than or equal + binary_le = dnnl_binary_le, + /// Binary less than + binary_lt = dnnl_binary_lt, + /// Binary equal + binary_eq = dnnl_binary_eq, + /// Binary not equal + binary_ne = dnnl_binary_ne, + /// Nearest Neighbor resampling method + resampling_nearest = dnnl_resampling_nearest, + /// Linear (Bilinear, Trilinear) resampling method + resampling_linear = dnnl_resampling_linear, + /// Reduction using max operation + reduction_max = dnnl_reduction_max, + /// Reduction using min operation + reduction_min = dnnl_reduction_min, + /// Reduction using sum operation + reduction_sum = dnnl_reduction_sum, + /// Reduction using mul operation + reduction_mul = dnnl_reduction_mul, + /// Reduction using mean operation + reduction_mean = dnnl_reduction_mean, + /// Reduction using norm_lp_max operation + reduction_norm_lp_max = dnnl_reduction_norm_lp_max, + /// Reduction using norm_lp_sum operation + reduction_norm_lp_sum = dnnl_reduction_norm_lp_sum, + /// Reduction using norm_lp_power_p_max operation + reduction_norm_lp_power_p_max = dnnl_reduction_norm_lp_power_p_max, + /// Reduction using norm_lp_power_p_sum operation + reduction_norm_lp_power_p_sum = dnnl_reduction_norm_lp_power_p_sum, + /// Softmax, numerically stable + softmax_accurate = dnnl_softmax_accurate, + /// LogSoftmax, numerically stable + softmax_log = dnnl_softmax_log, +}; + +/// Converts algorithm kind enum value from C++ API to C API type. +/// @param aalgorithm C++ API algorithm kind enum value. +/// @returns Corresponding C API algorithm kind enum value. +inline dnnl_alg_kind_t convert_to_c(algorithm aalgorithm) { + return static_cast(aalgorithm); +} + +/// @} dnnl_api_attributes + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// Flags for normalization primitives. +enum class normalization_flags : unsigned { + /// Use no normalization flags. If specified, the library computes mean and + /// variance on forward propagation for training and inference, outputs them + /// on forward propagation for training, and computes the respective + /// derivatives on backward propagation. + none = dnnl_normalization_flags_none, + + /// Use global statistics. If specified, the library uses mean and + /// variance provided by the user as an input on forward propagation and + /// does not compute their derivatives on backward propagation. Otherwise, + /// the library computes mean and variance on forward propagation for + /// training and inference, outputs them on forward propagation for + /// training, and computes the respective derivatives on backward + /// propagation. + use_global_stats = dnnl_use_global_stats, + + /// Use scale parameter. If specified, the user is expected to pass scale as + /// input on forward propagation. On backward propagation of type + /// #dnnl::prop_kind::backward, the library computes its derivative. + use_scale = dnnl_use_scale, + + /// Use shift parameter. If specified, the user is expected to pass shift as + /// input on forward propagation. On backward propagation of type + /// #dnnl::prop_kind::backward, the library computes its derivative. + use_shift = dnnl_use_shift, + + /// Fuse normalization with ReLU. On training, normalization will require + /// the workspace to implement backward propagation. On inference, the + /// workspace is not required and behavior is the same as when normalization + /// is fused with ReLU using the post-ops API. + fuse_norm_relu = dnnl_fuse_norm_relu, + + /// Fuse normalization with elementwise binary Add and then fuse with ReLU. + /// On training, normalization will require the workspace to implement + /// backward propagation. On inference, the workspace is not required. + fuse_norm_add_relu = dnnl_fuse_norm_add_relu, +}; + +/// Converts normalization flags enum value from C++ API to C API type. +/// @param flags C++ API normalization flags enum value. +/// @returns Corresponding C API normalization flags enum value. +inline dnnl_normalization_flags_t convert_to_c(normalization_flags flags) { + return static_cast(flags); +} + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_rnn +/// @{ + +/// RNN cell flags. +enum class rnn_flags : unsigned { + /// Undefined RNN flags + undef = dnnl_rnn_flags_undef, + /// Do not add weights gradient to existing diff_weights memory + diff_weights_overwrite = dnnl_rnn_flags_diff_weights_overwrite, +}; + +/// Converts RNN cell flags enum value from C++ API to C API type. +/// @param flags C++ API RNN cell flags enum value. +/// @returns Corresponding C API RNN cell flags enum value. +inline dnnl_rnn_flags_t convert_to_c(rnn_flags flags) { + return static_cast(flags); +} + +DNNL_DEFINE_BITMASK_OPS(normalization_flags) +DNNL_DEFINE_BITMASK_OPS(rnn_flags) + +/// A direction of RNN primitive execution +enum class rnn_direction { + /// Undefined RNN direction. + undef = dnnl_rnn_direction_undef, + /// Unidirectional execution of RNN primitive from left to right. + unidirectional_left2right = dnnl_unidirectional_left2right, + /// Unidirectional execution of RNN primitive from right to left. + unidirectional_right2left = dnnl_unidirectional_right2left, + /// Bidirectional execution of RNN primitive with concatenation of the + /// results. + bidirectional_concat = dnnl_bidirectional_concat, + /// Bidirectional execution of RNN primitive with summation of the + /// results. + bidirectional_sum = dnnl_bidirectional_sum, +}; + +/// Converts RNN direction enum value from C++ API to C API type. +/// @param dir C++ API RNN direction enum value. +/// @returns Corresponding C API RNN direction enum value. +inline dnnl_rnn_direction_t convert_to_c(rnn_direction dir) { + return static_cast(dir); +} + +/// @} dnnl_api_rnn + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// Primitive descriptor query specification. +/// +/// In general, queries are not used with the C++ API because most queries are +/// implemented as class members. +/// +/// See @ref dnnl_query_t for more information. +enum class query { + /// no query + undef = dnnl_query_undef, + + /// execution engine + engine = dnnl_query_engine, + /// primitive kind + primitive_kind = dnnl_query_primitive_kind, + + /// number of inputs expected + num_of_inputs_s32 = dnnl_query_num_of_inputs_s32, + /// number of outputs expected + num_of_outputs_s32 = dnnl_query_num_of_outputs_s32, + + /// runtime estimation (seconds), unimplemented + time_estimate_f64 = dnnl_query_time_estimate_f64, + /// memory required for scratchpad (bytes) + /// + /// @sa @ref dev_guide_attributes_scratchpad + memory_consumption_s64 = dnnl_query_memory_consumption_s64, + + /// scratchpad engine + /// + /// engine to be used for creating scratchpad memory + scratchpad_engine = dnnl_query_scratchpad_engine, + + /// reorder source engine + reorder_src_engine = dnnl_query_reorder_src_engine, + /// reorder destination engine + reorder_dst_engine = dnnl_query_reorder_dst_engine, + + /// implementation name + impl_info_str = dnnl_query_impl_info_str, + + /// propagation kind + prop_kind = dnnl_query_prop_kind, + + /// size of cache blob ID in bytes + cache_blob_id_size_s64 = dnnl_query_cache_blob_id_size_s64, + + /// cache blob ID (pointer to array) + cache_blob_id = dnnl_query_cache_blob_id, + + /// strides + strides = dnnl_query_strides, + /// dilations + dilations = dnnl_query_dilations, + /// left padding + padding_l = dnnl_query_padding_l, + /// right padding + padding_r = dnnl_query_padding_r, + /// epsilon + epsilon_f32 = dnnl_query_epsilon_f32, + /// flags + flags = dnnl_query_flags, + /// algorithm kind + alg_kind = dnnl_query_alg_kind, + /// alpha + alpha_f32 = dnnl_query_alpha_f32, + /// beta + beta_f32 = dnnl_query_beta_f32, + /// axis + axis_s32 = dnnl_query_axis_s32, + /// LRN parameter local size + local_size_s64 = dnnl_query_local_size_s64, + /// LRN parameter K + k_f32 = dnnl_query_k_f32, + /// Reduction parameter P + p_f32 = dnnl_query_p_f32, + /// Resampling parameter factors + factors = dnnl_query_factors, + /// RNN parameter cell kind + cell_kind = dnnl_query_cell_kind, + /// RNN parameter direction + direction = dnnl_query_direction, + /// RNN parameter activation kind + activation_kind = dnnl_query_activation_kind, + /// Pooling parameter kernel + kernel = dnnl_query_kernel, + /// Shuffle parameter group size + group_size_s64 = dnnl_query_group_size_s64, + + /// source memory desc + src_md = dnnl_query_src_md, + /// source gradient (diff) memory desc + diff_src_md = dnnl_query_diff_src_md, + /// weights memory descriptor desc + weights_md = dnnl_query_weights_md, + /// weights gradient (diff) memory desc + diff_weights_md = dnnl_query_diff_weights_md, + /// destination memory desc + dst_md = dnnl_query_dst_md, + /// destination gradient (diff) memory desc + diff_dst_md = dnnl_query_diff_dst_md, + /// workspace memory desc + workspace_md = dnnl_query_workspace_md, + /// scratchpad memory desc + scratchpad_md = dnnl_query_scratchpad_md, + /// memory desc of an execute argument + exec_arg_md = dnnl_query_exec_arg_md, + + /// number of dimensions + ndims_s32 = dnnl_query_ndims_s32, + /// vector of dimensions + dims = dnnl_query_dims, + /// data type + data_type = dnnl_query_data_type, + /// submemory offset + submemory_offset_s64 = dnnl_query_submemory_offset_s64, + /// vector of padded dimensions + padded_dims = dnnl_query_padded_dims, + /// vector of padded offsets + padded_offsets = dnnl_query_padded_offsets, + /// format kind + format_kind = dnnl_query_format_kind, + /// number of innermost blocks + inner_nblks_s32 = dnnl_query_inner_nblks_s32, + /// vector of sizes of the innermost blocks + inner_blks = dnnl_query_inner_blks, + /// vector of logical indices of the blocks + inner_idxs = dnnl_query_inner_idxs, +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Sparse encoding + sparse_encoding = dnnl_query_sparse_encoding, + /// Number of non-zero entries + nnz_s64 = dnnl_query_nnz_s64, + /// Number of buffers required for a memory descriptor + num_handles_s32 = dnnl_query_num_handles_s32, +#endif +}; + +/// Converts query enum value from C++ API to C API type. +/// @param aquery C++ API query enum value. +/// @returns Corresponding C API query enum value. +inline dnnl_query_t convert_to_c(query aquery) { + return static_cast(aquery); +} + +/// @} dnnl_api_primitives_common + +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_memory Memory +/// +/// A container that describes and stores data. Memory objects can contain +/// data of various types and formats. There are two levels of abstraction: +/// +/// 1. **Memory descriptor** -- engine-agnostic logical description of data +/// (number of dimensions, dimension sizes, and data type), and, +/// optionally, the information about the physical format of data in +/// memory. If this information is not known yet, a memory descriptor can +/// be created with #dnnl::memory::format_tag::any. This allows +/// compute-intensive primitives to choose the best format for +/// computation. The user is responsible for reordering the data into the +/// chosen format when formats do not match. +/// +/// A memory descriptor can be initialized either by specifying dimensions +/// and a memory format tag or strides for each of them, or by +/// manipulating the dnnl_memory_desc_t structure directly. +/// +/// @warning +/// The latter approach requires understanding how the physical data +/// representation is mapped to the structure and is discouraged. This +/// topic is discussed in @ref dev_guide_understanding_memory_formats. +/// +/// The user can query the amount of memory required by a memory +/// descriptor using the #dnnl::memory::desc::get_size() function. The +/// size of data in general cannot be computed as the product of +/// dimensions multiplied by the size of the data type. So users are +/// required to use this function for better code portability. +/// +/// Two memory descriptors can be compared using the equality and +/// inequality operators. The comparison is especially useful when +/// checking whether it is necessary to reorder data from the user's data +/// format to a primitive's format. +/// +/// 2. **Memory object** -- an engine-specific object that handles the memory +/// buffer and its description (a memory descriptor). For the CPU engine or +/// with USM, the memory buffer handle is simply a pointer to @c void. The +/// memory buffer can be queried using #dnnl::memory::get_data_handle() and +/// set using #dnnl::memory::set_data_handle(). The underlying SYCL buffer, +/// when used, can be queried using #dnnl::sycl_interop::get_buffer and set +/// using #dnnl::sycl_interop::set_buffer. A memory object can also be +/// queried for the underlying memory descriptor and for its engine using +/// #dnnl::memory::get_desc() and dnnl::memory::get_engine(). +/// +/// Along with ordinary memory descriptors with all dimensions being positive, +/// the library supports *zero-volume* memory descriptors with one or more +/// dimensions set to zero. This is used to support the NumPy\* convention. +/// If a zero-volume memory is passed to a primitive, the primitive typically +/// does not perform any computations with this memory. For example: +/// +/// - A concatenation primitive would ignore all memory object with zeroes in +/// the concat dimension / axis. +/// +/// - A forward convolution with a source memory object with zero in the +/// minibatch dimension would always produce a destination memory object +/// with a zero in the minibatch dimension and perform no computations. +/// +/// - However, a forward convolution with a zero in one of the weights +/// dimensions is ill-defined and is considered to be an error by the +/// library because there is no clear definition of what the output values +/// should be. +/// +/// Memory buffer of a zero-volume memory is never accessed. +/// +/// @{ + +/// Memory object. +/// +/// A memory object encapsulates a handle to a memory buffer allocated on a +/// specific engine, tensor dimensions, data type, and memory format, which is +/// the way tensor indices map to offsets in linear memory space. Memory +/// objects are passed to primitives during execution. +struct memory : public handle { + using handle::handle; + + /// Integer type for representing dimension sizes and indices. + typedef dnnl_dim_t dim; + /// Vector of dimensions. Implementations are free to force a limit on the + /// vector's length. + typedef std::vector dims; + + /// Helper function that validates that an `std::vector` of dimensions can + /// be safely converted to the C API array ::dnnl_dims_t. Throws if + /// validation fails. + /// + /// @param v Vector of dimensions. + /// @param min_size Minimum expected size of the vector. + template + static void validate_dims(const std::vector &v, int min_size = 0) { + validate_container_size( + v, "dimensions are invalid", min_size, DNNL_MAX_NDIMS); + } + + /// Data type specification. + enum class data_type { + /// Undefined data type (used for empty memory descriptors). + undef = dnnl_data_type_undef, + /// [OFP8 standard 8-bit floating-point](https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-06-20-pdf) + /// with a 5-bit exponent and a 2-bit mantissa. + f8_e5m2 = dnnl_f8_e5m2, + /// [OFP8 standard 8-bit floating-point](https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-06-20-pdf) + /// with a 4-bit exponent and a 3-bit mantissa. + f8_e4m3 = dnnl_f8_e4m3, + /// [16-bit/half-precision floating point](https://en.wikipedia.org/wiki/Half-precision_floating-point_format). + f16 = dnnl_f16, + /// non-standard + /// [16-bit floating point with 7-bit mantissa](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format). + bf16 = dnnl_bf16, + /// [32-bit/single-precision floating point](https://en.wikipedia.org/wiki/Single-precision_floating-point_format). + f32 = dnnl_f32, + //// [64-bit/double-precision floating point](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). + f64 = dnnl_f64, + /// 32-bit signed integer. + s32 = dnnl_s32, + /// 8-bit signed integer. + s8 = dnnl_s8, + /// 8-bit unsigned integer. + u8 = dnnl_u8, + /// 4-bit signed integer. + s4 = dnnl_s4, + /// 4-bit unsigned integer. + u4 = dnnl_u4, + }; + + /// Returns size of data type in bytes. + /// @returns The number of bytes occupied by data type. + static size_t data_type_size(data_type adata_type) { + return dnnl_data_type_size(convert_to_c(adata_type)); + } + + /// Memory format kind + enum class format_kind { + /// Undefined memory format kind, used for empty memory descriptors. + undef = dnnl_format_kind_undef, + /// A special format kind that indicates that the actual format will be + /// selected by a primitive automatically. + any = dnnl_format_kind_any, + /// A tensor in a generic format described by the stride and blocking + /// values in each dimension. + blocked = dnnl_blocked, +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Format kind for sparse tensors. + sparse = dnnl_format_kind_sparse, +#endif + /// A special format kind that indicates that tensor format is opaque. + opaque = dnnl_format_kind_opaque, + }; + +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Sparse encodings. + enum class sparse_encoding { + /// Undefined sparse encoding kind, used for empty memory descriptors. + undef = dnnl_sparse_encoding_undef, + /// Compressed Sparse Row (CSR) encoding. + csr = dnnl_csr, + /// An encoding that is used for an opaque storage schema for + /// tensors with unstructured sparsity. A memory descriptor with the + /// packed encoding cannot be used to create a memory object. It can + /// only be used to create a primitive descriptor to query the + /// actual memory descriptor (similar to the format tag `any`). + packed = dnnl_packed, + }; +#endif + + /// Memory format tag specification. + /// + /// Memory format tags can be further divided into two categories: + /// + /// - Domain-agnostic names, i.e. names that do not depend on the tensor + /// usage in the specific primitive. These names use letters from `a` + /// to `f` to denote logical dimensions and form the order in which the + /// dimensions are laid in memory. For example, + /// #dnnl::memory::format_tag::ab is used to denote a 2D tensor where the + /// second logical dimension (denoted as `b`) is the innermost, i.e. + /// has stride = 1, and the first logical dimension (`a`) is laid out in + /// memory with stride equal to the size of the second dimension. On the + /// other hand, #dnnl::memory::format_tag::ba is the transposed version + /// of the same tensor: the outermost dimension (`a`) becomes the + /// innermost one. + /// + /// - Domain-specific names, i.e. names that make sense only in the + /// context of a certain domain, such as CNN. These names are + /// aliases to the corresponding domain-agnostic tags and used mostly + /// for convenience. For example, #dnnl::memory::format_tag::nc + /// is used to denote 2D CNN activations tensor memory format, where + /// the channels dimension is the innermost one and the batch dimension + /// is the outermost one. Moreover, #dnnl::memory::format_tag::nc is + /// an alias for #dnnl::memory::format_tag::ab, because for + /// CNN primitives the logical dimensions of activations tensors come + /// in order: batch, channels, spatial. In other words, batch + /// corresponds to the first logical dimension (`a`), and channels + /// correspond to the second one (`b`). + /// + /// The following domain-specific notation applies to memory format tags: + /// - @c 'n' denotes the mini-batch dimension + /// - @c 'c' denotes a channels dimension + /// - When there are multiple channel dimensions (for example, + /// in convolution weights tensor), @c 'i' and @c 'o' denote dimensions + /// of input and output channels + /// - @c 'g' denotes a groups dimension for convolution weights + /// - @c 'd', @c 'h', and @c 'w' denote spatial depth, height, and width + /// respectively + /// + /// See @ref dnnl_format_tag_t for a detailed description. + enum class format_tag { + /// Undefined memory format tag + undef = dnnl_format_tag_undef, + /// Placeholder memory format tag. Used to instruct the primitive to + /// select a format automatically. + any = dnnl_format_tag_any, + + /// plain 1D tensor + a = dnnl_a, + + /// plain 2D tensor + ab = dnnl_ab, + /// permuted 2D tensor + ba = dnnl_ba, + + /// plain 3D tensor + abc = dnnl_abc, + /// permuted 3D tensor + acb = dnnl_acb, + /// permuted 3D tensor + bac = dnnl_bac, + /// permuted 3D tensor + bca = dnnl_bca, + /// permuted 3D tensor + cba = dnnl_cba, + + /// plain 4D tensor + abcd = dnnl_abcd, + /// permuted 4D tensor + abdc = dnnl_abdc, + /// permuted 4D tensor + acbd = dnnl_acbd, + /// permuted 4D tensor + acdb = dnnl_acdb, + /// permuted 4D tensor + adbc = dnnl_adbc, + /// permuted 4D tensor + bacd = dnnl_bacd, + /// permuted 4D tensor + bcda = dnnl_bcda, + /// permuted 4D tensor + cdba = dnnl_cdba, + /// permuted 4D tensor + dcab = dnnl_dcab, + + /// plain 5D tensor + abcde = dnnl_abcde, + /// permuted 5D tensor + abdec = dnnl_abdec, + /// permuted 5D tensor + acbde = dnnl_acbde, + /// permuted 5D tensor + acdeb = dnnl_acdeb, + /// permuted 5D tensor + bacde = dnnl_bacde, + /// permuted 5D tensor + bcdea = dnnl_bcdea, + /// permuted 5D tensor + cdeba = dnnl_cdeba, + /// permuted 5D tensor + decab = dnnl_decab, + /// permuted 5D tensor + abced = dnnl_abced, + + /// plain 6D tensor + abcdef = dnnl_abcdef, + /// permuted 6D tensor + abdfce = dnnl_abdfce, + /// permuted 6D tensor + acbdef = dnnl_acbdef, + /// permuted 6D tensor + abdefc = dnnl_abdefc, + /// permuted 6D tensor + defcab = dnnl_defcab, + /// permuted 6D tensor + abcdfe = dnnl_abcdfe, + + /// plain 7D tensor + abcdefg = dnnl_abcdefg, + /// permuted 7D tensor + abcdegf = dnnl_abcdegf, + + /// plain 8D tensor + abcdefgh = dnnl_abcdefgh, + /// permuted 8D tensor + abcdefhg = dnnl_abcdefhg, + + /// plain 9D tensor + abcdefghi = dnnl_abcdefghi, + /// permuted 9D tensor + abcdefgih = dnnl_abcdefgih, + + /// plain 10D tensor + abcdefghij = dnnl_abcdefghij, + /// permuted 10D tensor + abcdefghji = dnnl_abcdefghji, + + /// plain 11D tensor + abcdefghijk = dnnl_abcdefghijk, + /// permuted 11D tensor + abcdefghikj = dnnl_abcdefghikj, + + /// plain 12D tensor + abcdefghijkl = dnnl_abcdefghijkl, + /// permuted 12D tensor + abcdefghijlk = dnnl_abcdefghijlk, + + /// 1D tensor; an alias for #dnnl::memory::format_tag::a + x = a, + /// 2D CNN activations tensor; an alias for #dnnl::memory::format_tag::ab + nc = ab, + /// 2D CNN activations tensor; an alias for #dnnl::memory::format_tag::ba + cn = ba, + /// 2D RNN statistics tensor; an alias for #dnnl::memory::format_tag::ab + tn = ab, + /// 2D RNN statistics tensor; an alias for #dnnl::memory::format_tag::ba + nt = ba, + /// 3D CNN activations tensor; an alias for #dnnl::memory::format_tag::abc + ncw = abc, + /// 3D CNN activations tensor; an alias for #dnnl::memory::format_tag::acb + nwc = acb, + /// 4D CNN activations tensor; an alias for #dnnl::memory::format_tag::abcd + nchw = abcd, + /// 4D CNN activations tensor; an alias for #dnnl::memory::format_tag::acdb + nhwc = acdb, + /// 4D CNN activations tensor; an alias for #dnnl::memory::format_tag::bcda + chwn = bcda, + /// 5D CNN activations tensor; an alias for #dnnl::memory::format_tag::abcde + ncdhw = abcde, + /// 5D CNN activations tensor; an alias for #dnnl::memory::format_tag::acdeb + ndhwc = acdeb, + + /// 2D CNN weights tensor; an alias for #dnnl::memory::format_tag::ab + oi = ab, + /// 2D CNN weights tensor; an alias for #dnnl::memory::format_tag::ba + io = ba, + /// 3D CNN weights tensor; an alias for #dnnl::memory::format_tag::abc + oiw = abc, + /// 3D CNN weights tensor; an alias for #dnnl::memory::format_tag::acb + owi = acb, + /// 3D CNN weights tensor; an alias for #dnnl::memory::format_tag::cba + wio = cba, + /// 3D CNN weights tensor; an alias for #dnnl::memory::format_tag::bca + iwo = bca, + /// 4D CNN weights tensor; an alias for #dnnl::memory::format_tag::abcd + oihw = abcd, + /// 4D CNN weights tensor; an alias for #dnnl::memory::format_tag::cdba + hwio = cdba, + /// 4D CNN weights tensor; an alias for #dnnl::memory::format_tag::acdb + ohwi = acdb, + /// 4D CNN weights tensor; an alias for #dnnl::memory::format_tag::bcda + ihwo = bcda, + /// 4D CNN weights tensor; an alias for #dnnl::memory::format_tag::bacd + iohw = bacd, + /// 5D CNN weights tensor; an alias for #dnnl::memory::format_tag::abcde + oidhw = abcde, + /// 5D CNN weights tensor; an alias for #dnnl::memory::format_tag::cdeba + dhwio = cdeba, + /// 5D CNN weights tensor; an alias for #dnnl::memory::format_tag::acdeb + odhwi = acdeb, + /// 5D CNN weights tensor; an alias for #dnnl::memory::format_tag::bacde + iodhw = bacde, + /// 5D CNN weights tensor; an alias for #dnnl::memory::format_tag::bcdea + idhwo = bcdea, + + /// 4D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abcd + goiw = abcd, + /// 4D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abdc + gowi = abdc, + /// 4D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::dcab + wigo = dcab, + /// 5D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abdec + gohwi = abdec, + /// 5D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abcde + goihw = abcde, + /// 5D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::decab + hwigo = decab, + /// 5D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::acbde + giohw = acbde, + /// 6D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abcdef + goidhw = abcdef, + /// 6D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abcdef + giodhw = acbdef, + /// 6D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::abdefc + godhwi = abdefc, + /// 6D CNN weights tensor with groups; an alias for #dnnl::memory::format_tag::defcab + dhwigo = defcab, + + /// 3D RNN data tensor in the format (seq_length, batch, input + /// channels); an alias for #dnnl::memory::format_tag::abc. + tnc = abc, + /// 3D RNN data tensor in the format (batch, seq_length, input + /// channels); an alias for #dnnl::memory::format_tag::bac. + ntc = bac, + /// 4D RNN states tensor in the format (num_layers, num_directions, + /// batch, state channels); an alias for #dnnl::memory::format_tag::abcd. + ldnc = abcd, + /// 5D RNN weights tensor in the format (num_layers, num_directions, + /// input_channels, num_gates, output_channels); + /// an alias for #dnnl::memory::format_tag::abcde. + /// + /// - For LSTM cells, the gates order is input, forget, candidate + /// and output gate. + /// - For GRU cells, the gates order is update, reset and output gate. + ldigo = abcde, + /// 5D RNN weights tensor in the format (num_layers, num_directions, + /// num_gates, output_channels, input_channels); + /// an alias for #dnnl::memory::format_tag::abdec. + /// + /// - For LSTM cells, the gates order is input, forget, candidate + /// and output gate. + /// - For GRU cells, the gates order is update, reset and output gate. + ldgoi = abdec, + /// 4D LSTM projection tensor in the format (num_layers, num_directions, + /// num_channels_in_hidden_state, num_channels_in_recurrent_projection); + /// an alias for #dnnl::memory::format_tag::abcd. + ldio = abcd, + /// 4D LSTM projection tensor in the format (num_layers, num_directions, + /// num_channels_in_recurrent_projection, num_channels_in_hidden_state); + /// an alias for #dnnl::memory::format_tag::abdc. + ldoi = abdc, + /// 4D RNN bias tensor in the format (num_layers, num_directions, + /// num_gates, output_channels); + /// an alias for #dnnl::memory::format_tag::abcd. + /// + /// - For LSTM cells, the gates order is input, forget, candidate + /// and output gate. + /// - For GRU cells, the gates order is update, reset and output gate. + ldgo = abcd, + + // Opaque blocked formats + + AB16b16a = dnnl_AB16b16a, + AB16b32a = dnnl_AB16b32a, + AB16b48a = dnnl_AB16b48a, + AB16b64a = dnnl_AB16b64a, + AB8b16a2b = dnnl_AB8b16a2b, + AB8b32a2b = dnnl_AB8b32a2b, + AB8b64a2b = dnnl_AB8b64a2b, + AB4b16a4b = dnnl_AB4b16a4b, + AB4b32a4b = dnnl_AB4b32a4b, + AB4b64a4b = dnnl_AB4b64a4b, + AB16b16a4b = dnnl_AB16b16a4b, + AB16b32a4b = dnnl_AB16b32a4b, + AB16b48a4b = dnnl_AB16b48a4b, + AB16b64a4b = dnnl_AB16b64a4b, + AB16b16a2b = dnnl_AB16b16a2b, + AB16b32a2b = dnnl_AB16b32a2b, + AB16b48a2b = dnnl_AB16b48a2b, + AB16b64a2b = dnnl_AB16b64a2b, + Ab4a = dnnl_Ab4a, + Ab8a = dnnl_Ab8a, + Abc16a = dnnl_Abc16a, + ABc16a16b = dnnl_ABc16a16b, + ABc4a4b = dnnl_ABc4a4b, + aBc16b = dnnl_aBc16b, + aBc32b = dnnl_aBc32b, + ABc16b16a = dnnl_ABc16b16a, + AcB16b16a = dnnl_AcB16b16a, + ABc16b32a = dnnl_ABc16b32a, + AcB16b32a = dnnl_AcB16b32a, + ABc16b48a = dnnl_ABc16b48a, + AcB16b48a = dnnl_AcB16b48a, + ABc16b64a = dnnl_ABc16b64a, + AcB16b64a = dnnl_AcB16b64a, + Abc4a = dnnl_Abc4a, + aBc4b = dnnl_aBc4b, + ABc4b16a4b = dnnl_ABc4b16a4b, + AcB4b16a4b = dnnl_AcB4b16a4b, + ABc4b32a4b = dnnl_ABc4b32a4b, + AcB4b32a4b = dnnl_AcB4b32a4b, + ABc4b64a4b = dnnl_ABc4b64a4b, + AcB4b64a4b = dnnl_AcB4b64a4b, + ABc2b8a4b = dnnl_ABc2b8a4b, + ABc16a16b2a = dnnl_ABc16a16b2a, + ABc16b16a4b = dnnl_ABc16b16a4b, + ABc16b32a4b = dnnl_ABc16b32a4b, + ABc16b48a4b = dnnl_ABc16b48a4b, + ABc16b64a4b = dnnl_ABc16b64a4b, + ABc16b16a2b = dnnl_ABc16b16a2b, + ABc16b32a2b = dnnl_ABc16b32a2b, + ABc16b48a2b = dnnl_ABc16b48a2b, + ABc16b64a2b = dnnl_ABc16b64a2b, + ABc4b4a = dnnl_ABc4b4a, + ABc8a16b2a = dnnl_ABc8a16b2a, + ABc8a8b = dnnl_ABc8a8b, + ABc8a4b = dnnl_ABc8a4b, + aBc8b = dnnl_aBc8b, + ABc8b16a2b = dnnl_ABc8b16a2b, + AcB8b16a2b = dnnl_AcB8b16a2b, + ABc8b32a2b = dnnl_ABc8b32a2b, + AcB8b32a2b = dnnl_AcB8b32a2b, + ABc8b64a2b = dnnl_ABc8b64a2b, + AcB8b64a2b = dnnl_AcB8b64a2b, + ABc8b8a = dnnl_ABc8b8a, + AcB8b8a = dnnl_AcB8b8a, + Abcd8a = dnnl_Abcd8a, + Abcd16a = dnnl_Abcd16a, + Abcd32a = dnnl_Abcd32a, + ABcd16a16b = dnnl_ABcd16a16b, + aBcd16b = dnnl_aBcd16b, + aBcd32b = dnnl_aBcd32b, + ABcd16b16a = dnnl_ABcd16b16a, + AcdB16b16a = dnnl_AcdB16b16a, + ABcd16b32a = dnnl_ABcd16b32a, + AcdB16b32a = dnnl_AcdB16b32a, + ABcd16b48a = dnnl_ABcd16b48a, + AcdB16b48a = dnnl_AcdB16b48a, + ABcd16b64a = dnnl_ABcd16b64a, + AcdB16b64a = dnnl_AcdB16b64a, + aBCd16b16c = dnnl_aBCd16b16c, + aBCd16c16b = dnnl_aBCd16c16b, + Abcd4a = dnnl_Abcd4a, + aBcd4b = dnnl_aBcd4b, + ABcd4b16a4b = dnnl_ABcd4b16a4b, + AcdB4b16a4b = dnnl_AcdB4b16a4b, + ABcd4b32a4b = dnnl_ABcd4b32a4b, + AcdB4b32a4b = dnnl_AcdB4b32a4b, + ABcd4b64a4b = dnnl_ABcd4b64a4b, + AcdB4b64a4b = dnnl_AcdB4b64a4b, + ABcd2b8a4b = dnnl_ABcd2b8a4b, + ABcd4b4a = dnnl_ABcd4b4a, + ABcd4a4b = dnnl_ABcd4a4b, + aBCd4c16b4c = dnnl_aBCd4c16b4c, + aBCd2c8b4c = dnnl_aBCd2c8b4c, + ABcd16a16b2a = dnnl_ABcd16a16b2a, + ABcd16b16a4b = dnnl_ABcd16b16a4b, + ABcd16b32a4b = dnnl_ABcd16b32a4b, + ABcd16b48a4b = dnnl_ABcd16b48a4b, + ABcd16b64a4b = dnnl_ABcd16b64a4b, + ABcd16b16a2b = dnnl_ABcd16b16a2b, + ABcd16b32a2b = dnnl_ABcd16b32a2b, + ABcd16b48a2b = dnnl_ABcd16b48a2b, + ABcd16b64a2b = dnnl_ABcd16b64a2b, + aBCd16b16c2b = dnnl_aBCd16b16c2b, + aBCd16c16b4c = dnnl_aBCd16c16b4c, + aBCd16c16b2c = dnnl_aBCd16c16b2c, + aBCd4c4b = dnnl_aBCd4c4b, + aBCd4b4c = dnnl_aBCd4b4c, + ABcd8a16b2a = dnnl_ABcd8a16b2a, + ABcd8a8b = dnnl_ABcd8a8b, + ABcd8a4b = dnnl_ABcd8a4b, + ABcd8a2b = dnnl_ABcd8a2b, + /// 4D tensor blocked by 2nd dimension with block size 8 + aBcd8b = dnnl_aBcd8b, + ABcd8b16a2b = dnnl_ABcd8b16a2b, + AcdB8b16a2b = dnnl_AcdB8b16a2b, + ABcd8b32a2b = dnnl_ABcd8b32a2b, + AcdB8b32a2b = dnnl_AcdB8b32a2b, + ABcd8b64a2b = dnnl_ABcd8b64a2b, + AcdB8b64a2b = dnnl_AcdB8b64a2b, + aBCd8b16c2b = dnnl_aBCd8b16c2b, + /// 4D tensor blocked by 1st and 2nd dimension with block size 8 + ABcd8b8a = dnnl_ABcd8b8a, + AcdB8b8a = dnnl_AcdB8b8a, + aBCd8b8c = dnnl_aBCd8b8c, + aBCd8b4c = dnnl_aBCd8b4c, + aBCd8c16b2c = dnnl_aBCd8c16b2c, + aBCd8c8b = dnnl_aBCd8c8b, + Abcde16a = dnnl_Abcde16a, + Abcde32a = dnnl_Abcde32a, + ABcde16a16b = dnnl_ABcde16a16b, + aBcde16b = dnnl_aBcde16b, + aBcde32b = dnnl_aBcde32b, + ABcde16b16a = dnnl_ABcde16b16a, + AcdeB16b16a = dnnl_AcdeB16b16a, + ABcde16b32a = dnnl_ABcde16b32a, + AcdeB16b32a = dnnl_AcdeB16b32a, + ABcde16b48a = dnnl_ABcde16b48a, + AcdeB16b48a = dnnl_AcdeB16b48a, + ABcde16b64a = dnnl_ABcde16b64a, + AcdeB16b64a = dnnl_AcdeB16b64a, + aBCde16b16c = dnnl_aBCde16b16c, + aBCde16c16b = dnnl_aBCde16c16b, + aBCde2c8b4c = dnnl_aBCde2c8b4c, + Abcde4a = dnnl_Abcde4a, + aBcde4b = dnnl_aBcde4b, + ABcde4b4a = dnnl_ABcde4b4a, + ABcde4a4b = dnnl_ABcde4a4b, + aBCde4b4c = dnnl_aBCde4b4c, + aBCde4c16b4c = dnnl_aBCde4c16b4c, + aBCde16b16c2b = dnnl_aBCde16b16c2b, + aBCde16c16b4c = dnnl_aBCde16c16b4c, + aBCde16c16b2c = dnnl_aBCde16c16b2c, + aBCdef16c16b2c = dnnl_aBCdef16c16b2c, + aBCde4c4b = dnnl_aBCde4c4b, + Abcde8a = dnnl_Abcde8a, + ABcde8a8b = dnnl_ABcde8a8b, + ABcde8a4b = dnnl_ABcde8a4b, + aBcde8b = dnnl_aBcde8b, + ABcde8b16a2b = dnnl_ABcde8b16a2b, + AcdeB8b16a2b = dnnl_AcdeB8b16a2b, + ABcde8b32a2b = dnnl_ABcde8b32a2b, + AcdeB8b32a2b = dnnl_AcdeB8b32a2b, + ABcde8b64a2b = dnnl_ABcde8b64a2b, + AcdeB8b64a2b = dnnl_AcdeB8b64a2b, + ABcde4b16a4b = dnnl_ABcde4b16a4b, + AcdeB4b16a4b = dnnl_AcdeB4b16a4b, + ABcde4b32a4b = dnnl_ABcde4b32a4b, + AcdeB4b32a4b = dnnl_AcdeB4b32a4b, + ABcde4b64a4b = dnnl_ABcde4b64a4b, + AcdeB4b64a4b = dnnl_AcdeB4b64a4b, + ABcde16b16a4b = dnnl_ABcde16b16a4b, + ABcde16b32a4b = dnnl_ABcde16b32a4b, + ABcde16b48a4b = dnnl_ABcde16b48a4b, + ABcde16b64a4b = dnnl_ABcde16b64a4b, + ABcde16b16a2b = dnnl_ABcde16b16a2b, + ABcde16b32a2b = dnnl_ABcde16b32a2b, + ABcde16b48a2b = dnnl_ABcde16b48a2b, + ABcde16b64a2b = dnnl_ABcde16b64a2b, + ABcde2b8a4b = dnnl_ABcde2b8a4b, + aBCde8b16c2b = dnnl_aBCde8b16c2b, + ABcde8b8a = dnnl_ABcde8b8a, + AcdeB8b8a = dnnl_AcdeB8b8a, + aBCde8b8c = dnnl_aBCde8b8c, + aBCde8b4c = dnnl_aBCde8b4c, + ABcd4a8b8a4b = dnnl_ABcd4a8b8a4b, + ABcd2a8b8a2b = dnnl_ABcd2a8b8a2b, + aBCde4b8c8b4c = dnnl_aBCde4b8c8b4c, + aBCde2b8c8b2c = dnnl_aBCde2b8c8b2c, + aBCde8c16b2c = dnnl_aBCde8c16b2c, + aBCde8c8b = dnnl_aBCde8c8b, + aBcdef16b = dnnl_aBcdef16b, + aBCdef16b16c = dnnl_aBCdef16b16c, + aBCdef16c16b = dnnl_aBCdef16c16b, + aBcdef4b = dnnl_aBcdef4b, + aBCdef2c8b4c = dnnl_aBCdef2c8b4c, + aBCdef4c4b = dnnl_aBCdef4c4b, + aBCdef4b4c = dnnl_aBCdef4b4c, + aBCdef8b8c = dnnl_aBCdef8b8c, + aBCdef8b4c = dnnl_aBCdef8b4c, + aBCdef8c16b2c = dnnl_aBCdef8c16b2c, + aBCdef4c16b4c = dnnl_aBCdef4c16b4c, + aBCdef8c8b = dnnl_aBCdef8c8b, + aBdc16b = dnnl_aBdc16b, + aBdc4b = dnnl_aBdc4b, + aBdc8b = dnnl_aBdc8b, + aBdC8b2c = dnnl_aBdC8b2c, + aBdC8b4c = dnnl_aBdC8b4c, + aBdec16b = dnnl_aBdec16b, + aBdec4b = dnnl_aBdec4b, + aBdec8b = dnnl_aBdec8b, + aBdeC8b2c = dnnl_aBdeC8b2c, + aBdeC8b4c = dnnl_aBdeC8b4c, + aBdefc16b = dnnl_aBdefc16b, + aCBdef16c16b = dnnl_aCBdef16c16b, + aCBdef16b16c = dnnl_aCBdef16b16c, + aBdefc4b = dnnl_aBdefc4b, + aBdefc8b = dnnl_aBdefc8b, + aBdefC8b2c = dnnl_aBdefC8b2c, + aBdefC8b4c = dnnl_aBdefC8b4c, + Acb16a = dnnl_Acb16a, + Acb4a = dnnl_Acb4a, + Acb8a = dnnl_Acb8a, + AcB8a2b = dnnl_AcB8a2b, + AcB8a4b = dnnl_AcB8a4b, + aCBd16b16c = dnnl_aCBd16b16c, + aCBd16c16b = dnnl_aCBd16c16b, + aCBde16b16c = dnnl_aCBde16b16c, + aCBde16c16b = dnnl_aCBde16c16b, + Acdb16a = dnnl_Acdb16a, + Acdb4a = dnnl_Acdb4a, + Acdb8a = dnnl_Acdb8a, + AcdB8a2b = dnnl_AcdB8a2b, + AcdB8a4b = dnnl_AcdB8a4b, + Acdeb16a = dnnl_Acdeb16a, + Acdeb4a = dnnl_Acdeb4a, + Acdeb8a = dnnl_Acdeb8a, + AcdeB8a2b = dnnl_AcdeB8a2b, + AcdeB8a4b = dnnl_AcdeB8a4b, + BAc16a16b = dnnl_BAc16a16b, + BAc16b16a = dnnl_BAc16b16a, + BAcd16a16b = dnnl_BAcd16a16b, + BAcd16b16a = dnnl_BAcd16b16a, + ABcd32a32b = dnnl_ABcd32a32b, + BAcde16b16a = dnnl_BAcde16b16a, + BAcde16a16b = dnnl_BAcde16a16b, + aBdec32b = dnnl_aBdec32b, + Abcdef16a = dnnl_Abcdef16a, + Abcdef32a = dnnl_Abcdef32a, + Acdb32a = dnnl_Acdb32a, + aBCd2b4c2b = dnnl_aBCd2b4c2b, + aBCde2b4c2b = dnnl_aBCde2b4c2b, + aBCdef2b4c2b = dnnl_aBCdef2b4c2b, + aBCd2c4b2c = dnnl_aBCd2c4b2c, + aBCde2c4b2c = dnnl_aBCde2c4b2c, + aBCdef2c4b2c = dnnl_aBCdef2c4b2c, + aBCd4b8c2b = dnnl_aBCd4b8c2b, + aBCde4b8c2b = dnnl_aBCde4b8c2b, + aBCdef4b8c2b = dnnl_aBCdef4b8c2b, + aBCd4c8b2c = dnnl_aBCd4c8b2c, + aBCde4c8b2c = dnnl_aBCde4c8b2c, + aBCdef4c8b2c = dnnl_aBCdef4c8b2c, + AB32a32b8a4b = dnnl_AB32a32b8a4b, + AB32a32b8a2b = dnnl_AB32a32b8a2b, + AB8a4b = dnnl_AB8a4b, + AB8a2b = dnnl_AB8a2b, + abDc16d = dnnl_abDc16d, + abDc32d = dnnl_abDc32d, + abDC32d4c = dnnl_abDC32d4c, + abCd32c = dnnl_abCd32c, + abdEc16e = dnnl_abdEc16e, + abdEc32e = dnnl_abdEc32e, + abdEC32e2c = dnnl_abdEC32e2c, + abdEC32e4c = dnnl_abdEC32e4c, + abdCe16c = dnnl_abdCe16c, + abdCe32c = dnnl_abdCe32c, + abdCE32c2e = dnnl_abdCE32c2e, + aBCdef16c16b4c = dnnl_aBCdef16c16b4c, + aBdC16b4c = dnnl_aBdC16b4c, + aBdeC16b4c = dnnl_aBdeC16b4c, + AcB16a4b = dnnl_AcB16a4b, + AcdB16a2b = dnnl_AcdB16a2b, + aBdefC16b4c = dnnl_aBdefC16b4c, + AcdeB16a4b = dnnl_AcdeB16a4b, + + Acb32a = dnnl_Acb32a, + AcB32a2b = dnnl_AcB32a2b, + AcB32a4b = dnnl_AcB32a4b, + Acb48a = dnnl_Acb48a, + AcB48a2b = dnnl_AcB48a2b, + AcB48a4b = dnnl_AcB48a4b, + Acb64a = dnnl_Acb64a, + AcB64a2b = dnnl_AcB64a2b, + AcB64a4b = dnnl_AcB64a4b, + cBa2b = dnnl_cBa2b, + cBa4b = dnnl_cBa4b, + aBdc32b = dnnl_aBdc32b, + aBdC32b2c = dnnl_aBdC32b2c, + aBdC32b4c = dnnl_aBdC32b4c, + aBdc48b = dnnl_aBdc48b, + aBdC48b2c = dnnl_aBdC48b2c, + aBdC48b4c = dnnl_aBdC48b4c, + aBdc64b = dnnl_aBdc64b, + aBdC64b2c = dnnl_aBdC64b2c, + aBdC64b4c = dnnl_aBdC64b4c, + adcb = dnnl_adcb, + adCb2c = dnnl_adCb2c, + adCb4c = dnnl_adCb4c, + AcdB32a2b = dnnl_AcdB32a2b, + AcdB32a4b = dnnl_AcdB32a4b, + Acdb48a = dnnl_Acdb48a, + AcdB48a2b = dnnl_AcdB48a2b, + AcdB48a4b = dnnl_AcdB48a4b, + Acdb64a = dnnl_Acdb64a, + AcdB64a2b = dnnl_AcdB64a2b, + AcdB64a4b = dnnl_AcdB64a4b, + cdBa2b = dnnl_cdBa2b, + cdBa4b = dnnl_cdBa4b, + aBdeC32b2c = dnnl_aBdeC32b2c, + aBdeC32b4c = dnnl_aBdeC32b4c, + aBdec48b = dnnl_aBdec48b, + aBdeC48b2c = dnnl_aBdeC48b2c, + aBdeC48b4c = dnnl_aBdeC48b4c, + aBdec64b = dnnl_aBdec64b, + aBdeC64b2c = dnnl_aBdeC64b2c, + aBdeC64b4c = dnnl_aBdeC64b4c, + adecb = dnnl_adecb, + adeCb2c = dnnl_adeCb2c, + adeCb4c = dnnl_adeCb4c, + Acdeb32a = dnnl_Acdeb32a, + AcdeB32a2b = dnnl_AcdeB32a2b, + AcdeB32a4b = dnnl_AcdeB32a4b, + Acdeb48a = dnnl_Acdeb48a, + AcdeB48a2b = dnnl_AcdeB48a2b, + AcdeB48a4b = dnnl_AcdeB48a4b, + Acdeb64a = dnnl_Acdeb64a, + AcdeB64a2b = dnnl_AcdeB64a2b, + AcdeB64a4b = dnnl_AcdeB64a4b, + cdeBa2b = dnnl_cdeBa2b, + cdeBa4b = dnnl_cdeBa4b, + aBdefc32b = dnnl_aBdefc32b, + aBdefC32b2c = dnnl_aBdefC32b2c, + aBdefC32b4c = dnnl_aBdefC32b4c, + aBdefc48b = dnnl_aBdefc48b, + aBdefC48b2c = dnnl_aBdefC48b2c, + aBdefC48b4c = dnnl_aBdefC48b4c, + aBdefc64b = dnnl_aBdefc64b, + aBdefC64b2c = dnnl_aBdefC64b2c, + aBdefC64b4c = dnnl_aBdefC64b4c, + adefcb = dnnl_adefcb, + adefCb2c = dnnl_adefCb2c, + adefCb4c = dnnl_adefCb4c, + ABc32a32b = dnnl_ABc32a32b, + BAc8a16b2a = dnnl_BAc8a16b2a, + BAcd8a16b2a = dnnl_BAcd8a16b2a, + ABcde8a16b2a = dnnl_ABcde8a16b2a, + aCBd8b16c2b = dnnl_aCBd8b16c2b, + BAcde8a16b2a = dnnl_BAcde8a16b2a, + aCBde8b16c2b = dnnl_aCBde8b16c2b, + ABcde32a32b = dnnl_ABcde32a32b, + ABc4a8b8a4b = dnnl_ABc4a8b8a4b, + ABcde4a8b8a4b = dnnl_ABcde4a8b8a4b, + BAc4b8a8b4a = dnnl_BAc4b8a8b4a, + BAcd4b8a8b4a = dnnl_BAcd4b8a8b4a, + BAcde4b8a8b4a = dnnl_BAcde4b8a8b4a, + aBCd4b8c8b4c = dnnl_aBCd4b8c8b4c, + aBCdef4b8c8b4c = dnnl_aBCdef4b8c8b4c, + aBCdef8b16c2b = dnnl_aBCdef8b16c2b, + aCBdef8b16c2b = dnnl_aCBdef8b16c2b, + aBdC16b2c = dnnl_aBdC16b2c, + aBdeC16b2c = dnnl_aBdeC16b2c, + aBdefC16b2c = dnnl_aBdefC16b2c, + aBedc16b = dnnl_aBedc16b, + AcB16a2b = dnnl_AcB16a2b, + AcdB16a4b = dnnl_AcdB16a4b, + AcdeB16a2b = dnnl_AcdeB16a2b, + Adcb16a = dnnl_Adcb16a, + aCBd4c8b8c4b = dnnl_aCBd4c8b8c4b, + aCBde4c8b8c4b = dnnl_aCBde4c8b8c4b, + aCBdef4c8b8c4b = dnnl_aCBdef4c8b8c4b, + ABc32a16b = dnnl_ABc32a16b, + ABcd16a32b = dnnl_ABcd16a32b, + ABcd32a16b = dnnl_ABcd32a16b, + ABcde32a16b = dnnl_ABcde32a16b, + AB48a16b = dnnl_AB48a16b, + AB48a32b = dnnl_AB48a32b, + ABc40a16b = dnnl_ABc40a16b, + ABc40a32b = dnnl_ABc40a32b, + aBC48b16c = dnnl_aBC48b16c, + aBC48b32c = dnnl_aBC48b32c, + ABcd40a16b = dnnl_ABcd40a16b, + ABcd40a32b = dnnl_ABcd40a32b, + BA16a16b = dnnl_BA16a16b, + BA16a32b = dnnl_BA16a32b, + BA16a48b = dnnl_BA16a48b, + BA16a64b = dnnl_BA16a64b, + BA16a16b2a = dnnl_BA16a16b2a, + BA16a32b2a = dnnl_BA16a32b2a, + BA16a48b2a = dnnl_BA16a48b2a, + BA16a64b2a = dnnl_BA16a64b2a, + BA16a16b4a = dnnl_BA16a16b4a, + BA16a32b4a = dnnl_BA16a32b4a, + BA16a48b4a = dnnl_BA16a48b4a, + BA16a64b4a = dnnl_BA16a64b4a, + decbA16a = dnnl_decbA16a, + decbA8a = dnnl_decbA8a, + defcbA16a = dnnl_defcbA16a, + defcbA8a = dnnl_defcbA8a, + aCB16b16c = dnnl_aCB16b16c, + aCB16b32c = dnnl_aCB16b32c, + aCB16b48c = dnnl_aCB16b48c, + aCB16b64c = dnnl_aCB16b64c, + aCB16b16c2b = dnnl_aCB16b16c2b, + aCB16b32c2b = dnnl_aCB16b32c2b, + aCB16b48c2b = dnnl_aCB16b48c2b, + aCB16b64c2b = dnnl_aCB16b64c2b, + aCB16b16c4b = dnnl_aCB16b16c4b, + aCB16b32c4b = dnnl_aCB16b32c4b, + aCB16b48c4b = dnnl_aCB16b48c4b, + aCB16b64c4b = dnnl_aCB16b64c4b, + Acb24a = dnnl_Acb24a, + Acdb24a = dnnl_Acdb24a, + Acdeb24a = dnnl_Acdeb24a, + aBdc24b = dnnl_aBdc24b, + aBdec24b = dnnl_aBdec24b, + aBdefc24b = dnnl_aBdefc24b, + AcB24a2b = dnnl_AcB24a2b, + AcdB24a2b = dnnl_AcdB24a2b, + AcdeB24a2b = dnnl_AcdeB24a2b, + aBdC24b2c = dnnl_aBdC24b2c, + aBdeC24b2c = dnnl_aBdeC24b2c, + aBdefC24b2c = dnnl_aBdefC24b2c, + AcB24a4b = dnnl_AcB24a4b, + AcdB24a4b = dnnl_AcdB24a4b, + AcdeB24a4b = dnnl_AcdeB24a4b, + aBdC24b4c = dnnl_aBdC24b4c, + aBdeC24b4c = dnnl_aBdeC24b4c, + aBdefC24b4c = dnnl_aBdefC24b4c, + AB8b32a = dnnl_AB8b32a, + ABc8b32a = dnnl_ABc8b32a, + AcB8b32a = dnnl_AcB8b32a, + ABcd8b32a = dnnl_ABcd8b32a, + AcdB8b32a = dnnl_AcdB8b32a, + ABcde8b32a = dnnl_ABcde8b32a, + AcdeB8b32a = dnnl_AcdeB8b32a, + AB8b24a = dnnl_AB8b24a, + ABc8b24a = dnnl_ABc8b24a, + AcB8b24a = dnnl_AcB8b24a, + ABcd8b24a = dnnl_ABcd8b24a, + AcdB8b24a = dnnl_AcdB8b24a, + ABcde8b24a = dnnl_ABcde8b24a, + AcdeB8b24a = dnnl_AcdeB8b24a, + AB8b16a = dnnl_AB8b16a, + ABc8b16a = dnnl_ABc8b16a, + AcB8b16a = dnnl_AcB8b16a, + ABcd8b16a = dnnl_ABcd8b16a, + AcdB8b16a = dnnl_AcdB8b16a, + ABcde8b16a = dnnl_ABcde8b16a, + AcdeB8b16a = dnnl_AcdeB8b16a, + AB8b8a = dnnl_AB8b8a, + + format_tag_last = dnnl_format_tag_last, + + nCdhw16c = dnnl_nCdhw16c, + nCdhw4c = dnnl_nCdhw4c, + nCdhw8c = dnnl_nCdhw8c, + nChw16c = dnnl_nChw16c, + nChw4c = dnnl_nChw4c, + nChw8c = dnnl_nChw8c, + nCw16c = dnnl_nCw16c, + nCw4c = dnnl_nCw4c, + nCw8c = dnnl_nCw8c, + NCw16n16c = dnnl_NCw16n16c, + NChw16n16c = dnnl_NChw16n16c, + NCdhw16n16c = dnnl_NCdhw16n16c, + NCdhw32n32c = dnnl_NCdhw32n32c, + NChw32n32c = dnnl_NChw32n32c, + IOhw16i16o = dnnl_IOhw16i16o, + OI16i16o = dnnl_OI16i16o, + OI16i32o = dnnl_OI16i32o, + OI16i48o = dnnl_OI16i48o, + OI16i64o = dnnl_OI16i64o, + OI8i16o2i = dnnl_OI8i16o2i, + OI8i32o2i = dnnl_OI8i32o2i, + OI8i64o2i = dnnl_OI8i64o2i, + OI4i8o4i = dnnl_OI4i8o4i, + OI4i16o4i = dnnl_OI4i16o4i, + OI4i24o4i = dnnl_OI4i24o4i, + OI4i32o4i = dnnl_OI4i32o4i, + OI4i64o4i = dnnl_OI4i64o4i, + Ohwi32o = dnnl_Ohwi32o, + IOdhw16i16o = dnnl_IOdhw16i16o, + gIOhw16i16o = dnnl_gIOhw16i16o, + gOhwi32o = dnnl_gOhwi32o, + Goidhw16g = dnnl_Goidhw16g, + IOw16o16i = dnnl_IOw16o16i, + OIw16i16o = dnnl_OIw16i16o, + OwI16i16o = dnnl_OwI16i16o, + OIw16i32o = dnnl_OIw16i32o, + OwI16i32o = dnnl_OwI16i32o, + OIw16i48o = dnnl_OIw16i48o, + OwI16i48o = dnnl_OwI16i48o, + OIw16i64o = dnnl_OIw16i64o, + OwI16i64o = dnnl_OwI16i64o, + IOw16i16o = dnnl_IOw16i16o, + gIOw16i16o = dnnl_gIOw16i16o, + OIw16o16i = dnnl_OIw16o16i, + Oiw16o = dnnl_Oiw16o, + OIw4i8o4i = dnnl_OIw4i8o4i, + OwI4i8o4i = dnnl_OwI4i8o4i, + OIw4i16o4i = dnnl_OIw4i16o4i, + OwI4i16o4i = dnnl_OwI4i16o4i, + OIw4i24o4i = dnnl_OIw4i24o4i, + OwI4i24o4i = dnnl_OwI4i24o4i, + OIw4i32o4i = dnnl_OIw4i32o4i, + OwI4i32o4i = dnnl_OwI4i32o4i, + OIw4i64o4i = dnnl_OIw4i64o4i, + OwI4i64o4i = dnnl_OwI4i64o4i, + OIw2i8o4i = dnnl_OIw2i8o4i, + OIw4i4o = dnnl_OIw4i4o, + OIw4o4i = dnnl_OIw4o4i, + Oiw4o = dnnl_Oiw4o, + OIw8i16o2i = dnnl_OIw8i16o2i, + OwI8i16o2i = dnnl_OwI8i16o2i, + OIw8i32o2i = dnnl_OIw8i32o2i, + OwI8i32o2i = dnnl_OwI8i32o2i, + OIw8i64o2i = dnnl_OIw8i64o2i, + OwI8i64o2i = dnnl_OwI8i64o2i, + OIw8i8o = dnnl_OIw8i8o, + OwI8i8o = dnnl_OwI8i8o, + OIw8o16i2o = dnnl_OIw8o16i2o, + OIw8o8i = dnnl_OIw8o8i, + OIw8o4i = dnnl_OIw8o4i, + OIw16i16o4i = dnnl_OIw16i16o4i, + OIw16i32o4i = dnnl_OIw16i32o4i, + OIw16i48o4i = dnnl_OIw16i48o4i, + OIw16i64o4i = dnnl_OIw16i64o4i, + OIw16i16o2i = dnnl_OIw16i16o2i, + OIw16i32o2i = dnnl_OIw16i32o2i, + OIw16i48o2i = dnnl_OIw16i48o2i, + OIw16i64o2i = dnnl_OIw16i64o2i, + OIw16o16i2o = dnnl_OIw16o16i2o, + Owi16o = dnnl_Owi16o, + OwI16o2i = dnnl_OwI16o2i, + Iwo16i = dnnl_Iwo16i, + IwO16i2o = dnnl_IwO16i2o, + IwO16i4o = dnnl_IwO16i4o, + Owi4o = dnnl_Owi4o, + Owi8o = dnnl_Owi8o, + OwI8o2i = dnnl_OwI8o2i, + OwI8o4i = dnnl_OwI8o4i, + IOhw16o16i = dnnl_IOhw16o16i, + Ohwi16o = dnnl_Ohwi16o, + OhwI16o2i = dnnl_OhwI16o2i, + Ihwo16i = dnnl_Ihwo16i, + IhwO16i2o = dnnl_IhwO16i2o, + IhwO16i4o = dnnl_IhwO16i4o, + Ohwi4o = dnnl_Ohwi4o, + Ohwi8o = dnnl_Ohwi8o, + OhwI8o2i = dnnl_OhwI8o2i, + OhwI8o4i = dnnl_OhwI8o4i, + OIhw16i16o = dnnl_OIhw16i16o, + OhwI16i16o = dnnl_OhwI16i16o, + OIhw16i32o = dnnl_OIhw16i32o, + OhwI16i32o = dnnl_OhwI16i32o, + OIhw16i48o = dnnl_OIhw16i48o, + OhwI16i48o = dnnl_OhwI16i48o, + OIhw16i64o = dnnl_OIhw16i64o, + OhwI16i64o = dnnl_OhwI16i64o, + OIhw16o16i = dnnl_OIhw16o16i, + Oihw16o = dnnl_Oihw16o, + OIhw4i8o4i = dnnl_OIhw4i8o4i, + OhwI4i8o4i = dnnl_OhwI4i8o4i, + OIhw4i16o4i = dnnl_OIhw4i16o4i, + OhwI4i16o4i = dnnl_OhwI4i16o4i, + OIhw4i24o4i = dnnl_OIhw4i24o4i, + OhwI4i24o4i = dnnl_OhwI4i24o4i, + OIhw4i32o4i = dnnl_OIhw4i32o4i, + OhwI4i32o4i = dnnl_OhwI4i32o4i, + OIhw4i64o4i = dnnl_OIhw4i64o4i, + OhwI4i64o4i = dnnl_OhwI4i64o4i, + OIhw4i4o = dnnl_OIhw4i4o, + OIhw4o4i = dnnl_OIhw4o4i, + Oihw4o = dnnl_Oihw4o, + OIhw8i16o2i = dnnl_OIhw8i16o2i, + OhwI8i16o2i = dnnl_OhwI8i16o2i, + OIhw8i32o2i = dnnl_OIhw8i32o2i, + OhwI8i32o2i = dnnl_OhwI8i32o2i, + OIhw8i64o2i = dnnl_OIhw8i64o2i, + OhwI8i64o2i = dnnl_OhwI8i64o2i, + OIhw8i8o = dnnl_OIhw8i8o, + OhwI8i8o = dnnl_OhwI8i8o, + OIhw8o16i2o = dnnl_OIhw8o16i2o, + OIhw8o8i = dnnl_OIhw8o8i, + OIhw8o4i = dnnl_OIhw8o4i, + OIhw2i8o4i = dnnl_OIhw2i8o4i, + IOdhw16o16i = dnnl_IOdhw16o16i, + Odhwi16o = dnnl_Odhwi16o, + OdhwI16o2i = dnnl_OdhwI16o2i, + Idhwo16i = dnnl_Idhwo16i, + IdhwO16i2o = dnnl_IdhwO16i2o, + IdhwO16i4o = dnnl_IdhwO16i4o, + Odhwi4o = dnnl_Odhwi4o, + Odhwi8o = dnnl_Odhwi8o, + OdhwI8o2i = dnnl_OdhwI8o2i, + OdhwI8o4i = dnnl_OdhwI8o4i, + OIdhw16i16o = dnnl_OIdhw16i16o, + OdhwI16i16o = dnnl_OdhwI16i16o, + OIdhw16i32o = dnnl_OIdhw16i32o, + OdhwI16i32o = dnnl_OdhwI16i32o, + OIdhw16i48o = dnnl_OIdhw16i48o, + OdhwI16i48o = dnnl_OdhwI16i48o, + OIdhw16i64o = dnnl_OIdhw16i64o, + OdhwI16i64o = dnnl_OdhwI16i64o, + OIdhw16o16i = dnnl_OIdhw16o16i, + OIdhw16o16i2o = dnnl_OIdhw16o16i2o, + Oidhw16o = dnnl_Oidhw16o, + OIdhw4i4o = dnnl_OIdhw4i4o, + OIdhw4o4i = dnnl_OIdhw4o4i, + Oidhw4o = dnnl_Oidhw4o, + OIdhw8i16o2i = dnnl_OIdhw8i16o2i, + OdhwI8i16o2i = dnnl_OdhwI8i16o2i, + OIdhw8i32o2i = dnnl_OIdhw8i32o2i, + OdhwI8i32o2i = dnnl_OdhwI8i32o2i, + OIdhw8i64o2i = dnnl_OIdhw8i64o2i, + OdhwI8i64o2i = dnnl_OdhwI8i64o2i, + OIdhw4i8o4i = dnnl_OIdhw4i8o4i, + OdhwI4i8o4i = dnnl_OdhwI4i8o4i, + OIdhw4i16o4i = dnnl_OIdhw4i16o4i, + OdhwI4i16o4i = dnnl_OdhwI4i16o4i, + OIdhw16i16o4i = dnnl_OIdhw16i16o4i, + OIdhw16i32o4i = dnnl_OIdhw16i32o4i, + OIdhw16i48o4i = dnnl_OIdhw16i48o4i, + OIdhw16i64o4i = dnnl_OIdhw16i64o4i, + OIdhw16i16o2i = dnnl_OIdhw16i16o2i, + OIdhw16i32o2i = dnnl_OIdhw16i32o2i, + OIdhw16i48o2i = dnnl_OIdhw16i48o2i, + OIdhw16i64o2i = dnnl_OIdhw16i64o2i, + OIdhw4i24o4i = dnnl_OIdhw4i24o4i, + OdhwI4i24o4i = dnnl_OdhwI4i24o4i, + OIdhw4i32o4i = dnnl_OIdhw4i32o4i, + OdhwI4i32o4i = dnnl_OdhwI4i32o4i, + OIdhw4i64o4i = dnnl_OIdhw4i64o4i, + OdhwI4i64o4i = dnnl_OdhwI4i64o4i, + OIdhw2i8o4i = dnnl_OIdhw2i8o4i, + OIdhw8i8o = dnnl_OIdhw8i8o, + OdhwI8i8o = dnnl_OdhwI8i8o, + OIdhw8o8i = dnnl_OIdhw8o8i, + OIdhw8o4i = dnnl_OIdhw8o4i, + gIOw16o16i = dnnl_gIOw16o16i, + gOIw16i16o = dnnl_gOIw16i16o, + gOIw16o16i = dnnl_gOIw16o16i, + gOiw16o = dnnl_gOiw16o, + gOIw4i16o4i = dnnl_gOIw4i16o4i, + gOIw2i8o4i = dnnl_gOIw2i8o4i, + gOIw4i4o = dnnl_gOIw4i4o, + gOIw4o4i = dnnl_gOIw4o4i, + gOiw4o = dnnl_gOiw4o, + gOIw8i16o2i = dnnl_gOIw8i16o2i, + gOIw8i8o = dnnl_gOIw8i8o, + gOIw8o16i2o = dnnl_gOIw8o16i2o, + gOIw8o8i = dnnl_gOIw8o8i, + gOIw8o4i = dnnl_gOIw8o4i, + gOIw16i16o4i = dnnl_gOIw16i16o4i, + gOIw16i16o2i = dnnl_gOIw16i16o2i, + gOIw16o16i2o = dnnl_gOIw16o16i2o, + gOwi16o = dnnl_gOwi16o, + gOwI16o2i = dnnl_gOwI16o2i, + gIwo16i = dnnl_gIwo16i, + gIwO16i2o = dnnl_gIwO16i2o, + gIwO16i4o = dnnl_gIwO16i4o, + gOwi4o = dnnl_gOwi4o, + gOwi8o = dnnl_gOwi8o, + gOwI8o2i = dnnl_gOwI8o2i, + gOwI8o4i = dnnl_gOwI8o4i, + Goiw8g = dnnl_Goiw8g, + Goiw16g = dnnl_Goiw16g, + gIOhw16o16i = dnnl_gIOhw16o16i, + gOhwi16o = dnnl_gOhwi16o, + gOhwI16o2i = dnnl_gOhwI16o2i, + gIhwo16i = dnnl_gIhwo16i, + gIhwO16i2o = dnnl_gIhwO16i2o, + gIhwO16i4o = dnnl_gIhwO16i4o, + gOhwi4o = dnnl_gOhwi4o, + gOhwi8o = dnnl_gOhwi8o, + gOhwI8o2i = dnnl_gOhwI8o2i, + gOhwI8o4i = dnnl_gOhwI8o4i, + Goihw16g = dnnl_Goihw16g, + gOIhw16i16o = dnnl_gOIhw16i16o, + gOIhw16o16i = dnnl_gOIhw16o16i, + gOihw16o = dnnl_gOihw16o, + gOIhw4i16o4i = dnnl_gOIhw4i16o4i, + gOIhw2i8o4i = dnnl_gOIhw2i8o4i, + gOIhw4i4o = dnnl_gOIhw4i4o, + gOIhw4o4i = dnnl_gOIhw4o4i, + gOihw4o = dnnl_gOihw4o, + Goihw8g = dnnl_Goihw8g, + gOIhw8i16o2i = dnnl_gOIhw8i16o2i, + gOIhw8i8o = dnnl_gOIhw8i8o, + gOIhw8o16i2o = dnnl_gOIhw8o16i2o, + OIw4o8i8o4i = dnnl_OIw4o8i8o4i, + OIdhw4o8i8o4i = dnnl_OIdhw4o8i8o4i, + OIhw4o8i8o4i = dnnl_OIhw4o8i8o4i, + OIhw2o8i8o2i = dnnl_OIhw2o8i8o2i, + gOIw4o8i8o4i = dnnl_gOIw4o8i8o4i, + gOIdhw4o8i8o4i = dnnl_gOIdhw4o8i8o4i, + gOIhw4o8i8o4i = dnnl_gOIhw4o8i8o4i, + gOIhw2o8i8o2i = dnnl_gOIhw2o8i8o2i, + OIhw16i16o4i = dnnl_OIhw16i16o4i, + OIhw16i32o4i = dnnl_OIhw16i32o4i, + OIhw16i48o4i = dnnl_OIhw16i48o4i, + OIhw16i64o4i = dnnl_OIhw16i64o4i, + OIhw16i16o2i = dnnl_OIhw16i16o2i, + OIhw16i32o2i = dnnl_OIhw16i32o2i, + OIhw16i48o2i = dnnl_OIhw16i48o2i, + OIhw16i64o2i = dnnl_OIhw16i64o2i, + OIhw16o16i2o = dnnl_OIhw16o16i2o, + gOIhw16i16o4i = dnnl_gOIhw16i16o4i, + gOIhw16i16o2i = dnnl_gOIhw16i16o2i, + gOIhw16o16i2o = dnnl_gOIhw16o16i2o, + gOIhw8o8i = dnnl_gOIhw8o8i, + gOIhw8o4i = dnnl_gOIhw8o4i, + gIOdhw16i16o = dnnl_gIOdhw16i16o, + gIOdhw16o16i = dnnl_gIOdhw16o16i, + gOdhwi16o = dnnl_gOdhwi16o, + gOdhwI16o2i = dnnl_gOdhwI16o2i, + gIdhwo16i = dnnl_gIdhwo16i, + gIdhwO16i2o = dnnl_gIdhwO16i2o, + gIdhwO16i4o = dnnl_gIdhwO16i4o, + gOdhwi4o = dnnl_gOdhwi4o, + gOdhwi8o = dnnl_gOdhwi8o, + gOdhwI8o2i = dnnl_gOdhwI8o2i, + gOdhwI8o4i = dnnl_gOdhwI8o4i, + gOIdhw16i16o = dnnl_gOIdhw16i16o, + gOIdhw16o16i = dnnl_gOIdhw16o16i, + gOIdhw16o16i2o = dnnl_gOIdhw16o16i2o, + gOidhw16o = dnnl_gOidhw16o, + gOIdhw4i4o = dnnl_gOIdhw4i4o, + gOIdhw4o4i = dnnl_gOIdhw4o4i, + gOidhw4o = dnnl_gOidhw4o, + gOIdhw8i16o2i = dnnl_gOIdhw8i16o2i, + gOIdhw4i16o4i = dnnl_gOIdhw4i16o4i, + gOIdhw16i16o4i = dnnl_gOIdhw16i16o4i, + gOIdhw16i16o2i = dnnl_gOIdhw16i16o2i, + gOIdhw2i8o4i = dnnl_gOIdhw2i8o4i, + gOIdhw8i8o = dnnl_gOIdhw8i8o, + gOIdhw8o8i = dnnl_gOIdhw8o8i, + gOIdhw8o4i = dnnl_gOIdhw8o4i, + gOIw2i4o2i = dnnl_gOIw2i4o2i, + gOIhw2i4o2i = dnnl_gOIhw2i4o2i, + gOIdhw2i4o2i = dnnl_gOIdhw2i4o2i, + gOIw2o4i2o = dnnl_gOIw2o4i2o, + gOIhw2o4i2o = dnnl_gOIhw2o4i2o, + gOIdhw2o4i2o = dnnl_gOIdhw2o4i2o, + gOIw4i8o2i = dnnl_gOIw4i8o2i, + gOIhw4i8o2i = dnnl_gOIhw4i8o2i, + gOIdhw4i8o2i = dnnl_gOIdhw4i8o2i, + gOIw4o8i2o = dnnl_gOIw4o8i2o, + gOIhw4o8i2o = dnnl_gOIhw4o8i2o, + gOIdhw4o8i2o = dnnl_gOIdhw4o8i2o, + + ldOi16o = abDc16d, + ldOi32o = abDc32d, + ldOI32o4i = abDC32d4c, + ldgOi16o = abdEc16e, + ldgOi32o = abdEc32e, + ldgOI32o2i = abdEC32e2c, + ldgOI32o4i = abdEC32e4c, + OwI16o4i = dnnl_OwI16o4i, + OhwI16o4i = dnnl_OhwI16o4i, + gOwI16o4i = dnnl_gOwI16o4i, + gOhwI16o4i = dnnl_gOhwI16o4i, + OdhwI16o4i = dnnl_OdhwI16o4i, + gOdhwI16o4i = dnnl_gOdhwI16o4i, + + Owi32o = dnnl_Owi32o, + OwI32o2i = dnnl_OwI32o2i, + OwI32o4i = dnnl_OwI32o4i, + Owi48o = dnnl_Owi48o, + OwI48o2i = dnnl_OwI48o2i, + OwI48o4i = dnnl_OwI48o4i, + Owi64o = dnnl_Owi64o, + OwI64o2i = dnnl_OwI64o2i, + OwI64o4i = dnnl_OwI64o4i, + Iwo32i = dnnl_Iwo32i, + IwO32i2o = dnnl_IwO32i2o, + IwO32i4o = dnnl_IwO32i4o, + Iwo48i = dnnl_Iwo48i, + IwO48i2o = dnnl_IwO48i2o, + IwO48i4o = dnnl_IwO48i4o, + Iwo64i = dnnl_Iwo64i, + IwO64i2o = dnnl_IwO64i2o, + IwO64i4o = dnnl_IwO64i4o, + wIo2i = dnnl_wIo2i, + wIo4i = dnnl_wIo4i, + gOwi32o = dnnl_gOwi32o, + gOwI32o2i = dnnl_gOwI32o2i, + gOwI32o4i = dnnl_gOwI32o4i, + gOwi48o = dnnl_gOwi48o, + gOwI48o2i = dnnl_gOwI48o2i, + gOwI48o4i = dnnl_gOwI48o4i, + gOwi64o = dnnl_gOwi64o, + gOwI64o2i = dnnl_gOwI64o2i, + gOwI64o4i = dnnl_gOwI64o4i, + gIwo32i = dnnl_gIwo32i, + gIwO32i2o = dnnl_gIwO32i2o, + gIwO32i4o = dnnl_gIwO32i4o, + gIwo48i = dnnl_gIwo48i, + gIwO48i2o = dnnl_gIwO48i2o, + gIwO48i4o = dnnl_gIwO48i4o, + gIwo64i = dnnl_gIwo64i, + gIwO64i2o = dnnl_gIwO64i2o, + gIwO64i4o = dnnl_gIwO64i4o, + gwio = dnnl_gwio, + gwIo2i = dnnl_gwIo2i, + gwIo4i = dnnl_gwIo4i, + OhwI32o = dnnl_OhwI32o, + OhwI32o2i = dnnl_OhwI32o2i, + OhwI32o4i = dnnl_OhwI32o4i, + Ohwi48o = dnnl_Ohwi48o, + OhwI48o2i = dnnl_OhwI48o2i, + OhwI48o4i = dnnl_OhwI48o4i, + Ohwi64o = dnnl_Ohwi64o, + OhwI64o2i = dnnl_OhwI64o2i, + OhwI64o4i = dnnl_OhwI64o4i, + Ihwo32i = dnnl_Ihwo32i, + IhwO32i2o = dnnl_IhwO32i2o, + IhwO32i4o = dnnl_IhwO32i4o, + Ihwo48i = dnnl_Ihwo48i, + IhwO48i2o = dnnl_IhwO48i2o, + IhwO48i4o = dnnl_IhwO48i4o, + Ihwo64i = dnnl_Ihwo64i, + IhwO64i2o = dnnl_IhwO64i2o, + IhwO64i4o = dnnl_IhwO64i4o, + hwIo2i = dnnl_hwIo2i, + hwIo4i = dnnl_hwIo4i, + gOhwI32o = dnnl_gOhwI32o, + gOhwI32o2i = dnnl_gOhwI32o2i, + gOhwI32o4i = dnnl_gOhwI32o4i, + gOhwi48o = dnnl_gOhwi48o, + gOhwI48o2i = dnnl_gOhwI48o2i, + gOhwI48o4i = dnnl_gOhwI48o4i, + gOhwi64o = dnnl_gOhwi64o, + gOhwI64o2i = dnnl_gOhwI64o2i, + gOhwI64o4i = dnnl_gOhwI64o4i, + gIhwo32i = dnnl_gIhwo32i, + gIhwO32i2o = dnnl_gIhwO32i2o, + gIhwO32i4o = dnnl_gIhwO32i4o, + gIhwo48i = dnnl_gIhwo48i, + gIhwO48i2o = dnnl_gIhwO48i2o, + gIhwO48i4o = dnnl_gIhwO48i4o, + gIhwo64i = dnnl_gIhwo64i, + gIhwO64i2o = dnnl_gIhwO64i2o, + gIhwO64i4o = dnnl_gIhwO64i4o, + ghwio = dnnl_ghwio, + ghwIo2i = dnnl_ghwIo2i, + ghwIo4i = dnnl_ghwIo4i, + Odhwi32o = dnnl_Odhwi32o, + OdhwI32o2i = dnnl_OdhwI32o2i, + OdhwI32o4i = dnnl_OdhwI32o4i, + Odhwi48o = dnnl_Odhwi48o, + OdhwI48o2i = dnnl_OdhwI48o2i, + OdhwI48o4i = dnnl_OdhwI48o4i, + Odhwi64o = dnnl_Odhwi64o, + OdhwI64o2i = dnnl_OdhwI64o2i, + OdhwI64o4i = dnnl_OdhwI64o4i, + Idhwo32i = dnnl_Idhwo32i, + IdhwO32i2o = dnnl_IdhwO32i2o, + IdhwO32i4o = dnnl_IdhwO32i4o, + Idhwo48i = dnnl_Idhwo48i, + IdhwO48i2o = dnnl_IdhwO48i2o, + IdhwO48i4o = dnnl_IdhwO48i4o, + Idhwo64i = dnnl_Idhwo64i, + IdhwO64i2o = dnnl_IdhwO64i2o, + IdhwO64i4o = dnnl_IdhwO64i4o, + dhwIo2i = dnnl_dhwIo2i, + dhwIo4i = dnnl_dhwIo4i, + gOdhwi32o = dnnl_gOdhwi32o, + gOdhwI32o2i = dnnl_gOdhwI32o2i, + gOdhwI32o4i = dnnl_gOdhwI32o4i, + gOdhwi48o = dnnl_gOdhwi48o, + gOdhwI48o2i = dnnl_gOdhwI48o2i, + gOdhwI48o4i = dnnl_gOdhwI48o4i, + gOdhwi64o = dnnl_gOdhwi64o, + gOdhwI64o2i = dnnl_gOdhwI64o2i, + gOdhwI64o4i = dnnl_gOdhwI64o4i, + gIdhwo32i = dnnl_gIdhwo32i, + gIdhwO32i2o = dnnl_gIdhwO32i2o, + gIdhwO32i4o = dnnl_gIdhwO32i4o, + gIdhwo48i = dnnl_gIdhwo48i, + gIdhwO48i2o = dnnl_gIdhwO48i2o, + gIdhwO48i4o = dnnl_gIdhwO48i4o, + gIdhwo64i = dnnl_gIdhwo64i, + gIdhwO64i2o = dnnl_gIdhwO64i2o, + gIdhwO64i4o = dnnl_gIdhwO64i4o, + gdhwio = dnnl_gdhwio, + gdhwIo2i = dnnl_gdhwIo2i, + gdhwIo4i = dnnl_gdhwIo4i, + ldIo32i = dnnl_ldIo32i, + ldgIo16i = dnnl_ldgIo16i, + ldgIo32i = dnnl_ldgIo32i, + ldgIO32i2o = dnnl_ldgIO32i2o, + nCdhw32c = dnnl_nCdhw32c, + nChw32c = dnnl_nChw32c, + nCw32c = dnnl_nCw32c, + NCw32n16c = dnnl_NCw32n16c, + NChw32n16c = dnnl_NChw32n16c, + NCdhw32n16c = dnnl_NCdhw32n16c, + NCw32n32c = dnnl_NCw32n32c, + OI16i16o4i = dnnl_OI16i16o4i, + IOw8o16i2o = dnnl_IOw8o16i2o, + IOhw8o16i2o = dnnl_IOhw8o16i2o, + Owhi16o = dnnl_Owhi16o, + OIdhw8o16i2o = dnnl_OIdhw8o16i2o, + IOdhw8o16i2o = dnnl_IOdhw8o16i2o, + Goiw4g = dnnl_Goiw4g, + gIOw8o16i2o = dnnl_gIOw8o16i2o, + Goiw32g = dnnl_Goiw32g, + Goihw4g = dnnl_Goihw4g, + gIOhw8o16i2o = dnnl_gIOhw8o16i2o, + Goihw32g = dnnl_Goihw32g, + gOwhi16o = dnnl_gOwhi16o, + IOw4i8o8i4o = dnnl_IOw4i8o8i4o, + IOhw4i8o8i4o = dnnl_IOhw4i8o8i4o, + IOdhw4i8o8i4o = dnnl_IOdhw4i8o8i4o, + gIOw4i8o8i4o = dnnl_gIOw4i8o8i4o, + gIOhw4i8o8i4o = dnnl_gIOhw4i8o8i4o, + gIOdhw4i8o8i4o = dnnl_gIOdhw4i8o8i4o, + gOIdhw8o16i2o = dnnl_gOIdhw8o16i2o, + gIOdhw8o16i2o = dnnl_gIOdhw8o16i2o, + Goidhw32g = dnnl_Goidhw32g, + OI16i32o4i = dnnl_OI16i32o4i, + OI16i48o4i = dnnl_OI16i48o4i, + OI16i64o4i = dnnl_OI16i64o4i, + OI16i16o2i = dnnl_OI16i16o2i, + OI16i32o2i = dnnl_OI16i32o2i, + OI16i48o2i = dnnl_OI16i48o2i, + OI16i64o2i = dnnl_OI16i64o2i, + aBdeC16c16b4c = dnnl_aBdeC16c16b4c, + AcB16b16a2b = dnnl_AcB16b16a2b, + aBdC16c16b2c = dnnl_aBdC16c16b2c, + AcB16b16a4b = dnnl_AcB16b16a4b, + aBdC16c16b4c = dnnl_aBdC16c16b4c, + AcdB16b16a2b = dnnl_AcdB16b16a2b, + aBdefC16c16b4c = dnnl_aBdefC16c16b4c, + AcdeB16b16a4b = dnnl_AcdeB16b16a4b, + AcB16b32a2b = dnnl_AcB16b32a2b, + AcB16b32a4b = dnnl_AcB16b32a4b, + AcB16b48a2b = dnnl_AcB16b48a2b, + AcB16b48a4b = dnnl_AcB16b48a4b, + AcB16b64a2b = dnnl_AcB16b64a2b, + AcB16b64a4b = dnnl_AcB16b64a4b, + aBdC16c32b2c = dnnl_aBdC16c32b2c, + aBdC16c32b4c = dnnl_aBdC16c32b4c, + aBdC16c48b2c = dnnl_aBdC16c48b2c, + aBdC16c48b4c = dnnl_aBdC16c48b4c, + aBdC16c64b2c = dnnl_aBdC16c64b2c, + aBdC16c64b4c = dnnl_aBdC16c64b4c, + AcdB16b32a2b = dnnl_AcdB16b32a2b, + AcdB16b32a4b = dnnl_AcdB16b32a4b, + AcdB16b48a2b = dnnl_AcdB16b48a2b, + AcdB16b48a4b = dnnl_AcdB16b48a4b, + AcdB16b64a2b = dnnl_AcdB16b64a2b, + AcdB16b64a4b = dnnl_AcdB16b64a4b, + aBdeC16c32b2c = dnnl_aBdeC16c32b2c, + aBdeC16c32b4c = dnnl_aBdeC16c32b4c, + aBdeC16c48b2c = dnnl_aBdeC16c48b2c, + aBdeC16c48b4c = dnnl_aBdeC16c48b4c, + aBdeC16c64b2c = dnnl_aBdeC16c64b2c, + aBdeC16c64b4c = dnnl_aBdeC16c64b4c, + AcdeB16b32a2b = dnnl_AcdeB16b32a2b, + AcdeB16b32a4b = dnnl_AcdeB16b32a4b, + AcdeB16b48a2b = dnnl_AcdeB16b48a2b, + AcdeB16b48a4b = dnnl_AcdeB16b48a4b, + AcdeB16b64a2b = dnnl_AcdeB16b64a2b, + AcdeB16b64a4b = dnnl_AcdeB16b64a4b, + aBdefC16c32b2c = dnnl_aBdefC16c32b2c, + aBdefC16c32b4c = dnnl_aBdefC16c32b4c, + aBdefC16c48b2c = dnnl_aBdefC16c48b2c, + aBdefC16c48b4c = dnnl_aBdefC16c48b4c, + aBdefC16c64b2c = dnnl_aBdefC16c64b2c, + aBdefC16c64b4c = dnnl_aBdefC16c64b4c, + OwI16i16o2i = dnnl_OwI16i16o2i, + gOwI16i16o2i = dnnl_gOwI16i16o2i, + OhwI16i16o2i = dnnl_OhwI16i16o2i, + gOhwI16i16o2i = dnnl_gOhwI16i16o2i, + OdhwI16i16o2i = dnnl_OdhwI16i16o2i, + gOdhwI16i16o2i = dnnl_gOdhwI16i16o2i, + OwI16i16o4i = dnnl_OwI16i16o4i, + gOwI16i16o4i = dnnl_gOwI16i16o4i, + OhwI16i16o4i = dnnl_OhwI16i16o4i, + gOhwI16i16o4i = dnnl_gOhwI16i16o4i, + OdhwI16i16o4i = dnnl_OdhwI16i16o4i, + gOdhwI16i16o4i = dnnl_gOdhwI16i16o4i, + OwI16i32o2i = dnnl_OwI16i32o2i, + OwI16i32o4i = dnnl_OwI16i32o4i, + OwI16i48o2i = dnnl_OwI16i48o2i, + OwI16i48o4i = dnnl_OwI16i48o4i, + OwI16i64o2i = dnnl_OwI16i64o2i, + OwI16i64o4i = dnnl_OwI16i64o4i, + gOwI16i32o2i = dnnl_gOwI16i32o2i, + gOwI16i32o4i = dnnl_gOwI16i32o4i, + gOwI16i48o2i = dnnl_gOwI16i48o2i, + gOwI16i48o4i = dnnl_gOwI16i48o4i, + gOwI16i64o2i = dnnl_gOwI16i64o2i, + gOwI16i64o4i = dnnl_gOwI16i64o4i, + OhwI16i32o2i = dnnl_OhwI16i32o2i, + OhwI16i32o4i = dnnl_OhwI16i32o4i, + OhwI16i48o2i = dnnl_OhwI16i48o2i, + OhwI16i48o4i = dnnl_OhwI16i48o4i, + OhwI16i64o2i = dnnl_OhwI16i64o2i, + OhwI16i64o4i = dnnl_OhwI16i64o4i, + gOhwI16i32o2i = dnnl_gOhwI16i32o2i, + gOhwI16i32o4i = dnnl_gOhwI16i32o4i, + gOhwI16i48o2i = dnnl_gOhwI16i48o2i, + gOhwI16i48o4i = dnnl_gOhwI16i48o4i, + gOhwI16i64o2i = dnnl_gOhwI16i64o2i, + gOhwI16i64o4i = dnnl_gOhwI16i64o4i, + OdhwI16i32o2i = dnnl_OdhwI16i32o2i, + OdhwI16i32o4i = dnnl_OdhwI16i32o4i, + OdhwI16i48o2i = dnnl_OdhwI16i48o2i, + OdhwI16i48o4i = dnnl_OdhwI16i48o4i, + OdhwI16i64o2i = dnnl_OdhwI16i64o2i, + OdhwI16i64o4i = dnnl_OdhwI16i64o4i, + IdhwO16o32i2o = dnnl_IdhwO16o32i2o, + IdhwO16o32i4o = dnnl_IdhwO16o32i4o, + IdhwO16o48i2o = dnnl_IdhwO16o48i2o, + IdhwO16o48i4o = dnnl_IdhwO16o48i4o, + IdhwO16o64i2o = dnnl_IdhwO16o64i2o, + IdhwO16o64i4o = dnnl_IdhwO16o64i4o, + gOdhwI16i32o2i = dnnl_gOdhwI16i32o2i, + gOdhwI16i32o4i = dnnl_gOdhwI16i32o4i, + gOdhwI16i48o2i = dnnl_gOdhwI16i48o2i, + gOdhwI16i48o4i = dnnl_gOdhwI16i48o4i, + gOdhwI16i64o2i = dnnl_gOdhwI16i64o2i, + gOdhwI16i64o4i = dnnl_gOdhwI16i64o4i, + gIdhwO16o32i2o = dnnl_gIdhwO16o32i2o, + gIdhwO16o32i4o = dnnl_gIdhwO16o32i4o, + gIdhwO16o48i2o = dnnl_gIdhwO16o48i2o, + gIdhwO16o48i4o = dnnl_gIdhwO16o48i4o, + gIdhwO16o64i2o = dnnl_gIdhwO16o64i2o, + gIdhwO16o64i4o = dnnl_gIdhwO16o64i4o, + IwO16o16i2o = dnnl_IwO16o16i2o, + IwO16o16i4o = dnnl_IwO16o16i4o, + IhwO16o16i2o = dnnl_IhwO16o16i2o, + IhwO16o16i4o = dnnl_IhwO16o16i4o, + IdhwO16o16i2o = dnnl_IdhwO16o16i2o, + IdhwO16o16i4o = dnnl_IdhwO16o16i4o, + gIwO16o16i2o = dnnl_gIwO16o16i2o, + gIwO16o16i4o = dnnl_gIwO16o16i4o, + gIhwO16o16i2o = dnnl_gIhwO16o16i2o, + gIhwO16o16i4o = dnnl_gIhwO16o16i4o, + gIdhwO16o16i2o = dnnl_gIdhwO16o16i2o, + gIdhwO16o16i4o = dnnl_gIdhwO16o16i4o, + IwO16o32i2o = dnnl_IwO16o32i2o, + IwO16o32i4o = dnnl_IwO16o32i4o, + IwO16o48i2o = dnnl_IwO16o48i2o, + IwO16o48i4o = dnnl_IwO16o48i4o, + IwO16o64i2o = dnnl_IwO16o64i2o, + IwO16o64i4o = dnnl_IwO16o64i4o, + gIwO16o32i2o = dnnl_gIwO16o32i2o, + gIwO16o32i4o = dnnl_gIwO16o32i4o, + gIwO16o48i2o = dnnl_gIwO16o48i2o, + gIwO16o48i4o = dnnl_gIwO16o48i4o, + gIwO16o64i2o = dnnl_gIwO16o64i2o, + gIwO16o64i4o = dnnl_gIwO16o64i4o, + IhwO16o32i2o = dnnl_IhwO16o32i2o, + IhwO16o32i4o = dnnl_IhwO16o32i4o, + IhwO16o48i2o = dnnl_IhwO16o48i2o, + IhwO16o48i4o = dnnl_IhwO16o48i4o, + IhwO16o64i2o = dnnl_IhwO16o64i2o, + IhwO16o64i4o = dnnl_IhwO16o64i4o, + gIhwO16o32i2o = dnnl_gIhwO16o32i2o, + gIhwO16o32i4o = dnnl_gIhwO16o32i4o, + gIhwO16o48i2o = dnnl_gIhwO16o48i2o, + gIhwO16o48i4o = dnnl_gIhwO16o48i4o, + gIhwO16o64i2o = dnnl_gIhwO16o64i2o, + gIhwO16o64i4o = dnnl_gIhwO16o64i4o, + aBdeC16c16b2c = dnnl_aBdeC16c16b2c, + aBdefC16c16b2c = dnnl_aBdefC16c16b2c, + AcdB16b16a4b = dnnl_AcdB16b16a4b, + AcdeB16b16a2b = dnnl_AcdeB16b16a2b, + hwioG16g = dnnl_hwioG16g, + hwioG8g = dnnl_hwioG8g, + dhwioG16g = dnnl_dhwioG16g, + dhwioG8g = dnnl_dhwioG8g, + ABc4a2b = dnnl_ABc4a2b, + ABc8a2b = dnnl_ABc8a2b, + ABcd4a2b = dnnl_ABcd4a2b, + ABcde4a2b = dnnl_ABcde4a2b, + ABcde8a2b = dnnl_ABcde8a2b, + ABcd4a8b8a2b = dnnl_ABcd4a8b8a2b, + NCdhw40n32c = dnnl_NCdhw40n32c, + NChw40n32c = dnnl_NChw40n32c, + NCw40n32c = dnnl_NCw40n32c, + OIdhw4o8i8o2i = dnnl_OIdhw4o8i8o2i, + OIhw4o8i8o2i = dnnl_OIhw4o8i8o2i, + OIw4o8i8o2i = dnnl_OIw4o8i8o2i, + gOIdhw4o8i8o2i = dnnl_gOIdhw4o8i8o2i, + gOIhw4o8i8o2i = dnnl_gOIhw4o8i8o2i, + gOIw4o8i8o2i = dnnl_gOIw4o8i8o2i, + IOdhw4i8o8i2o = dnnl_IOdhw4i8o8i2o, + IOhw4i8o8i2o = dnnl_IOhw4i8o8i2o, + IOw4i8o8i2o = dnnl_IOw4i8o8i2o, + gIOdhw4i8o8i2o = dnnl_gIOdhw4i8o8i2o, + gIOhw4i8o8i2o = dnnl_gIOhw4i8o8i2o, + gIOw4i8o8i2o = dnnl_gIOw4i8o8i2o, + aBCd8b2c = dnnl_aBCd8b2c, + ABcde40a16b = dnnl_ABcde40a16b, + ABcde40a32b = dnnl_ABcde40a32b, + aBCde8b2c = dnnl_aBCde8b2c, + ABcde4a8b8a2b = dnnl_ABcde4a8b8a2b, + ABc4a8b8a2b = dnnl_ABc4a8b8a2b, + aBCdef4b8c8b2c = dnnl_aBCdef4b8c8b2c, + aBCde4b8c8b2c = dnnl_aBCde4b8c8b2c, + aBCd4b8c8b2c = dnnl_aBCd4b8c8b2c, + BAcde4b8a8b2a = dnnl_BAcde4b8a8b2a, + BAcd4b8a8b2a = dnnl_BAcd4b8a8b2a, + BAc4b8a8b2a = dnnl_BAc4b8a8b2a, + aCBdef4c8b8c2b = dnnl_aCBdef4c8b8c2b, + aCBde4c8b8c2b = dnnl_aCBde4c8b8c2b, + aCBd4c8b8c2b = dnnl_aCBd4c8b8c2b, + aBCdef8b2c = dnnl_aBCdef8b2c, + AB32a16b = dnnl_AB32a16b, + AB32a32b = dnnl_AB32a32b, + BA4b8a8b2a = dnnl_BA4b8a8b2a, + BA4b8a8b4a = dnnl_BA4b8a8b4a, + aBC32b16c = dnnl_aBC32b16c, + aBC32b32c = dnnl_aBC32b32c, + aCB4c8b8c2b = dnnl_aCB4c8b8c2b, + aCB4c8b8c4b = dnnl_aCB4c8b8c4b, + ABc2b8a16b4a = dnnl_ABc2b8a16b4a, + ABcd2b8a16b4a = dnnl_ABcd2b8a16b4a, + ABcde2b8a16b4a = dnnl_ABcde2b8a16b4a, + ABc2a8b16a4b = dnnl_ABc2a8b16a4b, + ABc2a8b16a2b = dnnl_ABc2a8b16a2b, + ABc2b32a8b = dnnl_ABc2b32a8b, + ABcd2a8b16a4b = dnnl_ABcd2a8b16a4b, + ABcd2a8b16a2b = dnnl_ABcd2a8b16a2b, + aCBd2c8b16c2b = dnnl_aCBd2c8b16c2b, + ABcd2b32a8b = dnnl_ABcd2b32a8b, + aBCd2c8b16c2b = dnnl_aBCd2c8b16c2b, + ABcde2a8b16a4b = dnnl_ABcde2a8b16a4b, + ABcde2a8b16a2b = dnnl_ABcde2a8b16a2b, + aCBde2c8b16c2b = dnnl_aCBde2c8b16c2b, + ABcde2b32a8b = dnnl_ABcde2b32a8b, + aBC2b8c16b2c = dnnl_aBC2b8c16b2c, + aBCd2b8c16b2c = dnnl_aBCd2b8c16b2c, + aBCde2b8c16b2c = dnnl_aBCde2b8c16b2c, + aBCdef2b8c16b2c = dnnl_aBCdef2b8c16b2c, + BAcde2b8a16b4a = dnnl_BAcde2b8a16b4a, + BAcd2b8a16b4a = dnnl_BAcd2b8a16b4a, + BAc2b8a16b4a = dnnl_BAc2b8a16b4a, + BAcde2b8a16b2a = dnnl_BAcde2b8a16b2a, + BAcd2b8a16b2a = dnnl_BAcd2b8a16b2a, + BAc2b8a16b2a = dnnl_BAc2b8a16b2a, + aBCde2c8b16c2b = dnnl_aBCde2c8b16c2b, + aBCdef2c8b16c2b = dnnl_aBCdef2c8b16c2b, + aCBdef2c8b16c2b = dnnl_aCBdef2c8b16c2b, + aBCd2b8c16b4c = dnnl_aBCd2b8c16b4c, + aBCde2b8c16b4c = dnnl_aBCde2b8c16b4c, + NCdhw40n16c = dnnl_NCdhw40n16c, + NCw40n16c = dnnl_NCw40n16c, + NChw40n16c = dnnl_NChw40n16c, + NCw2c32n8c = dnnl_NCw2c32n8c, + NChw2c32n8c = dnnl_NChw2c32n8c, + NCdhw2c32n8c = dnnl_NCdhw2c32n8c, + OIw2i8o16i4o = dnnl_OIw2i8o16i4o, + OIhw2i8o16i4o = dnnl_OIhw2i8o16i4o, + OIdhw2i8o16i4o = dnnl_OIdhw2i8o16i4o, + OIw2o8i16o4i = dnnl_OIw2o8i16o4i, + OIw2o8i16o2i = dnnl_OIw2o8i16o2i, + IOw2i8o16i4o = dnnl_IOw2i8o16i4o, + IOw2i8o16i2o = dnnl_IOw2i8o16i2o, + OIhw2o8i16o4i = dnnl_OIhw2o8i16o4i, + OIhw2o8i16o2i = dnnl_OIhw2o8i16o2i, + IOhw2i8o16i4o = dnnl_IOhw2i8o16i4o, + IOhw2i8o16i2o = dnnl_IOhw2i8o16i2o, + OIdhw2o8i16o4i = dnnl_OIdhw2o8i16o4i, + OIdhw2o8i16o2i = dnnl_OIdhw2o8i16o2i, + IOdhw2i8o16i4o = dnnl_IOdhw2i8o16i4o, + IOdhw2i8o16i2o = dnnl_IOdhw2i8o16i2o, + gOIw2o8i16o2i = dnnl_gOIw2o8i16o2i, + gIOw2i8o16i2o = dnnl_gIOw2i8o16i2o, + gIOhw2i8o16i2o = dnnl_gIOhw2i8o16i2o, + gIOdhw2i8o16i2o = dnnl_gIOdhw2i8o16i2o, + gOIhw2o8i16o2i = dnnl_gOIhw2o8i16o2i, + gOIdhw2o8i16o2i = dnnl_gOIdhw2o8i16o2i, + gOIw2o8i16o4i = dnnl_gOIw2o8i16o4i, + gOIhw2o8i16o4i = dnnl_gOIhw2o8i16o4i, + BA4b8a16b2a = dnnl_BA4b8a16b2a, + BA4b8a16b4a = dnnl_BA4b8a16b4a, + aCB4c8b16c2b = dnnl_aCB4c8b16c2b, + aCB4c8b16c4b = dnnl_aCB4c8b16c4b, + aCB16c2b = dnnl_aCB16c2b, + aCB16c4b = dnnl_aCB16c4b, + BA16b2a = dnnl_BA16b2a, + BA16b4a = dnnl_BA16b4a, + BA4b4a = dnnl_BA4b4a, + BA8b4a = dnnl_BA8b4a, + aBC16b16c = dnnl_aBC16b16c, + aBC16b32c = dnnl_aBC16b32c, + AB16a16b = dnnl_AB16a16b, + AB16a32b = dnnl_AB16a32b, + ABcde16a16b2a = dnnl_ABcde16a16b2a, + aBCdef16b16c2b = dnnl_aBCdef16b16c2b, + Acedb16a = dnnl_Acedb16a, + aBdfec16b = dnnl_aBdfec16b, + Odwhi16o = dnnl_Odwhi16o, + gOdwhi16o = dnnl_gOdwhi16o, + abdEC64e2c = dnnl_abdEC64e2c, + abdEC64e4c = dnnl_abdEC64e4c, + ldgOI64o2i = abdEC64e2c, + ldgOI64o4i = abdEC64e4c, + abCd4c = dnnl_abCd4c, + abCde4c = dnnl_abCde4c, + abCdef4c = dnnl_abCdef4c, + abCde32c = dnnl_abCde32c, + abCdef32c = dnnl_abCdef32c, + aCdefB16b32c2b = dnnl_aCdefB16b32c2b, + aCdefB16b32c4b = dnnl_aCdefB16b32c4b, + aCdefB16b48c2b = dnnl_aCdefB16b48c2b, + aCdefB16b48c4b = dnnl_aCdefB16b48c4b, + aCdefB16b64c2b = dnnl_aCdefB16b64c2b, + aCdefB16b64c4b = dnnl_aCdefB16b64c4b, + BcdeA16a32b2a = dnnl_BcdeA16a32b2a, + BcdeA16a32b4a = dnnl_BcdeA16a32b4a, + BcdeA16a48b2a = dnnl_BcdeA16a48b2a, + BcdeA16a48b4a = dnnl_BcdeA16a48b4a, + BcdeA16a64b2a = dnnl_BcdeA16a64b2a, + BcdeA16a64b4a = dnnl_BcdeA16a64b4a, + aCdefb32c = dnnl_aCdefb32c, + aCdefB32c2b = dnnl_aCdefB32c2b, + aCdefB32c4b = dnnl_aCdefB32c4b, + aCdefb48c = dnnl_aCdefb48c, + aCdefB48c2b = dnnl_aCdefB48c2b, + aCdefB48c4b = dnnl_aCdefB48c4b, + aCdefb64c = dnnl_aCdefb64c, + aCdefB64c2b = dnnl_aCdefB64c2b, + aCdefB64c4b = dnnl_aCdefB64c4b, + Bcdea32b = dnnl_Bcdea32b, + BcdeA32b2a = dnnl_BcdeA32b2a, + BcdeA32b4a = dnnl_BcdeA32b4a, + Bcdea48b = dnnl_Bcdea48b, + BcdeA48b2a = dnnl_BcdeA48b2a, + BcdeA48b4a = dnnl_BcdeA48b4a, + Bcdea64b = dnnl_Bcdea64b, + BcdeA64b2a = dnnl_BcdeA64b2a, + BcdeA64b4a = dnnl_BcdeA64b4a, + Bca32b = dnnl_Bca32b, + BcA32b2a = dnnl_BcA32b2a, + BcA32b4a = dnnl_BcA32b4a, + Bca48b = dnnl_Bca48b, + BcA48b2a = dnnl_BcA48b2a, + BcA48b4a = dnnl_BcA48b4a, + Bca64b = dnnl_Bca64b, + BcA64b2a = dnnl_BcA64b2a, + BcA64b4a = dnnl_BcA64b4a, + aCdb32c = dnnl_aCdb32c, + aCdB32c2b = dnnl_aCdB32c2b, + aCdB32c4b = dnnl_aCdB32c4b, + aCdb48c = dnnl_aCdb48c, + aCdB48c2b = dnnl_aCdB48c2b, + aCdB48c4b = dnnl_aCdB48c4b, + aCdb64c = dnnl_aCdb64c, + aCdB64c2b = dnnl_aCdB64c2b, + aCdB64c4b = dnnl_aCdB64c4b, + BcA16a16b2a = dnnl_BcA16a16b2a, + BcA16a16b4a = dnnl_BcA16a16b4a, + BcdA16a16b2a = dnnl_BcdA16a16b2a, + BcdA16a16b4a = dnnl_BcdA16a16b4a, + BcdeA16a16b2a = dnnl_BcdeA16a16b2a, + BcdeA16a16b4a = dnnl_BcdeA16a16b4a, + aCdB16b16c2b = dnnl_aCdB16b16c2b, + aCdB16b16c4b = dnnl_aCdB16b16c4b, + aCdeB16b16c2b = dnnl_aCdeB16b16c2b, + aCdeB16b16c4b = dnnl_aCdeB16b16c4b, + aCdefB16b16c2b = dnnl_aCdefB16b16c2b, + aCdefB16b16c4b = dnnl_aCdefB16b16c4b, + BcA16a32b2a = dnnl_BcA16a32b2a, + BcA16a32b4a = dnnl_BcA16a32b4a, + BcA16a48b2a = dnnl_BcA16a48b2a, + BcA16a48b4a = dnnl_BcA16a48b4a, + BcA16a64b2a = dnnl_BcA16a64b2a, + BcA16a64b4a = dnnl_BcA16a64b4a, + aCdB16b32c2b = dnnl_aCdB16b32c2b, + aCdB16b32c4b = dnnl_aCdB16b32c4b, + aCdB16b48c2b = dnnl_aCdB16b48c2b, + aCdB16b48c4b = dnnl_aCdB16b48c4b, + aCdB16b64c2b = dnnl_aCdB16b64c2b, + aCdB16b64c4b = dnnl_aCdB16b64c4b, + BcdA16a32b2a = dnnl_BcdA16a32b2a, + BcdA16a32b4a = dnnl_BcdA16a32b4a, + BcdA16a48b2a = dnnl_BcdA16a48b2a, + BcdA16a48b4a = dnnl_BcdA16a48b4a, + BcdA16a64b2a = dnnl_BcdA16a64b2a, + BcdA16a64b4a = dnnl_BcdA16a64b4a, + aCdeB16b32c2b = dnnl_aCdeB16b32c2b, + aCdeB16b32c4b = dnnl_aCdeB16b32c4b, + aCdeB16b48c2b = dnnl_aCdeB16b48c2b, + aCdeB16b48c4b = dnnl_aCdeB16b48c4b, + aCdeB16b64c2b = dnnl_aCdeB16b64c2b, + aCdeB16b64c4b = dnnl_aCdeB16b64c4b, + Bca16b = dnnl_Bca16b, + BcA16b2a = dnnl_BcA16b2a, + BcA16b4a = dnnl_BcA16b4a, + Bcda16b = dnnl_Bcda16b, + BcdA16b2a = dnnl_BcdA16b2a, + BcdA16b4a = dnnl_BcdA16b4a, + Bcdea16b = dnnl_Bcdea16b, + BcdeA16b2a = dnnl_BcdeA16b2a, + BcdeA16b4a = dnnl_BcdeA16b4a, + aCdb16c = dnnl_aCdb16c, + aCdB16c2b = dnnl_aCdB16c2b, + aCdB16c4b = dnnl_aCdB16c4b, + aCdeb16c = dnnl_aCdeb16c, + aCdeB16c2b = dnnl_aCdeB16c2b, + aCdeB16c4b = dnnl_aCdeB16c4b, + aCdefb16c = dnnl_aCdefb16c, + aCdefB16c2b = dnnl_aCdefB16c2b, + aCdefB16c4b = dnnl_aCdefB16c4b, + Bcda32b = dnnl_Bcda32b, + BcdA32b2a = dnnl_BcdA32b2a, + BcdA32b4a = dnnl_BcdA32b4a, + Bcda48b = dnnl_Bcda48b, + BcdA48b2a = dnnl_BcdA48b2a, + BcdA48b4a = dnnl_BcdA48b4a, + Bcda64b = dnnl_Bcda64b, + BcdA64b2a = dnnl_BcdA64b2a, + BcdA64b4a = dnnl_BcdA64b4a, + aCdeb32c = dnnl_aCdeb32c, + aCdeB32c2b = dnnl_aCdeB32c2b, + aCdeB32c4b = dnnl_aCdeB32c4b, + aCdeb48c = dnnl_aCdeb48c, + aCdeB48c2b = dnnl_aCdeB48c2b, + aCdeB48c4b = dnnl_aCdeB48c4b, + aCdeb64c = dnnl_aCdeb64c, + aCdeB64c2b = dnnl_aCdeB64c2b, + aCdeB64c4b = dnnl_aCdeB64c4b, + NChw16n32c = dnnl_NChw16n32c, + goIw4i = dnnl_goIw4i, + goIw32i = dnnl_goIw32i, + goIhw4i = dnnl_goIhw4i, + goIhw32i = dnnl_goIhw32i, + goIdhw4i = dnnl_goIdhw4i, + goIdhw32i = dnnl_goIdhw32i, + cab = dnnl_cab, + cdab = dnnl_cdab, + cdeab = dnnl_cdeab, + woi = dnnl_woi, + hwoi = dnnl_hwoi, + dhwoi = dnnl_dhwoi, + Owi24o = dnnl_Owi24o, + Ohwi24o = dnnl_Ohwi24o, + Odhwi24o = dnnl_Odhwi24o, + gOwi24o = dnnl_gOwi24o, + gOhwi24o = dnnl_gOhwi24o, + gOdhwi24o = dnnl_gOdhwi24o, + OwI24o2i = dnnl_OwI24o2i, + OhwI24o2i = dnnl_OhwI24o2i, + OdhwI24o2i = dnnl_OdhwI24o2i, + gOwI24o2i = dnnl_gOwI24o2i, + gOhwI24o2i = dnnl_gOhwI24o2i, + gOdhwI24o2i = dnnl_gOdhwI24o2i, + OwI24o4i = dnnl_OwI24o4i, + OhwI24o4i = dnnl_OhwI24o4i, + OdhwI24o4i = dnnl_OdhwI24o4i, + gOwI24o4i = dnnl_gOwI24o4i, + gOhwI24o4i = dnnl_gOhwI24o4i, + gOdhwI24o4i = dnnl_gOdhwI24o4i, + OI8i32o = dnnl_OI8i32o, + OIw8i32o = dnnl_OIw8i32o, + OwI8i32o = dnnl_OwI8i32o, + OIhw8i32o = dnnl_OIhw8i32o, + OhwI8i32o = dnnl_OhwI8i32o, + OIdhw8i32o = dnnl_OIdhw8i32o, + OdhwI8i32o = dnnl_OdhwI8i32o, + OI8i24o = dnnl_OI8i24o, + OIw8i24o = dnnl_OIw8i24o, + OwI8i24o = dnnl_OwI8i24o, + OIhw8i24o = dnnl_OIhw8i24o, + OhwI8i24o = dnnl_OhwI8i24o, + OIdhw8i24o = dnnl_OIdhw8i24o, + OdhwI8i24o = dnnl_OdhwI8i24o, + OI8i16o = dnnl_OI8i16o, + OIw8i16o = dnnl_OIw8i16o, + OwI8i16o = dnnl_OwI8i16o, + OIhw8i16o = dnnl_OIhw8i16o, + OhwI8i16o = dnnl_OhwI8i16o, + OIdhw8i16o = dnnl_OIdhw8i16o, + OdhwI8i16o = dnnl_OdhwI8i16o, + OI8i8o = dnnl_OI8i8o, + AB4b8a4b = dnnl_AB4b8a4b, + AB4b24a4b = dnnl_AB4b24a4b, + ABc4b8a4b = dnnl_ABc4b8a4b, + AcB4b8a4b = dnnl_AcB4b8a4b, + ABc4b24a4b = dnnl_ABc4b24a4b, + AcB4b24a4b = dnnl_AcB4b24a4b, + ABcd4b8a4b = dnnl_ABcd4b8a4b, + AcdB4b8a4b = dnnl_AcdB4b8a4b, + ABcd4b24a4b = dnnl_ABcd4b24a4b, + AcdB4b24a4b = dnnl_AcdB4b24a4b, + ABcde4b8a4b = dnnl_ABcde4b8a4b, + AcdeB4b8a4b = dnnl_AcdeB4b8a4b, + ABcde4b24a4b = dnnl_ABcde4b24a4b, + AcdeB4b24a4b = dnnl_AcdeB4b24a4b, + Bca8b = dnnl_Bca8b, + BcA8b2a = dnnl_BcA8b2a, + Bcda8b = dnnl_Bcda8b, + BcdA8b2a = dnnl_BcdA8b2a, + Bcdea8b = dnnl_Bcdea8b, + BcdeA8b2a = dnnl_BcdeA8b2a, + aCdb8c = dnnl_aCdb8c, + aCdB8c2b = dnnl_aCdB8c2b, + aCdeb8c = dnnl_aCdeb8c, + aCdeB8c2b = dnnl_aCdeB8c2b, + aCdefb8c = dnnl_aCdefb8c, + aCdefB8c2b = dnnl_aCdefB8c2b, + Bca24b = dnnl_Bca24b, + BcA24b2a = dnnl_BcA24b2a, + Bcda24b = dnnl_Bcda24b, + BcdA24b2a = dnnl_BcdA24b2a, + Bcdea24b = dnnl_Bcdea24b, + BcdeA24b2a = dnnl_BcdeA24b2a, + aCdb24c = dnnl_aCdb24c, + aCdB24c2b = dnnl_aCdB24c2b, + aCdeb24c = dnnl_aCdeb24c, + aCdeB24c2b = dnnl_aCdeB24c2b, + aCdefb24c = dnnl_aCdefb24c, + aCdefB24c2b = dnnl_aCdefB24c2b, + Iwo8i = dnnl_Iwo8i, + IwO8i2o = dnnl_IwO8i2o, + Iwo24i = dnnl_Iwo24i, + IwO24i2o = dnnl_IwO24i2o, + Ihwo8i = dnnl_Ihwo8i, + IhwO8i2o = dnnl_IhwO8i2o, + Ihwo24i = dnnl_Ihwo24i, + IhwO24i2o = dnnl_IhwO24i2o, + Idhwo8i = dnnl_Idhwo8i, + IdhwO8i2o = dnnl_IdhwO8i2o, + Idhwo24i = dnnl_Idhwo24i, + IdhwO24i2o = dnnl_IdhwO24i2o, + gIwo8i = dnnl_gIwo8i, + gIwO8i2o = dnnl_gIwO8i2o, + gIwo24i = dnnl_gIwo24i, + gIwO24i2o = dnnl_gIwO24i2o, + gIhwo8i = dnnl_gIhwo8i, + gIhwO8i2o = dnnl_gIhwO8i2o, + gIhwo24i = dnnl_gIhwo24i, + gIhwO24i2o = dnnl_gIhwO24i2o, + gIdhwo8i = dnnl_gIdhwo8i, + gIdhwO8i2o = dnnl_gIdhwO8i2o, + gIdhwo24i = dnnl_gIdhwo24i, + gIdhwO24i2o = dnnl_gIdhwO24i2o, + OhwI24o = dnnl_OhwI24o, + gOhwI24o = dnnl_gOhwI24o, + AB8b24a2b = dnnl_AB8b24a2b, + ABc8b24a2b = dnnl_ABc8b24a2b, + AcB8b24a2b = dnnl_AcB8b24a2b, + ABcd8b24a2b = dnnl_ABcd8b24a2b, + AcdB8b24a2b = dnnl_AcdB8b24a2b, + ABcde8b24a2b = dnnl_ABcde8b24a2b, + AcdeB8b24a2b = dnnl_AcdeB8b24a2b, + AB8b8a2b = dnnl_AB8b8a2b, + ABc8b8a2b = dnnl_ABc8b8a2b, + AcB8b8a2b = dnnl_AcB8b8a2b, + ABcd8b8a2b = dnnl_ABcd8b8a2b, + AcdB8b8a2b = dnnl_AcdB8b8a2b, + ABcde8b8a2b = dnnl_ABcde8b8a2b, + AcdeB8b8a2b = dnnl_AcdeB8b8a2b, + OI8i8o2i = dnnl_OI8i8o2i, + OI8i24o2i = dnnl_OI8i24o2i, + OIw8i8o2i = dnnl_OIw8i8o2i, + OwI8i8o2i = dnnl_OwI8i8o2i, + OIw8i24o2i = dnnl_OIw8i24o2i, + OwI8i24o2i = dnnl_OwI8i24o2i, + OIhw8i8o2i = dnnl_OIhw8i8o2i, + OhwI8i8o2i = dnnl_OhwI8i8o2i, + OIhw8i24o2i = dnnl_OIhw8i24o2i, + OhwI8i24o2i = dnnl_OhwI8i24o2i, + OIdhw8i8o2i = dnnl_OIdhw8i8o2i, + OdhwI8i8o2i = dnnl_OdhwI8i8o2i, + OIdhw8i24o2i = dnnl_OIdhw8i24o2i, + OdhwI8i24o2i = dnnl_OdhwI8i24o2i, + BcA8b4a = dnnl_BcA8b4a, + BcdA8b4a = dnnl_BcdA8b4a, + BcdeA8b4a = dnnl_BcdeA8b4a, + aCdB8c4b = dnnl_aCdB8c4b, + aCdeB8c4b = dnnl_aCdeB8c4b, + aCdefB8c4b = dnnl_aCdefB8c4b, + BcA24b4a = dnnl_BcA24b4a, + BcdA24b4a = dnnl_BcdA24b4a, + BcdeA24b4a = dnnl_BcdeA24b4a, + aCdB24c4b = dnnl_aCdB24c4b, + aCdeB24c4b = dnnl_aCdeB24c4b, + aCdefB24c4b = dnnl_aCdefB24c4b, + ABc16a4b = dnnl_ABc16a4b, + ABcd16a4b = dnnl_ABcd16a4b, + ABcde16a4b = dnnl_ABcde16a4b, + IwO8i4o = dnnl_IwO8i4o, + IwO24i4o = dnnl_IwO24i4o, + IhwO8i4o = dnnl_IhwO8i4o, + IhwO24i4o = dnnl_IhwO24i4o, + IdhwO8i4o = dnnl_IdhwO8i4o, + IdhwO24i4o = dnnl_IdhwO24i4o, + gIwO8i4o = dnnl_gIwO8i4o, + gIwO24i4o = dnnl_gIwO24i4o, + gIhwO8i4o = dnnl_gIhwO8i4o, + gIhwO24i4o = dnnl_gIhwO24i4o, + gIdhwO8i4o = dnnl_gIdhwO8i4o, + gIdhwO24i4o = dnnl_gIdhwO24i4o, + BA2a24b = dnnl_BA2a24b, + aCB2b24c = dnnl_aCB2b24c, + BA2a8b = dnnl_BA2a8b, + aCB2b8c = dnnl_aCB2b8c, + BA8a24b = dnnl_BA8a24b, + aCB8b24c = dnnl_aCB8b24c, + BA8a16b = dnnl_BA8a16b, + aCB8b16c = dnnl_aCB8b16c, + BA8a8b = dnnl_BA8a8b, + aCB8b8c = dnnl_aCB8b8c, + bcad = dnnl_bcad, + cabd = dnnl_cabd, + dabc = dnnl_dabc, + }; + + /// A memory descriptor. + struct desc : public handle { + using handle::handle; + + friend struct memory; + + /// Constructs a zero (empty) memory descriptor. Such a memory + /// descriptor can be used to indicate absence of an argument. + desc() { + dnnl_memory_desc_t zero_md = nullptr; + error::wrap_c_api( + dnnl_memory_desc_create_with_tag(&zero_md, 0, nullptr, + dnnl_data_type_undef, dnnl_format_tag_undef), + "could not create a zero memory descriptor"); + reset(zero_md); + } + + /// Constructs a memory descriptor. + /// + /// @note + /// The logical order of dimensions corresponds to the `abc...` + /// format tag, and the physical meaning of the dimensions depends + /// both on the primitive that would operate on this memory and + /// the operation context. + /// + /// @param adims Tensor dimensions. + /// @param adata_type Data precision/type. + /// @param aformat_tag Memory format tag. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be constructed. This flag is + /// optional and defaults to false. + desc(const dims &adims, data_type adata_type, format_tag aformat_tag, + bool allow_empty = false) { + validate_dims(adims); + dnnl_memory_desc_t md = nullptr; + dnnl_status_t status = dnnl_memory_desc_create_with_tag(&md, + (int)adims.size(), adims.data(), convert_to_c(adata_type), + convert_to_c(aformat_tag)); + if (!allow_empty) + error::wrap_c_api(status, + "could not construct a memory descriptor using a " + "format tag"); + reset(md); + } + + /// Constructs a memory descriptor by strides. + /// + /// @note + /// The logical order of dimensions corresponds to the `abc...` + /// format tag, and the physical meaning of the dimensions depends + /// both on the primitive that would operate on this memory and + /// the operation context. + /// + /// @param adims Tensor dimensions. + /// @param adata_type Data precision/type. + /// @param strides Strides for each dimension. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be constructed. This flag is + /// optional and defaults to false. + desc(const dims &adims, data_type adata_type, const dims &strides, + bool allow_empty = false) { + validate_dims(adims); + if (!strides.empty()) validate_dims(strides, (int)adims.size()); + dnnl_memory_desc_t md = nullptr; + dnnl_status_t status = dnnl_memory_desc_create_with_strides(&md, + (int)adims.size(), adims.data(), convert_to_c(adata_type), + strides.empty() ? nullptr : &strides[0]); + if (!allow_empty) + error::wrap_c_api(status, + "could not construct a memory descriptor using " + "strides"); + reset(md); + } +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Function for creating a memory descriptor for CSR sparse encoding. + /// + /// The created memory descriptor will describe a memory object that + /// contains 3 buffers. The buffers have the following meaning and + /// assigned numbers (index): + /// - 0: values + /// - 1: indices + /// - 2: pointers + /// + /// @param adims Tensor dimensions. + /// @param adata_type Data precision/type. + /// @param nnz Number of non-zero entries. + /// @param index_dt Data type of indices. + /// @param pointer_dt Data type of pointers. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be constructed. This flag is + /// optional and defaults to false. + static desc csr(const dims &adims, data_type adata_type, dim nnz, + data_type index_dt, data_type pointer_dt, + bool allow_empty = false) { + validate_dims(adims); + dnnl_memory_desc_t md = nullptr; + dnnl_status_t status = dnnl_memory_desc_create_with_csr_encoding( + &md, (int)adims.size(), adims.data(), + convert_to_c(adata_type), nnz, convert_to_c(index_dt), + convert_to_c(pointer_dt)); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a memory descriptor for CSR sparse " + "encoding"); + return desc {md}; + } + + /// Function for creating a memory descriptor for packed sparse + /// encoding. + /// + /// The created memory descriptor cannot be used to create a memory + /// object. It can only be used to create a primitive descriptor to + /// query the actual memory descriptor (similar to the format tag + /// `any`). + /// + /// @warning + /// The meaning and content of the handles of the memory object that + /// is created using the queried memory descriptor are unspecified + /// therefore using the content is an undefined behavior. + /// + /// @param adims Tensor dimensions. + /// @param adata_type Data precision/type. + /// @param nnz Number of non-zero entries. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be constructed. This flag is + /// optional and defaults to false. + static desc packed(const dims &adims, data_type adata_type, dim nnz, + bool allow_empty = false) { + validate_dims(adims); + dnnl_memory_desc_t md = nullptr; + dnnl_status_t status = dnnl_memory_desc_create_with_packed_encoding( + &md, (int)adims.size(), adims.data(), + convert_to_c(adata_type), nnz); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a memory descriptor for packed " + "sparse encoding"); + return desc {md}; + } +#endif + /// Construct a memory descriptor from a C API ::dnnl_memory_desc_t + /// handle. The resulting handle is not weak and the C handle will be + /// destroyed during the destruction of the C++ object. + /// + /// @param md The C API memory descriptor. + desc(dnnl_memory_desc_t md) : handle(md) {} + + /// Construct a memory descriptor from a binary blob. + /// + /// @param blob A binary blob previously queried from a memory descriptor. + desc(const std::vector &blob) { + dnnl_memory_desc_t md = nullptr; + error::wrap_c_api( + dnnl_memory_desc_create_with_blob(&md, blob.data()), + "could not create a memory descriptor from blob"); + reset(md); + } + + /// Constructs a memory descriptor for a region inside an area + /// described by this memory descriptor. + // + /// @param adims Sizes of the region. + /// @param offsets Offsets to the region from the encompassing + /// memory object in each dimension. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be returned. This flag is optional + /// and defaults to false. + /// @returns A memory descriptor for the region. + desc submemory_desc(const dims &adims, const dims &offsets, + bool allow_empty = false) const { + validate_dims(adims, get_ndims()); + validate_dims(offsets, get_ndims()); + dnnl_memory_desc_t sub_md = nullptr; + dnnl_status_t status = dnnl_memory_desc_create_submemory( + &sub_md, get(), adims.data(), offsets.data()); + if (!allow_empty) + error::wrap_c_api(status, "could not construct a sub-memory"); + return desc(sub_md); + } + + /// Constructs a memory descriptor by reshaping an existing one. The + /// new memory descriptor inherits the data type. This operation is + /// valid only for memory descriptors that have format_kind set to + /// #dnnl::memory::format_kind::blocked or + /// #dnnl::memory::format_kind::any. + /// + /// The operation ensures that the transformation of the physical memory + /// format corresponds to the transformation of the logical dimensions. + /// If such transformation is impossible, the function either throws an + /// exception (default) or returns a zero memory descriptor depending on + /// the `allow_empty` flag. + /// + /// The reshape operation can be described as a combination of the + /// following basic operations: + /// 1. Add a dimension of size `1`. This is always possible. + /// 2. Remove a dimension of size `1`. This is possible only if the + /// dimension has no padding (i.e. + /// `padded_dims[dim] == dims[dim] && dims[dim] == 1`). + /// 3. Split a dimension into multiple ones. This is possible only if + /// the product of all tensor dimensions stays constant and the + /// dimension being split does not have padding (i.e. + /// `padded_dims[dim] = dims[dim]`). + /// 4. Join multiple consecutive dimensions into a single one. As in + /// the cases above, this requires that the dimensions do not have + /// padding and that the memory format is such that in physical + /// memory these dimensions are dense and have the same order as + /// their logical counterparts. This also assumes that these + /// dimensions are not blocked. + /// - Here, 'dense' means: + /// `stride for dim[i] == (stride for dim[i + 1]) * dim[i + 1]`; + /// - And 'same order' means: + /// `i < j` if and only if `stride for dim[j] <= stride for dim[i]`. + /// + /// @warning + /// Some combinations of physical memory layout and/or offsets or + /// dimensions may result in a failure to make a reshape. + /// + /// @param adims New dimensions. The product of dimensions must + /// remain constant. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be returned. This flag is optional + /// and defaults to false. + /// @returns A new memory descriptor with new dimensions. + desc reshape(const dims &adims, bool allow_empty = false) const { + if (get_ndims()) validate_dims(adims, 1); + dnnl_memory_desc_t out_md = nullptr; + dnnl_status_t status = dnnl_memory_desc_reshape( + &out_md, get(), (int)adims.size(), adims.data()); + if (!allow_empty) + error::wrap_c_api( + status, "could not reshape a memory descriptor"); + return desc(out_md); + } + + /// Constructs a memory descriptor by permuting axes in an existing + /// one. + /// + /// The physical memory layout representation is adjusted accordingly + /// to maintain the consistency between the logical and physical parts + /// of the memory descriptor. The new memory descriptor inherits the + /// data type. + /// + /// The new memory descriptor inherits the data type. This operation is + /// valid only for memory descriptors that have format_kind set to + /// #dnnl::memory::format_kind::blocked or + /// #dnnl::memory::format_kind::any. + /// + /// The logical axes will be permuted in the following manner: + /// @code + /// for (i = 0; i < get_ndims(); i++) + /// new_desc.dims()[permutation[i]] = dims()[i]; + /// @endcode + /// + /// Example: + /// @code + /// std::vector permutation = {1, 0}; // swap the first and + /// // the second axes + /// dnnl::memory::desc in_md( + /// {2, 3}, data_type, memory::format_tag::ab); + /// dnnl::memory::desc expect_out_md( + /// {3, 2}, data_type, memory::format_tag::ba); + /// + /// assert(in_md.permute_axes(permutation) == expect_out_md); + /// @endcode + /// + /// @param permutation Axes permutation. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case a + /// zero memory descriptor will be returned. This flag is optional + /// and defaults to false. + /// @returns A new memory descriptor with new dimensions. + desc permute_axes(const std::vector &permutation, + bool allow_empty = false) const { + validate_dims(permutation, get_ndims()); + dnnl_memory_desc_t out_md = nullptr; + dnnl_status_t status = dnnl_memory_desc_permute_axes( + &out_md, get(), permutation.data()); + if (!allow_empty) + error::wrap_c_api(status, + "could not permute axes of a memory descriptor"); + return desc(out_md); + } + + /// Returns a number of dimensions of the memory descriptor. + /// + /// @returns A number of dimensions. + int get_ndims() const { return query_s32(query::ndims_s32); } + + /// Returns padded dimensions of the memory descriptor. + /// + /// @returns A copy of the padded dimensions vector. + memory::dims get_padded_dims() const { + return query_dims(query::padded_dims); + } + + /// Returns padded offsets of the memory descriptor. + /// + /// @returns A copy of the padded offsets vector. + memory::dims get_padded_offsets() const { + return query_dims(query::padded_offsets); + } + + /// Returns a submemory offset of the memory descriptor. + /// + /// @returns A submemory offset. + memory::dim get_submemory_offset() const { + dnnl_dim_t submemory_offset; + dnnl_status_t status = dnnl_memory_desc_query( + get(), dnnl_query_submemory_offset_s64, &submemory_offset); + return status == dnnl_success ? submemory_offset : 0; + } + + /// Returns strides of the memory descriptor. + /// + /// @note + /// This API is only applicable to memory descriptors with format + /// kind #dnnl_blocked. + /// + /// @returns A copy of the strides vector. + /// @returns An empty #dnnl::memory::dims if the memory descriptor + /// does not have strides. + memory::dims get_strides() const { return query_dims(query::strides); } + + /// Returns a number of inner blocks of the memory descriptor. + /// + /// @note + /// This API is only applicable to memory descriptors with format + /// kind #dnnl_blocked. + /// + /// @returns A number of inner blocks. + int get_inner_nblks() const { + return query_s32(query::inner_nblks_s32); + } + + /// Returns inner blocks of the memory descriptor. + /// + /// @note + /// This API is only applicable to memory descriptors with format + /// kind #dnnl_blocked. + /// + /// @returns A copy of the inner blocks vector. + /// @returns An empty #dnnl::memory::dims if the memory descriptor + /// does not have inner blocks. + memory::dims get_inner_blks() const { + return query_dims(query::inner_blks); + } + + /// Returns inner indices of the memory descriptor. + /// + /// @note + /// This API is only applicable to memory descriptors with format + /// kind #dnnl_blocked. + /// + /// @returns A copy of the inner indices vector. + /// @returns An empty #dnnl::memory::dims if the memory descriptor + /// does not have inner indices. + memory::dims get_inner_idxs() const { + return query_dims(query::inner_idxs); + } + +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Returns number of handles. + /// + /// @returns A number of handles. + int get_num_handles() const { + int nhandles; + dnnl_status_t status = dnnl_memory_desc_query_v2( + get(), dnnl_query_num_handles_s32, 0, &nhandles); + return status == dnnl_success ? nhandles : 0; + } + + /// Returns a number of non-zero entries of the memory descriptor. + /// + /// @returns A number non-zero entries. + dim get_nnz() const { + dnnl_dim_t nnz; + dnnl_status_t status = dnnl_memory_desc_query_v2( + get(), dnnl_query_nnz_s64, 0, &nnz); + return status == dnnl_success ? nnz : 0; + } + + /// Returns the sparse encoding of the memory descriptor. + /// + /// @returns the sparse encoding kind. + memory::sparse_encoding get_sparse_encoding() const { + dnnl_sparse_encoding_t sparse_encoding; + dnnl_status_t status = dnnl_memory_desc_query_v2( + get(), dnnl_query_sparse_encoding, 0, &sparse_encoding); + return status == dnnl_success + ? static_cast( + sparse_encoding) + : dnnl::memory::sparse_encoding::undef; + } + + /// Returns the data type of the memory descriptor. + /// + /// @returns The data type. + memory::data_type get_data_type(int index = 0) const { + return query_data_type(query::data_type, index); + } +#else + /// Returns the data type of the memory descriptor. + /// + /// @returns The data type. + memory::data_type get_data_type() const { + return query_data_type(query::data_type); + } +#endif + + /// Returns the format kind of the memory descriptor. + /// + /// @returns the format kind. + memory::format_kind get_format_kind() const { + dnnl_format_kind_t format_kind; + dnnl_status_t status = dnnl_memory_desc_query( + get(), dnnl_query_format_kind, &format_kind); + return status == dnnl_success + ? static_cast(format_kind) + : dnnl::memory::format_kind::undef; + } + + /// Returns dimensions of the memory descriptor. + /// + /// Potentially expensive due to the data copy involved. + /// @returns A copy of the dimensions vector. + memory::dims get_dims() const { return query_dims(query::dims); } + +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Returns size of the memory descriptor in bytes. + /// @param index Data index. Defaults to 0. + /// @returns The number of bytes required to allocate a memory buffer + /// for data with a particular @p index described by this memory + /// descriptor including the padding area. + size_t get_size(int index = 0) const { + return dnnl_memory_desc_get_size_v2(get(), index); + } +#else + /// Returns size of the memory descriptor in bytes. + /// @returns The number of bytes required to allocate a memory buffer + /// for the memory object described by this memory descriptor + /// including the padding area. + size_t get_size() const { return dnnl_memory_desc_get_size(get()); } +#endif + + /// Returns a binary blob associated with the given memory descriptor + /// @returns The memory descriptor blob associated with the memory descriptor + std::vector get_blob() { + size_t size; + dnnl_status_t status + = dnnl_memory_desc_get_blob(nullptr, &size, get()); + error::wrap_c_api( + status, "could not get memory descriptor blob size"); + + std::vector out_blob(size); + status = dnnl_memory_desc_get_blob(out_blob.data(), &size, get()); + error::wrap_c_api(status, "could not get memory descriptor blob"); + return out_blob; + } + + /// Checks whether the memory descriptor is zero (empty). + /// @returns @c true if the memory descriptor describes an empty + /// memory and @c false otherwise. + bool is_zero() const { return get_ndims() == 0; } + + /// An equality operator. + /// @param other Another memory descriptor. + /// @returns Whether this and the other memory descriptors have + /// the same format tag, dimensions, strides, blocking, etc. + bool operator==(const desc &other) const { + return dnnl_memory_desc_equal(get(), other.get()) != 0; + } + + /// An inequality operator. + /// @param other Another memory descriptor. + /// @returns Whether this and the other memory descriptors describe + /// different memory. + bool operator!=(const desc &other) const { return !operator==(other); } + + private: +#ifdef DNNL_EXPERIMENTAL_SPARSE + memory::data_type query_data_type(query what, int index) const { + dnnl_data_type_t data_type; + dnnl_status_t status = dnnl_memory_desc_query_v2( + get(), dnnl::convert_to_c(what), index, &data_type); + return status == dnnl_success + ? static_cast(data_type) + : dnnl::memory::data_type::undef; + } +#else + memory::data_type query_data_type(query what) const { + dnnl_data_type_t data_type; + dnnl_status_t status = dnnl_memory_desc_query( + get(), dnnl::convert_to_c(what), &data_type); + return status == dnnl_success + ? static_cast(data_type) + : dnnl::memory::data_type::undef; + } +#endif + + int query_s32(query what) const { + int res; + dnnl_status_t status = dnnl_memory_desc_query( + get(), dnnl::convert_to_c(what), &res); + return status == dnnl_success ? res : 0; + } + + memory::dims query_dims(query what) const { + dnnl_dims_t *c_dims; + dnnl_status_t status = dnnl_memory_desc_query( + get(), dnnl::convert_to_c(what), &c_dims); + + const int ndims + = (what == query::inner_idxs || what == query::inner_blks) + ? get_inner_nblks() + : get_ndims(); + + return status == dnnl_success + ? memory::dims(*c_dims, *c_dims + ndims) + : memory::dims {}; + } + }; + + /// Default constructor. + /// + /// Constructs an empty memory object, which can be used to indicate + /// absence of a parameter. + memory() = default; + +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Constructs a memory object. + /// + /// Unless @p handle is equal to #DNNL_MEMORY_NONE, the constructed memory + /// object will have the underlying buffer set. In this case, the buffer + /// will be initialized as if #dnnl::memory::set_data_handle() had been + /// called. + /// + /// @sa memory::set_data_handle() + /// + /// @param md Memory descriptor. + /// @param aengine Engine to store the data on. + /// @param handle Handle of the memory buffer to use. + /// - A pointer to the user-allocated buffer. In this case the library + /// doesn't own the buffer. + /// - The #DNNL_MEMORY_ALLOCATE special value. Instructs the library to + /// allocate the buffer for the memory object. In this case the + /// library owns the buffer. + /// - #DNNL_MEMORY_NONE to create dnnl::memory without an underlying + /// buffer. + memory(const desc &md, const engine &aengine, void *handle) + : memory(md, aengine, std::vector {handle}) {} + + /// Constructs a memory object with multiple handles. + /// + /// Unless @p handle is equal to #DNNL_MEMORY_NONE, the constructed memory + /// object will have the underlying buffer set. In this case, the buffer + /// will be initialized as if #dnnl::memory::set_data_handle() had been + /// called. + /// + /// @sa memory::set_data_handle() + /// + /// @param md Memory descriptor. + /// @param aengine Engine to store the data on. + /// @param handles Handles of the memory buffers to use. + /// For each element of the @p handles vector the following applies: + /// - A pointer to the user-allocated buffer. In this case the library + /// doesn't own the buffer. + /// - The #DNNL_MEMORY_ALLOCATE special value. Instructs the library to + /// allocate the buffer for the memory object. In this case the + /// library owns the buffer. + /// - #DNNL_MEMORY_NONE Instructs the library to skip allocation of the + /// memory buffer. + memory(const desc &md, const engine &aengine, std::vector handles) { + dnnl_memory_t result; + dnnl_status_t status = dnnl_memory_create_v2(&result, md.get(), + aengine.get(), (int)handles.size(), handles.data()); + error::wrap_c_api(status, "could not create a memory object"); + reset(result); + } + + /// Constructs a memory object. + /// + /// The underlying buffer(s) for the memory will be allocated by the + /// library. + /// @param md Memory descriptor. + /// @param aengine Engine to store the data on. + memory(const desc &md, const engine &aengine) { + dnnl_status_t status; + dnnl_memory_t result; + const int nhandles = md.get_num_handles(); + + std::vector handles(nhandles, DNNL_MEMORY_ALLOCATE); + status = dnnl_memory_create_v2(&result, md.get(), aengine.get(), + (int)handles.size(), handles.data()); + + error::wrap_c_api(status, "could not create a memory object"); + reset(result); + } +#else + /// Constructs a memory object. + /// + /// Unless @p handle is equal to #DNNL_MEMORY_NONE, the constructed memory + /// object will have the underlying buffer set. In this case, the buffer + /// will be initialized as if #dnnl::memory::set_data_handle() had been + /// called. + /// + /// @sa memory::set_data_handle() + /// + /// @param md Memory descriptor. + /// @param aengine Engine to store the data on. + /// @param handle Handle of the memory buffer to use. + /// - A pointer to the user-allocated buffer. In this case the library + /// doesn't own the buffer. + /// - The #DNNL_MEMORY_ALLOCATE special value. Instructs the library to + /// allocate the buffer for the memory object. In this case the + /// library owns the buffer. + /// - #DNNL_MEMORY_NONE to create dnnl::memory without an underlying + /// buffer. + memory(const desc &md, const engine &aengine, void *handle) { + dnnl_memory_t result; + error::wrap_c_api( + dnnl_memory_create(&result, md.get(), aengine.get(), handle), + "could not create a memory object"); + reset(result); + } + + /// Constructs a memory object. + /// + /// The underlying buffer for the memory will be allocated by the library. + /// + /// @param md Memory descriptor. + /// @param aengine Engine to store the data on. + memory(const desc &md, const engine &aengine) + : memory(md, aengine, DNNL_MEMORY_ALLOCATE) {} +#endif + + /// Returns the associated memory descriptor. + desc get_desc() const { + const_dnnl_memory_desc_t cdesc; + error::wrap_c_api(dnnl_memory_get_memory_desc(get(), &cdesc), + "could not get a memory descriptor from a memory object"); + dnnl_memory_desc_t cloned_md = nullptr; + error::wrap_c_api(dnnl_memory_desc_clone(&cloned_md, cdesc), + "could not clone a memory descriptor"); + return desc(cloned_md); + } + + /// Returns the associated engine. + engine get_engine() const { + dnnl_engine_t c_engine; + error::wrap_c_api(dnnl_memory_get_engine(get(), &c_engine), + "could not get an engine from a memory object"); + return engine(c_engine, true); + } + +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Returns an underlying memory buffer that corresponds to the given index. + /// + /// On the CPU engine, or when using USM, this is a pointer to the + /// allocated memory. + void *get_data_handle(int index = 0) const { + void *handle; + error::wrap_c_api(dnnl_memory_get_data_handle_v2(get(), &handle, index), + "could not get a native handle from a memory object"); + return handle; + } + + /// Sets an underlying memory buffer that corresponds to the given index. + /// + /// @param handle Memory buffer to use. On the CPU engine or when USM is + /// used, the memory buffer is a pointer to the actual data. For OpenCL + /// it is a cl_mem. It must have at least + /// #dnnl::memory::desc::get_size() bytes allocated. + /// @param index Memory index to attach the buffer. Defaults to 0. + void set_data_handle(void *handle, int index = 0) const { + error::wrap_c_api(dnnl_memory_set_data_handle_v2(get(), handle, index), + "could not set native handle of a memory object"); + } + + /// Maps a memory object and returns a host-side pointer to a memory + /// buffer with a copy of its contents. The memory buffer corresponds to + /// the given index. + /// + /// Mapping enables read/write directly from/to the memory contents for + /// engines that do not support direct memory access. + /// + /// Mapping is an exclusive operation - a memory object cannot be used in + /// other operations until it is unmapped via #dnnl::memory::unmap_data() + /// call. + /// + /// @note + /// Any primitives working with the memory should be completed before + /// the memory is mapped. Use #dnnl::stream::wait() to synchronize the + /// corresponding execution stream. + /// + /// @note + /// The map_data and unmap_data functions are provided mainly for + /// debug and testing purposes and their performance may be suboptimal. + /// + /// @tparam T Data type to return a pointer to. + /// @param index Index of the buffer. Defaults to 0. + /// @returns Pointer to the mapped memory. + template + T *map_data(int index = 0) const { + void *mapped_ptr; + error::wrap_c_api(dnnl_memory_map_data_v2(get(), &mapped_ptr, index), + "could not map memory object data"); + return static_cast(mapped_ptr); + } + + /// Unmaps a memory object and writes back any changes made to the + /// previously mapped memory buffer. The memory buffer corresponds to + /// the given index. + /// + /// @note + /// The map_data and unmap_data functions are provided mainly for + /// debug and testing purposes and their performance may be + /// suboptimal. + /// + /// @param mapped_ptr A pointer previously returned by + /// #dnnl::memory::map_data(). + /// @param index Index of the buffer. Defaults to 0. + void unmap_data(void *mapped_ptr, int index = 0) const { + error::wrap_c_api(dnnl_memory_unmap_data_v2(get(), mapped_ptr, index), + "could not unmap memory object data"); + } +#else + /// Returns the underlying memory buffer. + /// + /// On the CPU engine, or when using USM, this is a pointer to the + /// allocated memory. + void *get_data_handle() const { + void *handle; + error::wrap_c_api(dnnl_memory_get_data_handle(get(), &handle), + "could not get a native handle from a memory object"); + return handle; + } + + /// Sets the underlying memory buffer. + /// + /// @param handle Memory buffer to use. On the CPU engine or when USM is + /// used, the memory buffer is a pointer to the actual data. For OpenCL + /// it is a cl_mem. It must have at least + /// #dnnl::memory::desc::get_size() bytes allocated. + void set_data_handle(void *handle) const { + error::wrap_c_api(dnnl_memory_set_data_handle(get(), handle), + "could not set native handle of a memory object"); + } + + /// Maps a memory object and returns a host-side pointer to a memory + /// buffer with a copy of its contents. + /// + /// Mapping enables read/write directly from/to the memory contents for + /// engines that do not support direct memory access. + /// + /// Mapping is an exclusive operation - a memory object cannot be used in + /// other operations until it is unmapped via #dnnl::memory::unmap_data() + /// call. + /// + /// @note + /// Any primitives working with the memory should be completed before + /// the memory is mapped. Use #dnnl::stream::wait() to synchronize the + /// corresponding execution stream. + /// + /// @note + /// The map_data and unmap_data functions are provided mainly for + /// debug and testing purposes and their performance may be suboptimal. + /// + /// @tparam T Data type to return a pointer to. + /// @returns Pointer to the mapped memory. + template + T *map_data() const { + void *mapped_ptr; + error::wrap_c_api(dnnl_memory_map_data(get(), &mapped_ptr), + "could not map memory object data"); + return static_cast(mapped_ptr); + } + + /// Unmaps a memory object and writes back any changes made to the + /// previously mapped memory buffer. + /// + /// @note + /// The map_data and unmap_data functions are provided mainly for + /// debug and testing purposes and their performance may be + /// suboptimal. + /// + /// @param mapped_ptr A pointer previously returned by + /// #dnnl::memory::map_data(). + void unmap_data(void *mapped_ptr) const { + error::wrap_c_api(dnnl_memory_unmap_data(get(), mapped_ptr), + "could not unmap memory object data"); + } +#endif + + static dnnl_data_type_t convert_to_c(data_type adata_type) { + return static_cast(adata_type); + } + static dnnl_format_tag_t convert_to_c(format_tag format) { + return static_cast(format); + } +}; + +inline bool operator==(dnnl_data_type_t a, memory::data_type b) { + return a == memory::convert_to_c(b); +} +inline bool operator!=(dnnl_data_type_t a, memory::data_type b) { + return !(a == b); +} +inline bool operator==(memory::data_type a, dnnl_data_type_t b) { + return b == a; +} +inline bool operator!=(memory::data_type a, dnnl_data_type_t b) { + return !(a == b); +} + +inline bool operator==(dnnl_format_tag_t a, memory::format_tag b) { + return a == memory::convert_to_c(b); +} +inline bool operator!=(dnnl_format_tag_t a, memory::format_tag b) { + return !(a == b); +} +inline bool operator==(memory::format_tag a, dnnl_format_tag_t b) { + return b == a; +} +inline bool operator!=(memory::format_tag a, dnnl_format_tag_t b) { + return !(a == b); +} + +/// @} dnnl_api_memory + +/// @addtogroup dnnl_api_primitives +/// @{ +/// @addtogroup dnnl_api_attributes Attributes +/// +/// A container for parameters that extend primitives behavior. +/// +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_post_ops_t p) { + return dnnl_post_ops_destroy(p); + } +}; +/// @endcond + +/// Post-ops. +/// +/// Post-ops are computations executed after the main primitive computations +/// and are attached to the primitive via primitive attributes. +/// +/// @sa @ref dev_guide_attributes_post_ops +/// +struct post_ops : public handle { + using handle::handle; + + /// Constructs an empty sequence of post-ops. + post_ops() { + dnnl_post_ops_t result; + error::wrap_c_api( + dnnl_post_ops_create(&result), "could not create post-ops"); + reset(result); + } + + /// Creates post-ops primitive attribute from a C API ::dnnl_post_ops_t + /// handle. The resulting handle is not weak and the C handle will be + /// destroyed during the destruction of the C++ object. + /// + /// @param post_ops The C API post-ops primitive attribute. + post_ops(dnnl_post_ops_t post_ops) : handle(post_ops) {} + + /// Returns the number of post-ops entries. + int len() const { return dnnl_post_ops_len(get()); } + + /// Returns the primitive kind of post-op at entry with a certain index. + /// @param index Index of the post-op to return the kind for. + /// @returns Primitive kind of the post-op at the specified index. + primitive::kind kind(int index) const { + error::wrap_c_api(index < len() ? dnnl_success : dnnl_invalid_arguments, + "post-ops index is out of range"); + return static_cast( + dnnl_post_ops_get_kind(get(), index)); + } + + /// Appends an accumulation (sum) post-op. Prior to accumulating the + /// result, the previous value will be will be reduced by zero point + /// @p zero_point and multiplied by a scaling factor @p scale. + /// + /// The kind of this post-op is #dnnl::primitive::kind::sum. + /// + /// This feature may improve performance for cases like dequantize the + /// asymmetrically quantized sum's src1 tensor to f32 domain before + /// performing the sum operation by subtracting @p zero_point before the + /// scaling. + /// + /// In the simplest case when the accumulation is the only post-op, + /// the computations will be `dst[:] := scale * (dst[:] - zero_point) + + /// op(...)` instead of `dst[:] := op(...)`. + /// + /// If @p data_type is specified, the original dst tensor will be + /// reinterpreted as a tensor with the provided data type. Because it is a + /// reinterpretation, data_type and dst data type should have the same size. + /// As a result, computations will be `dst[:] <- scale * + /// (as_data_type(dst[:]) - zero_point) + op(...)` instead of + /// `dst[:] <- op(...)`. + /// + /// @note + /// This post-op executes in-place and does not change the + /// destination layout. + /// + /// @param scale Scaling factor. + /// @param zero_point Zero point. + /// @param data_type Data type. + void append_sum(float scale = 1.f, int32_t zero_point = 0, + memory::data_type data_type = memory::data_type::undef) { + error::wrap_c_api(dnnl_post_ops_append_sum(get(), scale, zero_point, + memory::convert_to_c(data_type)), + "could not append a sum post-op"); + } + + /// Returns the parameters of an accumulation (sum) post-op. + /// + /// @param index Index of the sum post-op. + /// @param scale Scaling factor of the sum post-op. + void get_params_sum(int index, float &scale) const { + error::wrap_c_api(dnnl_post_ops_get_params_sum( + get(), index, &scale, nullptr, nullptr), + "could not get parameters of a sum post-op"); + } + + /// Returns the parameters of an accumulation (sum) post-op. + /// + /// @param index Index of the sum post-op. + /// @param scale Scaling factor of the sum post-op. + /// @param data_type Data type of the sum post-op. + void get_params_sum( + int index, float &scale, memory::data_type &data_type) const { + dnnl_data_type_t c_data_type; + error::wrap_c_api(dnnl_post_ops_get_params_sum( + get(), index, &scale, nullptr, &c_data_type), + "could not get parameters of a sum post-op"); + data_type = static_cast(c_data_type); + } + + /// Returns the parameters of an accumulation (sum) post-op. + /// + /// @param index Index of the sum post-op. + /// @param scale Scaling factor of the sum post-op. + /// @param zero_point Single scalar int32_t value of zeropoint. + /// @param data_type Data type of the sum post-op. + void get_params_sum(int index, float &scale, int32_t &zero_point, + memory::data_type &data_type) const { + dnnl_data_type_t c_data_type; + error::wrap_c_api(dnnl_post_ops_get_params_sum(get(), index, &scale, + &zero_point, &c_data_type), + "could not get parameters of a sum post-op"); + data_type = static_cast(c_data_type); + } + + /// Appends an elementwise post-op. + /// + /// The kind of this post-op is #dnnl::primitive::kind::eltwise. + /// + /// In the simplest case when the elementwise is the only post-op, the + /// computations would be `dst[:] := eltwise_op (op(...))` instead + /// of `dst[:] <- op(...)`, where eltwise_op is configured with the given + /// parameters. + /// + /// @param aalgorithm Elementwise algorithm. + /// @param alpha Alpha parameter for the elementwise algorithm. + /// @param beta Beta parameter for the elementwise algorithm. + void append_eltwise(algorithm aalgorithm, float alpha, float beta) { + error::wrap_c_api(dnnl_post_ops_append_eltwise( + get(), convert_to_c(aalgorithm), alpha, beta), + "could not append an elementwise post-op"); + } + + /// Returns parameters of an elementwise post-op. + /// + /// @param index Index of the post-op. + /// @param aalgorithm Output elementwise algorithm kind. + /// @param alpha Output alpha parameter for the elementwise algorithm. + /// @param beta Output beta parameter for the elementwise algorithm. + void get_params_eltwise( + int index, algorithm &aalgorithm, float &alpha, float &beta) const { + dnnl_alg_kind_t c_alg; + error::wrap_c_api(dnnl_post_ops_get_params_eltwise( + get(), index, &c_alg, &alpha, &beta), + "could not get parameters of an elementwise post-op"); + aalgorithm = static_cast(c_alg); + } + + /// Appends a depthwise post-op convolution. + /// + /// This post-op can only be fused with a 2D 1x1 convolution (convolution + /// with weights spatial dimension equal to 1 i.e., kh=kw=1). + /// + /// The kind of this post-op is #dnnl_convolution. + /// + /// The number of outputs for primitive remain same as before. The output + /// spatial size can be derived as below: + /// + /// output_height = ceil(output_height_1x1_convolution, stride) + /// output_width = ceil(output_width_1x1_convolution, stride) + /// + /// See @ref dev_guide_attributes_post_ops_depthwise and + /// @ref dev_guide_attributes_post_ops_depthwise_fusion for more info. + /// + /// @param weights_data_type Weights data type of depthwise post-op + /// @param bias_data_type Bias data type of depthwise post-op + /// @param dst_data_type Output data type of depthwise post-op + /// @param kernel_size Size of kernel of depthwise post-op + /// @param stride_size Size of stride of depthwise post-op + /// @param padding_l_size Size of left and top paddings of depthwise post-op + void append_dw(memory::data_type weights_data_type, + memory::data_type bias_data_type, memory::data_type dst_data_type, + memory::dim kernel_size, memory::dim stride_size, + memory::dim padding_l_size) { + + error::wrap_c_api(dnnl_post_ops_append_dw(get(), + memory::convert_to_c(weights_data_type), + memory::convert_to_c(bias_data_type), + memory::convert_to_c(dst_data_type), + kernel_size, stride_size, padding_l_size), + "could not append depthwise post-op"); + } + + /// Returns the parameters of an depthwise post-op. + /// + /// @param index Index of the elementwise post-op. + /// @param weights_data_type Weights data type of depthwise post-op + /// @param bias_data_type Bias data type of depthwise post-op + /// @param dst_data_type Output data type of depthwise post-op + /// @param kernel_size Size of kernel of depthwise post-op + /// @param stride_size Size of stride of depthwise post-op + /// @param padding_l_size Size of left and top paddings of depthwise post-op + void get_params_dw(int index, memory::data_type &weights_data_type, + memory::data_type &bias_data_type, memory::data_type &dst_data_type, + memory::dim &kernel_size, memory::dim &stride_size, + memory::dim &padding_l_size) const { + + dnnl_data_type_t c_weights_data_type; + dnnl_data_type_t c_bias_data_type; + dnnl_data_type_t c_dst_data_type; + dnnl_dim_t c_kernel_size; + dnnl_dim_t c_stride_size; + dnnl_dim_t c_padding_l_size; + error::wrap_c_api( + dnnl_post_ops_get_params_dw(get(), index, &c_weights_data_type, + &c_bias_data_type, &c_dst_data_type, &c_kernel_size, + &c_stride_size, &c_padding_l_size), + "could not get parameters of depthwise post-op"); + + weights_data_type = static_cast(c_weights_data_type); + bias_data_type = static_cast(c_bias_data_type); + dst_data_type = static_cast(c_dst_data_type); + kernel_size = c_kernel_size; + stride_size = c_stride_size; + padding_l_size = c_padding_l_size; + } + + /// Appends a binary post-op. + /// + /// The kind of this post operation is #dnnl_binary. + /// + /// In the simplest case when the binary is the only post operation, the + /// computations would be: + /// + /// dst[:] <- binary_op (dst[:], another_input[:]) + /// + /// where binary_op is configured with the given parameters. binary_op + /// supports broadcast semantics for a second operand. + /// + /// @param aalgorithm Binary algorithm for the post-op. + /// @param src1_desc Memory descriptor of a second operand. + void append_binary(algorithm aalgorithm, const memory::desc &src1_desc) { + error::wrap_c_api(dnnl_post_ops_append_binary(get(), + convert_to_c(aalgorithm), src1_desc.get()), + "could not append a binary post-op"); + } + + /// Returns the parameters of a binary post-op. + /// + /// @param index Index of the binary post-op. + /// @param aalgorithm Output binary algorithm kind. + /// @param src1_desc Output memory descriptor of a second operand. + void get_params_binary( + int index, algorithm &aalgorithm, memory::desc &src1_desc) const { + dnnl_alg_kind_t c_alg; + const_dnnl_memory_desc_t cdesc; + error::wrap_c_api( + dnnl_post_ops_get_params_binary(get(), index, &c_alg, &cdesc), + "could not get parameters of a binary post-op"); + aalgorithm = static_cast(c_alg); + dnnl_memory_desc_t cloned_md = nullptr; + error::wrap_c_api(dnnl_memory_desc_clone(&cloned_md, cdesc), + "could not clone a memory descriptor"); + src1_desc = memory::desc(cloned_md); + } + + /// Appends a prelu forward post-op. + /// + /// The kind of this post-op is #dnnl::primitive::kind::prelu. + /// + /// The post-op can be defined as: + /// + /// dst[:] <- prelu(dst[:], weights[:]) + /// prelu: + /// dst[:] <- dst[:] if dst[:] > 0 + /// dst[:] <- dst[:] * weights[:] if dst[:] <= 0 + /// + /// + /// Example usage: + /// @code + /// int mb = 32, oc = 32, + /// oh = 14, ow = 14; // convolution output params + /// // unique weights per output channel + /// vector weights = { ... }; + /// int oc_dim = 1; // mb_dim = 0, channel_dim = 1, height_dim = 2, ... + /// + /// // construct a convolution descriptor + /// dnnl::convolution::desc conv_d; + /// + /// dnnl::primitive_attr attr; + /// attr.append_prelu(1 << oc_dim); + /// + /// dnnl::primitive_desc conv_pd(conv_d, attr, engine); + /// memory prelu_weights({{1}, dt::f32, {1}}, eng, weights.data()); + /// + /// std::unordered_map conv_args; + /// + /// conv_args.insert( + /// {DNNL_ARG_ATTR_MULTIPLE_POST_OP(0) | DNNL_ARG_WEIGHTS, prelu_weights}) + /// @endcode + /// + /// @note + /// The order of dimensions does not depend on how elements are laid + /// out in memory. For example: + /// - for a 2D CNN activations tensor the order is always (n, c) + /// - for a 4D CNN activations tensor the order is always (n, c, h, w) + /// - for a 5D CNN weights tensor the order is always + /// (g, oc, ic, kh, kw) + /// + /// Prelu weights tensor is passed in runtime execution phase. Prelu + /// weights tensor data type is implicitly assumed as f32 using plain + /// layout (a, ab, acb, acdb, acdeb). + /// + /// @param mask Defines the correspondence between the output tensor + /// dimensions and the prelu weights tensor. The set i-th bit indicates + /// that a dedicated weights value is used for each index along that + /// dimension. Set the mask to 0 to use a common weights value + /// for the whole output tensor. + void append_prelu(int mask) { + error::wrap_c_api(dnnl_post_ops_append_prelu(get(), mask), + "could not append a prelu post-op"); + } + + /// Returns the parameters of a prelu post-op. + /// + /// @param index Index of the prelu post-op. + /// @param mask Weights mask of prelu post-op. + void get_params_prelu(int index, int &mask) const { + error::wrap_c_api(dnnl_post_ops_get_params_prelu(get(), index, &mask), + "could not get parameters of a binary post-op"); + } +}; + +/// @cond DO_NOT_DOCUMENT_THIS +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_primitive_attr_t p) { + return dnnl_primitive_attr_destroy(p); + } +}; +/// @endcond + +/// Primitive attributes. +/// +/// @sa @ref dev_guide_attributes +struct primitive_attr : public handle { + using handle::handle; + + /// Constructs default (empty) primitive attributes. + primitive_attr() { + dnnl_primitive_attr_t result; + error::wrap_c_api(dnnl_primitive_attr_create(&result), + "could not create primitive attribute"); + reset(result); + } + + /// Creates primitive attributes from a C API ::dnnl_primitive_attr_t + /// handle. The resulting handle is not weak and the C handle will be + /// destroyed during the destruction of the C++ object. + /// + /// @param attr The C API primitive attributes. + primitive_attr(dnnl_primitive_attr_t attr) + : handle(attr) {} + + /// Returns the fpmath mode + fpmath_mode get_fpmath_mode() const { + dnnl_fpmath_mode_t result; + error::wrap_c_api(dnnl_primitive_attr_get_fpmath_mode(get(), &result), + "could not get fpmath mode primitive attribute"); + return fpmath_mode(result); + } + + /// Returns the fpmath mode + /// + /// @param mode Specified fpmath mode. + /// @param apply_to_int Use floating-point arithmetic for integer primitives. + void get_fpmath_mode(fpmath_mode &mode, bool &apply_to_int) const { + dnnl_fpmath_mode_t c_mode; + int c_apply_to_int; + error::wrap_c_api(dnnl_primitive_attr_get_fpmath_mode_v2( + get(), &c_mode, &c_apply_to_int), + "could not get fpmath mode primitive attribute"); + mode = fpmath_mode(c_mode); + apply_to_int = static_cast(c_apply_to_int); + } + + /// Sets fpmath mode. + /// + /// @param mode Specified fpmath mode. + /// @param apply_to_int Boolean. Use of floating-point arithmetic for integer primitives. + void set_fpmath_mode(fpmath_mode mode, bool apply_to_int = false) { + error::wrap_c_api(dnnl_primitive_attr_set_fpmath_mode_v2(get(), + dnnl::convert_to_c(mode), apply_to_int), + "could not set fpmath mode primitive attribute"); + } + + /// Returns the accumulation mode + accumulation_mode get_accumulation_mode() const { + dnnl_accumulation_mode_t result; + error::wrap_c_api( + dnnl_primitive_attr_get_accumulation_mode(get(), &result), + "could not get accumulation mode primitive attribute"); + return accumulation_mode(result); + } + + /// Sets accumulation mode. + /// + /// @param mode Specified accumulation mode. + void set_accumulation_mode(accumulation_mode mode) { + error::wrap_c_api(dnnl_primitive_attr_set_accumulation_mode( + get(), dnnl::convert_to_c(mode)), + "could not set accumulation mode primitive attribute"); + } + + /// Returns the deterministic attribute value + bool get_deterministic() const { + int result; + error::wrap_c_api(dnnl_primitive_attr_get_deterministic(get(), &result), + "could not get deterministic primitive attribute"); + return static_cast(result); + } + + /// Sets deterministic attribute value + /// + /// @param value Specified deterministic mode. + void set_deterministic(bool value) { + error::wrap_c_api(dnnl_primitive_attr_set_deterministic( + get(), static_cast(value)), + "could not set deterministic primitive attribute"); + } + + /// Returns the scratchpad mode. + scratchpad_mode get_scratchpad_mode() const { + dnnl_scratchpad_mode_t result; + error::wrap_c_api( + dnnl_primitive_attr_get_scratchpad_mode(get(), &result), + "could not get scratchpad mode primitive attribute"); + return scratchpad_mode(result); + } + + /// Sets scratchpad mode. + /// + /// @param mode Specified scratchpad mode. + void set_scratchpad_mode(scratchpad_mode mode) { + error::wrap_c_api(dnnl_primitive_attr_set_scratchpad_mode( + get(), dnnl::convert_to_c(mode)), + "could not set scratchpad mode primitive attribute"); + } + + /// Sets scaling factors for primitive operations for a given memory + /// argument. The scaling factors must be passed at execution time + /// as an argument with index #DNNL_ARG_ATTR_SCALES | arg. + /// + /// @sa dnnl_primitive_attr_set_scales_mask + /// + /// @param arg Parameter argument index as passed to the + /// primitive::execute() call. + /// @param mask Scaling factors correspondence mask that defines the + /// correspondence between the tensor dimensions and the @p scales + /// vector. The set i-th bit indicates that a dedicated scaling factor + /// is used for each index along that dimension. Set the mask to 0 to + /// use a common scaling factor for the whole output tensor. + void set_scales_mask(int arg, int mask) { + error::wrap_c_api(dnnl_primitive_attr_set_scales_mask(get(), arg, mask), + "could not set scales primitive attribute"); + } + + /// Sets scaling factors for primitive operations for a given memory + /// argument. The scaling factors must be passed at execution time + /// as an argument with index #DNNL_ARG_ATTR_SCALES | arg. + /// + /// @sa dnnl_primitive_attr_set_scales + /// + /// @param arg Parameter argument index as passed to the + /// primitive::execute() call. + /// @param mask Scales correspondence mask that defines the + /// correspondence between the tensor dimensions and the @p + /// scales vector. The set i-th bit indicates that a dedicated + /// scale is used for each index along that dimension. Set the + /// mask to 0 to use a common scale for the whole output tensor. + /// @param groups Scaling factors correspondence groups that define the + /// correspondence between the tensor dimensions and the scales array. + /// The set i-th dimension indicates a number of groups of scaling + /// factors used for that logical dimension in a memory indicated by @p arg. + /// @param data_type Scaling factors data_type. + void set_scales(int arg, int mask, const memory::dims &groups, + memory::data_type data_type = memory::data_type::f32) { + error::wrap_c_api(dnnl_primitive_attr_set_scales(get(), arg, mask, + (int)groups.size(), groups.data(), + memory::convert_to_c(data_type)), + "could not set scales primitive attribute"); + } + + /// Sets zero points for primitive operations for a given memory argument. + /// The zero points must be passed at execution time as an argument with + /// index #DNNL_ARG_ATTR_ZERO_POINTS | arg. + /// + /// @sa dnnl_primitive_attr_set_zero_points_mask + /// + /// @param arg Parameter argument index as passed to the + /// primitive::execute() call. + /// @param mask Zero point correspondence mask that defines the + /// correspondence between the tensor dimensions and the @p + /// zero_points vector. The set i-th bit indicates that a dedicated + /// zero point is used for each index along that dimension. Set the + /// mask to 0 to use a common zero point for the whole output tensor. + void set_zero_points_mask(int arg, int mask) { + error::wrap_c_api( + dnnl_primitive_attr_set_zero_points_mask(get(), arg, mask), + "could not set zero points primitive attribute"); + } + + /// Sets zero points for primitive operations for a given memory argument. + /// The zero points must be passed at execution time as an argument with + /// index #DNNL_ARG_ATTR_ZERO_POINTS | arg. + /// + /// @sa dnnl_primitive_attr_set_zero_points + /// + /// @param arg Parameter argument index as passed to the + /// primitive::execute() call. + /// @param mask Zero point correspondence mask that defines the + /// correspondence between the tensor dimensions and the @p + /// zero_points vector. The set i-th bit indicates that a dedicated + /// zero point is used for each index along that dimension. Set the + /// mask to 0 to use a common zero point for the whole output tensor. + /// @param groups Zero point factors correspondence groups that define the + /// correspondence between the tensor dimensions and the zero_points array. + /// The set i-th dimension indicates a number of groups of zero point + /// factors used for that logical dimension in a memory indicated by @p arg. + /// @param data_type Zero point factors data_type. + void set_zero_points(int arg, int mask, const memory::dims &groups, + memory::data_type data_type = memory::data_type::s32) { + error::wrap_c_api(dnnl_primitive_attr_set_zero_points(get(), arg, mask, + (int)groups.size(), groups.data(), + memory::convert_to_c(data_type)), + "could not set zero points primitive attribute"); + } + + /// Returns post-ops previously set via set_post_ops(). + /// + /// @returns Post-ops. + const post_ops get_post_ops() const { + const_dnnl_post_ops_t const_c_post_ops; + error::wrap_c_api( + dnnl_primitive_attr_get_post_ops(get(), &const_c_post_ops), + "could not get post-ops primitive attribute"); + dnnl_post_ops_t c_post_ops; + error::wrap_c_api(dnnl_post_ops_clone(&c_post_ops, const_c_post_ops), + "could not clone post-ops primitive attribute"); + return post_ops(c_post_ops); + } + + /// Sets post-ops. + /// + /// @note + /// There is no way to check whether the post-ops would be supported + /// by the target primitive. Any error will be reported + /// by the respective primitive descriptor constructor. + /// + /// @param ops Post-ops object to copy post-ops from. + void set_post_ops(const post_ops ops) { + error::wrap_c_api(dnnl_primitive_attr_set_post_ops(get(), ops.get()), + "could not set post-ops primitive attribute"); + } + + /// Sets quantization scale and shift parameters for RNN data tensors. + /// + /// For performance reasons, the low-precision configuration of the RNN + /// primitives expect input activations to have the unsigned 8-bit integer + /// data type. The scale and shift parameters are used to quantize + /// floating-point data to unsigned integer and must be passed to the RNN + /// primitive using attributes. + /// + /// The quantization formula is `scale * data + shift`. + /// + /// Example usage: + /// @code + /// // RNN parameters + /// int l = 2, t = 2, mb = 32, sic = 32, slc = 32, dic = 32, dlc = 32; + /// // Activations quantization parameters + /// float scale = 63.f, shift = 64.f; + /// + /// primitive_attr attr; + /// + /// // Set scale and shift for int8 quantization of activation + /// attr.set_rnn_data_qparams(scale, shift); + /// + /// // Create an RNN primitive descriptor. + /// vanilla_rnn_forward::primitive_desc rnn_d( + /// engine, /* arguments */, attr); + /// @endcode + /// + /// @note + /// Quantization scale and shift are common for src_layer, src_iter, + /// dst_iter, and dst_layer. + /// + /// @param scale The value to scale the data by. + /// @param shift The value to shift the data by. + void set_rnn_data_qparams(float scale, float shift) { + error::wrap_c_api( + dnnl_primitive_attr_set_rnn_data_qparams(get(), scale, shift), + "could not set RNN data quantization parameters primitive " + "attribute"); + } + + /// Returns the quantization scale and shift parameters for RNN data + /// tensors. + /// + /// @note + /// Quantization scale and shift are common for src_layer, src_iter, + /// dst_iter, and dst_layer. + /// + /// @param scale The value to scale the data by. + /// @param shift The value to shift the data by. + void get_rnn_data_qparams(float &scale, float &shift) { + float c_scale, c_shift; + error::wrap_c_api(dnnl_primitive_attr_get_rnn_data_qparams( + get(), &c_scale, &c_shift), + "could not set RNN data quantization parameters primitive " + "attribute"); + scale = c_scale; + shift = c_shift; + } + + /// Sets quantization scaling factors for RNN weights tensors. The + /// low-precision configuration of the RNN primitives expect input weights + /// to use the signed 8-bit integer data type. The scaling factors are + /// used to quantize floating-point data to signed integer and must be + /// passed to RNN primitives using attributes. + /// + /// @note + /// The dimension order is always native and does not depend on the + /// actual layout used. For example, five-dimensional weights always + /// have (l, d, i, g, o) logical dimension ordering. + /// + /// @note + /// Quantization scales are common for weights_layer and + /// weights_iteration + /// + /// @param mask Scaling factors correspondence mask that defines the + /// correspondence between the output tensor dimensions and the @p + /// scales vector. The set i-th bit indicates that a dedicated scaling + /// factor should be used each index along that dimension. Set the + /// mask to 0 to use a common scaling factor for the whole output + /// tensor. + /// @param scales Constant vector of output scaling factors. The following + /// equality must hold: + /// \f$scales.size() = \prod\limits_{d \in mask} weights.dims[d].\f$ + /// Violations can only be detected when the attributes are used to + /// create a primitive descriptor. + void set_rnn_weights_qparams(int mask, const std::vector &scales) { + error::wrap_c_api(dnnl_primitive_attr_set_rnn_weights_qparams(get(), + (int)scales.size(), mask, scales.data()), + "could not set RNN weights quantization parameters primitive " + "attribute"); + } + + /// Returns the quantization scaling factors for RNN projection weights + /// tensors. + /// + /// @note + /// The dimension order is always native and does not depend on the + /// actual layout used. For example, five-dimensional weights always + /// have (l, d, i, g, o) logical dimension ordering. + /// + /// @param mask Scaling factors correspondence mask that defines the + /// correspondence between the output tensor dimensions and the @p + /// scales vector. The set i-th bit indicates that a dedicated scaling + /// factor should be used each index along that dimension. Set the + /// mask to 0 to use a common scaling factor for the whole output + /// tensor. + /// @param scales Constant vector of output scaling factors. The following + /// equality must hold: + /// \f$scales.size() = \prod\limits_{d \in mask} weights.dims[d].\f$ + /// Violations can only be detected when the attributes are used to + /// create a primitive descriptor. + void get_rnn_weights_qparams(int &mask, std::vector &scales) { + dnnl_dim_t count; + int c_mask; + const float *c_scales; + error::wrap_c_api(dnnl_primitive_attr_get_rnn_weights_qparams( + get(), &count, &c_mask, &c_scales), + "could not get primitive RNN weights quantization " + "parameters attributes"); + scales.resize(count); + + mask = c_mask; + for (dnnl_dim_t c = 0; c < count; c++) + scales[c] = c_scales[c]; + } + + /// Sets quantization scaling factors for RNN projection weights tensors. + // The low-precision configuration of the RNN primitives expect input + // weights to use the signed 8-bit integer data type. The scaling factors + // are used to quantize floating-point data to signed integer and must be + /// passed to RNN primitives using attributes. + /// + /// @note + /// The dimension order is always native and does not depend on the + /// actual layout used. For example, five-dimensional weights always + /// have (l, d, i, g, o) logical dimension ordering. + /// + /// @note + /// Quantization scales are common for weights_layer and + /// weights_iteration + /// + /// @param mask Scaling factors correspondence mask that defines the + /// correspondence between the output tensor dimensions and the @p + /// scales vector. The set i-th bit indicates that a dedicated scaling + /// factor should be used each index along that dimension. Set the + /// mask to 0 to use a common scaling factor for the whole output + /// tensor. + /// @param scales Constant vector of output scaling factors. The following + /// equality must hold: + /// \f$scales.size() = \prod\limits_{d \in mask} weights.dims[d].\f$ + /// Violations can only be detected when the attributes are used to + /// create a primitive descriptor. + void set_rnn_weights_projection_qparams( + int mask, const std::vector &scales) { + error::wrap_c_api( + dnnl_primitive_attr_set_rnn_weights_projection_qparams( + get(), (int)scales.size(), mask, scales.data()), + "could not set primitive RNN weights projection quantization " + "parameters attributes"); + } + + /// Returns the quantization scaling factors for RNN projection weights + /// tensors. + /// + /// @note + /// The dimension order is always native and does not depend on the + /// actual layout used. For example, five-dimensional weights always + /// have (l, d, i, g, o) logical dimension ordering. + /// + /// @param mask Scaling factors correspondence mask that defines the + /// correspondence between the output tensor dimensions and the @p + /// scales vector. The set i-th bit indicates that a dedicated scaling + /// factor should be used each index along that dimension. Set the + /// mask to 0 to use a common scaling factor for the whole output + /// tensor. + /// @param scales Constant vector of output scaling factors. The following + /// equality must hold: + /// \f$scales.size() = \prod\limits_{d \in mask} weights.dims[d].\f$ + /// Violations can only be detected when the attributes are used to + /// create a primitive descriptor. + void get_rnn_weights_projection_qparams( + int &mask, std::vector &scales) { + dnnl_dim_t count; + int c_mask; + const float *c_scales; + error::wrap_c_api( + dnnl_primitive_attr_get_rnn_weights_projection_qparams( + get(), &count, &c_mask, &c_scales), + "could not get primitive RNN weights projection quantization " + "parameters attributes"); + scales.resize(count); + + mask = c_mask; + for (dnnl_dim_t c = 0; c < count; c++) + scales[c] = c_scales[c]; + } +}; + +/// @} dnnl_api_attributes + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// Base class for all primitive descriptors. +struct primitive_desc_base : public handle { + using handle::handle; + + /// Default constructor. Produces an empty object. + primitive_desc_base() = default; + + /// Returns the engine of the primitive descriptor. + /// @returns The engine of the primitive descriptor. + engine get_engine() const { return query_engine(query::engine); } + + /// Returns implementation name. + /// @returns The implementation name. + const char *impl_info_str() const { + const char *res; + error::wrap_c_api(dnnl_primitive_desc_query( + get(), dnnl_query_impl_info_str, 0, &res), + "could not retrieve implementation info string from a " + "primitive descriptor"); + return res; + } + + /// Returns a memory::dim value (same as int64_t). + /// @param what The value to query. + /// @returns The result of the query. + memory::dim query_s64(query what) const { + memory::dim res; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl::convert_to_c(what), 0, &res); + return status == dnnl_success ? res : 0; + } + + /// Returns strides. + /// @returns Strides. + /// @returns An empty #dnnl::memory::dims if the primitive does not have + /// a strides parameter. + memory::dims get_strides() const { return query_dims(query::strides); } + + /// Returns dilations. + /// @returns Dilations. + /// @returns An empty #dnnl::memory::dims if the primitive does not have + /// a dilations parameter. + memory::dims get_dilations() const { return query_dims(query::dilations); } + + /// Returns a left padding. + /// @returns A left padding. + /// @returns An empty #dnnl::memory::dims if the primitive does not have + /// a left padding parameter. + memory::dims get_padding_l() const { return query_dims(query::padding_l); } + + /// Returns a right padding. + /// @returns A right padding. + /// @returns An empty #dnnl::memory::dims if the primitive does not have + /// a right padding parameter. + memory::dims get_padding_r() const { return query_dims(query::padding_r); } + + /// Returns an epsilon. + /// @returns An epsilon. + /// @returns Zero if the primitive does not have an epsilon parameter. + float get_epsilon() const { return query_f32(query::epsilon_f32); } + + /// Returns flags. + /// @tparam T Flags enumeration type. + /// @returns Flags. + /// @returns Zero if the primitive does not have a flags parameter. + template + T get_flags() const { + unsigned res; + dnnl_status_t status + = dnnl_primitive_desc_query(get(), dnnl_query_flags, 0, &res); + return static_cast(status == dnnl_success ? res : 0x0U); + } + + /// Returns an algorithm kind. + /// @returns An algorithm kind. + /// @returns #dnnl::algorithm::undef if the primitive does not have an + /// algorithm parameter. + dnnl::algorithm get_algorithm() const { return query_alg(query::alg_kind); } + + /// Returns an alpha. + /// @returns An alpha. + /// @returns Zero if the primitive does not have an alpha parameter. + float get_alpha() const { return query_f32(query::alpha_f32); } + + /// Returns a beta. + /// @returns A beta. + /// @returns Zero if the primitive does not have a beta parameter. + float get_beta() const { return query_f32(query::beta_f32); } + + /// Returns an axis. + /// @returns An axis. + /// @returns A negative number if the primitive does not have an axis + /// parameter. + int get_axis() const { + int res; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl_query_axis_s32, 0, &res); + return status == dnnl_success ? res : -1; + } + + /// Returns an LRN local size parameter. + /// @returns An LRN local size parameter. + /// @returns Zero if the primitive does not have an LRN local size + /// parameter. + memory::dim get_local_size() const { + return query_s64(query::local_size_s64); + } + + /// Returns an LRN K parameter. + /// @returns An LRN K parameter. + /// @returns Zero if the primitive does not have an LRN K parameter. + float get_k() const { return query_f32(query::k_f32); } + + /// Returns a reduction P parameter. + /// @returns A reduction P parameter. + /// @returns Zero if the primitive does not have a reduction P parameter. + float get_p() const { return query_f32(query::p_f32); } + + /// Returns a resampling factors parameters. + /// @returns A vector of factors. + /// @returns An empty vector if the primitive does not have a resampling + /// factors parameter. + std::vector get_factors() const { + float *factors; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl_query_factors, 0, &factors); + + const bool is_backward = get_prop_kind() != prop_kind::forward_training + && get_prop_kind() != prop_kind::forward_inference; + const_dnnl_memory_desc_t md = dnnl_primitive_desc_query_md(get(), + is_backward ? dnnl_query_diff_dst_md : dnnl_query_dst_md, 0); + + int ndims; + error::wrap_c_api( + dnnl_memory_desc_query(md, dnnl_query_ndims_s32, &ndims), + "could not query ndims from a memory descriptor"); + + return status == dnnl_success + ? std::vector(factors, factors + (ndims - 2)) + : std::vector {}; + } + + /// Returns an RNN cell kind parameter. + /// @returns An RNN cell kind parameter. + /// @returns #dnnl::algorithm::undef if the primitive does not have an + /// RNN cell kind parameter. + dnnl::algorithm get_cell_kind() const { + return query_alg(query::cell_kind); + } + + /// Returns an RNN direction parameter. + /// @returns An RNN direction parameter. + /// @returns #dnnl::rnn_direction::undef if the primitive does not have + /// an RNN direction parameter. + dnnl::rnn_direction get_direction() const { + dnnl_rnn_direction_t direction; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl_query_direction, 0, &direction); + return status == dnnl_success + ? static_cast(direction) + : dnnl::rnn_direction::undef; + } + + /// Returns an RNN activation kind parameter. + /// @returns An RNN activation kind parameter. + /// @returns #dnnl::algorithm::undef if the primitive does not have an + /// RNN activation kind parameter. + dnnl::algorithm get_activation_kind() const { + return query_alg(query::activation_kind); + } + + /// Returns a pooling kernel parameter. + /// @returns A pooling kernel parameter. + /// @returns An empty #dnnl::memory::dims if the primitive does not have + /// a pooling kernel parameter. + memory::dims get_kernel() const { return query_dims(query::kernel); } + + /// Returns a group size parameter. + /// @returns A group size parameter. + /// @returns Zero if the primitive does not have a group size + /// parameter. + memory::dim get_group_size() const { + return query_s64(query::group_size_s64); + } + + /// Returns a propagation kind. + /// @returns A propagation kind. + /// @returns #dnnl::prop_kind::undef if the primitive does not have + /// a propagation parameter. + dnnl::prop_kind get_prop_kind() const { + dnnl_prop_kind_t prop_kind; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl_query_prop_kind, 0, &prop_kind); + return status == dnnl_success ? static_cast(prop_kind) + : dnnl::prop_kind::undef; + } + + /// Returns a memory descriptor. + /// + /// @note + /// There are also convenience methods + /// #dnnl::primitive_desc_base::src_desc(), + /// #dnnl::primitive_desc_base::dst_desc(), and others. + /// + /// @param what The kind of parameter to query; can be + /// #dnnl::query::src_md, #dnnl::query::dst_md, etc. + /// @param idx Index of the parameter. For example, convolution bias can + /// be queried with what = #dnnl::query::weights_md and idx = 1. + /// @returns The requested memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// parameter of the specified kind or index. + memory::desc query_md(query what, int idx = 0) const { + std::vector valid_q {query::src_md, query::diff_src_md, + query::weights_md, query::diff_weights_md, query::dst_md, + query::diff_dst_md, query::workspace_md, query::scratchpad_md, + query::exec_arg_md}; + if (!std::any_of(valid_q.cbegin(), valid_q.cend(), + [=](query q) { return what == q; })) + DNNL_THROW_ERROR(dnnl_invalid_arguments, + "memory descriptor query is invalid"); + + const_dnnl_memory_desc_t cdesc = dnnl_primitive_desc_query_md( + get(), dnnl::convert_to_c(what), idx); + if (!cdesc) return memory::desc(); + + dnnl_memory_desc_t cloned_md = nullptr; + error::wrap_c_api(dnnl_memory_desc_clone(&cloned_md, cdesc), + "could not clone a memory descriptor"); + + return memory::desc(cloned_md); + } + + /// Returns a source memory descriptor. + /// @param idx Source index. + /// @returns Source memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// source parameter with index @p idx. + memory::desc src_desc(int idx) const { + return query_md(query::src_md, idx); + } + + /// Returns a destination memory descriptor. + /// @param idx Destination index. + /// @returns Destination memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// destination parameter with index @p idx. + memory::desc dst_desc(int idx) const { + return query_md(query::dst_md, idx); + } + + /// Returns a weights memory descriptor. + /// @param idx Weights index. + /// @returns Weights memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// weights parameter with index @p idx. + memory::desc weights_desc(int idx) const { + return query_md(query::weights_md, idx); + } + + /// Returns a diff source memory descriptor. + /// @param idx Diff source index. + /// @returns Diff source memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff source parameter with index @p idx. + memory::desc diff_src_desc(int idx) const { + return query_md(query::diff_src_md, idx); + } + + /// Returns a diff destination memory descriptor. + /// @param idx Diff destination index. + /// @returns Diff destination memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff destination parameter with index @p idx. + memory::desc diff_dst_desc(int idx) const { + return query_md(query::diff_dst_md, idx); + } + + /// Returns a diff weights memory descriptor. + /// @param idx Diff weights index. + /// @returns Diff weights memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff weights parameter with index @p idx. + memory::desc diff_weights_desc(int idx) const { + return query_md(query::diff_weights_md, idx); + } + + // Separate versions without the index argument for documentation + // purposes. + + /// Returns a source memory descriptor. + /// @returns Source memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// source parameter. + memory::desc src_desc() const { return src_desc(0); } + + /// Returns a destination memory descriptor. + /// @returns Destination memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// destination parameter. + memory::desc dst_desc() const { return dst_desc(0); } + + /// Returns a weights memory descriptor. + /// @returns Weights memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// weights parameter. + memory::desc weights_desc() const { return weights_desc(0); } + + /// Returns a diff source memory descriptor. + /// @returns Diff source memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff source memory with. + memory::desc diff_src_desc() const { return diff_src_desc(0); } + + /// Returns a diff destination memory descriptor. + /// @returns Diff destination memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff destination parameter. + memory::desc diff_dst_desc() const { return diff_dst_desc(0); } + + /// Returns a diff weights memory descriptor. + /// @returns Diff weights memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff weights parameter. + memory::desc diff_weights_desc() const { return diff_weights_desc(0); } + + /// Returns the workspace memory descriptor. + /// @returns Workspace memory descriptor. + /// @returns A zero memory descriptor if the primitive does not require + /// workspace parameter. + memory::desc workspace_desc() const { + return query_md(query::workspace_md, 0); + } + + /// Returns the scratchpad memory descriptor. + /// @returns scratchpad memory descriptor. + /// @returns A zero memory descriptor if the primitive does not require + /// scratchpad parameter. + /// @sa @ref dev_guide_attributes_scratchpad + memory::desc scratchpad_desc() const { + return query_md(query::scratchpad_md, 0); + } + + /// Returns the engine on which the scratchpad memory is located. + /// @returns The engine on which the scratchpad memory is located. + engine scratchpad_engine() const { + dnnl_engine_t c_engine; + error::wrap_c_api(dnnl_primitive_desc_query(get(), + dnnl::convert_to_c(query::scratchpad_engine), + 0, &c_engine), + "could not retrieve scratchpad engine from a primitive " + "descriptor"); + return engine(c_engine, true); + } + + /// Returns the primitive attributes. + /// @returns The primitive attributes. + primitive_attr get_primitive_attr() const { + const_dnnl_primitive_attr_t const_c_attr; + error::wrap_c_api(dnnl_primitive_desc_get_attr(get(), &const_c_attr), + "could not get attributes from a primitive descriptor"); + dnnl_primitive_attr_t c_attr; + error::wrap_c_api(dnnl_primitive_attr_clone(&c_attr, const_c_attr), + "could not clone primitive attributes"); + return primitive_attr(c_attr); + } + + /// Returns the kind of the primitive descriptor. + /// @returns The kind of the primitive descriptor. + dnnl::primitive::kind get_kind() const { + dnnl_primitive_kind_t kind; + error::wrap_c_api(dnnl_primitive_desc_query(get(), + dnnl_query_primitive_kind, 0, (void *)&kind), + "could not get primitive kind from a primitive descriptor"); + return static_cast(kind); + } + + /// Returns the cache blob ID of the primitive descriptor. + /// @returns The cache blob ID of the primitive descriptor. + std::vector get_cache_blob_id() const { + dnnl_dim_t count; + const uint8_t *c_id; + error::wrap_c_api( + dnnl_primitive_desc_query(get(), + dnnl::convert_to_c(query::cache_blob_id_size_s64), 0, + (void *)&count), + "could not get size of cache blob ID from a primitive " + "descriptor"); + error::wrap_c_api(dnnl_primitive_desc_query(get(), + dnnl::convert_to_c(query::cache_blob_id), 0, + (void **)&c_id), + "could not get cache blob ID from a primitive descriptor"); + std::vector id(c_id, c_id + count); + return id; + } + +protected: + /// Returns a float value. + /// @param what The value to query. + /// @returns The result of the query. + /// @returns Zero if the primitive doesn't support the query. + float query_f32(query what) const { + float res; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl::convert_to_c(what), 0, &res); + return status == dnnl_success ? res : 0.0f; + } + + /// Returns an #dnnl::algorithm value. + /// @param what The value to query. + /// @returns The result of the query. + /// @returns #dnnl::algorithm::undef if the primitive doesn't support + /// the query. + algorithm query_alg(query what) const { + dnnl_alg_kind_t res; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl::convert_to_c(what), 0, &res); + return status == dnnl_success ? static_cast(res) + : algorithm::undef; + } + + /// Returns a memory::dims value. + /// @param what The value to query. + /// @returns The result of the query. + /// @returns An empty #dnnl::memory::dims if the primitive doesn't support + /// the query. + memory::dims query_dims(query what) const { + const bool is_backward = get_prop_kind() != prop_kind::forward_training + && get_prop_kind() != prop_kind::forward_inference; + const_dnnl_memory_desc_t md = dnnl_primitive_desc_query_md(get(), + is_backward ? dnnl_query_diff_dst_md : dnnl_query_dst_md, 0); + + int nspatial_dims = 0; + if (md) { + int ndims; + error::wrap_c_api( + dnnl_memory_desc_query(md, dnnl_query_ndims_s32, &ndims), + "could not query ndims from a memory descriptor"); + nspatial_dims = ndims - 2; + } + + dnnl_dims_t *c_dims; + dnnl_status_t status = dnnl_primitive_desc_query( + get(), dnnl::convert_to_c(what), 0, &c_dims); + return status == dnnl_success + ? memory::dims(*c_dims, *c_dims + nspatial_dims) + : memory::dims {}; + } + + /// Returns an #dnnl::engine value. + /// @param what The value to query. + /// @returns The result of the query. + /// @returns A weak handle to the engine that the primitive descriptor was + /// created with. + engine query_engine(query what) const { + dnnl_engine_t c_engine; + error::wrap_c_api(dnnl_primitive_desc_query(get(), + dnnl::convert_to_c(what), 0, &c_engine), + "could not get an engine from a primitive_desc"); + return engine(c_engine, true); + } + + /// Resets the value of the handle to a clone of a C API primitive + /// descriptor. + /// @param pd A C API primitive descriptor to clone. + void reset_with_clone(const_dnnl_primitive_desc_t pd) { + dnnl_primitive_desc_t new_pd; + error::wrap_c_api(dnnl_primitive_desc_clone(&new_pd, pd), + "could not clone a primitive descriptor"); + reset(new_pd); + } + + /// Constructs a primitive descriptor base object from a clone of a C API + /// primitive descriptor after verifying that it is what the caller + /// expects. + /// + /// @note + /// The @p prim_kind should map to a primitive that does not have + /// different values of propagation kind (e.g. #dnnl::binary). + /// @note + /// Primitive descriptor base constructed this way does not support + /// next_impl() (will throw). + /// + /// @param pd C API primitive descriptor to clone. + /// @param prim_kind Expected primitive kind. + primitive_desc_base( + dnnl_primitive_desc_t pd, dnnl::primitive::kind prim_kind) + : primitive_desc_base(pd, prim_kind, dnnl::prop_kind::undef) {} + + /// Constructs a primitive descriptor base object from a clone of a C API + /// primitive descriptor after verifying that it is what the caller + /// expects. + /// + /// @note + /// Primitive descriptor base constructed this way does not support + /// next_impl() (will throw). + /// + /// @param pd C API primitive descriptor to clone. + /// @param prim_kind Expected primitive kind. + /// @param aprop_kind Expected propagation kind. + primitive_desc_base(dnnl_primitive_desc_t pd, + dnnl::primitive::kind prim_kind, dnnl::prop_kind aprop_kind) + : primitive_desc_base(pd, prim_kind, aprop_kind, aprop_kind) {} + + /// Constructs a primitive descriptor base object from a clone of a C API + /// primitive descriptor after verifying that it is what the caller + /// expects. + /// + /// @note + /// Primitive descriptor base constructed this way does not support + /// next_impl() (will throw). + /// + /// @param pd C API primitive descriptor to clone. + /// @param prim_kind Expected primitive kind. + /// @param prop_kind1 Expected propagation kind (option 1). + /// @param prop_kind2 Expected propagation kind (option 2). This value is + /// checked if the check with @p prop_kind1 fails. + primitive_desc_base(dnnl_primitive_desc_t pd, + dnnl::primitive::kind prim_kind, dnnl::prop_kind prop_kind1, + dnnl::prop_kind prop_kind2) { + // It is OK to pass an empty primitive descriptor + if (pd == nullptr) return; + + dnnl_status_t rc; + + dnnl_primitive_kind_t c_prim_kind = convert_to_c(prim_kind); + dnnl_prop_kind_t c_prop_kind1 = convert_to_c(prop_kind1); + dnnl_prop_kind_t c_prop_kind2 = convert_to_c(prop_kind2); + + // Check that primitive kind matches + dnnl_primitive_kind_t pd_kind; + rc = dnnl_primitive_desc_query( + pd, dnnl_query_primitive_kind, 0, (void *)&pd_kind); + error::wrap_c_api( + rc, "could not get primitive kind from a primitive descriptor"); + if (pd_kind != c_prim_kind) + DNNL_THROW_ERROR(dnnl_invalid_arguments, + "primitive descriptor operation kind mismatch"); + + // Check that propagation kind matches + dnnl_prop_kind_t pd_prop_kind; + rc = dnnl_primitive_desc_query( + pd, dnnl_query_prop_kind, 0, (void *)&pd_prop_kind); + + // Something went wrong + if (rc != dnnl_success && rc != dnnl_unimplemented) + DNNL_THROW_ERROR(dnnl_invalid_arguments, + "could not get propagation kind from the primitive " + "descriptor"); + + // Everything is fine + if ((rc == dnnl_unimplemented && c_prop_kind1 == dnnl_prop_kind_undef) + || (rc == dnnl_success + && (pd_prop_kind == c_prop_kind1 + || pd_prop_kind == c_prop_kind2))) { + reset_with_clone(pd); + return; + } + + // We could get the propagation kind but there is a mismatch + DNNL_THROW_ERROR(dnnl_invalid_arguments, + "primitive descriptor propagation kind mismatch"); + } + + /// Returns a constant reference to a static instance of default constructed + /// primitive attributes + static const primitive_attr &default_attr() { + static const primitive_attr attr; + return attr; + } + + const_dnnl_memory_desc_t optional_arg(const memory::desc *md) { + return md ? md->get() : nullptr; + } + + const dnnl_dim_t *optional_arg(const memory::dims *dims) { + return dims ? dims->data() : nullptr; + } + + const float *optional_arg(const std::vector *arg) { + return arg ? arg->data() : nullptr; + } + + using base = primitive_desc_base; +}; + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_reorder Reorder +/// +/// A primitive to copy data between two memory objects. This primitive is +/// typically used to change the way the data is laid out in memory. +/// +/// @sa @ref dev_guide_reorder in developer guide +/// +/// @{ + +/// Reorder primitive. +struct reorder : public primitive { + /// Primitive descriptor for a reorder primitive. + struct primitive_desc : public primitive_desc_base { + using primitive_desc_base::primitive_desc_base; + + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for reorder primitive. + /// + /// @note + /// If @p allow_empty is true, the constructor does not throw if a + /// primitive descriptor cannot be created. + /// + /// @param src_engine Engine on which the source memory object will be + /// located. + /// @param src_md Source memory descriptor. + /// @param dst_engine Engine on which the destination memory object + /// will be located. + /// @param dst_md Destination memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is allowed + /// to fail without throwing an exception. In this case an empty + /// object will be produced. This flag is optional and defaults to + /// false. + primitive_desc(const engine &src_engine, const memory::desc &src_md, + const engine &dst_engine, const memory::desc &dst_md, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t result; + dnnl_status_t status = dnnl_reorder_primitive_desc_create(&result, + src_md.get(), src_engine.get(), dst_md.get(), + dst_engine.get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a reorder " + "primitive"); + reset(status == dnnl_success ? result : dnnl_primitive_desc_t()); + } + + /// Constructs a primitive descriptor for reorder primitive. + /// + /// @param src Source memory object. It is used to obtain the source + /// memory descriptor and engine. + /// @param dst Destination memory object. It is used to obtain the + /// destination memory descriptor and engine. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is allowed + /// to fail without throwing an exception. In this case an empty + /// object will be produced. This flag is optional and defaults to + /// false. + primitive_desc(const memory &src, const memory &dst, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t result; + auto src_md = src.get_desc(); + auto dst_md = dst.get_desc(); + dnnl_status_t status = dnnl_reorder_primitive_desc_create(&result, + src_md.get(), src.get_engine().get(), dst_md.get(), + dst.get_engine().get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a reorder " + "primitive"); + reset(status == dnnl_success ? result : dnnl_primitive_desc_t()); + } + + /// Constructs a primitive descriptor for reorder primitive from a C + /// API primitive descriptor which must have a matching kind. + /// + /// @param pd C API primitive descriptor for reorder primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : primitive_desc_base(pd, dnnl::primitive::kind::reorder) {} + + /// Returns the engine on which the source memory is allocated. + /// @returns The engine on which the source memory is allocated. + engine get_src_engine() const { + return query_engine(dnnl::query::reorder_src_engine); + } + + /// Returns the engine on which the destination memory is allocated. + /// @returns The engine on which the destination memory is allocated. + engine get_dst_engine() const { + return query_engine(dnnl::query::reorder_dst_engine); + } + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + }; + + /// Default constructor. Produces an empty object. + reorder() = default; + + /// Constructs a reorder primitive. + /// @param pd Primitive descriptor for reorder primitive. + reorder(const primitive_desc &pd) : primitive(pd.get()) {} + + /// Constructs a reorder primitive from a cache blob. + /// @param pd Primitive descriptor for reorder primitive. + /// @param cache_blob Cache blob. + reorder(const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd.get(), cache_blob) {} + + /// Constructs a reorder primitive that would reorder data between memory + /// objects having the same memory descriptors as memory objects @p src and + /// @p dst. + /// + /// @param src Source memory object. + /// @param dst Destination memory object. + /// @param attr Primitive attributes to use (optional). + reorder(const memory &src, const memory &dst, + const primitive_attr &attr = primitive_attr()) + : primitive(primitive_desc(src, dst, attr).get()) {} + + using primitive::execute; + + /// Executes the reorder primitive. + /// + /// @param astream Stream object. The stream must belong to the same engine + /// as the primitive. + /// @param src Source memory object. + /// @param dst Destination memory object. + void execute(const stream &astream, memory &src, memory &dst) const { + primitive::execute(astream, {{DNNL_ARG_FROM, src}, {DNNL_ARG_TO, dst}}); + } +}; + +/// @} dnnl_api_reorder + +/// @addtogroup dnnl_api_concat Concat +/// +/// A primitive to concatenate data by arbitrary dimension. +/// +/// @sa @ref dev_guide_concat in developer guide +/// +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS +inline std::vector convert_to_c( + const std::vector &mds) { + std::vector c_mds; + c_mds.reserve(mds.size()); + for (const auto &md : mds) + c_mds.push_back(md.get()); + return c_mds; +} +/// @endcond + +/// Tensor concatenation (concat) primitive. +struct concat : public primitive { + /// Primitive descriptor for a concat primitive. + struct primitive_desc : public primitive_desc_base { + using primitive_desc_base::primitive_desc_base; + + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an out-of-place concatenation + /// primitive. + /// + /// @param aengine Engine to perform the operation on. + /// @param dst Destination memory descriptor. + /// @param concat_dimension Source tensors will be concatenated over + /// dimension with this index. Note that order of dimensions does + /// not depend on memory format. + /// @param srcs Vector of source memory descriptors. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &dst, + int concat_dimension, const std::vector &srcs, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + auto c_srcs = convert_to_c(srcs); + + dnnl_primitive_desc_t result; + dnnl_status_t status = dnnl_concat_primitive_desc_create(&result, + aengine.get(), dst.get(), (int)c_srcs.size(), + concat_dimension, c_srcs.data(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a concat " + "primitive"); + reset(status == dnnl_success ? result : dnnl_primitive_desc_t()); + } + + /// Constructs a primitive descriptor for an out-of-place concatenation + /// primitive. + /// + /// This version derives the destination memory descriptor + /// automatically. + /// + /// @param aengine Engine to perform the operation on. + /// @param concat_dimension Source tensors will be concatenated over + /// dimension with this index. Note that order of dimensions does + /// not depend on memory format. + /// @param srcs Vector of source memory descriptors. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, int concat_dimension, + const std::vector &srcs, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + auto c_api_srcs = convert_to_c(srcs); + + dnnl_primitive_desc_t result; + dnnl_status_t status = dnnl_concat_primitive_desc_create(&result, + aengine.get(), nullptr, (int)c_api_srcs.size(), + concat_dimension, c_api_srcs.data(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a concat " + "primitive"); + reset(status == dnnl_success ? result : dnnl_primitive_desc_t()); + } + + /// Constructs a primitive descriptor for concat primitive from a C + /// API primitive descriptor which must have a matching kind. + /// + /// @param pd C API primitive descriptor for concat primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : primitive_desc_base(pd, dnnl::primitive::kind::concat) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc(int)const + memory::desc src_desc(int idx = 0) const { return base::src_desc(idx); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + }; + + /// Default constructor. Produces an empty object. + concat() = default; + + /// Constructs a concatenation primitive. + /// @param pd Primitive descriptor for concatenation primitive. + concat(const primitive_desc &pd) : primitive(pd.get()) {} + + /// Constructs a concatenation primitive from a cache blob. + /// @param pd Primitive descriptor for concatenation primitive. + /// @param cache_blob Cache blob. + concat(const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd.get(), cache_blob) {} +}; + +/// @} dnnl_api_concat + +/// @addtogroup dnnl_api_sum Sum +/// +/// A primitive to sum multiple tensors. +/// +/// @sa @ref dev_guide_sum in developer guide +/// +/// @{ + +/// Out-of-place summation (sum) primitive. +struct sum : public primitive { + /// Primitive descriptor for a sum primitive. + struct primitive_desc : public primitive_desc_base { + using primitive_desc_base::primitive_desc_base; + + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a sum primitive. + /// + /// @param aengine Engine to perform the operation on. + /// @param dst Destination memory descriptor. + /// @param scales Vector of scales to multiply data in each source + /// memory by. + /// @param srcs Vector of source memory descriptors. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &dst, + const std::vector &scales, + const std::vector &srcs, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + validate_container_size(scales, + "counts of scales and sources are not equal", + (int)srcs.size(), (int)srcs.size()); + + auto c_api_srcs = convert_to_c(srcs); + + dnnl_primitive_desc_t result; + dnnl_status_t status = dnnl_sum_primitive_desc_create(&result, + aengine.get(), dst.get(), (int)c_api_srcs.size(), + scales.data(), c_api_srcs.data(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a sum " + "primitive"); + reset(status == dnnl_success ? result : dnnl_primitive_desc_t()); + } + + /// Constructs a primitive descriptor for a sum primitive. + /// + /// This version derives the destination memory descriptor + /// automatically. + /// + /// @param aengine Engine on which to perform the operation. + /// @param scales Vector of scales by which to multiply data in each + /// source memory object. + /// @param srcs Vector of source memory descriptors. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const std::vector &scales, + const std::vector &srcs, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + validate_container_size(scales, + "counts of scales and sources are not equal", + (int)srcs.size(), (int)srcs.size()); + + auto c_api_srcs = convert_to_c(srcs); + dnnl_primitive_desc_t result; + dnnl_status_t status = dnnl_sum_primitive_desc_create(&result, + aengine.get(), nullptr, (int)c_api_srcs.size(), + scales.data(), c_api_srcs.data(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a sum " + "primitive"); + reset(status == dnnl_success ? result : dnnl_primitive_desc_t()); + } + + /// Constructs a primitive descriptor for sum primitive from a C API + /// primitive descriptor which must have a matching kind. + /// + /// @param pd C API primitive descriptor for sum primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : primitive_desc_base(pd, dnnl::primitive::kind::sum) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc(int)const + memory::desc src_desc(int idx = 0) const { return base::src_desc(idx); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + }; + + /// Default constructor. Produces an empty object. + sum() = default; + + /// Constructs a sum primitive. + /// @param pd Primitive descriptor for sum primitive. + sum(const primitive_desc &pd) : primitive(pd.get()) {} + + /// Constructs a sum primitive from a cache blob. + /// @param pd Primitive descriptor for sum primitive. + /// @param cache_blob Cache blob. + sum(const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd.get(), cache_blob) {} +}; + +/// @} dnnl_api_sum + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// A base class for descriptors of all primitives that support iteration +/// over multiple implementations. +struct primitive_desc : public primitive_desc_base { + using primitive_desc_base::primitive_desc_base; + + primitive_desc() = default; + + /// Changes the primitive descriptor to point to the next available + /// implementation. + /// + /// @returns @c true on success and @c false if the last available + /// implementation has already been reached. In the latter case, the + /// primitive descriptor itself is kept unchanged. + bool next_impl() { + dnnl_status_t status = dnnl_primitive_desc_next_impl(get()); + if (status == dnnl_last_impl_reached) return false; + error::wrap_c_api(status, "last available implementation is reached"); + return true; + } +}; + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_convolution Convolution +/// +/// A primitive to perform 1D, 2D or 3D convolution. Supported variants are +/// forward propagation, backward propagation, and weights gradient with or +/// without bias. +/// +/// @sa @ref dev_guide_convolution in developer guide +/// +/// @{ + +/// Convolution forward propagation primitive. +struct convolution_forward : public primitive { + /// Primitive descriptor for a convolution forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a convolution forward + /// propagation primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param bias_desc Bias memory descriptor. Passing zero memory + /// descriptor disables the bias term. + /// @param dst_desc Destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &bias_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, &bias_desc, dst_desc, strides, nullptr, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution forward + /// propagation primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &dst_desc, + const memory::dims &strides, const memory::dims &padding_l, + const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, nullptr, dst_desc, strides, nullptr, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution forward + /// propagation primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param bias_desc Bias memory descriptor. Passing zero memory + /// descriptor disables the bias term. + /// @param dst_desc Destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &bias_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, &bias_desc, dst_desc, strides, &dilates, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution forward + /// propagation primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &dst_desc, + const memory::dims &strides, const memory::dims &dilates, + const memory::dims &padding_l, const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, nullptr, dst_desc, strides, &dilates, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a convolution forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::convolution, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// Returns the bias memory descriptor. + /// @returns The bias memory descriptor. + /// @returns A zero memory descriptor of the primitive does not have a + /// bias parameter. + memory::desc bias_desc() const { return base::weights_desc(1); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + + private: + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc *bias_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims *dilates, const memory::dims &padding_l, + const memory::dims &padding_r, const primitive_attr &attr, + bool allow_empty) { + + memory::validate_dims(strides, src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, src_desc.get_ndims() - 2); + + if (dilates) + memory::validate_dims(*dilates, src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_convolution_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + convert_to_c(aalgorithm), src_desc.get(), + weights_desc.get(), optional_arg(bias_desc), + dst_desc.get(), &strides[0], optional_arg(dilates), + &padding_l[0], &padding_r[0], attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "convolution forward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + convolution_forward() = default; + + /// Constructs a convolution forward propagation primitive. + /// @param pd Primitive descriptor for a convolution forward propagation + /// primitive. + convolution_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a convolution forward propagation primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a convolution forward propagation + /// primitive. + /// @param cache_blob Cache blob. + convolution_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Convolution backward propagation primitive. +struct convolution_backward_data : public primitive { + /// Primitive descriptor for a convolution backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a convolution backward + /// propagation primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param diff_src_desc Diff source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, weights_desc, + diff_dst_desc, strides, nullptr, padding_l, padding_r, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution backward + /// propagation primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param diff_src_desc Diff source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, weights_desc, + diff_dst_desc, strides, &dilates, padding_l, padding_r, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a convolution backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::convolution, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + + private: + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims *dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + memory::validate_dims(strides, diff_src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, diff_src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, diff_src_desc.get_ndims() - 2); + + if (dilates) + memory::validate_dims(*dilates, diff_src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_convolution_backward_data_primitive_desc_create(&pd, + aengine.get(), convert_to_c(aalgorithm), + diff_src_desc.get(), weights_desc.get(), + diff_dst_desc.get(), &strides[0], + optional_arg(dilates), &padding_l[0], &padding_r[0], + hint_fwd_pd.get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "convolution backward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + convolution_backward_data() = default; + + /// Constructs a convolution backward propagation primitive. + /// @param pd Primitive descriptor for a convolution backward propagation + /// primitive. + convolution_backward_data(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a convolution backward propagation primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a convolution backward propagation + /// primitive. + /// @param cache_blob Cache blob. + convolution_backward_data( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Convolution weights gradient primitive. +struct convolution_backward_weights : public primitive { + /// Primitive descriptor for a convolution weights gradient primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a convolution weights gradient + /// primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_bias_desc Diff bias memory descriptor. Passing zero + /// memory descriptor disables the bias term. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + &diff_bias_desc, diff_dst_desc, strides, nullptr, padding_l, + padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution weights gradient + /// primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + nullptr, diff_dst_desc, strides, nullptr, padding_l, + padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution weights + /// gradient primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_bias_desc Diff bias memory descriptor. Passing zero + /// memory descriptor disables the bias term. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + &diff_bias_desc, diff_dst_desc, strides, &dilates, + padding_l, padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution weights + /// gradient primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Convolution algorithm. Possible values are + /// #dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd, and + /// #dnnl::algorithm::convolution_auto. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + nullptr, diff_dst_desc, strides, &dilates, padding_l, + padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a convolution weights gradient + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a convolution weights + /// gradient primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::convolution, + dnnl::prop_kind::backward_weights) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_weights_desc()const + memory::desc diff_weights_desc() const { + return base::diff_weights_desc(0); + } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// Returns the diff bias memory descriptor. + /// @returns The diff bias memory descriptor. + /// @returns A zero memory descriptor of the primitive does not have a + /// diff bias parameter. + memory::desc diff_bias_desc() const { + return base::diff_weights_desc(1); + } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + + private: + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc *diff_bias_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims *dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const convolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + memory::validate_dims(strides, src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, src_desc.get_ndims() - 2); + + if (dilates) + memory::validate_dims(*dilates, src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_convolution_backward_weights_primitive_desc_create( + &pd, aengine.get(), convert_to_c(aalgorithm), + src_desc.get(), diff_weights_desc.get(), + optional_arg(diff_bias_desc), diff_dst_desc.get(), + &strides[0], optional_arg(dilates), &padding_l[0], + &padding_r[0], hint_fwd_pd.get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "convolution weights update primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + convolution_backward_weights() = default; + + /// Constructs a convolution weights gradient primitive. + /// @param pd Primitive descriptor for a convolution weights gradient + /// primitive. + convolution_backward_weights(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a convolution weights gradient primitive from a cache blob. + /// @param pd Primitive descriptor for a convolution weights gradient + /// primitive. + /// @param cache_blob Cache blob. + convolution_backward_weights( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_convolution +// +/// @addtogroup dnnl_api_deconvolution Deconvolution +/// +/// A primitive to perform 1D, 2D or 3D deconvolution. Supported variants are +/// forward propagation, backward propagation, and weights gradient with or +/// without bias. +/// +/// @{ + +/// Deconvolution forward propagation primitive. +struct deconvolution_forward : public primitive { + /// Primitive descriptor for a deconvolution forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a deconvolution forward + /// propagation primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Deconvolution algorithm: + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param bias_desc Bias memory descriptor. Passing zero memory + /// descriptor disables the bias term. + /// @param dst_desc Destination memory descriptor. + /// @param strides Vector of strides for spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &bias_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, &bias_desc, dst_desc, strides, nullptr, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution forward + /// propagation primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Deconvolution algorithm: + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param strides Vector of strides for spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &dst_desc, + const memory::dims &strides, const memory::dims &padding_l, + const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, nullptr, dst_desc, strides, nullptr, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution forward + /// propagation primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Deconvolution algorithm: + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param bias_desc Bias memory descriptor. Passing zero memory + /// descriptor disables the bias term. + /// @param dst_desc Destination memory descriptor. + /// @param strides Vector of strides for spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &bias_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, &bias_desc, dst_desc, strides, &dilates, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution forward + /// propagation primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Deconvolution algorithm: + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param strides Vector of strides for spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &dst_desc, + const memory::dims &strides, const memory::dims &dilates, + const memory::dims &padding_l, const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + weights_desc, nullptr, dst_desc, strides, &dilates, + padding_l, padding_r, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a deconvolution forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::deconvolution, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::convolution_forward::primitive_desc::bias_desc()const + memory::desc bias_desc() const { return base::weights_desc(1); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + + private: + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc *bias_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims *dilates, const memory::dims &padding_l, + const memory::dims &padding_r, const primitive_attr &attr, + bool allow_empty) { + + memory::validate_dims(strides, src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, src_desc.get_ndims() - 2); + + if (dilates) + memory::validate_dims(*dilates, src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_deconvolution_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + convert_to_c(aalgorithm), src_desc.get(), + weights_desc.get(), optional_arg(bias_desc), + dst_desc.get(), &strides[0], optional_arg(dilates), + &padding_l[0], &padding_r[0], attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "deconvolution forward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + deconvolution_forward() = default; + + /// Constructs a deconvolution forward propagation primitive. + /// @param pd Primitive descriptor for a deconvolution forward propagation + /// primitive. + deconvolution_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a deconvolution forward propagation primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a deconvolution forward propagation + /// primitive. + /// @param cache_blob Cache blob. + deconvolution_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Deconvolution backward propagation primitive. +struct deconvolution_backward_data : public primitive { + /// Primitive descriptor for a deconvolution backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a deconvolution backward + /// propagation primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Deconvolution algorithm + /// (#dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd). + /// @param diff_src_desc Diff source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a deconvolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, weights_desc, + diff_dst_desc, strides, nullptr, padding_l, padding_r, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution backward + /// propagation primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Deconvolution algorithm + /// (#dnnl::algorithm::convolution_direct, + /// #dnnl::algorithm::convolution_winograd). + /// @param diff_src_desc Diff source memory descriptor. + /// @param weights_desc Weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a deconvolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, weights_desc, + diff_dst_desc, strides, &dilates, padding_l, padding_r, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a deconvolution backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::deconvolution, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + + private: + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims *dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + memory::validate_dims(strides, diff_src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, diff_src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, diff_src_desc.get_ndims() - 2); + + if (dilates) + memory::validate_dims(*dilates, diff_src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_deconvolution_backward_data_primitive_desc_create( + &pd, aengine.get(), convert_to_c(aalgorithm), + diff_src_desc.get(), weights_desc.get(), + diff_dst_desc.get(), &strides[0], + optional_arg(dilates), &padding_l[0], &padding_r[0], + hint_fwd_pd.get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "deconvolution backward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + deconvolution_backward_data() = default; + + /// Constructs a deconvolution backward propagation primitive. + /// @param pd Primitive descriptor for a deconvolution backward propagation + /// primitive. + deconvolution_backward_data(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a deconvolution backward propagation primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a deconvolution backward propagation + /// primitive. + /// @param cache_blob Cache blob. + deconvolution_backward_data( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Deconvolution weights gradient primitive. +struct deconvolution_backward_weights : public primitive { + /// Primitive descriptor for a deconvolution weights gradient primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a deconvolution weights + /// gradient primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Deconvolution algorithm. Possible values are + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_bias_desc Diff bias memory descriptor. Passing zero + /// memory descriptor disables the bias term. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a deconvolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + &diff_bias_desc, diff_dst_desc, strides, nullptr, padding_l, + padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution weights + /// gradient primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p padding_l, and @p padding_r contain values + /// for spatial dimensions only and hence must have the same number of + /// elements as there are spatial dimensions. The order of values is + /// the same as in the tensor: depth (for 3D tensors), height (for 3D + /// and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Deconvolution algorithm. Possible values are + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a deconvolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &padding_l, const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + nullptr, diff_dst_desc, strides, nullptr, padding_l, + padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution weights + /// gradient primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Deconvolution algorithm. Possible values are + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_bias_desc Diff bias memory descriptor. Passing zero + /// memory descriptor disables the bias term. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a deconvolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + &diff_bias_desc, diff_dst_desc, strides, &dilates, + padding_l, padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution weights + /// gradient primitive without bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// Arrays @p strides, @p dilates, @p padding_l, and @p padding_r + /// contain values for spatial dimensions only and hence must have the + /// same number of elements as there are spatial dimensions. The order + /// of values is the same as in the tensor: depth (for 3D tensors), + /// height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Deconvolution algorithm. Possible values are + /// #dnnl::algorithm::deconvolution_direct, and + /// #dnnl::algorithm::deconvolution_winograd. + /// @param src_desc Source memory descriptor. + /// @param diff_weights_desc Diff weights memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Strides for each spatial dimension. + /// @param dilates Dilations for each spatial dimension. A zero value + /// means no dilation in the corresponding dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a deconvolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, src_desc, diff_weights_desc, + nullptr, diff_dst_desc, strides, &dilates, padding_l, + padding_r, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a deconvolution weights + /// gradient primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a deconvolution weights + /// gradient primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::deconvolution, + dnnl::prop_kind::backward_weights) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_weights_desc()const + memory::desc diff_weights_desc() const { + return base::diff_weights_desc(0); + } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::convolution_backward_weights::primitive_desc::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return base::diff_weights_desc(1); + } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + + private: + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc *diff_bias_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims *dilates, const memory::dims &padding_l, + const memory::dims &padding_r, + const deconvolution_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + memory::validate_dims(strides, src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, src_desc.get_ndims() - 2); + + if (dilates) + memory::validate_dims(*dilates, src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_deconvolution_backward_weights_primitive_desc_create( + &pd, aengine.get(), convert_to_c(aalgorithm), + src_desc.get(), diff_weights_desc.get(), + optional_arg(diff_bias_desc), diff_dst_desc.get(), + &strides[0], optional_arg(dilates), &padding_l[0], + &padding_r[0], hint_fwd_pd.get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "deconvolution weights update primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + deconvolution_backward_weights() = default; + + /// Constructs a deconvolution weights gradient primitive. + /// @param pd Primitive descriptor for a deconvolution weights gradient + /// primitive. + deconvolution_backward_weights(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a deconvolution weights gradient primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a deconvolution weights gradient + /// primitive. + /// @param cache_blob Cache blob. + deconvolution_backward_weights( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_deconvolution + +/// @addtogroup dnnl_api_lrn LRN +/// +/// A primitive to perform local response normalization (LRN) across or within +/// channels. +/// +/// @sa @ref dev_guide_lrn in developer guide +/// +/// @{ + +/// Local response normalization (LRN) forward propagation primitive. +struct lrn_forward : public primitive { + /// Primitive descriptor for an LRN forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an LRN forward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm LRN algorithm kind: either + /// #dnnl::algorithm::lrn_across_channels, or + /// #dnnl::algorithm::lrn_within_channel. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param local_size Regularization local size. + /// @param alpha The alpha regularization parameter. + /// @param beta The beta regularization parameter. + /// @param k The k regularization parameter. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, memory::dim local_size, + float alpha, float beta, float k, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_lrn_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + convert_to_c(aalgorithm), src_desc.get(), dst_desc.get(), + local_size, alpha, beta, k, attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a lrn " + "forward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for an LRN forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an LRN forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::lrn, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_alpha()const + float get_alpha() const { return base::get_alpha(); } + + /// @copydoc dnnl::primitive_desc_base::get_beta()const + float get_beta() const { return base::get_beta(); } + + /// @copydoc dnnl::primitive_desc_base::get_local_size()const + memory::dim get_local_size() const { return base::get_local_size(); } + + /// @copydoc dnnl::primitive_desc_base::get_k()const + float get_k() const { return base::get_k(); } + }; + + /// Default constructor. Produces an empty object. + lrn_forward() = default; + + /// Constructs an LRN forward propagation primitive. + /// @param pd Primitive descriptor for an LRN forward propagation + /// primitive. + lrn_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LRN forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LRN forward propagation + /// primitive. + /// @param cache_blob Cache blob. + lrn_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Local response normalization (LRN) backward propagation primitive. +struct lrn_backward : public primitive { + /// Primitive descriptor for an LRN backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an LRN backward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aalgorithm LRN algorithm kind: either + /// #dnnl::algorithm::lrn_across_channels, or + /// #dnnl::algorithm::lrn_within_channel. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param local_size Regularization local size. + /// @param alpha The alpha regularization parameter. + /// @param beta The beta regularization parameter. + /// @param k The k regularization parameter. + /// @param hint_fwd_pd Primitive descriptor for an LRN forward + /// propagation primitive. It is used as a hint for deciding which + /// memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + memory::dim local_size, float alpha, float beta, float k, + const lrn_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_lrn_backward_primitive_desc_create(&pd, + aengine.get(), convert_to_c(aalgorithm), + diff_src_desc.get(), diff_dst_desc.get(), src_desc.get(), + local_size, alpha, beta, k, hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a lrn " + "backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for an LRN backward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an LRN backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::lrn, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_alpha()const + float get_alpha() const { return base::get_alpha(); } + + /// @copydoc dnnl::primitive_desc_base::get_beta()const + float get_beta() const { return base::get_beta(); } + + /// @copydoc dnnl::primitive_desc_base::get_local_size()const + memory::dim get_local_size() const { return base::get_local_size(); } + + /// @copydoc dnnl::primitive_desc_base::get_k()const + float get_k() const { return base::get_k(); } + }; + + /// Default constructor. Produces an empty object. + lrn_backward() = default; + + /// Constructs an LRN backward propagation primitive. + /// @param pd Primitive descriptor for an LRN backward propagation + /// primitive. + lrn_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LRN backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LRN backward propagation + /// primitive. + /// @param cache_blob Cache blob. + lrn_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_lrn + +/// @addtogroup dnnl_api_eltwise Eltwise +/// +/// A primitive to perform elementwise operations such as the +/// rectifier linear unit (ReLU). +/// +/// Both forward and backward propagation primitives support in-place +/// operation; that is, src and dst can refer to the same memory for forward +/// propagation, and diff_dst and diff_src can refer to the same memory for +/// backward propagation. +/// +/// @warning +/// Because the original source data is required for backward propagation, +/// in-place forward propagation is not generally supported in the +/// training mode. However, for algorithms supporting destination as input +/// memory, dst can be used for the backward propagation, which makes it +/// possible to get performance benefit even in the training mode. +/// +/// @sa @ref dev_guide_eltwise in developer guide +/// +/// @{ + +/// Elementwise unary operation forward propagation primitive. +struct eltwise_forward : public primitive { + /// Primitive descriptor for an elementwise forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an elementwise forward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Elementwise algorithm kind. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + dst_desc, nullptr, nullptr, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an elementwise forward + /// propagation primitive with an alpha parameter. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Elementwise algorithm kind. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param alpha The alpha parameter for the elementwise operation. + /// Specific meaning depends on the algorithm. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, float alpha, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + dst_desc, &alpha, nullptr, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an elementwise forward + /// propagation primitive with an alpha and beta parameters. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Elementwise algorithm kind. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param alpha The alpha parameter for the elementwise operation. + /// Specific meaning depends on the algorithm. + /// @param beta The beta parameter for the elementwise operation. + /// Specific meaning depends on the algorithm. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, float alpha, float beta, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, src_desc, + dst_desc, &alpha, &beta, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an eltwise forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for an eltwise forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::eltwise, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + dnnl::algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_alpha()const + float get_alpha() const { return base::get_alpha(); } + + /// @copydoc dnnl::primitive_desc_base::get_beta()const + float get_beta() const { return base::get_beta(); } + + private: + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, const float *alpha, + const float *beta, const primitive_attr &attr, + bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_eltwise_forward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(aalgorithm), src_desc.get(), + dst_desc.get(), alpha ? *alpha : 0.0f, beta ? *beta : 0.0f, + attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for an " + "eltwise forward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + eltwise_forward() = default; + + /// Constructs an eltwise forward propagation primitive. + /// @param pd Primitive descriptor for an eltwise forward propagation + /// primitive. + eltwise_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an eltwise forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an eltwise forward propagation + /// primitive. + /// @param cache_blob Cache blob. + eltwise_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Elementwise unary operation backward propagation primitive. +struct eltwise_backward : public primitive { + /// Primitive descriptor for eltwise backward propagation. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an elementwise backward + /// propagation primitive with an alpha parameter. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Elementwise algorithm kind. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param data_desc Destination memory descriptor if one of the + /// "use_dst_for_bwd" algorithms are used (such as + /// #dnnl_eltwise_relu_use_dst_for_bwd), source memory descriptor + /// otherwise. + /// @param hint_fwd_pd Primitive descriptor for an elementwise + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const memory::desc &data_desc, + const eltwise_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, diff_dst_desc, + data_desc, nullptr, nullptr, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for an elementwise backward + /// propagation primitive with an alpha parameter. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Elementwise algorithm kind. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param data_desc Destination memory descriptor if one of the + /// "use_dst_for_bwd" algorithms are used (such as + /// #dnnl_eltwise_relu_use_dst_for_bwd), source memory descriptor + /// otherwise. + /// @param alpha The alpha parameter for the elementwise operation. + /// Specific meaning depends on the algorithm. + /// @param hint_fwd_pd Primitive descriptor for an elementwise + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const memory::desc &data_desc, float alpha, + const eltwise_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, diff_dst_desc, + data_desc, &alpha, nullptr, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for an elementwise backward + /// propagation primitive with an alpha and beta parameters. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Elementwise algorithm kind. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param data_desc Destination memory descriptor if one of the + /// "use_dst_for_bwd" algorithms are used (such as + /// #dnnl_eltwise_relu_use_dst_for_bwd), source memory descriptor + /// otherwise. + /// @param alpha The alpha parameter for the elementwise operation. + /// Specific meaning depends on the algorithm. + /// @param beta The beta parameter for the elementwise operation. + /// Specific meaning depends on the algorithm. + /// @param hint_fwd_pd Primitive descriptor for an elementwise + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const memory::desc &data_desc, float alpha, float beta, + const eltwise_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, diff_src_desc, diff_dst_desc, + data_desc, &alpha, &beta, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an eltwise backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for an eltwise backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::eltwise, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + dnnl::algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_alpha()const + float get_alpha() const { return base::get_alpha(); } + + /// @copydoc dnnl::primitive_desc_base::get_beta()const + float get_beta() const { return base::get_beta(); } + + private: + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const memory::desc &data_desc, const float *alpha, + const float *beta, + const eltwise_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_eltwise_backward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aalgorithm), + diff_src_desc.get(), diff_dst_desc.get(), data_desc.get(), + alpha ? *alpha : 0.0f, beta ? *beta : 0.0f, + hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for an " + "eltwise backward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + eltwise_backward() = default; + + /// Constructs an eltwise backward propagation primitive. + /// @param pd Primitive descriptor for an eltwise backward propagation + /// primitive. + eltwise_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an eltwise backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an eltwise backward propagation + /// primitive. + /// @param cache_blob Cache blob. + eltwise_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_eltwise + +/// @addtogroup dnnl_api_softmax Softmax +/// +/// A primitive to perform softmax. +/// +/// @sa @ref dev_guide_softmax in developer guide +/// +/// @{ + +/// Softmax forward propagation primitive. +struct softmax_forward : public primitive { + /// Primitive descriptor for a softmax forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a softmax forward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Softmax algorithm kind: either + /// #dnnl::algorithm::softmax_accurate, + /// or #dnnl::algorithm::softmax_log. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param axis Axis over which softmax is computed. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, int axis, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_softmax_forward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(aalgorithm), src_desc.get(), + dst_desc.get(), axis, attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a softmax " + "forward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a softmax forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a softmax forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::softmax, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + dnnl::algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_axis()const + int get_axis() const { return base::get_axis(); } + }; + + /// Default constructor. Produces an empty object. + softmax_forward() = default; + + /// Constructs a softmax forward propagation primitive. + /// @param pd Primitive descriptor for a softmax forward propagation + /// primitive. + softmax_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a softmax forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a softmax forward propagation + /// primitive. + /// @param cache_blob Cache blob. + softmax_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Softmax backward propagation primitive. +struct softmax_backward : public primitive { + /// Primitive descriptor for a softmax backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a softmax backward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Softmax algorithm kind: either + /// #dnnl::algorithm::softmax_accurate, + /// or #dnnl::algorithm::softmax_log. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param axis Axis over which softmax is computed. + /// @param hint_fwd_pd Primitive descriptor for a softmax + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &dst_desc, + int axis, const softmax_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_softmax_backward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aalgorithm), + diff_src_desc.get(), diff_dst_desc.get(), dst_desc.get(), + axis, hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a softmax " + "backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a softmax backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a softmax backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::softmax, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + dnnl::algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_axis()const + int get_axis() const { return base::get_axis(); } + }; + + /// Default constructor. Produces an empty object. + softmax_backward() = default; + + /// Constructs a softmax backward propagation primitive. + /// @param pd Primitive descriptor for a softmax backward propagation + /// primitive. + softmax_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a softmax backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a softmax backward propagation + /// primitive. + /// @param cache_blob Cache blob. + softmax_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_softmax + +/// @addtogroup dnnl_api_batch_normalization Batch Normalization +/// +/// A primitive to perform batch normalization. +/// +/// Both forward and backward propagation primitives support in-place +/// operation; that is, src and dst can refer to the same memory for forward +/// propagation, and diff_dst and diff_src can refer to the same memory for +/// backward propagation. +/// +/// The batch normalization primitives computations can be controlled by +/// specifying different @ref dnnl::normalization_flags values. For example, +/// batch normalization forward propagation can be configured to either +/// compute the mean and variance or take them as arguments. It can either +/// perform scaling and shifting using gamma and beta parameters or not. +/// Optionally, it can also perform a fused ReLU, which in case of training +/// would also require a workspace. +/// +/// @sa @ref dev_guide_batch_normalization in developer guide +/// +/// @{ + +/// Batch normalization forward propagation primitive. +struct batch_normalization_forward : public primitive { + /// Primitive descriptor for a batch normalization forward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a batch normalization forward + /// propagation primitive. + /// + /// @note + /// In-place operation is supported: the dst can refer to the same + /// memory as the src. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param epsilon Batch normalization epsilon parameter. + /// @param flags Batch normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + float epsilon, normalization_flags flags, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_batch_normalization_forward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + src_desc.get(), dst_desc.get(), epsilon, + convert_to_c(flags), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a batch " + "normalization forward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a batch normalization + /// forward propagation primitive from a C API primitive descriptor + /// that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a batch normalization + /// forward propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, + dnnl::primitive::kind::batch_normalization, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// Returns memory descriptor for mean. + /// @returns Memory descriptor for mean. + memory::desc mean_desc() const { return stat_desc(mean); } + + /// Returns memory descriptor for variance. + /// @returns Memory descriptor for variance. + memory::desc variance_desc() const { return stat_desc(var); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// Returns normalization flags. + /// @return Normalization flags. + normalization_flags get_flags() const { + return base::get_flags(); + } + + private: + enum { + mean = 1, + var = 2, + }; + memory::desc stat_desc(int kind) const { + const bool use_global_stats + = (get_flags() & normalization_flags::use_global_stats) + != normalization_flags::none; + return query_md( + use_global_stats ? query::src_md : query::dst_md, kind); + } + }; + + /// Default constructor. Produces an empty object. + batch_normalization_forward() = default; + + /// Constructs a batch normalization forward propagation primitive. + /// @param pd Primitive descriptor for a batch normalization forward + /// propagation primitive. + batch_normalization_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a batch normalization forward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a batch normalization forward + /// propagation primitive. + /// @param cache_blob Cache blob. + batch_normalization_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Batch normalization backward propagation primitive. +struct batch_normalization_backward : public primitive { + /// Primitive descriptor for a batch normalization backward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a batch normalization backward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::backward_data and #dnnl::prop_kind::backward + /// (diffs for all parameters are computed in this case). + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param epsilon Batch normalization epsilon parameter. + /// @param flags Batch normalization flags (@ref + /// dnnl::normalization_flags). + /// @param hint_fwd_pd Primitive descriptor for a batch normalization + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + float epsilon, normalization_flags flags, + const batch_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_batch_normalization_backward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + diff_src_desc.get(), diff_dst_desc.get(), + src_desc.get(), epsilon, convert_to_c(flags), + hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a batch " + "normalization backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a batch normalization + /// backward propagation primitive from a C API primitive descriptor + /// that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a batch normalization + /// backward propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, + dnnl::primitive::kind::batch_normalization, + dnnl::prop_kind::backward, dnnl::prop_kind::backward_data) { + } + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_weights_desc()const + memory::desc diff_weights_desc() const { + return base::diff_weights_desc(0); + } + + /// @copydoc dnnl::batch_normalization_forward::primitive_desc::mean_desc()const + memory::desc mean_desc() const { return query_md(query::src_md, 1); } + + /// @copydoc dnnl::batch_normalization_forward::primitive_desc::variance_desc()const + memory::desc variance_desc() const { + return query_md(query::src_md, 2); + } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// Returns normalization flags. + /// @return Normalization flags. + normalization_flags get_flags() const { + return base::get_flags(); + } + }; + + /// Default constructor. Produces an empty object. + batch_normalization_backward() = default; + + /// Constructs a batch normalization backward propagation primitive. + /// @param pd Primitive descriptor for a batch normalization backward + /// propagation primitive. + batch_normalization_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a batch normalization backward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a batch normalization backward + /// propagation primitive. + /// @param cache_blob Cache blob. + batch_normalization_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_batch_normalization + +/// @addtogroup dnnl_api_group_normalization Group Normalization +/// +/// A primitive to perform group normalization. +/// +/// Both forward and backward propagation primitives support in-place +/// operation; that is, src and dst can refer to the same memory for forward +/// propagation, and diff_dst and diff_src can refer to the same memory for +/// backward propagation. +/// +/// The group normalization primitives computations can be controlled by +/// specifying different @ref dnnl::normalization_flags values. For example, +/// group normalization forward propagation can be configured to either +/// compute the mean and variance or take them as arguments. It can either +/// perform scaling and shifting using gamma and beta parameters or not. +/// +/// @sa @ref dev_guide_group_normalization in developer guide +/// +/// @{ + +/// Group normalization forward propagation primitive. +struct group_normalization_forward : public primitive { + /// Primitive descriptor for a group normalization forward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a group normalization forward + /// propagation primitive. + /// + /// @note + /// In-place operation is supported: the dst can refer to the same + /// memory as the src. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param groups Group normalization groups parameter. + /// @param epsilon Group normalization epsilon parameter. + /// @param flags Group normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + memory::dim groups, float epsilon, normalization_flags flags, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_group_normalization_forward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + src_desc.get(), dst_desc.get(), groups, epsilon, + convert_to_c(flags), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a group " + "normalization forward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a group normalization + /// forward propagation primitive from a C API primitive descriptor + /// that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a group normalization + /// forward propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, + dnnl::primitive::kind::group_normalization, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// Returns memory descriptor for mean. + /// @returns Memory descriptor for mean. + memory::desc mean_desc() const { return stat_desc(mean); } + + /// Returns memory descriptor for variance. + /// @returns Memory descriptor for variance. + memory::desc variance_desc() const { return stat_desc(var); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_group_size()const + memory::dim get_group_size() const { return base::get_group_size(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// Returns normalization flags. + /// @return Normalization flags. + normalization_flags get_flags() const { + return base::get_flags(); + } + + private: + enum { + mean = 1, + var = 2, + }; + memory::desc stat_desc(int kind) const { + const bool use_global_stats + = (get_flags() & normalization_flags::use_global_stats) + != normalization_flags::none; + return query_md( + use_global_stats ? query::src_md : query::dst_md, kind); + } + }; + + /// Default constructor. Produces an empty object. + group_normalization_forward() = default; + + /// Constructs a group normalization forward propagation primitive. + /// @param pd Primitive descriptor for a group normalization forward + /// propagation primitive. + group_normalization_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a group normalization forward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a group normalization forward + /// propagation primitive. + /// @param cache_blob Cache blob. + group_normalization_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Group normalization backward propagation primitive. +struct group_normalization_backward : public primitive { + /// Primitive descriptor for a group normalization backward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a group normalization backward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::backward_data and #dnnl::prop_kind::backward + /// (diffs for all parameters are computed in this case). + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param groups Group normalization groups parameter. + /// @param epsilon Group normalization epsilon parameter. + /// @param flags Group normalization flags (@ref + /// dnnl::normalization_flags). + /// @param hint_fwd_pd Primitive descriptor for a group normalization + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + memory::dim groups, float epsilon, normalization_flags flags, + const group_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_group_normalization_backward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + diff_src_desc.get(), diff_dst_desc.get(), + src_desc.get(), groups, epsilon, + convert_to_c(flags), hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a group " + "normalization backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a group normalization + /// backward propagation primitive from a C API primitive descriptor + /// that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a group normalization + /// backward propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, + dnnl::primitive::kind::group_normalization, + dnnl::prop_kind::backward, dnnl::prop_kind::backward_data) { + } + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_weights_desc()const + memory::desc diff_weights_desc() const { + return base::diff_weights_desc(0); + } + + /// @copydoc dnnl::group_normalization_forward::primitive_desc::mean_desc()const + memory::desc mean_desc() const { return query_md(query::src_md, 1); } + + /// @copydoc dnnl::group_normalization_forward::primitive_desc::variance_desc()const + memory::desc variance_desc() const { + return query_md(query::src_md, 2); + } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_group_size()const + memory::dim get_group_size() const { return base::get_group_size(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// Returns normalization flags. + /// @return Normalization flags. + normalization_flags get_flags() const { + return base::get_flags(); + } + }; + + /// Default constructor. Produces an empty object. + group_normalization_backward() = default; + + /// Constructs a group normalization backward propagation primitive. + /// @param pd Primitive descriptor for a group normalization backward + /// propagation primitive. + group_normalization_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a group normalization backward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a group normalization backward + /// propagation primitive. + /// @param cache_blob Cache blob. + group_normalization_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_group_normalization + +/// @addtogroup dnnl_api_layer_normalization Layer Normalization +/// +/// A primitive to perform layer normalization. Normalization is performed +/// within the last logical dimension of data tensor. +/// +/// Both forward and backward propagation primitives support in-place +/// operation; that is, src and dst can refer to the same memory for forward +/// propagation, and diff_dst and diff_src can refer to the same memory for +/// backward propagation. +/// +/// The layer normalization primitives computations can be controlled by +/// specifying different @ref dnnl::normalization_flags values. For example, +/// layer normalization forward propagation can be configured to either +/// compute the mean and variance or take them as arguments. It can either +/// perform scaling and shifting using gamma and beta parameters or not. +/// +/// @sa @ref dev_guide_layer_normalization in developer guide +/// +/// @{ + +/// Layer normalization forward propagation primitive. +struct layer_normalization_forward : public primitive { + /// Primitive descriptor for a layer normalization forward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a layer normalization forward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param stat_desc Statistics memory descriptors. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + const memory::desc &stat_desc, float epsilon, + normalization_flags flags, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, src_desc, dst_desc, + &stat_desc, memory::data_type::f32, epsilon, flags, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization forward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + float epsilon, normalization_flags flags, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, src_desc, dst_desc, nullptr, + memory::data_type::f32, epsilon, flags, attr, allow_empty) { + } + + /// Constructs a primitive descriptor for a layer normalization forward + /// propagation primitive with a user-provided data type for the scale + /// and shift memory objects. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param stat_desc Statistics memory descriptors. + /// @param scale_shift_data_type Data type of scale and shift memory. + /// If neither scale nor shift flag are specified the parameter + /// is ignored. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + const memory::desc &stat_desc, + memory::data_type scale_shift_data_type, float epsilon, + normalization_flags flags, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, src_desc, dst_desc, + &stat_desc, scale_shift_data_type, epsilon, flags, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization forward + /// propagation primitive with a user-provided data type for the scale + /// and shift memory objects. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param scale_shift_data_type Data type of scale and shift memory. + /// If neither scale nor shift flag are specified the parameter + /// is ignored. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + memory::data_type scale_shift_data_type, float epsilon, + normalization_flags flags, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, src_desc, dst_desc, nullptr, + scale_shift_data_type, epsilon, flags, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization + /// forward propagation primitive from a C API primitive descriptor + /// that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a layer normalization + /// forward propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, + dnnl::primitive::kind::layer_normalization, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::batch_normalization_forward::primitive_desc::mean_desc()const + memory::desc mean_desc() const { return stat_desc(mean); } + + /// @copydoc dnnl::batch_normalization_forward::primitive_desc::variance_desc()const + memory::desc variance_desc() const { return stat_desc(var); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// Returns normalization flags. + /// @return Normalization flags. + normalization_flags get_flags() const { + return base::get_flags(); + } + + private: + enum { + mean = 1, + var = 2, + }; + memory::desc stat_desc(int kind) const { + const bool use_global_stats + = (get_flags() & normalization_flags::use_global_stats) + != normalization_flags::none; + return query_md( + use_global_stats ? query::src_md : query::dst_md, kind); + } + + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + const memory::desc *stat_desc, + memory::data_type scale_shift_data_type, float epsilon, + normalization_flags flags, const primitive_attr &attr, + bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_layer_normalization_forward_primitive_desc_create_v2( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + src_desc.get(), dst_desc.get(), + optional_arg(stat_desc), + memory::convert_to_c(scale_shift_data_type), + epsilon, convert_to_c(flags), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a layer " + "normalization forward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + layer_normalization_forward() = default; + + /// Constructs a layer normalization forward propagation primitive. + /// @param pd Primitive descriptor for a layer normalization forward + /// propagation primitive. + layer_normalization_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a layer normalization forward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a layer normalization forward + /// propagation primitive. + /// @param cache_blob Cache blob. + layer_normalization_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Layer normalization backward propagation primitive. +struct layer_normalization_backward : public primitive { + /// Primitive descriptor for a layer normalization backward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a layer normalization backward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::backward_data and #dnnl::prop_kind::backward + /// (diffs for all parameters are computed in this case). + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param stat_desc Statistics memory descriptors. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param hint_fwd_pd Primitive descriptor for a layer normalization + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + const memory::desc &stat_desc, float epsilon, + normalization_flags flags, + const layer_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, diff_src_desc, diff_dst_desc, + src_desc, &stat_desc, memory::data_type::f32, + memory::data_type::f32, epsilon, flags, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization backward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::backward_data and #dnnl::prop_kind::backward + /// (diffs for all parameters are computed in this case). + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param hint_fwd_pd Primitive descriptor for a layer normalization + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + float epsilon, normalization_flags flags, + const layer_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, diff_src_desc, diff_dst_desc, + src_desc, nullptr, memory::data_type::f32, + memory::data_type::f32, epsilon, flags, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization backward + /// propagation primitive with a user-provided data type for the scale + /// and shift memory objects. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::backward_data and #dnnl::prop_kind::backward + /// (diffs for all parameters are computed in this case). + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param stat_desc Statistics memory descriptors. + /// @param diff_scale_shift_data_type Data type of diff scale and shift + /// memory. If neither scale nor shift flag are specified the + /// parameter is ignored. + /// @param scale_shift_data_type Data type of scale and shift memory. + /// If neither scale nor shift flag are specified the parameter + /// is ignored. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param hint_fwd_pd Primitive descriptor for a layer normalization + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + const memory::desc &stat_desc, + memory::data_type diff_scale_shift_data_type, + memory::data_type scale_shift_data_type, float epsilon, + normalization_flags flags, + const layer_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, diff_src_desc, diff_dst_desc, + src_desc, &stat_desc, diff_scale_shift_data_type, + scale_shift_data_type, epsilon, flags, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization backward + /// propagation primitive with a user-provided data type for the scale + /// and shift memory objects. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::backward_data and #dnnl::prop_kind::backward + /// (diffs for all parameters are computed in this case). + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param src_desc Source memory descriptor. + /// @param diff_scale_shift_data_type Data type of diff scale and shift + /// memory. If neither scale nor shift flag are specified the + /// parameter is ignored. + /// @param scale_shift_data_type Data type of scale and shift memory. + /// If neither scale nor shift flag are specified the parameter + /// is ignored. + /// @param epsilon Layer normalization epsilon parameter. + /// @param flags Layer normalization flags (@ref + /// dnnl::normalization_flags). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param hint_fwd_pd Primitive descriptor for a layer normalization + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + memory::data_type diff_scale_shift_data_type, + memory::data_type scale_shift_data_type, float epsilon, + normalization_flags flags, + const layer_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, diff_src_desc, diff_dst_desc, + src_desc, nullptr, diff_scale_shift_data_type, + scale_shift_data_type, epsilon, flags, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for a layer normalization + /// backward propagation primitive from a C API primitive descriptor + /// that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a layer normalization + /// backward propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, + dnnl::primitive::kind::layer_normalization, + dnnl::prop_kind::backward, dnnl::prop_kind::backward_data) { + } + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_weights_desc()const + memory::desc diff_weights_desc() const { + return base::diff_weights_desc(0); + } + + /// @copydoc dnnl::batch_normalization_forward::primitive_desc::mean_desc()const + memory::desc mean_desc() const { return query_md(query::src_md, 1); } + + /// @copydoc dnnl::batch_normalization_forward::primitive_desc::variance_desc()const + memory::desc variance_desc() const { + return query_md(query::src_md, 2); + } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + dnnl::prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// Returns normalization flags. + /// @return Normalization flags. + normalization_flags get_flags() const { + return base::get_flags(); + } + + private: + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::desc &src_desc, + const memory::desc *stat_desc, + memory::data_type diff_scale_shift_data_type, + memory::data_type scale_shift_data_type, float epsilon, + normalization_flags flags, + const layer_normalization_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_layer_normalization_backward_primitive_desc_create_v2( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + diff_src_desc.get(), diff_dst_desc.get(), + src_desc.get(), optional_arg(stat_desc), + memory::convert_to_c(diff_scale_shift_data_type), + memory::convert_to_c(scale_shift_data_type), + epsilon, convert_to_c(flags), hint_fwd_pd.get(), + attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a layer " + "normalization backward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + layer_normalization_backward() = default; + + /// Constructs a layer normalization backward propagation primitive. + /// @param pd Primitive descriptor for a layer normalization backward + /// propagation primitive. + layer_normalization_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a layer normalization backward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a layer normalization backward + /// propagation primitive. + /// @param cache_blob Cache blob. + layer_normalization_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_layer_normalization + +/// @addtogroup dnnl_api_inner_product Inner Product +/// +/// A primitive to compute an inner product. +/// +/// @sa @ref dev_guide_inner_product in developer guide +/// +/// @{ + +/// Inner product forward propagation primitive. +struct inner_product_forward : public primitive { + /// Primitive descriptor for an inner product forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an inner product forward + /// propagation primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Memory descriptor for src. + /// @param weights_desc Memory descriptor for weights. + /// @param bias_desc Memory descriptor for bias. + /// @param dst_desc Memory descriptor for dst. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &weights_desc, + const memory::desc &bias_desc, const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, src_desc, weights_desc, + &bias_desc, dst_desc, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an inner product forward + /// propagation primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Memory descriptor for src. + /// @param weights_desc Memory descriptor for weights. + /// @param dst_desc Memory descriptor for dst. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &weights_desc, + const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, src_desc, weights_desc, + nullptr, dst_desc, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an inner product forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for an inner product forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::inner_product, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::convolution_forward::primitive_desc::bias_desc()const + memory::desc bias_desc() const { return base::weights_desc(1); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + private: + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &weights_desc, + const memory::desc *bias_desc, const memory::desc &dst_desc, + const primitive_attr &attr, bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_inner_product_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + src_desc.get(), weights_desc.get(), + optional_arg(bias_desc), dst_desc.get(), + attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for an inner " + "product forward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + inner_product_forward() = default; + + /// Constructs an inner product forward propagation primitive. + /// @param pd Primitive descriptor for an inner product forward + /// propagation primitive. + inner_product_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an inner product forward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for an inner product forward + /// propagation primitive. + /// @param cache_blob Cache blob. + inner_product_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Inner product backward propagation primitive. +struct inner_product_backward_data : public primitive { + /// Primitive descriptor for an inner product backward propagation + /// primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an inner product backward + /// propagation primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param diff_src_desc Memory descriptor for diff src. + /// @param weights_desc Memory descriptor for weights. + /// @param diff_dst_desc Memory descriptor for diff dst. + /// @param hint_fwd_pd Primitive descriptor for an inner product + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &diff_src_desc, + const memory::desc &weights_desc, + const memory::desc &diff_dst_desc, + const inner_product_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_inner_product_backward_data_primitive_desc_create( + &pd, aengine.get(), diff_src_desc.get(), + weights_desc.get(), diff_dst_desc.get(), + hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for an inner " + "product backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for an inner product backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for an inner product backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::inner_product, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { return base::weights_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + }; + + /// Default constructor. Produces an empty object. + inner_product_backward_data() = default; + + /// Constructs an inner product backward propagation primitive. + /// @param pd Primitive descriptor for an inner product backward + /// propagation primitive. + inner_product_backward_data(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an inner product backward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for an inner product backward + /// propagation primitive. + /// @param cache_blob Cache blob. + inner_product_backward_data( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Inner product weights gradient primitive. +struct inner_product_backward_weights : public primitive { + /// Primitive descriptor for an inner product weights gradient primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an inner product weights + /// update primitive with bias. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param src_desc Memory descriptor for src. + /// @param diff_weights_desc Memory descriptor for diff weights. + /// @param diff_bias_desc Memory descriptor for diff bias. + /// @param diff_dst_desc Memory descriptor for diff dst. + /// @param hint_fwd_pd Primitive descriptor for an inner product + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_desc, + const inner_product_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, src_desc, diff_weights_desc, + &diff_bias_desc, diff_dst_desc, hint_fwd_pd, attr, + allow_empty) {} + + /// Constructs a primitive descriptor for an inner product weights + /// update primitive. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param src_desc Memory descriptor for src. + /// @param diff_weights_desc Memory descriptor for diff weights. + /// @param diff_dst_desc Memory descriptor for diff dst. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param hint_fwd_pd Primitive descriptor for an inner product + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_dst_desc, + const inner_product_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, src_desc, diff_weights_desc, nullptr, + diff_dst_desc, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an inner product weights + /// update primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for an inner product weights + /// gradient primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::inner_product, + dnnl::prop_kind::backward_weights) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_weights_desc()const + memory::desc diff_weights_desc() const { + return base::diff_weights_desc(0); + } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::convolution_backward_weights::primitive_desc::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return base::diff_weights_desc(1); + } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + private: + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &diff_weights_desc, + const memory::desc *diff_bias_desc, + const memory::desc &diff_dst_desc, + const inner_product_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_inner_product_backward_weights_primitive_desc_create( + &pd, aengine.get(), src_desc.get(), + diff_weights_desc.get(), + optional_arg(diff_bias_desc), diff_dst_desc.get(), + hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for an inner " + "product weights gradient primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + inner_product_backward_weights() = default; + + /// Constructs an inner product weights gradient primitive. + /// @param pd Primitive descriptor for an inner product weights gradient + /// primitive. + inner_product_backward_weights(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an inner product weights gradient primitive from a cache + /// blob. + /// @param pd Primitive descriptor for an inner product weights gradient + /// primitive. + /// @param cache_blob Cache blob. + inner_product_backward_weights( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_inner_product + +/// @addtogroup dnnl_api_rnn RNN +/// +/// A primitive to compute recurrent neural network layers. +/// +/// @sa @ref dev_guide_rnn in developer guide +/// +/// @{ + +/// Base class for primitive descriptors for RNN primitives. +struct rnn_primitive_desc_base : public primitive_desc { + using primitive_desc::primitive_desc; + + /// Default constructor. Produces an empty object. + rnn_primitive_desc_base() = default; + + /// Constructs an RNN primitive descriptor base from a C API primitive + /// descriptor while checking that it actually describes the expected + /// primitive by comparing propagation and primitive kinds. + /// + /// @param pd C API primitive descriptor. + /// @param aprop_kind Expected propagation kind. + /// @param cell_kind Expected cell kind. + rnn_primitive_desc_base(dnnl_primitive_desc_t pd, + dnnl::prop_kind aprop_kind, dnnl::algorithm cell_kind) + : rnn_primitive_desc_base(pd, aprop_kind, aprop_kind, cell_kind) {} + + /// Returns source layer memory descriptor. + /// @returns Source layer memory descriptor. + memory::desc src_layer_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_SRC_LAYER); + } + + /// Returns AUGRU attention memory descriptor. + /// @returns AUGRU attention memory descriptor. + memory::desc augru_attention_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_AUGRU_ATTENTION); + } + + /// Returns source iteration memory descriptor. + /// @returns Source iteration memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// source iteration parameter. + memory::desc src_iter_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_SRC_ITER); + } + + /// Returns source recurrent cell state memory descriptor. + /// @returns Source recurrent cell state memory descriptor. + memory::desc src_iter_c_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_SRC_ITER_C); + } + + /// Returns weights layer memory descriptor. + /// @returns Weights layer memory descriptor. + memory::desc weights_layer_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_WEIGHTS_LAYER); + } + + /// Returns weights iteration memory descriptor. + /// @returns Weights iteration memory descriptor. + memory::desc weights_iter_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_WEIGHTS_ITER); + } + + /// Returns weights peephole memory descriptor. + /// @returns Weights peephole memory descriptor. + memory::desc weights_peephole_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_WEIGHTS_PEEPHOLE); + } + + /// Returns weights projection memory descriptor. + /// @returns Weights projection memory descriptor. + memory::desc weights_projection_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_WEIGHTS_PROJECTION); + } + + /// Returns bias memory descriptor. + /// @returns Bias memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// bias parameter. + memory::desc bias_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_BIAS); + } + + /// Returns destination layer memory descriptor. + /// @returns Destination layer memory descriptor. + memory::desc dst_layer_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DST_LAYER); + } + + /// Returns destination iteration memory descriptor. + /// @returns Destination iteration memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// destination iteration parameter. + memory::desc dst_iter_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DST_ITER); + } + + /// Returns destination recurrent cell state memory descriptor. + /// @returns Destination recurrent cell state memory descriptor. + memory::desc dst_iter_c_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DST_ITER_C); + } + + /// Returns diff source layer memory descriptor. + /// @returns Diff source layer memory descriptor. + memory::desc diff_src_layer_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_SRC_LAYER); + } + + /// Returns diff AUGRU attention memory descriptor. + /// @returns Diff AUGRU attention memory descriptor. + memory::desc diff_augru_attention_desc() const { + return base::query_md( + query::exec_arg_md, DNNL_ARG_DIFF_AUGRU_ATTENTION); + } + + /// Returns diff source iteration memory descriptor. + /// @returns Diff source iteration memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff source iteration parameter. + memory::desc diff_src_iter_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_SRC_ITER); + } + + /// Returns diff source recurrent cell state memory descriptor. + /// @returns Diff source recurrent cell state memory descriptor. + memory::desc diff_src_iter_c_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_SRC_ITER_C); + } + + /// Returns diff weights layer memory descriptor. + /// @returns Diff weights layer memory descriptor. + memory::desc diff_weights_layer_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_WEIGHTS_LAYER); + } + + /// Returns diff weights iteration memory descriptor. + /// @returns Diff weights iteration memory descriptor. + memory::desc diff_weights_iter_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_WEIGHTS_ITER); + } + + /// Returns diff weights peephole memory descriptor. + /// @returns Diff weights peephole memory descriptor. + memory::desc diff_weights_peephole_desc() const { + return base::query_md( + query::exec_arg_md, DNNL_ARG_DIFF_WEIGHTS_PEEPHOLE); + } + + /// Returns diff weights projection memory descriptor. + /// @returns Diff weights projection memory descriptor. + memory::desc diff_weights_projection_desc() const { + return base::query_md( + query::exec_arg_md, DNNL_ARG_DIFF_WEIGHTS_PROJECTION); + } + + /// Returns diff bias memory descriptor. + /// @returns Diff bias memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff bias parameter. + memory::desc diff_bias_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_BIAS); + } + + /// Returns diff destination layer memory descriptor. + /// @returns Diff destination layer memory descriptor. + memory::desc diff_dst_layer_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_DST_LAYER); + } + + /// Returns diff destination iteration memory descriptor. + /// @returns Diff destination iteration memory descriptor. + /// @returns A zero memory descriptor if the primitive does not have a + /// diff destination iteration parameter. + memory::desc diff_dst_iter_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_DST_ITER); + } + + /// Returns diff destination recurrent cell state memory descriptor. + /// @returns Diff destination recurrent cell state memory descriptor. + memory::desc diff_dst_iter_c_desc() const { + return base::query_md(query::exec_arg_md, DNNL_ARG_DIFF_DST_ITER_C); + } + +protected: + using rnn_base = rnn_primitive_desc_base; + + // (Deliberately not using doxygen comments) + // + // Constructs an RNN primitive descriptor base from a C API primitive + // descriptor while checking that it actually describes the expected + // primitive by comparing propagation and primitive kinds. Caller can + // pass two options propagation kinds. This is typically used to check + // that propagation kind is inference or training forward propagation. + // + // @param pd C API primitive descriptor. + // @param prop_kind1 Expected propagation kind. + // @param prop_kind2 Expected propagation kind. + // @param cell_kind Expected cell kind. + rnn_primitive_desc_base(dnnl_primitive_desc_t pd, + dnnl::prop_kind prop_kind1, dnnl::prop_kind prop_kind2, + dnnl::algorithm cell_kind) { + + dnnl_status_t rc; + + dnnl_primitive_kind_t q_primitive_kind; + rc = dnnl_primitive_desc_query( + pd, dnnl_query_primitive_kind, 0, &q_primitive_kind); + error::wrap_c_api(rc, + "could not retrieve a primitive kind from a primitive " + "descriptor for an RNN primitive"); + + dnnl_prop_kind_t q_prop_kind; + rc = dnnl_primitive_desc_query( + pd, dnnl_query_prop_kind, 0, &q_prop_kind); + error::wrap_c_api(rc, + "could not retrieve a propagation kind from a primitive " + "descriptor for an RNN primitive"); + + dnnl_alg_kind_t q_cell_kind; + rc = dnnl_primitive_desc_query( + pd, dnnl_query_cell_kind, 0, &q_cell_kind); + error::wrap_c_api(rc, + "could not retrieve a cell kind from a primitive descriptor " + "for an RNN primitive"); + + dnnl_prop_kind_t c_prop_kind1 = convert_to_c(prop_kind1); + dnnl_prop_kind_t c_prop_kind2 = convert_to_c(prop_kind2); + dnnl_alg_kind_t c_cell_kind = convert_to_c(cell_kind); + + bool ok = q_primitive_kind == dnnl_rnn + && (q_prop_kind == c_prop_kind1 || q_prop_kind == c_prop_kind2) + && q_cell_kind == c_cell_kind; + + if (!ok) + DNNL_THROW_ERROR(dnnl_invalid_arguments, + "mismatch between expected and provided descriptors for an " + "RNN primitive"); + + reset_with_clone(pd); + } + + // Constructs an RNN forward propagation primitive descriptor base for + // any cell kind. + rnn_primitive_desc_base(const engine &aengine, algorithm cell_kind, + prop_kind aprop_kind, algorithm activation, rnn_direction direction, + const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc *src_iter_c_desc, + const memory::desc *attention_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc *weights_peephole_desc, + const memory::desc *weights_projection_desc, + const memory::desc &bias_desc, const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc *dst_iter_c_desc, rnn_flags flags, float alpha, + float beta, const primitive_attr &attr, bool allow_empty) { + + dnnl_status_t status = dnnl_success; + const char *msg + = "could not create a primitive descriptor for a requested " + "cell kind"; + + dnnl_primitive_desc_t pd = nullptr; + switch (cell_kind) { + case algorithm::vanilla_rnn: + status = dnnl_vanilla_rnn_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(activation), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), weights_layer_desc.get(), + weights_iter_desc.get(), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + convert_to_c(flags), alpha, beta, attr.get()); + msg = "could not create a primitive descriptor for a vanilla " + "RNN forward propagation primitive"; + break; + case algorithm::vanilla_lstm: + status = dnnl_lstm_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), optional_arg(src_iter_c_desc), + weights_layer_desc.get(), weights_iter_desc.get(), + optional_arg(weights_peephole_desc), + optional_arg(weights_projection_desc), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + optional_arg(dst_iter_c_desc), convert_to_c(flags), + attr.get()); + msg = "could not create a primitive descriptor for an LSTM " + "forward propagation primitive"; + break; + case algorithm::vanilla_gru: + status = dnnl_gru_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), weights_layer_desc.get(), + weights_iter_desc.get(), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + convert_to_c(flags), attr.get()); + msg = "could not create a primitive descriptor for a GRU " + "forward propagation primitive"; + break; + case algorithm::lbr_gru: + status = dnnl_lbr_gru_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), weights_layer_desc.get(), + weights_iter_desc.get(), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + convert_to_c(flags), attr.get()); + msg = "could not create a primitive descriptor for an LBR GRU " + "forward propagation primitive"; + break; + case algorithm::vanilla_augru: + status = dnnl_augru_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), optional_arg(attention_desc), + weights_layer_desc.get(), weights_iter_desc.get(), + bias_desc.get(), dst_layer_desc.get(), + dst_iter_desc.get(), convert_to_c(flags), attr.get()); + msg = "could not create a primitive descriptor for an AUGRU " + "forward propagation primitive"; + break; + case algorithm::lbr_augru: + status = dnnl_lbr_augru_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), optional_arg(attention_desc), + weights_layer_desc.get(), weights_iter_desc.get(), + bias_desc.get(), dst_layer_desc.get(), + dst_iter_desc.get(), convert_to_c(flags), attr.get()); + msg = "could not create a primitive descriptor for an LBR " + "AUGRU forward propagation primitive"; + break; + default: status = dnnl_unimplemented; + } + + if (!allow_empty) error::wrap_c_api(status, msg); + reset(pd); + } + + // Constructs an RNN backward propagation primitive descriptor base for + // any cell kind. + rnn_primitive_desc_base(const engine &aengine, algorithm cell_kind, + prop_kind aprop_kind, algorithm activation, rnn_direction direction, + const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc *src_iter_c_desc, + const memory::desc *attention_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc *weights_peephole_desc, + const memory::desc *weights_projection_desc, + const memory::desc &bias_desc, const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc *dst_iter_c_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc *diff_src_iter_c_desc, + const memory::desc *diff_attention_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc *diff_weights_peephole_desc, + const memory::desc *diff_weights_projection_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const memory::desc *diff_dst_iter_c_desc, rnn_flags flags, + float alpha, float beta, const rnn_primitive_desc_base &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + dnnl_status_t status = dnnl_success; + const char *msg = ""; + + dnnl_primitive_desc_t pd = nullptr; + switch (cell_kind) { + case algorithm::vanilla_rnn: + status = dnnl_vanilla_rnn_backward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(activation), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), weights_layer_desc.get(), + weights_iter_desc.get(), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + diff_src_layer_desc.get(), diff_src_iter_desc.get(), + diff_weights_layer_desc.get(), + diff_weights_iter_desc.get(), diff_bias_desc.get(), + diff_dst_layer_desc.get(), diff_dst_iter_desc.get(), + convert_to_c(flags), alpha, beta, hint_fwd_pd.get(), + attr.get()); + msg = "could not create a primitive descriptor for a vanilla " + "RNN backward propagation primitive"; + break; + case algorithm::vanilla_lstm: + status = dnnl_lstm_backward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), optional_arg(src_iter_c_desc), + weights_layer_desc.get(), weights_iter_desc.get(), + optional_arg(weights_peephole_desc), + optional_arg(weights_projection_desc), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + optional_arg(dst_iter_c_desc), + diff_src_layer_desc.get(), diff_src_iter_desc.get(), + optional_arg(diff_src_iter_c_desc), + diff_weights_layer_desc.get(), + diff_weights_iter_desc.get(), + optional_arg(diff_weights_peephole_desc), + optional_arg(diff_weights_projection_desc), + diff_bias_desc.get(), diff_dst_layer_desc.get(), + diff_dst_iter_desc.get(), + optional_arg(diff_dst_iter_c_desc), convert_to_c(flags), + hint_fwd_pd.get(), attr.get()); + msg = "could not create a primitive descriptor for an LSTM " + "backward propagation primitive"; + break; + case algorithm::vanilla_gru: + status = dnnl_gru_backward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), weights_layer_desc.get(), + weights_iter_desc.get(), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + diff_src_layer_desc.get(), diff_src_iter_desc.get(), + diff_weights_layer_desc.get(), + diff_weights_iter_desc.get(), diff_bias_desc.get(), + diff_dst_layer_desc.get(), diff_dst_iter_desc.get(), + convert_to_c(flags), hint_fwd_pd.get(), attr.get()); + msg = "could not create a primitive descriptor for a GRU " + "backward propagation primitive"; + break; + case algorithm::lbr_gru: + status = dnnl_lbr_gru_backward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), weights_layer_desc.get(), + weights_iter_desc.get(), bias_desc.get(), + dst_layer_desc.get(), dst_iter_desc.get(), + diff_src_layer_desc.get(), diff_src_iter_desc.get(), + diff_weights_layer_desc.get(), + diff_weights_iter_desc.get(), diff_bias_desc.get(), + diff_dst_layer_desc.get(), diff_dst_iter_desc.get(), + convert_to_c(flags), hint_fwd_pd.get(), attr.get()); + msg = "could not create a primitive descriptor for an LBR GRU " + "backward propagation primitive"; + break; + case algorithm::vanilla_augru: + status = dnnl_augru_backward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), optional_arg(attention_desc), + weights_layer_desc.get(), weights_iter_desc.get(), + bias_desc.get(), dst_layer_desc.get(), + dst_iter_desc.get(), diff_src_layer_desc.get(), + diff_src_iter_desc.get(), + optional_arg(diff_attention_desc), + diff_weights_layer_desc.get(), + diff_weights_iter_desc.get(), diff_bias_desc.get(), + diff_dst_layer_desc.get(), diff_dst_iter_desc.get(), + convert_to_c(flags), hint_fwd_pd.get(), attr.get()); + msg = "could not create a primitive descriptor for an AUGRU " + "backward propagation primitive"; + break; + case algorithm::lbr_augru: + status = dnnl_lbr_augru_backward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + dnnl::convert_to_c(direction), src_layer_desc.get(), + src_iter_desc.get(), optional_arg(attention_desc), + weights_layer_desc.get(), weights_iter_desc.get(), + bias_desc.get(), dst_layer_desc.get(), + dst_iter_desc.get(), diff_src_layer_desc.get(), + diff_src_iter_desc.get(), + optional_arg(diff_attention_desc), + diff_weights_layer_desc.get(), + diff_weights_iter_desc.get(), diff_bias_desc.get(), + diff_dst_layer_desc.get(), diff_dst_iter_desc.get(), + convert_to_c(flags), hint_fwd_pd.get(), attr.get()); + msg = "could not create a primitive descriptor for an LBR " + "AUGRU backward propagation primitive"; + break; + default: status = dnnl_unimplemented; + } + if (!allow_empty) error::wrap_c_api(status, msg); + reset(pd); + } +}; + +/// Vanilla RNN forward propagation primitive. +struct vanilla_rnn_forward : public primitive { + /// Primitive descriptor for a vanilla RNN forward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a vanilla RNN forward + /// propagation primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc. + /// + /// This would then indicate that the RNN forward propagation primitive + /// should not use them and should default to zero values instead. + /// + /// @note + /// All memory descriptors except @p src_iter_desc can be + /// initialized with an #dnnl::memory::format_tag::any value of @p + /// format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param activation Activation kind. Possible values are + /// #dnnl::algorithm::eltwise_relu, + /// #dnnl::algorithm::eltwise_tanh, or + /// #dnnl::algorithm::eltwise_logistic. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm activation, rnn_direction direction, + const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_rnn, + aprop_kind, activation, direction, src_layer_desc, + src_iter_desc, nullptr, nullptr, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, rnn_flags::undef, + 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a vanilla RNN forward + /// propagation primitive with alpha parameter. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc. + /// + /// This would then indicate that the RNN forward propagation primitive + /// should not use them and should default to zero values instead. + /// + /// @note + /// All memory descriptors except @p src_iter_desc can be + /// initialized with an #dnnl::memory::format_tag::any value of @p + /// format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param activation Activation kind. Possible values are + /// #dnnl::algorithm::eltwise_relu, + /// #dnnl::algorithm::eltwise_tanh, or + /// #dnnl::algorithm::eltwise_logistic. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param alpha Negative slope if activation is + /// #dnnl::algorithm::eltwise_relu. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm activation, rnn_direction direction, + const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, float alpha, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_rnn, + aprop_kind, activation, direction, src_layer_desc, + src_iter_desc, nullptr, nullptr, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, rnn_flags::undef, + alpha, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a vanilla RNN forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a vanilla RNN forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference, + dnnl::algorithm::vanilla_rnn) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_activation_kind()const + algorithm get_activation_kind() const { + return base::get_activation_kind(); + } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + + /// @copydoc dnnl::primitive_desc_base::get_alpha()const + float get_alpha() const { return base::get_alpha(); } + + /// @copydoc dnnl::primitive_desc_base::get_beta()const + float get_beta() const { return base::get_beta(); } + }; + + /// Default constructor. Produces an empty object. + vanilla_rnn_forward() = default; + + /// Constructs a vanilla RNN forward propagation primitive. + /// @param pd Primitive descriptor for a vanilla RNN forward + /// propagation primitive. + vanilla_rnn_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a vanilla RNN forward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a vanilla RNN forward + /// propagation primitive. + /// @param cache_blob Cache blob. + vanilla_rnn_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Vanilla RNN backward propagation primitive. +struct vanilla_rnn_backward : public primitive { + /// Primitive descriptor for an RNN backward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a vanilla RNN backward + /// propagation primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p diff_src_iter_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p diff_dst_iter_desc. + /// + /// This would then indicate that the RNN backward propagation + /// primitive should not use the respective data and should use zero + /// values instead. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param activation Activation kind. Possible values are + /// #dnnl::algorithm::eltwise_relu, + /// #dnnl::algorithm::eltwise_tanh, or + /// #dnnl::algorithm::eltwise_logistic. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param hint_fwd_pd Primitive descriptor for a vanilla RNN + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm activation, rnn_direction direction, + const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const vanilla_rnn_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_rnn, + aprop_kind, activation, direction, src_layer_desc, + src_iter_desc, nullptr, nullptr, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, diff_src_layer_desc, + diff_src_iter_desc, nullptr, nullptr, + diff_weights_layer_desc, diff_weights_iter_desc, nullptr, + nullptr, diff_bias_desc, diff_dst_layer_desc, + diff_dst_iter_desc, nullptr, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a vanilla RNN backward + /// propagation primitive with an alpha parameter. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p diff_src_iter_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p diff_dst_iter_desc. + /// + /// This would then indicate that the RNN backward propagation + /// primitive should not use the respective data and should use zero + /// values instead. + /// + /// @note + /// All the memory descriptors may be initialized with the + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param activation Activation kind. Possible values are + /// #dnnl::algorithm::eltwise_relu, + /// #dnnl::algorithm::eltwise_tanh, or + /// #dnnl::algorithm::eltwise_logistic. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param alpha Negative slope if activation is + /// #dnnl::algorithm::eltwise_relu. + /// @param hint_fwd_pd Primitive descriptor for a vanilla RNN + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm activation, rnn_direction direction, + const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, float alpha, + const vanilla_rnn_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_rnn, + aprop_kind, activation, direction, src_layer_desc, + src_iter_desc, nullptr, nullptr, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, diff_src_layer_desc, + diff_src_iter_desc, nullptr, nullptr, + diff_weights_layer_desc, diff_weights_iter_desc, nullptr, + nullptr, diff_bias_desc, diff_dst_layer_desc, + diff_dst_iter_desc, nullptr, rnn_flags::undef, alpha, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a vanilla RNN backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a vanilla RNN backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::backward, + dnnl::algorithm::vanilla_rnn) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_layer_desc()const + memory::desc diff_src_layer_desc() const { + return rnn_base::diff_src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_desc()const + memory::desc diff_src_iter_desc() const { + return rnn_base::diff_src_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_layer_desc()const + memory::desc diff_weights_layer_desc() const { + return rnn_base::diff_weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_iter_desc()const + memory::desc diff_weights_iter_desc() const { + return rnn_base::diff_weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return rnn_base::diff_bias_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_layer_desc()const + memory::desc diff_dst_layer_desc() const { + return rnn_base::diff_dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_desc()const + memory::desc diff_dst_iter_desc() const { + return rnn_base::diff_dst_iter_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_activation_kind()const + algorithm get_activation_kind() const { + return base::get_activation_kind(); + } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + + /// @copydoc dnnl::primitive_desc_base::get_alpha()const + float get_alpha() const { return base::get_alpha(); } + + /// @copydoc dnnl::primitive_desc_base::get_beta()const + float get_beta() const { return base::get_beta(); } + }; + + /// Default constructor. Produces an empty object. + vanilla_rnn_backward() = default; + + /// Constructs a vanilla RNN backward propagation primitive. + /// @param pd Primitive descriptor for a vanilla RNN backward + /// propagation primitive. + vanilla_rnn_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a vanilla RNN backward propagation primitive from + /// a cache blob. + /// @param pd Primitive descriptor for a vanilla RNN backward + /// propagation primitive. + /// @param cache_blob Cache blob. + vanilla_rnn_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// LSTM forward propagation primitive. +struct lstm_forward : public primitive { + /// Primitive descriptor for an LSTM forward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an LSTM (with or without + /// peephole and with or without projection) forward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p src_iter_c_desc, + /// - @p weights_peephole_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc together with @p dst_iter_c_desc. + /// + /// This would then indicate that the LSTM forward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// The @p weights_projection_desc may point to a zero memory + /// descriptor. This would then indicate that the LSTM doesn't have + /// recurrent projection layer. + /// + /// @note + /// All memory descriptors can be initialized with an + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param src_iter_c_desc Memory descriptor for the input recurrent + /// cell state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param weights_peephole_desc Memory descriptor for the weights + /// applied to the cell states (according to the Peephole LSTM + /// formula). + /// @param weights_projection_desc Memory descriptor for the weights + /// applied to the hidden states to get the recurrent projection + /// (according to the Projection LSTM formula). + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param dst_iter_c_desc Memory descriptor for the output recurrent + /// cell state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &src_iter_c_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &weights_peephole_desc, + const memory::desc &weights_projection_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &dst_iter_c_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_lstm, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, &src_iter_c_desc, nullptr, + weights_layer_desc, weights_iter_desc, + &weights_peephole_desc, &weights_projection_desc, bias_desc, + dst_layer_desc, dst_iter_desc, &dst_iter_c_desc, + rnn_flags::undef, 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an LSTM (with or without + /// peephole) forward propagation primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p src_iter_c_desc, + /// - @p weights_peephole_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc together with @p dst_iter_c_desc. + /// + /// This would then indicate that the LSTM forward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors can be initialized with an + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param src_iter_c_desc Memory descriptor for the input recurrent + /// cell state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param weights_peephole_desc Memory descriptor for the weights + /// applied to the cell states (according to the Peephole LSTM + /// formula). + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param dst_iter_c_desc Memory descriptor for the output recurrent + /// cell state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &src_iter_c_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &weights_peephole_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &dst_iter_c_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_lstm, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, &src_iter_c_desc, nullptr, + weights_layer_desc, weights_iter_desc, + &weights_peephole_desc, nullptr, bias_desc, dst_layer_desc, + dst_iter_desc, &dst_iter_c_desc, rnn_flags::undef, 0.0f, + 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an LSTM forward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p src_iter_c_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc together with @p dst_iter_c_desc. + /// + /// This would then indicate that the LSTM forward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors can be initialized with an + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param src_iter_c_desc Memory descriptor for the input recurrent + /// cell state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param dst_iter_c_desc Memory descriptor for the output recurrent + /// cell state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &src_iter_c_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &dst_iter_c_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_lstm, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, &src_iter_c_desc, nullptr, + weights_layer_desc, weights_iter_desc, nullptr, nullptr, + bias_desc, dst_layer_desc, dst_iter_desc, &dst_iter_c_desc, + rnn_flags::undef, 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an LSTM forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an LSTM forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference, + dnnl::algorithm::vanilla_lstm) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_c_desc() const { + return rnn_base::src_iter_c_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_peephole_desc()const + memory::desc weights_peephole_desc() const { + return rnn_base::weights_peephole_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_projection_desc()const + memory::desc weights_projection_desc() const { + return rnn_base::weights_projection_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc dst_iter_c_desc() const { + return rnn_base::dst_iter_c_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + lstm_forward() = default; + + /// Constructs an LSTM forward propagation primitive. + /// @param pd Primitive descriptor for an LSTM forward propagation + /// primitive. + lstm_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LSTM forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LSTM forward propagation + /// primitive. + /// @param cache_blob Cache blob. + lstm_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// LSTM backward propagation primitive. +struct lstm_backward : public primitive { + /// Primitive descriptor for an LSTM backward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs an LSTM (with or without peephole and with or without + /// projection) primitive descriptor for backward propagation + /// using @p prop_kind, @p direction, and memory descriptors. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p src_iter_c_desc, + /// @p diff_src_iter_desc, and @p diff_src_iter_c_desc, + /// - @p weights_peephole_desc together with + /// @p diff_weights_peephole_desc + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p dst_iter_c_desc, + /// @p diff_dst_iter_desc, and @p diff_dst_iter_c_desc. + /// + /// This would then indicate that the LSTM backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// The @p weights_projection_desc together with @p + /// diff_weights_projection_desc may point to a zero memory descriptor. + /// This would then indicate that the LSTM doesn't have recurrent + /// projection layer. + /// + /// @note + /// All memory descriptors can be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param src_iter_c_desc Memory descriptor for the input recurrent + /// cell state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param weights_peephole_desc Memory descriptor for the weights + /// applied to the cell states (according to the Peephole LSTM + /// formula). + /// @param weights_projection_desc Memory descriptor for the weights + /// applied to the hidden states to get the recurrent projection + /// (according to the Projection LSTM formula). + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param dst_iter_c_desc Memory descriptor for the output recurrent + /// cell state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_src_iter_c_desc Memory descriptor for the diff of + /// input recurrent cell state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_weights_peephole_desc Memory descriptor for the diff of + /// weights applied to the cell states (according to the Peephole + /// LSTM formula). + /// @param diff_weights_projection_desc Memory descriptor for the diff + /// of weights applied to the hidden states to get the recurrent + /// projection (according to the Projection LSTM formula). + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param diff_dst_iter_c_desc Memory descriptor for the diff of + /// output recurrent cell state vector. + /// @param hint_fwd_pd Primitive descriptor for an LSTM + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &src_iter_c_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &weights_peephole_desc, + const memory::desc &weights_projection_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &dst_iter_c_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_src_iter_c_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_weights_peephole_desc, + const memory::desc &diff_weights_projection_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const memory::desc &diff_dst_iter_c_desc, + const lstm_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_lstm, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, &src_iter_c_desc, nullptr, + weights_layer_desc, weights_iter_desc, + &weights_peephole_desc, &weights_projection_desc, bias_desc, + dst_layer_desc, dst_iter_desc, &dst_iter_c_desc, + diff_src_layer_desc, diff_src_iter_desc, + &diff_src_iter_c_desc, nullptr, diff_weights_layer_desc, + diff_weights_iter_desc, &diff_weights_peephole_desc, + &diff_weights_projection_desc, diff_bias_desc, + diff_dst_layer_desc, diff_dst_iter_desc, + &diff_dst_iter_c_desc, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs an LSTM (with or without peephole) primitive descriptor + /// for backward propagation using @p prop_kind, @p direction, + /// and memory descriptors. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p src_iter_c_desc, + /// @p diff_src_iter_desc, and @p diff_src_iter_c_desc, + /// - @p weights_peephole_desc together with + /// @p diff_weights_peephole_desc + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p dst_iter_c_desc, + /// @p diff_dst_iter_desc, and @p diff_dst_iter_c_desc. + /// + /// This would then indicate that the LSTM backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param src_iter_c_desc Memory descriptor for the input recurrent + /// cell state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param weights_peephole_desc Memory descriptor for the weights + /// applied to the cell states (according to the Peephole LSTM + /// formula). + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param dst_iter_c_desc Memory descriptor for the output recurrent + /// cell state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_src_iter_c_desc Memory descriptor for the diff of + /// input recurrent cell state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_weights_peephole_desc Memory descriptor for the diff of + /// weights applied to the cell states (according to the Peephole + /// LSTM formula). + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param diff_dst_iter_c_desc Memory descriptor for the diff of + /// output recurrent cell state vector. + /// @param hint_fwd_pd Primitive descriptor for an LSTM + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &src_iter_c_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &weights_peephole_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &dst_iter_c_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_src_iter_c_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_weights_peephole_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const memory::desc &diff_dst_iter_c_desc, + const lstm_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_lstm, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, &src_iter_c_desc, nullptr, + weights_layer_desc, weights_iter_desc, + &weights_peephole_desc, nullptr, bias_desc, dst_layer_desc, + dst_iter_desc, &dst_iter_c_desc, diff_src_layer_desc, + diff_src_iter_desc, &diff_src_iter_c_desc, nullptr, + diff_weights_layer_desc, diff_weights_iter_desc, + &diff_weights_peephole_desc, nullptr, diff_bias_desc, + diff_dst_layer_desc, diff_dst_iter_desc, + &diff_dst_iter_c_desc, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs an LSTM primitive descriptor for backward propagation + /// using @p prop_kind, @p direction, and memory descriptors. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p src_iter_c_desc, + /// @p diff_src_iter_desc, and @p diff_src_iter_c_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p dst_iter_c_desc, + /// @p diff_dst_iter_desc, and @p diff_dst_iter_c_desc. + /// + /// This would then indicate that the LSTM backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param src_iter_c_desc Memory descriptor for the input recurrent + /// cell state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param dst_iter_c_desc Memory descriptor for the output recurrent + /// cell state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_src_iter_c_desc Memory descriptor for the diff of + /// input recurrent cell state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param diff_dst_iter_c_desc Memory descriptor for the diff of + /// output recurrent cell state vector. + /// @param hint_fwd_pd Primitive descriptor for a convolution + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &src_iter_c_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &dst_iter_c_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_src_iter_c_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const memory::desc &diff_dst_iter_c_desc, + const lstm_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_lstm, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, &src_iter_c_desc, nullptr, + weights_layer_desc, weights_iter_desc, nullptr, nullptr, + bias_desc, dst_layer_desc, dst_iter_desc, &dst_iter_c_desc, + diff_src_layer_desc, diff_src_iter_desc, + &diff_src_iter_c_desc, nullptr, diff_weights_layer_desc, + diff_weights_iter_desc, nullptr, nullptr, diff_bias_desc, + diff_dst_layer_desc, diff_dst_iter_desc, + &diff_dst_iter_c_desc, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an LSTM backward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an LSTM backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::backward, + dnnl::algorithm::vanilla_lstm) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_c_desc() const { + return rnn_base::src_iter_c_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_peephole_desc()const + memory::desc weights_peephole_desc() const { + return rnn_base::weights_peephole_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_projection_desc()const + memory::desc weights_projection_desc() const { + return rnn_base::weights_projection_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc dst_iter_c_desc() const { + return rnn_base::dst_iter_c_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_layer_desc()const + memory::desc diff_src_layer_desc() const { + return rnn_base::diff_src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_desc()const + memory::desc diff_src_iter_desc() const { + return rnn_base::diff_src_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_c_desc()const + memory::desc diff_src_iter_c_desc() const { + return rnn_base::diff_src_iter_c_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_layer_desc()const + memory::desc diff_weights_layer_desc() const { + return rnn_base::diff_weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_iter_desc()const + memory::desc diff_weights_iter_desc() const { + return rnn_base::diff_weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_peephole_desc()const + memory::desc diff_weights_peephole_desc() const { + return rnn_base::diff_weights_peephole_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_projection_desc()const + memory::desc diff_weights_projection_desc() const { + return rnn_base::diff_weights_projection_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return rnn_base::diff_bias_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_layer_desc()const + memory::desc diff_dst_layer_desc() const { + return rnn_base::diff_dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_desc()const + memory::desc diff_dst_iter_desc() const { + return rnn_base::diff_dst_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_c_desc()const + memory::desc diff_dst_iter_c_desc() const { + return rnn_base::diff_dst_iter_c_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + lstm_backward() = default; + + /// Constructs an LSTM backward propagation primitive. + /// @param pd Primitive descriptor for an LSTM backward propagation + /// primitive. + lstm_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LSTM backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LSTM backward propagation + /// primitive. + /// @param cache_blob Cache blob. + lstm_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// GRU forward propagation primitive. +struct gru_forward : public primitive { + /// Primitive descriptor for a GRU forward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a GRU forward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc. + /// + /// This would then indicate that the GRU forward propagation primitive + /// should not use them and should default to zero values instead. + /// + /// @note + /// All memory descriptors except @p src_iter_desc may be + /// initialized with an #dnnl::memory::format_tag::any value of @p + /// format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_gru, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, nullptr, nullptr, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, rnn_flags::undef, + 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a GRU forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a GRU forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference, + dnnl::algorithm::vanilla_gru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + gru_forward() = default; + + /// Constructs a GRU forward propagation primitive. + /// @param pd Primitive descriptor for a GRU forward propagation + /// primitive. + gru_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a GRU forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a GRU forward propagation + /// primitive. + /// @param cache_blob Cache blob. + gru_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// GRU backward propagation primitive. +struct gru_backward : public primitive { + /// Primitive descriptor for a GRU backward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a GRU backward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p diff_src_iter_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p diff_dst_iter_desc. + /// + /// This would then indicate that the GRU backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param hint_fwd_pd Primitive descriptor for a GRU + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const gru_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_gru, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, nullptr, nullptr, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, diff_src_layer_desc, + diff_src_iter_desc, nullptr, nullptr, + diff_weights_layer_desc, diff_weights_iter_desc, nullptr, + nullptr, diff_bias_desc, diff_dst_layer_desc, + diff_dst_iter_desc, nullptr, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a GRU backward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a GRU backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::backward, + dnnl::algorithm::vanilla_gru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_layer_desc()const + memory::desc diff_src_layer_desc() const { + return rnn_base::diff_src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_desc()const + memory::desc diff_src_iter_desc() const { + return rnn_base::diff_src_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_layer_desc()const + memory::desc diff_weights_layer_desc() const { + return rnn_base::diff_weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_iter_desc()const + memory::desc diff_weights_iter_desc() const { + return rnn_base::diff_weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return rnn_base::diff_bias_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_layer_desc()const + memory::desc diff_dst_layer_desc() const { + return rnn_base::diff_dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_desc()const + memory::desc diff_dst_iter_desc() const { + return rnn_base::diff_dst_iter_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + gru_backward() = default; + + /// Constructs a GRU backward propagation primitive. + /// @param pd Primitive descriptor for a GRU backward propagation + /// primitive. + gru_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a GRU backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a GRU backward propagation + /// primitive. + /// @param cache_blob Cache blob. + gru_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// LBR GRU forward propagation primitive. +struct lbr_gru_forward : public primitive { + /// Primitive descriptor for an LBR GRU forward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for LBR GRU forward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc. + /// + /// This would then indicate that the LBR GRU forward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors except @p src_iter_desc may be + /// initialized with an #dnnl::memory::format_tag::any value of @p + /// format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::lbr_gru, aprop_kind, + algorithm::undef, direction, src_layer_desc, src_iter_desc, + nullptr, nullptr, weights_layer_desc, weights_iter_desc, + nullptr, nullptr, bias_desc, dst_layer_desc, dst_iter_desc, + nullptr, rnn_flags::undef, 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a LBR GRU forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a LBR GRU forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference, + dnnl::algorithm::lbr_gru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + lbr_gru_forward() = default; + + /// Constructs an LBR GRU forward propagation primitive. + /// @param pd Primitive descriptor for an LBR GRU forward propagation + /// primitive. + lbr_gru_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LBR GRU forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LBR GRU forward propagation + /// primitive. + /// @param cache_blob Cache blob. + lbr_gru_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// LBR GRU backward propagation primitive. +struct lbr_gru_backward : public primitive { + /// Primitive descriptor for an LBR GRU backward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for LBR GRU backward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p diff_src_iter_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p diff_dst_iter_desc. + /// + /// This would then indicate that the LBR GRU backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param hint_fwd_pd Primitive descriptor for an LBR GRU + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const lbr_gru_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::lbr_gru, aprop_kind, + algorithm::undef, direction, src_layer_desc, src_iter_desc, + nullptr, nullptr, weights_layer_desc, weights_iter_desc, + nullptr, nullptr, bias_desc, dst_layer_desc, dst_iter_desc, + nullptr, diff_src_layer_desc, diff_src_iter_desc, nullptr, + nullptr, diff_weights_layer_desc, diff_weights_iter_desc, + nullptr, nullptr, diff_bias_desc, diff_dst_layer_desc, + diff_dst_iter_desc, nullptr, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a LBR GRU backward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a LBR GRU backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base( + pd, dnnl::prop_kind::backward, dnnl::algorithm::lbr_gru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_layer_desc()const + memory::desc diff_src_layer_desc() const { + return rnn_base::diff_src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_desc()const + memory::desc diff_src_iter_desc() const { + return rnn_base::diff_src_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_layer_desc()const + memory::desc diff_weights_layer_desc() const { + return rnn_base::diff_weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_iter_desc()const + memory::desc diff_weights_iter_desc() const { + return rnn_base::diff_weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return rnn_base::diff_bias_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_layer_desc()const + memory::desc diff_dst_layer_desc() const { + return rnn_base::diff_dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_desc()const + memory::desc diff_dst_iter_desc() const { + return rnn_base::diff_dst_iter_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + lbr_gru_backward() = default; + + /// Constructs an LBR GRU backward propagation primitive. + /// @param pd Primitive descriptor for an LBR GRU backward propagation + /// primitive. + lbr_gru_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LBR GRU backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LBR GRU backward propagation + /// primitive. + /// @param cache_blob Cache blob. + lbr_gru_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// AUGRU forward propagation primitive. +struct augru_forward : public primitive { + /// Primitive descriptor for an AUGRU forward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an AUGRU forward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc. + /// + /// This would then indicate that the AUGRU forward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors except @p src_iter_desc may be + /// initialized with an #dnnl::memory::format_tag::any value of @p + /// format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param attention_desc Memory descriptor for the attention vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &attention_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_augru, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, nullptr, &attention_desc, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, rnn_flags::undef, + 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an AUGRU forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an AUGRU forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference, + dnnl::algorithm::vanilla_augru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::augru_attention_desc()const + memory::desc attention_desc() const { + return rnn_base::augru_attention_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + augru_forward() = default; + + /// Constructs an AUGRU forward propagation primitive. + /// @param pd Primitive descriptor for an AUGRU forward propagation + /// primitive. + augru_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an AUGRU forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an AUGRU forward propagation + /// primitive. + /// @param cache_blob Cache blob. + augru_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// AUGRU backward propagation primitive. +struct augru_backward : public primitive { + /// Descriptor for an AUGRU backward propagation primitive. + /// Primitive descriptor for an AUGRU backward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an AUGRU backward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p diff_src_iter_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p diff_dst_iter_desc. + /// + /// This would then indicate that the AUGRU backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param attention_desc Memory descriptor for the attention vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_attention_desc Memory descriptor for the diff of + /// attention vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param hint_fwd_pd Primitive descriptor for an AUGRU + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &attention_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_attention_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const augru_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::vanilla_augru, + aprop_kind, algorithm::undef, direction, src_layer_desc, + src_iter_desc, nullptr, &attention_desc, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, diff_src_layer_desc, + diff_src_iter_desc, nullptr, &diff_attention_desc, + diff_weights_layer_desc, diff_weights_iter_desc, nullptr, + nullptr, diff_bias_desc, diff_dst_layer_desc, + diff_dst_iter_desc, nullptr, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an AUGRU backward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an AUGRU backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::backward, + dnnl::algorithm::vanilla_augru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::augru_attention_desc()const + memory::desc attention_desc() const { + return rnn_base::augru_attention_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_layer_desc()const + memory::desc diff_src_layer_desc() const { + return rnn_base::diff_src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_desc()const + memory::desc diff_src_iter_desc() const { + return rnn_base::diff_src_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_augru_attention_desc()const + memory::desc diff_attention_desc() const { + return rnn_base::diff_augru_attention_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_layer_desc()const + memory::desc diff_weights_layer_desc() const { + return rnn_base::diff_weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_iter_desc()const + memory::desc diff_weights_iter_desc() const { + return rnn_base::diff_weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return rnn_base::diff_bias_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_layer_desc()const + memory::desc diff_dst_layer_desc() const { + return rnn_base::diff_dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_desc()const + memory::desc diff_dst_iter_desc() const { + return rnn_base::diff_dst_iter_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + augru_backward() = default; + + /// Constructs an AUGRU backward propagation primitive. + /// @param pd Primitive descriptor for an AUGRU backward propagation + /// primitive. + augru_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an AUGRU backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an AUGRU backward propagation + /// primitive. + /// @param cache_blob Cache blob. + augru_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// LBR AUGRU forward propagation primitive. +struct lbr_augru_forward : public primitive { + /// Descriptor for an LBR AUGRU forward propagation primitive. + + /// Primitive descriptor for an LBR AUGRU forward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for LBR AUGRU forward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc, + /// - @p bias_desc, + /// - @p dst_iter_desc. + /// + /// This would then indicate that the LBR AUGRU forward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors except @p src_iter_desc may be + /// initialized with an #dnnl::memory::format_tag::any value of @p + /// format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param attention_desc Memory descriptor for the attention vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &attention_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::lbr_augru, aprop_kind, + algorithm::undef, direction, src_layer_desc, src_iter_desc, + nullptr, &attention_desc, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, rnn_flags::undef, + 0.0f, 0.0f, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an LBR AUGRU forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for an LBR AUGRU forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference, + dnnl::algorithm::lbr_augru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::augru_attention_desc()const + memory::desc attention_desc() const { + return rnn_base::augru_attention_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + lbr_augru_forward() = default; + + /// Constructs an LBR AUGRU forward propagation primitive. + /// @param pd Primitive descriptor for an LBR AUGRU forward propagation + /// primitive. + lbr_augru_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LBR AUGRU forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LBR AUGRU forward propagation + /// primitive. + /// @param cache_blob Cache blob. + lbr_augru_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// LBR AUGRU backward propagation primitive. +struct lbr_augru_backward : public primitive { + /// Primitive descriptor for an LBR AUGRU backward propagation primitive. + struct primitive_desc : public rnn_primitive_desc_base { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for LBR AUGRU backward propagation + /// primitive. + /// + /// The following arguments may point to a zero memory descriptor: + /// - @p src_iter_desc together with @p diff_src_iter_desc, + /// - @p bias_desc together with @p diff_bias_desc, + /// - @p dst_iter_desc together with @p diff_dst_iter_desc. + /// + /// This would then indicate that the LBR AUGRU backward propagation + /// primitive should not use them and should default to zero values + /// instead. + /// + /// @note + /// All memory descriptors may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Must be + /// #dnnl::prop_kind::backward. + /// @param direction RNN direction. See @ref dnnl::rnn_direction for + /// more info. + /// @param src_layer_desc Memory descriptor for the input vector. + /// @param src_iter_desc Memory descriptor for the input recurrent + /// hidden state vector. + /// @param attention_desc Memory descriptor for the attention vector. + /// @param weights_layer_desc Memory descriptor for the weights + /// applied to the layer input. + /// @param weights_iter_desc Memory descriptor for the weights applied + /// to the recurrent input. + /// @param bias_desc Bias memory descriptor. + /// @param dst_layer_desc Memory descriptor for the output vector. + /// @param dst_iter_desc Memory descriptor for the output recurrent + /// hidden state vector. + /// @param diff_src_layer_desc Memory descriptor for the diff of input + /// vector. + /// @param diff_src_iter_desc Memory descriptor for the diff of input + /// recurrent hidden state vector. + /// @param diff_attention_desc Memory descriptor for the diff of + /// attention vector. + /// @param diff_weights_layer_desc Memory descriptor for the diff of + /// weights applied to the layer input. + /// @param diff_weights_iter_desc Memory descriptor for the diff of + /// weights applied to the recurrent input. + /// @param diff_bias_desc Diff bias memory descriptor. + /// @param diff_dst_layer_desc Memory descriptor for the diff of + /// output vector. + /// @param diff_dst_iter_desc Memory descriptor for the diff of output + /// recurrent hidden state vector. + /// @param hint_fwd_pd Primitive descriptor for an LBR AUGRU + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + rnn_direction direction, const memory::desc &src_layer_desc, + const memory::desc &src_iter_desc, + const memory::desc &attention_desc, + const memory::desc &weights_layer_desc, + const memory::desc &weights_iter_desc, + const memory::desc &bias_desc, + const memory::desc &dst_layer_desc, + const memory::desc &dst_iter_desc, + const memory::desc &diff_src_layer_desc, + const memory::desc &diff_src_iter_desc, + const memory::desc &diff_attention_desc, + const memory::desc &diff_weights_layer_desc, + const memory::desc &diff_weights_iter_desc, + const memory::desc &diff_bias_desc, + const memory::desc &diff_dst_layer_desc, + const memory::desc &diff_dst_iter_desc, + const lbr_augru_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : rnn_primitive_desc_base(aengine, algorithm::lbr_augru, aprop_kind, + algorithm::undef, direction, src_layer_desc, src_iter_desc, + nullptr, &attention_desc, weights_layer_desc, + weights_iter_desc, nullptr, nullptr, bias_desc, + dst_layer_desc, dst_iter_desc, nullptr, diff_src_layer_desc, + diff_src_iter_desc, nullptr, &diff_attention_desc, + diff_weights_layer_desc, diff_weights_iter_desc, nullptr, + nullptr, diff_bias_desc, diff_dst_layer_desc, + diff_dst_iter_desc, nullptr, rnn_flags::undef, 0.0f, 0.0f, + hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for an LBR AUGRU backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for an LBR AUGRU backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : rnn_primitive_desc_base(pd, dnnl::prop_kind::backward, + dnnl::algorithm::lbr_augru) {} + + /// @copydoc dnnl::rnn_primitive_desc_base::src_layer_desc()const + memory::desc src_layer_desc() const { + return rnn_base::src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::src_iter_desc()const + memory::desc src_iter_desc() const { return rnn_base::src_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::augru_attention_desc()const + memory::desc attention_desc() const { + return rnn_base::augru_attention_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_layer_desc()const + memory::desc weights_layer_desc() const { + return rnn_base::weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::weights_iter_desc()const + memory::desc weights_iter_desc() const { + return rnn_base::weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::bias_desc()const + memory::desc bias_desc() const { return rnn_base::bias_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_layer_desc()const + memory::desc dst_layer_desc() const { + return rnn_base::dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::dst_iter_desc()const + memory::desc dst_iter_desc() const { return rnn_base::dst_iter_desc(); } + + /// @copydoc dnnl::rnn_primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { + return rnn_base::workspace_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_layer_desc()const + memory::desc diff_src_layer_desc() const { + return rnn_base::diff_src_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_src_iter_desc()const + memory::desc diff_src_iter_desc() const { + return rnn_base::diff_src_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_augru_attention_desc()const + memory::desc diff_attention_desc() const { + return rnn_base::diff_augru_attention_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_layer_desc()const + memory::desc diff_weights_layer_desc() const { + return rnn_base::diff_weights_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_weights_iter_desc()const + memory::desc diff_weights_iter_desc() const { + return rnn_base::diff_weights_iter_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_bias_desc()const + memory::desc diff_bias_desc() const { + return rnn_base::diff_bias_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_layer_desc()const + memory::desc diff_dst_layer_desc() const { + return rnn_base::diff_dst_layer_desc(); + } + + /// @copydoc dnnl::rnn_primitive_desc_base::diff_dst_iter_desc()const + memory::desc diff_dst_iter_desc() const { + return rnn_base::diff_dst_iter_desc(); + } + + /// @copydoc dnnl::primitive_desc_base::get_cell_kind()const + algorithm get_cell_kind() const { return base::get_cell_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_direction()const + rnn_direction get_direction() const { return base::get_direction(); } + }; + + /// Default constructor. Produces an empty object. + lbr_augru_backward() = default; + + /// Constructs an LBR AUGRU backward propagation primitive. + /// @param pd Primitive descriptor for an LBR AUGRU backward propagation + /// primitive. + lbr_augru_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an LBR AUGRU backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for an LBR AUGRU backward propagation + /// primitive. + /// @param cache_blob Cache blob. + lbr_augru_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_rnn + +/// @addtogroup dnnl_api_shuffle Shuffle +/// +/// A primitive to shuffle tensor data along an axis. +/// +/// @sa @ref dev_guide_shuffle in developer guide +/// +/// @{ + +/// Shuffle forward propagation primitive. +struct shuffle_forward : public primitive { + /// Primitive descriptor for a shuffle forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a shuffle forward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param axis The axis along which the data is shuffled. + /// @param group_size Shuffle group size. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &dst_desc, + int axis, int group_size, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_shuffle_forward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + src_desc.get(), dst_desc.get(), axis, group_size, + attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a shuffle " + "forward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a shuffle forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a shuffle forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::shuffle, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_axis()const + int get_axis() const { return base::get_axis(); } + + /// @copydoc dnnl::primitive_desc_base::get_group_size()const + memory::dim get_group_size() const { return base::get_group_size(); } + }; + + /// Default constructor. Produces an empty object. + shuffle_forward() = default; + + /// Constructs a shuffle forward propagation primitive. + /// @param pd Primitive descriptor for a shuffle forward propagation + /// primitive. + shuffle_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a shuffle forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a shuffle forward propagation + /// primitive. + /// @param cache_blob Cache blob. + shuffle_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Shuffle backward propagation primitive. +struct shuffle_backward : public primitive { + /// Primitive descriptor for a shuffle backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a shuffle backward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param axis The axis along which the data is shuffled. + /// @param group_size Shuffle group size. + /// @param hint_fwd_pd Primitive descriptor for a shuffle forward + /// propagation primitive. It is used as a hint for deciding which + /// memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, int axis, int group_size, + const shuffle_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_shuffle_backward_primitive_desc_create( + &pd, aengine.get(), diff_src_desc.get(), + diff_dst_desc.get(), axis, group_size, hint_fwd_pd.get(), + attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a shuffle " + "backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a shuffle backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a shuffle backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::shuffle, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_axis()const + int get_axis() const { return base::get_axis(); } + + /// @copydoc dnnl::primitive_desc_base::get_group_size()const + memory::dim get_group_size() const { return base::get_group_size(); } + }; + + /// Default constructor. Produces an empty object. + shuffle_backward() = default; + + /// Constructs a shuffle backward propagation primitive. + /// @param pd Primitive descriptor for a shuffle backward propagation + /// primitive. + shuffle_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a shuffle backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a shuffle backward propagation + /// primitive. + /// @param cache_blob Cache blob. + shuffle_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_shuffle + +/// @addtogroup dnnl_api_binary Binary +/// +/// A primitive to perform tensor operations over two tensors. +/// +/// @sa @ref dev_guide_binary in developer guide +/// +/// @{ + +/// Elementwise binary operator primitive. +struct binary : public primitive { + /// Primitive descriptor for an elementwise binary operator primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for an elementwise binary operator + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Elementwise binary algorithm. + /// @param src0 Memory descriptor for source tensor #0. + /// @param src1 Memory descriptor for source tensor #1. + /// @param dst Memory descriptor for destination tensor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src0, const memory::desc &src1, + const memory::desc &dst, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_binary_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aalgorithm), src0.get(), + src1.get(), dst.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a binary " + "operation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a binary primitive from a C + /// API primitive descriptor that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a binary primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::binary) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc(int)const + memory::desc src_desc(int idx = 0) const { return base::src_desc(idx); } + + /// Returns the memory descriptor for source #0. + memory::desc src0_desc() const { return base::src_desc(0); } + + /// Returns the memory descriptor for source #1. + memory::desc src1_desc() const { return base::src_desc(1); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + }; + + /// Default constructor. Produces an empty object. + binary() = default; + + /// Constructs an elementwise binary operation primitive. + /// @param pd Primitive descriptor for an elementwise binary operation + /// primitive. + binary(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs an elementwise binary operation primitive from a cache blob. + /// @param pd Primitive descriptor for an elementwise binary operation + /// primitive. + /// @param cache_blob Cache blob. + binary(const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_binary + +/// @addtogroup dnnl_api_matmul Matrix Multiplication +/// +/// A primitive to perform matrix-matrix multiplication. The batched mode +/// is supported with 3D tensors. +/// +/// @sa @ref dev_guide_matmul in developer guide +/// +/// +/// @{ + +/// Matrix multiplication (matmul) primitive. +struct matmul : public primitive { + /// Primitive descriptor for a matmul primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a matmul primitive + /// without bias. + /// + /// @param aengine Engine to use. + /// @param src_desc Memory descriptor for source (matrix A). + /// @param weights_desc Memory descriptor for weights (matrix B). + /// @param dst_desc Memory descriptor for destination (matrix C). + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, src_desc, weights_desc, nullptr, dst_desc, + attr, allow_empty) {} + + /// Constructs a primitive descriptor for a matmul primitive with bias. + /// + /// @param aengine Engine to use. + /// @param src_desc Memory descriptor for source (matrix A). + /// @param weights_desc Memory descriptor for weights (matrix B). + /// @param dst_desc Memory descriptor for destination (matrix C). + /// @param bias_desc Memory descriptor for bias. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc &bias_desc, + const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, src_desc, weights_desc, &bias_desc, + dst_desc, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a matmul primitive from a C + /// API primitive descriptor that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a matmul primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::matmul) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return query_md(query::src_md, 0); } + + /// @copydoc dnnl::primitive_desc_base::weights_desc()const + memory::desc weights_desc() const { + return query_md(query::weights_md, 0); + } + + /// @copydoc dnnl::convolution_forward::primitive_desc::bias_desc()const + memory::desc bias_desc() const { + return query_md(query::weights_md, 1); + } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return query_md(query::dst_md, 0); } + + private: + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &weights_desc, const memory::desc *bias_desc, + const memory::desc &dst_desc, const primitive_attr &attr, + bool allow_empty) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_matmul_primitive_desc_create(&pd, + aengine.get(), src_desc.get(), weights_desc.get(), + optional_arg(bias_desc), dst_desc.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a matmul " + "primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + matmul() = default; + + /// Constructs a matmul primitive. + /// @param pd Primitive descriptor for a matmul primitive. + matmul(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a matmul primitive from a cache blob. + /// @param pd Primitive descriptor for a matmul primitive. + /// @param cache_blob Cache blob. + matmul(const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_matmul + +/// @addtogroup dnnl_api_resampling Resampling +/// +/// A primitive to compute resampling operation on 1D, 2D or 3D data tensor +/// using Nearest Neighbor, or Linear (Bilinear, Trilinear) interpolation +/// method. +/// +/// @sa @ref dev_guide_resampling in developer guide +/// +/// @{ + +/// Resampling forward propagation. +struct resampling_forward : public primitive { + /// Primitive descriptor for a resampling forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a resampling forward + /// propagation primitive using source and destination memory + /// descriptors. + /// + /// @note + /// Destination memory descriptor may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm resampling algorithm kind: either + /// #dnnl::algorithm::resampling_nearest, or + /// #dnnl::algorithm::resampling_linear + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, nullptr, src_desc, + &dst_desc, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a resampling forward + /// propagation primitive using source memory descriptor and + /// factors. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm resampling algorithm kind: either + /// #dnnl::algorithm::resampling_nearest, or + /// #dnnl::algorithm::resampling_linear + /// @param factors Vector of scaling factors for spatial dimension. + /// @param src_desc Source memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const std::vector &factors, + const memory::desc &src_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, &factors, + src_desc, nullptr, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a resampling forward + /// propagation primitive. + /// + /// @note + /// The destination memory descriptor may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm resampling algorithm kind: either + /// #dnnl::algorithm::resampling_nearest, or + /// #dnnl::algorithm::resampling_linear + /// @param factors Vector of scaling factors for spatial dimension. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const std::vector &factors, + const memory::desc &src_desc, const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aprop_kind, aalgorithm, &factors, + src_desc, &dst_desc, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a resampling forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a resampling forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::resampling, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + private: + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const std::vector *factors, + const memory::desc &src_desc, const memory::desc *dst_desc, + const primitive_attr &attr, bool allow_empty) { + + if (factors) + memory::validate_dims(*factors, src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_resampling_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + convert_to_c(aalgorithm), optional_arg(factors), + src_desc.get(), optional_arg(dst_desc), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "resampling forward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + resampling_forward() = default; + + /// Constructs a resampling forward propagation primitive. + /// @param pd Primitive descriptor for a resampling forward propagation + /// primitive. + resampling_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a resampling forward propagation primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a resampling forward propagation + /// primitive. + /// @param cache_blob Cache blob. + resampling_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Resampling backward propagation primitive. +struct resampling_backward : public primitive { + /// Primitive descriptor for resampling backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a resampling backward + /// propagation primitive using source and destination memory + /// descriptors. + /// + /// @param aengine Engine to use. + /// @param aalgorithm resampling algorithm kind: either + /// #dnnl::algorithm::resampling_nearest, or + /// #dnnl::algorithm::resampling_linear + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param hint_fwd_pd Primitive descriptor for a resampling + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const resampling_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, nullptr, diff_src_desc, + diff_dst_desc, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for resampling backward + /// propagation primitive. + /// + /// @param aengine Engine to use. + /// @param aalgorithm resampling algorithm kind: either + /// #dnnl::algorithm::resampling_nearest, or + /// #dnnl::algorithm::resampling_linear + /// @param factors Vector of scaling factors for spatial dimension. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param hint_fwd_pd Primitive descriptor for a resampling + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const std::vector &factors, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const resampling_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) + : primitive_desc(aengine, aalgorithm, &factors, diff_src_desc, + diff_dst_desc, hint_fwd_pd, attr, allow_empty) {} + + /// Constructs a primitive descriptor for a resampling backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a resampling backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::resampling, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + private: + primitive_desc(const engine &aengine, algorithm aalgorithm, + const std::vector *factors, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, + const resampling_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr, bool allow_empty) { + + if (factors) + memory::validate_dims(*factors, diff_src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status + = dnnl_resampling_backward_primitive_desc_create(&pd, + aengine.get(), convert_to_c(aalgorithm), + optional_arg(factors), diff_src_desc.get(), + diff_dst_desc.get(), hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "resampling backward propagation primitive"); + reset(pd); + } + }; + + /// Default constructor. Produces an empty object. + resampling_backward() = default; + + /// Constructs a resampling backward propagation primitive. + /// @param pd Primitive descriptor for a resampling backward propagation + /// primitive. + resampling_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a resampling backward propagation primitive from a cache + /// blob. + /// @param pd Primitive descriptor for a resampling backward propagation + /// primitive. + /// @param cache_blob Cache blob. + resampling_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_resampling + +/// @addtogroup dnnl_api_pooling Pooling +/// +/// A primitive to perform max or average pooling with dilation. +/// +/// @sa @ref dev_guide_pooling in developer guide +/// +/// @{ + +/// Pooling forward propagation primitive. +struct pooling_forward : public primitive { + /// Primitive descriptor for a pooling forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for pooling forward propagation + /// primitive. + /// + /// Arrays @p strides, @p kernel, @p dilation, @p padding_l + /// and @p padding_r contain values for spatial dimensions only and + /// hence must have the same number of elements as there are spatial + /// dimensions. The order of values is the same as in the tensor: + /// depth (for 3D tensors), height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param aalgorithm Pooling algorithm kind: either + /// #dnnl::algorithm::pooling_max, + /// #dnnl::algorithm::pooling_avg_include_padding, + /// or #dnnl::algorithm::pooling_avg_exclude_padding. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param strides Vector of strides for spatial dimension. + /// @param kernel Vector of kernel spatial dimensions. + /// @param dilation Array of dilations for spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + algorithm aalgorithm, const memory::desc &src_desc, + const memory::desc &dst_desc, const memory::dims &strides, + const memory::dims &kernel, const memory::dims &dilation, + const memory::dims &padding_l, const memory::dims &padding_r, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + memory::validate_dims(strides, src_desc.get_ndims() - 2); + memory::validate_dims(kernel, src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, src_desc.get_ndims() - 2); + memory::validate_dims(dilation, src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_pooling_forward_primitive_desc_create( + &pd, aengine.get(), dnnl::convert_to_c(aprop_kind), + convert_to_c(aalgorithm), src_desc.get(), dst_desc.get(), + &strides[0], &kernel[0], &dilation[0], &padding_l[0], + &padding_r[0], attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a descriptor for a pooling forward " + "propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a pooling forward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a pooling forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::pooling, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_kernel()const + memory::dims get_kernel() const { return base::get_kernel(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + }; + + /// Default constructor. Produces an empty object. + pooling_forward() = default; + + /// Constructs a pooling forward propagation primitive. + /// + /// @param pd Primitive descriptor for a pooling forward propagation + /// primitive. + pooling_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a pooling forward propagation primitive from a cache blob. + /// + /// @param pd Primitive descriptor for a pooling forward propagation + /// primitive. + /// @param cache_blob Cache blob. + pooling_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// Pooling backward propagation primitive. +struct pooling_backward : public primitive { + /// Primitive descriptor for a pooling backward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a pooling backward propagation + /// primitive. + /// + /// Arrays @p strides, @p kernel, @p dilation, @p padding_l + /// and @p padding_r contain values for spatial dimensions only and + /// hence must have the same number of elements as there are spatial + /// dimensions. The order of values is the same as in the tensor: + /// depth (for 3D tensors), height (for 3D and 2D tensors), and width. + /// + /// @param aengine Engine to use. + /// @param aalgorithm Pooling algorithm kind: either + /// #dnnl::algorithm::pooling_max, + /// #dnnl::algorithm::pooling_avg_include_padding, + /// or #dnnl::algorithm::pooling_avg_exclude_padding. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param strides Vector of strides for spatial dimension. + /// @param kernel Vector of kernel spatial dimensions. + /// @param dilation Array of dilations for spatial dimension. + /// @param padding_l Vector of padding values for low indices for each + /// spatial dimension `([[front,] top,] left)`. + /// @param padding_r Vector of padding values for high indices for + /// each spatial dimension `([[back,] bottom,] right)`. + /// @param hint_fwd_pd Primitive descriptor for a pooling + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &diff_src_desc, + const memory::desc &diff_dst_desc, const memory::dims &strides, + const memory::dims &kernel, const memory::dims &dilation, + const memory::dims &padding_l, const memory::dims &padding_r, + const pooling_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + memory::validate_dims(strides, diff_src_desc.get_ndims() - 2); + memory::validate_dims(kernel, diff_src_desc.get_ndims() - 2); + memory::validate_dims(padding_l, diff_src_desc.get_ndims() - 2); + memory::validate_dims(padding_r, diff_src_desc.get_ndims() - 2); + memory::validate_dims(dilation, diff_src_desc.get_ndims() - 2); + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_pooling_backward_primitive_desc_create( + &pd, aengine.get(), convert_to_c(aalgorithm), + diff_src_desc.get(), diff_dst_desc.get(), &strides[0], + &kernel[0], &dilation[0], &padding_l[0], &padding_r[0], + hint_fwd_pd.get(), attr.get()); + if (!allow_empty) + error::wrap_c_api(status, + "could not create a descriptor for a pooling backward " + "propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a pooling backward propagation + /// primitive from a C API primitive descriptor that must have a + /// matching kind. + /// + /// @param pd C API primitive descriptor for a pooling backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::pooling, + dnnl::prop_kind::backward_data) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::workspace_desc()const + memory::desc workspace_desc() const { return base::workspace_desc(); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + + /// @copydoc dnnl::primitive_desc_base::get_strides()const + memory::dims get_strides() const { return base::get_strides(); } + + /// @copydoc dnnl::primitive_desc_base::get_kernel()const + memory::dims get_kernel() const { return base::get_kernel(); } + + /// @copydoc dnnl::primitive_desc_base::get_dilations()const + memory::dims get_dilations() const { return base::get_dilations(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_l()const + memory::dims get_padding_l() const { return base::get_padding_l(); } + + /// @copydoc dnnl::primitive_desc_base::get_padding_r()const + memory::dims get_padding_r() const { return base::get_padding_r(); } + }; + + /// Default constructor. Produces an empty object. + pooling_backward() = default; + + /// Constructs a pooling backward propagation primitive. + /// + /// @param pd Primitive descriptor for a pooling backward propagation + /// primitive. + pooling_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a pooling backward propagation primitive from a cache blob. + /// + /// @param pd Primitive descriptor for a pooling backward propagation + /// primitive. + /// @param cache_blob Cache blob. + pooling_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_pooling + +/// @addtogroup dnnl_api_prelu PReLU +/// +/// PReLU primitive +/// A primitive to perform PReLU (leaky ReLU with trainable alpha parameter) +/// +/// @sa @ref dev_guide_prelu in developer guide +/// +/// @{ + +/// PReLU forward propagation primitive. +struct prelu_forward : public primitive { + /// Primitive descriptor for a PReLU forward propagation primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a PReLU forward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param aprop_kind Propagation kind. Possible values are + /// #dnnl::prop_kind::forward_training, and + /// #dnnl::prop_kind::forward_inference. + /// @param src_desc Source memory descriptor. + /// @param weight_desc Alpha parameters memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, prop_kind aprop_kind, + const memory::desc &src_desc, const memory::desc &weight_desc, + const memory::desc &dst_desc, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_prelu_forward_primitive_desc_create(&pd, + aengine.get(), dnnl::convert_to_c(aprop_kind), + src_desc.get(), weight_desc.get(), dst_desc.get(), + attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a prelu " + "forward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a prelu forward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a prelu forward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::prelu, + dnnl::prop_kind::forward_training, + dnnl::prop_kind::forward_inference) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + }; + + /// Default constructor. Produces an empty object. + prelu_forward() = default; + + /// Constructs a prelu forward propagation primitive. + /// @param pd Primitive descriptor for a prelu forward propagation + /// primitive. + prelu_forward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a prelu forward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a prelu forward propagation + /// primitive. + /// @param cache_blob Cache blob. + prelu_forward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// PReLU backward propagation primitive. +struct prelu_backward : public primitive { + /// Primitive descriptor for prelu backward propagation. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a descriptor for a PReLU backward propagation + /// primitive. + /// + /// @param aengine Engine to use. + /// @param src_desc Source memory descriptor. + /// @param weight_desc Alpha parameters memory descriptor. + /// @param diff_src_desc Diff source memory descriptor. + /// @param diff_weights_desc Diff alpha parameters memory descriptor. + /// @param diff_dst_desc Diff destination memory descriptor. + /// @param hint_fwd_pd Primitive descriptor for a PReLU + /// forward propagation primitive. It is used as a hint for + /// deciding which memory format to use. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, const memory::desc &src_desc, + const memory::desc &weight_desc, + const memory::desc &diff_src_desc, + const memory::desc &diff_weights_desc, + const memory::desc &diff_dst_desc, + const prelu_forward::primitive_desc &hint_fwd_pd, + const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_prelu_backward_primitive_desc_create( + &pd, aengine.get(), src_desc.get(), weight_desc.get(), + diff_src_desc.get(), diff_weights_desc.get(), + diff_dst_desc.get(), hint_fwd_pd.get(), attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a prelu " + "backward propagation primitive"); + reset(pd); + } + + /// Constructs a primitive descriptor for a prelu backward + /// propagation primitive from a C API primitive descriptor that must + /// have a matching kind. + /// + /// @param pd C API primitive descriptor for a prelu backward + /// propagation primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::prelu, + dnnl::prop_kind::backward) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_src_desc()const + memory::desc diff_src_desc() const { return base::diff_src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::diff_dst_desc()const + memory::desc diff_dst_desc() const { return base::diff_dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_prop_kind()const + prop_kind get_prop_kind() const { return base::get_prop_kind(); } + }; + + /// Default constructor. Produces an empty object. + prelu_backward() = default; + + /// Constructs a prelu backward propagation primitive. + /// @param pd Primitive descriptor for a prelu backward propagation + /// primitive. + prelu_backward(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a prelu backward propagation primitive from a cache blob. + /// @param pd Primitive descriptor for a prelu backward propagation + /// primitive. + /// @param cache_blob Cache blob. + prelu_backward( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_prelu + +/// @addtogroup dnnl_api_reduction Reduction +/// +/// A primitive to compute reduction operation on data tensor +/// using min, max, mul, sum, mean and norm_lp operations. +/// +/// @sa @ref dev_guide_reduction in developer guide +/// +/// @{ + +/// Reduction. +struct reduction : public primitive { + /// Primitive descriptor for a reduction primitive. + struct primitive_desc : public dnnl::primitive_desc { + /// Default constructor. Produces an empty object. + primitive_desc() = default; + + /// Constructs a primitive descriptor for a reduction primitive using + /// algorithm specific parameters, source and destination memory + /// descriptors. + /// + /// @note + /// Destination memory descriptor may be initialized with + /// #dnnl::memory::format_tag::any value of @p format_tag. + /// + /// @param aengine Engine to use. + /// @param aalgorithm reduction algorithm kind. Possible values: + /// #dnnl_reduction_max, #dnnl_reduction_min, #dnnl_reduction_sum, + /// #dnnl_reduction_mul, #dnnl_reduction_mean, + /// #dnnl_reduction_norm_lp_max, #dnnl_reduction_norm_lp_sum, + /// #dnnl_reduction_norm_lp_power_p_max, + /// #dnnl_reduction_norm_lp_power_p_sum. + /// @param p algorithm specific parameter. + /// @param eps algorithm specific parameter. + /// @param src_desc Source memory descriptor. + /// @param dst_desc Destination memory descriptor. + /// @param attr Primitive attributes to use. Attributes are optional + /// and default to empty attributes. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + primitive_desc(const engine &aengine, algorithm aalgorithm, + const memory::desc &src_desc, const memory::desc &dst_desc, + float p, float eps, const primitive_attr &attr = default_attr(), + bool allow_empty = false) { + + dnnl_primitive_desc_t pd = nullptr; + dnnl_status_t status = dnnl_reduction_primitive_desc_create(&pd, + aengine.get(), convert_to_c(aalgorithm), src_desc.get(), + dst_desc.get(), p, eps, attr.get()); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a primitive descriptor for a " + "reduction primitive descriptor"); + reset(pd); + } + + /// Constructs a primitive descriptor for a reduction primitive from a C + /// API primitive descriptor that must have a matching kind. + /// + /// @param pd C API primitive descriptor for a reduction primitive. + primitive_desc(dnnl_primitive_desc_t pd) + : dnnl::primitive_desc(pd, dnnl::primitive::kind::reduction) {} + + /// @copydoc dnnl::primitive_desc_base::src_desc()const + memory::desc src_desc() const { return base::src_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::dst_desc()const + memory::desc dst_desc() const { return base::dst_desc(0); } + + /// @copydoc dnnl::primitive_desc_base::get_p()const + float get_p() const { return base::get_p(); } + + /// @copydoc dnnl::primitive_desc_base::get_epsilon()const + float get_epsilon() const { return base::get_epsilon(); } + + /// @copydoc dnnl::primitive_desc_base::get_algorithm()const + algorithm get_algorithm() const { return base::get_algorithm(); } + }; + + /// Default constructor. Produces an empty object. + reduction() = default; + + /// Constructs a reduction primitive. + /// @param pd Primitive descriptor for a reduction primitive. + reduction(const primitive_desc &pd) : primitive(pd) {} + + /// Constructs a reduction primitive from a cache blob. + /// @param pd Primitive descriptor for a reduction primitive. + /// @param cache_blob Cache blob. + reduction(const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd, cache_blob) {} +}; + +/// @} dnnl_api_reduction + +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_service Service +/// +/// A set of functions that aid in oneDNN debugging and profiling. +/// +/// @{ + +/// @copydoc dnnl_version_t +using version_t = dnnl_version_t; + +/// Status values returned by the library functions. +enum class status { + /// @copydoc dnnl_success + success = dnnl_success, + /// @copydoc dnnl_out_of_memory + out_of_memory = dnnl_out_of_memory, + /// @copydoc dnnl_invalid_arguments + invalid_arguments = dnnl_invalid_arguments, + /// @copydoc dnnl_unimplemented + unimplemented = dnnl_unimplemented, + /// @copydoc dnnl_last_impl_reached + last_impl_reached = dnnl_last_impl_reached, + /// @copydoc dnnl_runtime_error + runtime_error = dnnl_runtime_error, + /// @copydoc dnnl_not_required + not_required = dnnl_not_required, +}; + +/// @copydoc dnnl_set_verbose() +inline status set_verbose(int level) { + return static_cast(dnnl_set_verbose(level)); +} + +/// @copydoc dnnl_version() +inline const version_t *version() { + return dnnl_version(); +} + +/// Returns the floating-point math mode that will be used by default +/// for all subsequently created primitives. +/// +/// @returns Output FP math mode. +inline fpmath_mode get_default_fpmath_mode() { + dnnl_fpmath_mode_t mode; + error::wrap_c_api(dnnl_get_default_fpmath_mode(&mode), + "could not get a default fpmath mode"); + return static_cast(mode); +} + +/// @copydoc dnnl_set_default_fpmath_mode() +inline status set_default_fpmath_mode(fpmath_mode mode) { + return static_cast( + dnnl_set_default_fpmath_mode(convert_to_c(mode))); +} + +/// @copydoc dnnl_set_jit_dump() +inline status set_jit_dump(int enable) { + return static_cast(dnnl_set_jit_dump(enable)); +} + +/// @copydoc dnnl_set_jit_profiling_flags() +inline status set_jit_profiling_flags(unsigned flags) { + return static_cast(dnnl_set_jit_profiling_flags(flags)); +} + +/// @copydoc dnnl_set_jit_profiling_jitdumpdir() +inline status set_jit_profiling_jitdumpdir(const std::string &dir) { + return static_cast(dnnl_set_jit_profiling_jitdumpdir(dir.c_str())); +} + +/// @copydoc dnnl_cpu_isa_t +enum class cpu_isa { + /// @copydoc dnnl_cpu_isa_default + isa_default = dnnl_cpu_isa_default, + /// @copydoc dnnl_cpu_isa_sse41 + sse41 = dnnl_cpu_isa_sse41, + /// @copydoc dnnl_cpu_isa_avx + avx = dnnl_cpu_isa_avx, + /// @copydoc dnnl_cpu_isa_avx2 + avx2 = dnnl_cpu_isa_avx2, + /// @copydoc dnnl_cpu_isa_avx2_vnni + avx2_vnni = dnnl_cpu_isa_avx2_vnni, + /// @copydoc dnnl_cpu_isa_avx2_vnni_2 + avx2_vnni_2 = dnnl_cpu_isa_avx2_vnni_2, + /// @copydoc dnnl_cpu_isa_avx512_core + avx512_core = dnnl_cpu_isa_avx512_core, + /// @copydoc dnnl_cpu_isa_avx512_core_vnni + avx512_core_vnni = dnnl_cpu_isa_avx512_core_vnni, + /// @copydoc dnnl_cpu_isa_avx512_core_bf16 + avx512_core_bf16 = dnnl_cpu_isa_avx512_core_bf16, + /// @copydoc dnnl_cpu_isa_avx10_1_512 + avx10_1_512 = dnnl_cpu_isa_avx10_1_512, + /// @copydoc dnnl_cpu_isa_avx512_core_fp16 + avx512_core_fp16 = dnnl_cpu_isa_avx512_core_fp16, + /// @copydoc dnnl_cpu_isa_avx10_1_512_amx + avx10_1_512_amx = dnnl_cpu_isa_avx10_1_512_amx, + /// @copydoc dnnl_cpu_isa_avx512_core_amx + avx512_core_amx = dnnl_cpu_isa_avx512_core_amx, + /// @copydoc dnnl_cpu_isa_avx10_1_512_amx_fp16 + avx10_1_512_amx_fp16 = dnnl_cpu_isa_avx10_1_512_amx_fp16, + /// @copydoc dnnl_cpu_isa_avx512_core_amx_fp16 + avx512_core_amx_fp16 = dnnl_cpu_isa_avx512_core_amx_fp16, +}; + +/// @copydoc dnnl_set_max_cpu_isa() +inline status set_max_cpu_isa(cpu_isa isa) { + return static_cast( + dnnl_set_max_cpu_isa(static_cast(isa))); +} + +/// @copydoc dnnl_get_effective_cpu_isa() +inline cpu_isa get_effective_cpu_isa() { + return static_cast(dnnl_get_effective_cpu_isa()); +} + +/// @copydoc dnnl_cpu_isa_hints_t +enum class cpu_isa_hints { + /// @copydoc dnnl_cpu_isa_no_hints + no_hints = dnnl_cpu_isa_no_hints, + /// @copydoc dnnl_cpu_isa_prefer_ymm + prefer_ymm = dnnl_cpu_isa_prefer_ymm, +}; + +/// @copydoc dnnl_set_cpu_isa_hints() +inline status set_cpu_isa_hints(cpu_isa_hints isa_hints) { + return static_cast(dnnl_set_cpu_isa_hints( + static_cast(isa_hints))); +} + +/// @copydoc dnnl_get_cpu_isa_hints() +inline cpu_isa_hints get_cpu_isa_hints() { + return static_cast(dnnl_get_cpu_isa_hints()); +} + +/// @} dnnl_api_service + +#ifdef DNNL_EXPERIMENTAL_PROFILING +/// @addtogroup dnnl_api_profiling Profiling +/// @{ + +/// Profiling data kind. +enum class profiling_data_kind { + /// Undefined profiling data kind. + undef = dnnl_profiling_data_kind_undef, + /// Data kind to query an execution time in nanoseconds. + time = dnnl_profiling_data_kind_time, +}; + +/// Resets a profiler's state. +/// +/// @param stream Stream associated with the profiler. +inline void reset_profiling(stream &stream) { + error::wrap_c_api( + dnnl_reset_profiling(stream.get()), "could not reset profiling"); +} + +/// Returns requested profiling data. The profiling data accumulates for each +/// primitive execution. The size of the vector will be equal to the number +/// of executions since the last `dnnl::reset_profiling` call. +/// +/// The profiling data can be reset by calling #dnnl::reset_profiling. +/// +/// @note +/// It is required to wait for all submitted primitives to complete +/// using #dnnl::stream::wait prior to querying profiling data. +/// +/// @param stream Stream that was used for executing a primitive that +/// is being profiled. +/// @param data_kind Profiling data kind to query. +/// +/// @returns A vector with the requested profiling data. +inline std::vector get_profiling_data( + stream &stream, profiling_data_kind data_kind) { + int num_entries = 0; + error::wrap_c_api( + dnnl_query_profiling_data(stream.get(), + static_cast(data_kind), + &num_entries, nullptr), + "could not get number of entries for profiling data"); + + if (num_entries == 0) return {}; + + std::vector data(num_entries); + error::wrap_c_api( + dnnl_query_profiling_data(stream.get(), + static_cast(data_kind), + &num_entries, data.data()), + "could not get profiling data"); + return data; +} + +/// @} dnnl_api_profiling +#endif + +/// @addtogroup dnnl_api_primitive_cache Primitive Cache +/// +/// A set of functions that provide primitive cache control. +/// +/// @{ + +/// Returns the number of primitives that can be held in the primitive cache +/// at the same time. +inline int get_primitive_cache_capacity() { + int result = 0; + error::wrap_c_api(dnnl_get_primitive_cache_capacity(&result), + "could not get primitive cache capacity"); + return result; +} + +/// @copydoc dnnl_set_primitive_cache_capacity(int capacity) +inline void set_primitive_cache_capacity(int capacity) { + error::wrap_c_api(dnnl_set_primitive_cache_capacity(capacity), + "could not set primitive cache capacity"); +} + +/// @} dnnl_api_primitive_cache + +/// @addtogroup dnnl_api_blas BLAS functions +/// +/// A subset of Basic Linear Algebra (BLAS) functions that perform +/// matrix-matrix multiplication. +/// +/// @{ + +/// @copydoc dnnl_sgemm() +inline status sgemm(char transa, char transb, dnnl_dim_t M, dnnl_dim_t N, + dnnl_dim_t K, float alpha, const float *A, dnnl_dim_t lda, + const float *B, dnnl_dim_t ldb, float beta, float *C, dnnl_dim_t ldc) { + return static_cast(dnnl_sgemm( + transa, transb, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc)); +} + +/// @copydoc dnnl_gemm_u8s8s32() +inline status gemm_u8s8s32(char transa, char transb, char offsetc, dnnl_dim_t M, + dnnl_dim_t N, dnnl_dim_t K, float alpha, const uint8_t *A, + dnnl_dim_t lda, uint8_t ao, const int8_t *B, dnnl_dim_t ldb, int8_t bo, + float beta, int32_t *C, dnnl_dim_t ldc, const int32_t *co) { + return static_cast(dnnl_gemm_u8s8s32(transa, transb, offsetc, M, N, + K, alpha, A, lda, ao, B, ldb, bo, beta, C, ldc, co)); +} + +/// @copydoc dnnl_gemm_s8s8s32() +inline status gemm_s8s8s32(char transa, char transb, char offsetc, dnnl_dim_t M, + dnnl_dim_t N, dnnl_dim_t K, float alpha, const int8_t *A, + dnnl_dim_t lda, int8_t ao, const int8_t *B, dnnl_dim_t ldb, int8_t bo, + float beta, int32_t *C, dnnl_dim_t ldc, const int32_t *co) { + return static_cast(dnnl_gemm_s8s8s32(transa, transb, offsetc, M, N, + K, alpha, A, lda, ao, B, ldb, bo, beta, C, ldc, co)); +} + +/// @} dnnl_api_blas + +// implementation section + +/// @cond DO_NOT_DOCUMENT_THIS +inline primitive::primitive(const_dnnl_primitive_desc_t c_pd) { + dnnl_primitive_t result; + error::wrap_c_api(dnnl_primitive_create(&result, c_pd), + "could not create a primitive"); + reset(result); +} + +inline primitive::primitive(const_dnnl_primitive_desc_t c_pd, + const std::vector &cache_blob) { + dnnl_primitive_t result; + size_t size = cache_blob.size(); + const uint8_t *cache_blob_data = cache_blob.data(); + error::wrap_c_api(dnnl_primitive_create_from_cache_blob( + &result, c_pd, size, cache_blob_data), + "could not create a primitive from a cache blob"); + reset(result); +} + +inline primitive::primitive(const primitive_desc &pd) : primitive(pd.get()) {} +inline primitive::primitive( + const primitive_desc &pd, const std::vector &cache_blob) + : primitive(pd.get(), cache_blob) {} + +inline void primitive::execute(const stream &astream, + const std::unordered_map &args) const { + std::vector c_args; + c_args.reserve(args.size()); + for (const auto &a : args) + c_args.push_back({a.first, a.second.get(true)}); + + error::wrap_c_api(dnnl_primitive_execute(get(), astream.get(), + (int)c_args.size(), c_args.data()), + "could not execute a primitive"); +} + +/// @endcond + +#undef DNNL_DEFINE_BITMASK_OPS + +} // namespace dnnl + +/// oneAPI namespace + +/// The oneAPI namespace. +/// Contains the oneapi::dnnl namespace as an alias to the ::dnnl namespace. +namespace oneapi { +// Note: without this guard, doxygen warns of potentially recursive namespace +#ifndef DOXYGEN_SHOULD_SKIP_THIS +/// oneDNN alias namespace +namespace dnnl = ::dnnl; +#endif +} // namespace oneapi + +/// @} dnnl_api + +#endif /* ONEAPI_DNNL_DNNL_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common.h new file mode 100644 index 0000000000000000000000000000000000000000..ff58a578cad363e337bea8909aa08303dec8c2d7 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common.h @@ -0,0 +1,175 @@ +/******************************************************************************* +* Copyright 2022-2023 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C common API + +#ifndef ONEAPI_DNNL_DNNL_COMMON_H +#define ONEAPI_DNNL_DNNL_COMMON_H + +#include "oneapi/dnnl/dnnl_common_types.h" +#include "oneapi/dnnl/dnnl_config.h" +#include "oneapi/dnnl/dnnl_version.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api oneDNN API +/// @{ + +/// @addtogroup dnnl_api_common Common API +/// @{ + +/// @addtogroup dnnl_api_engine Engine +/// @{ + +/// Returns the number of engines of a particular kind. +/// +/// @param kind Kind of engines to count. +/// @returns Count of the engines. +size_t DNNL_API dnnl_engine_get_count(dnnl_engine_kind_t kind); + +/// Creates an engine. +/// +/// @param engine Output engine. +/// @param kind Engine kind. +/// @param index Engine index that should be between 0 and the count of +/// engines of the requested kind. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_engine_create( + dnnl_engine_t *engine, dnnl_engine_kind_t kind, size_t index); + +/// Returns the kind of an engine. +/// +/// @param engine Engine to query. +/// @param kind Output engine kind. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_engine_get_kind( + dnnl_engine_t engine, dnnl_engine_kind_t *kind); + +/// Destroys an engine. +/// +/// @param engine Engine to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_engine_destroy(dnnl_engine_t engine); + +/// @} dnnl_api_engine + +/// @addtogroup dnnl_api_stream Stream +/// @{ + +/// Creates an execution stream. +/// +/// @param stream Output execution stream. +/// @param engine Engine to create the execution stream on. +/// @param flags Stream behavior flags (@sa dnnl_stream_flags_t). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_stream_create( + dnnl_stream_t *stream, dnnl_engine_t engine, unsigned flags); + +/// Returns the engine of a stream object. +/// +/// @param stream Stream object. +/// @param engine Output engine on which the stream is created. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_stream_get_engine( + const_dnnl_stream_t stream, dnnl_engine_t *engine); + +/// Waits for all primitives in the execution stream to finish computations. +/// +/// @param stream Execution stream. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_stream_wait(dnnl_stream_t stream); + +/// Destroys an execution stream. +/// +/// @param stream Execution stream to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_stream_destroy(dnnl_stream_t stream); + +/// @} dnnl_api_stream + +/// @addtogroup dnnl_api_fpmath_mode Floating-point Math Mode +/// @{ + +/// Returns the floating-point math mode that will be used by default +/// for all subsequently created primitives. +/// +/// @param mode Output FP math mode. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_get_default_fpmath_mode(dnnl_fpmath_mode_t *mode); + +/// Sets the floating-point math mode that will be used by default +/// for all subsequently created primitives. +/// +/// @param mode FP math mode. The possible values are: +/// #dnnl_fpmath_mode_strict, +/// #dnnl_fpmath_mode_bf16, +/// #dnnl_fpmath_mode_f16, +/// #dnnl_fpmath_mode_tf32, +/// #dnnl_fpmath_mode_any. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_set_default_fpmath_mode(dnnl_fpmath_mode_t mode); + +/// @} dnnl_api_fpmath_mode + +/// @addtogroup dnnl_api_service +/// @{ + +/// Configures verbose output to stdout. +/// +/// @note +/// Enabling verbose output affects performance. +/// This setting overrides the ONEDNN_VERBOSE environment variable. +/// +/// @param level Verbosity level: +/// - 0: no verbose output (default), +/// - 1: primitive and graph information at execution, +/// - 2: primitive and graph information at creation/compilation and execution. +/// @returns #dnnl_invalid_arguments/#dnnl::status::invalid_arguments if the +/// @p level value is invalid, and #dnnl_success/#dnnl::status::success on +/// success. +dnnl_status_t DNNL_API dnnl_set_verbose(int level); + +/// Returns library version information. +/// @returns Pointer to a constant structure containing +/// - major: major version number, +/// - minor: minor version number, +/// - patch: patch release number, +/// - hash: git commit hash. +const dnnl_version_t DNNL_API *dnnl_version(void); + +/// @} dnnl_api_service + +/// @} dnnl_api_common + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif /* ONEAPI_DNNL_DNNL_COMMON_H */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common.hpp new file mode 100644 index 0000000000000000000000000000000000000000..562f2d4aaa3ba398f5f63b3b627f5a5778b45ef2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common.hpp @@ -0,0 +1,479 @@ +/******************************************************************************* +* Copyright 2022-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C++ common API + +#ifndef ONEAPI_DNNL_DNNL_COMMON_HPP +#define ONEAPI_DNNL_DNNL_COMMON_HPP + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include +#include +#include +#include +#include +#include + +#include "oneapi/dnnl/dnnl_common.h" + +/// @endcond + +// __cpp_exceptions is referred from +// https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_exceptions.html +// gcc < 5 does not define __cpp_exceptions but __EXCEPTIONS, +// Microsoft C++ Compiler does not provide an option to disable exceptions +#ifndef DNNL_ENABLE_EXCEPTIONS +#if __cpp_exceptions || __EXCEPTIONS \ + || (defined(_MSC_VER) && !defined(__clang__)) +#define DNNL_ENABLE_EXCEPTIONS 1 +#else +#define DNNL_ENABLE_EXCEPTIONS 0 +#endif +#endif + +#if defined(__GNUC__) || defined(__clang__) +#define DNNL_TRAP() __builtin_trap() +#elif defined(__INTEL_COMPILER) || defined(_MSC_VER) +#define DNNL_TRAP() __debugbreak() +#else +#error "unknown compiler" +#endif + +#if DNNL_ENABLE_EXCEPTIONS +#define DNNL_THROW_ERROR(status, msg) throw error(status, msg) +#else +#include +#define DNNL_THROW_ERROR(status, msg) \ + do { \ + fputs(msg, stderr); \ + DNNL_TRAP(); \ + } while (0) +#endif + +/// @addtogroup dnnl_api oneDNN API +/// @{ + +/// oneDNN namespace +namespace dnnl { + +/// @addtogroup dnnl_api_common Common API +/// @{ + +/// @addtogroup dnnl_api_utils Utilities +/// Utility types and definitions. +/// @{ + +/// oneDNN exception class. +/// +/// This class captures the status returned by a failed C API function and +/// the error message from the call site. +struct error : public std::exception { + dnnl_status_t status; + const char *message; + + /// Constructs an instance of an exception class. + /// + /// @param status The error status returned by a C API function. + /// @param message The error message. + error(dnnl_status_t status, const char *message) + : status(status), message(message) {} + + /// Returns the explanatory string. + const char *what() const noexcept override { return message; } + + /// A convenience function for wrapping calls to C API functions. Checks + /// the return status and throws an dnnl::error in case of failure. + /// + /// @param status The error status returned by a C API function. + /// @param message The error message. + static void wrap_c_api(dnnl_status_t status, const char *message) { + if (status != dnnl_success) DNNL_THROW_ERROR(status, message); + } +}; + +/// A class that provides the destructor for a oneDNN C API handle. +template +struct handle_traits {}; + +/// oneDNN C API handle wrapper class. +/// +/// This class is used as the base class for primitive (dnnl::primitive), +/// engine (dnnl::engine), and stream (dnnl::stream) classes, as well as +/// others. An object of the dnnl::handle class can be passed by value. +/// +/// A handle can be weak, in which case it follows std::weak_ptr semantics. +/// Otherwise, it follows `std::shared_ptr` semantics. +/// +/// @note +/// The implementation stores oneDNN C API handles in a `std::shared_ptr` +/// with deleter set to a dummy function in the weak mode. +/// +template > +struct handle { +private: + static dnnl_status_t dummy_destructor(T) { return dnnl_success; } + std::shared_ptr::type> data_ {0}; + +protected: + bool operator==(const T other) const { return other == data_.get(); } + bool operator!=(const T other) const { return !(*this == other); } + +public: + /// Constructs an empty handle object. + /// + /// @warning + /// Uninitialized object cannot be used in most library calls and is + /// equivalent to a null pointer. Any attempt to use its methods, or + /// passing it to the other library function, will cause an exception + /// to be thrown. + handle() = default; + + /// Copy constructor. + handle(const handle &) = default; + /// Assignment operator. + handle &operator=(const handle &) = default; + /// Move constructor. + handle(handle &&) = default; + /// Move assignment operator. + handle &operator=(handle &&) = default; + + /// Constructs a handle wrapper object from a C API handle. + /// + /// @param t The C API handle to wrap. + /// @param weak A flag specifying whether to construct a weak wrapper; + /// defaults to @c false. + explicit handle(T t, bool weak = false) { reset(t, weak); } + + /// Resets the handle wrapper objects to wrap a new C API handle. + /// + /// @param t The new value of the C API handle. + /// @param weak A flag specifying whether the wrapper should be weak; + /// defaults to @c false. + void reset(T t, bool weak = false) { + data_.reset(t, weak ? &dummy_destructor : traits::destructor); + } + + /// Returns the underlying C API handle. + /// + /// @param allow_empty A flag signifying whether the method is allowed to + /// return an empty (null) object without throwing an exception. + /// @returns The underlying C API handle. + T get(bool allow_empty = false) const { + T result = data_.get(); + if (allow_empty == false && result == nullptr) + DNNL_THROW_ERROR( + dnnl_invalid_arguments, "object is not initialized"); + return result; + } + + /// Converts a handle to the underlying C API handle type. Does not throw + /// and returns `nullptr` if the object is empty. + /// + /// @returns The underlying C API handle. + explicit operator T() const { return get(true); } + + /// Checks whether the object is not empty. + /// + /// @returns Whether the object is not empty. + explicit operator bool() const { return get(true) != nullptr; } + + /// Equality operator. + /// + /// @param other Another handle wrapper. + /// @returns @c true if this and the other handle wrapper manage the same + /// underlying C API handle, and @c false otherwise. Empty handle + /// objects are considered to be equal. + bool operator==(const handle &other) const { + return other.data_.get() == data_.get(); + } + + /// Inequality operator. + /// + /// @param other Another handle wrapper. + /// @returns @c true if this and the other handle wrapper manage different + /// underlying C API handles, and @c false otherwise. Empty handle + /// objects are considered to be equal. + bool operator!=(const handle &other) const { return !(*this == other); } +}; + +/// @} dnnl_api_utils + +/// @addtogroup dnnl_api_engine Engine +/// +/// An abstraction of a computational device: a CPU, a specific GPU +/// card in the system, etc. Most primitives are created to execute +/// computations on one specific engine. The only exceptions are reorder +/// primitives that transfer data between two different engines. +/// +/// @sa @ref dev_guide_basic_concepts +/// +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_engine_t p) { + return dnnl_engine_destroy(p); + } +}; +/// @endcond + +/// An execution engine. +struct engine : public handle { + friend struct primitive; + friend struct reorder; + + /// Kinds of engines. + enum class kind { + /// An unspecified engine + any = dnnl_any_engine, + /// CPU engine + cpu = dnnl_cpu, + /// GPU engine + gpu = dnnl_gpu, + }; + + using handle::handle; + + /// Constructs an empty engine. An empty engine cannot be used in any + /// operations. + engine() = default; + + /// Returns the number of engines of a certain kind. + /// + /// @param akind The kind of engines to count. + /// @returns The number of engines of the specified kind. + static size_t get_count(kind akind) { + return dnnl_engine_get_count(convert_to_c(akind)); + } + + /// Constructs an engine. + /// + /// @param akind The kind of engine to construct. + /// @param index The index of the engine. Must be less than the value + /// returned by #get_count() for this particular kind of engine. + engine(kind akind, size_t index) { + dnnl_engine_t engine; + error::wrap_c_api( + dnnl_engine_create(&engine, convert_to_c(akind), index), + "could not create an engine"); + reset(engine); + } + + /// Returns the kind of the engine. + /// @returns The kind of the engine. + kind get_kind() const { + dnnl_engine_kind_t kind; + error::wrap_c_api(dnnl_engine_get_kind(get(), &kind), + "could not get kind of an engine"); + return static_cast(kind); + } + +private: + static dnnl_engine_kind_t convert_to_c(kind akind) { + return static_cast(akind); + } +}; + +/// Converts engine kind enum value from C++ API to C API type. +/// +/// @param akind C++ API engine kind enum value. +/// @returns Corresponding C API engine kind enum value. +inline dnnl_engine_kind_t convert_to_c(engine::kind akind) { + return static_cast(akind); +} + +/// @} dnnl_api_engine + +/// @addtogroup dnnl_api_stream Stream +/// +/// An encapsulation of execution context tied to a particular engine. +/// +/// @sa @ref dev_guide_basic_concepts +/// +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_stream_t p) { + return dnnl_stream_destroy(p); + } +}; +/// @endcond + +/// An execution stream. +struct stream : public handle { + using handle::handle; + + /// Stream flags. Can be combined using the bitwise OR operator. + enum class flags : unsigned { + /// In-order execution. + in_order = dnnl_stream_in_order, + /// Out-of-order execution. + out_of_order = dnnl_stream_out_of_order, + /// Default stream configuration. + default_flags = dnnl_stream_default_flags, +#ifdef DNNL_EXPERIMENTAL_PROFILING + /// Enables profiling capabilities. + profiling = dnnl_stream_profiling, +#endif + }; + + /// Constructs an empty stream. An empty stream cannot be used in any + /// operations. + stream() = default; + + /// Constructs a stream for the specified engine and with behavior + /// controlled by the specified flags. + /// + /// @param aengine Engine to create the stream on. + /// @param aflags Flags controlling stream behavior. + explicit stream( + const engine &aengine, flags aflags = flags::default_flags) { + dnnl_stream_t stream; + error::wrap_c_api(dnnl_stream_create(&stream, aengine.get(), + static_cast(aflags)), + "could not create a stream"); + reset(stream); + } + + /// Returns the associated engine. + engine get_engine() const { + dnnl_engine_t c_engine; + error::wrap_c_api(dnnl_stream_get_engine(get(), &c_engine), + "could not get an engine from a stream object"); + return engine(c_engine, true); + } + + /// Waits for all primitives executing in the stream to finish. + /// @returns The stream itself. + stream &wait() { + error::wrap_c_api( + dnnl_stream_wait(get()), "could not wait on a stream"); + return *this; + } +}; + +#define DNNL_DEFINE_BITMASK_OPS(enum_name) \ + inline enum_name operator|(enum_name lhs, enum_name rhs) { \ + return static_cast( \ + static_cast(lhs) | static_cast(rhs)); \ + } \ +\ + inline enum_name operator&(enum_name lhs, enum_name rhs) { \ + return static_cast( \ + static_cast(lhs) & static_cast(rhs)); \ + } \ +\ + inline enum_name operator^(enum_name lhs, enum_name rhs) { \ + return static_cast( \ + static_cast(lhs) ^ static_cast(rhs)); \ + } \ +\ + inline enum_name &operator|=(enum_name &lhs, enum_name rhs) { \ + lhs = static_cast( \ + static_cast(lhs) | static_cast(rhs)); \ + return lhs; \ + } \ +\ + inline enum_name &operator&=(enum_name &lhs, enum_name rhs) { \ + lhs = static_cast( \ + static_cast(lhs) & static_cast(rhs)); \ + return lhs; \ + } \ +\ + inline enum_name &operator^=(enum_name &lhs, enum_name rhs) { \ + lhs = static_cast( \ + static_cast(lhs) ^ static_cast(rhs)); \ + return lhs; \ + } \ +\ + inline enum_name operator~(enum_name rhs) { \ + return static_cast(~static_cast(rhs)); \ + } + +DNNL_DEFINE_BITMASK_OPS(stream::flags) + +/// @} dnnl_api_stream + +/// @addtogroup dnnl_api_fpmath_mode Floating-point Math Mode +/// @{ + +/// Floating-point math mode +enum class fpmath_mode { + /// Default behavior, no downconversions allowed + strict = dnnl_fpmath_mode_strict, + /// Implicit f32->bf16 conversions allowed + bf16 = dnnl_fpmath_mode_bf16, + /// Implicit f32->f16 conversions allowed + f16 = dnnl_fpmath_mode_f16, + /// Implicit f32->tf32 conversions allowed + tf32 = dnnl_fpmath_mode_tf32, + /// Implicit f32->f16, f32->tf32 or f32->bf16 conversions allowed + any = dnnl_fpmath_mode_any +}; + +/// Converts an fpmath mode enum value from C++ API to C API type. +/// +/// @param mode C++ API fpmath mode enum value. +/// @returns Corresponding C API fpmath mode enum value. +inline dnnl_fpmath_mode_t convert_to_c(fpmath_mode mode) { + return static_cast(mode); +} + +/// @} dnnl_api_fpmath_mode + +/// @addtogroup dnnl_api_accumulation_mode Accumulation Mode +/// @{ + +/// Accumulation mode +enum class accumulation_mode { + /// Default behavior, f32 for floating point computation, s32 for integer + strict = dnnl_accumulation_mode_strict, + /// same as strict except some partial accumulators can be rounded to + /// src/dst datatype in memory. + relaxed = dnnl_accumulation_mode_relaxed, + /// uses fastest implementation, could use src/dst datatype or + /// wider datatype for accumulators + any = dnnl_accumulation_mode_any, + /// use s32 accumulators during computation + s32 = dnnl_accumulation_mode_s32, + /// use f32 accumulators during computation + f32 = dnnl_accumulation_mode_f32, + /// use f16 accumulators during computation + f16 = dnnl_accumulation_mode_f16 +}; + +/// Converts an accumulation mode enum value from C++ API to C API type. +/// +/// @param mode C++ API accumulation mode enum value. +/// @returns Corresponding C API accumulation mode enum value. +inline dnnl_accumulation_mode_t convert_to_c(accumulation_mode mode) { + return static_cast(mode); +} + +/// @} dnnl_api_accumulation_mode + +/// @} dnnl_api_common + +} // namespace dnnl + +/// @} dnnl_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common_types.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common_types.h new file mode 100644 index 0000000000000000000000000000000000000000..1551f78038abd4050d5dd0c213df64cf71a6bd16 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_common_types.h @@ -0,0 +1,257 @@ +/******************************************************************************* +* Copyright 2022-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C API common types definitions + +#ifndef ONEAPI_DNNL_DNNL_COMMON_TYPES_H +#define ONEAPI_DNNL_DNNL_COMMON_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include + +#include "oneapi/dnnl/dnnl_config.h" + +/// @endcond + +/// @addtogroup dnnl_api oneDNN API +/// @{ + +/// @addtogroup dnnl_api_common Common API +/// @{ + +/// @addtogroup dnnl_api_utils +/// @{ + +/// Status values returned by the library functions. +typedef enum { + /// The operation was successful + dnnl_success = 0, + /// The operation failed due to an out-of-memory condition + dnnl_out_of_memory = 1, + /// The operation failed because of incorrect function arguments + dnnl_invalid_arguments = 2, + /// The operation failed because requested functionality is not implemented + dnnl_unimplemented = 3, + /// The last available implementation is reached + dnnl_last_impl_reached = 4, + /// Primitive or engine failed on execution + dnnl_runtime_error = 5, + /// Queried element is not required for given primitive + dnnl_not_required = 6, + /// The graph is not legitimate + dnnl_invalid_graph = 7, + /// The operation is not legitimate according to op schema + dnnl_invalid_graph_op = 8, + /// The shape cannot be inferred or compiled + dnnl_invalid_shape = 9, + /// The data type cannot be inferred or compiled + dnnl_invalid_data_type = 10, +} dnnl_status_t; + +/// @} dnnl_api_utils + +/// @addtogroup dnnl_api_data_types Data types +/// @{ + +/// Data type specification +typedef enum { + /// Undefined data type, used for empty memory descriptors. + dnnl_data_type_undef = 0, + /// 16-bit/half-precision floating point. + dnnl_f16 = 1, + /// non-standard 16-bit (bfloat16 w/ 7 bit mantissa) floating point. + dnnl_bf16 = 2, + /// 32-bit/single-precision floating point. + dnnl_f32 = 3, + /// 32-bit signed integer. + dnnl_s32 = 4, + /// 8-bit signed integer. + dnnl_s8 = 5, + /// 8-bit unsigned integer. + dnnl_u8 = 6, + /// 64-bit/double-precision floating point. + dnnl_f64 = 7, + /// Boolean data type. Size is C++ implementation defined. + dnnl_boolean = 8, + /// [OFP8 standard 8-bit floating-point](https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-06-20-pdf) + /// with a 5-bit exponent and a 2-bit mantissa. + dnnl_f8_e5m2 = 9, + /// [OFP8 standard 8-bit floating-point](https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-06-20-pdf) + /// with a 4-bit exponent and a 3-bit mantissa. + dnnl_f8_e4m3 = 10, + /// 4-bit signed integer. + dnnl_s4 = 11, + /// 4-bit unsigned integer. + dnnl_u4 = 12, + + /// Parameter to allow internal only data_types without undefined behavior. + /// This parameter is chosen to be valid for so long as sizeof(int) >= 2. + dnnl_data_type_max = 0x7fff, +} dnnl_data_type_t; + +/// Maximum number of dimensions a tensor can have. Only restricts the amount +/// of space used for the tensor description. Individual computational +/// primitives may support only tensors of certain dimensions. +#define DNNL_MAX_NDIMS 12 + +/// A type to describe tensor dimension. +typedef int64_t dnnl_dim_t; + +/// A type to describe tensor dimensions. +typedef dnnl_dim_t dnnl_dims_t[DNNL_MAX_NDIMS]; + +/// @} dnnl_api_data_types + +/// @addtogroup dnnl_api_fpmath_mode Floating-point Math Mode +/// @{ + +/// Floating-point math mode +typedef enum { + /// Default behavior, no downconversions allowed + dnnl_fpmath_mode_strict, + /// Implicit f32->bf16 conversions allowed + dnnl_fpmath_mode_bf16, + /// Implicit f32->f16 conversions allowed + dnnl_fpmath_mode_f16, + /// Implicit f32->f16, f32->tf32 or f32->bf16 conversions allowed + dnnl_fpmath_mode_any, + /// Implicit f32->tf32 conversions allowed + dnnl_fpmath_mode_tf32, +} dnnl_fpmath_mode_t; + +/// @} dnnl_api_fpmath_mode + +/// @addtogroup dnnl_api_accumulation_mode Accumulation Mode +/// @{ + +/// Accumulation mode +typedef enum { + /// Default behavior, f32/f64 for floating point computation, s32 + /// for integer + dnnl_accumulation_mode_strict, + /// Same as strict but allows some partial accumulators to be + /// rounded to src/dst datatype in memory. + dnnl_accumulation_mode_relaxed, + /// uses fastest implementation, could use src/dst datatype or + /// wider datatype for accumulators + dnnl_accumulation_mode_any, + /// use s32 accumulators during computation + dnnl_accumulation_mode_s32, + /// use f32 accumulators during computation + dnnl_accumulation_mode_f32, + /// use f16 accumulators during computation + dnnl_accumulation_mode_f16 +} dnnl_accumulation_mode_t; + +/// @} dnnl_api_accumulation_mode + +/// @addtogroup dnnl_api_engine Engine +/// @{ + +/// @brief Kinds of engines. +typedef enum { + /// An unspecified engine. + dnnl_any_engine, + /// CPU engine. + dnnl_cpu, + /// GPU engine. + dnnl_gpu, +} dnnl_engine_kind_t; + +/// @struct dnnl_engine +/// @brief An opaque structure to describe an engine. +struct dnnl_engine; +/// @brief An engine handle. +typedef struct dnnl_engine *dnnl_engine_t; +#if 0 +// FIXME: looks like this never happens +/// @brief A constant engine handle. +typedef const struct dnnl_engine *const_dnnl_engine_t; +#endif + +/// @} dnnl_api_engine + +/// @addtogroup dnnl_api_stream Stream +/// @{ + +/// @brief Stream flags. +typedef enum { + // In-order execution. + dnnl_stream_in_order = 0x1U, + /// Out-of-order execution. + dnnl_stream_out_of_order = 0x2U, + /// Default stream configuration. + dnnl_stream_default_flags = dnnl_stream_in_order, +#ifdef DNNL_EXPERIMENTAL_PROFILING + /// Enables profiling capabilities. + dnnl_stream_profiling = 0x4U, +#endif +} dnnl_stream_flags_t; + +/// @struct dnnl_stream +/// An opaque structure to describe an execution stream. +struct dnnl_stream; +/// An execution stream handle. +typedef struct dnnl_stream *dnnl_stream_t; +/// A constant execution stream handle. +typedef const struct dnnl_stream *const_dnnl_stream_t; + +/// @} dnnl_api_stream + +/// @addtogroup dnnl_api_service +/// @{ + +/// Structure containing version information as per [Semantic +/// Versioning](https://semver.org) +typedef struct { + int major; ///< Major version + int minor; ///< Minor version + int patch; ///< Patch version + const char *hash; ///< Git hash of the sources (may be absent) + unsigned cpu_runtime; ///< CPU runtime + unsigned gpu_runtime; ///< GPU runtime +} dnnl_version_t; + +/// @} dnnl_api_service + +/// @addtogroup dnnl_api_memory +/// @{ + +/// Special pointer value that indicates that a memory object should not have +/// an underlying buffer. +#define DNNL_MEMORY_NONE (NULL) + +/// Special pointer value that indicates that the library needs to allocate an +/// underlying buffer for a memory object. +#define DNNL_MEMORY_ALLOCATE ((void *)(size_t)-1) + +/// @} dnnl_api_memory + +/// @} dnnl_api_common + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_config.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_config.h new file mode 100644 index 0000000000000000000000000000000000000000..9e3cfca11cd8c5d1efa81008f051955d33ca21de --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_config.h @@ -0,0 +1,204 @@ +/******************************************************************************* +* Copyright 2019-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_CONFIG_H +#define ONEAPI_DNNL_DNNL_CONFIG_H + +/// @cond DO_NOT_DOCUMENT_THIS + +// All symbols shall be internal unless marked as DNNL_API +#if defined _WIN32 || defined __CYGWIN__ +#define DNNL_HELPER_DLL_IMPORT __declspec(dllimport) +#define DNNL_HELPER_DLL_EXPORT __declspec(dllexport) +#else +#if __GNUC__ >= 4 +#define DNNL_HELPER_DLL_IMPORT __attribute__((visibility("default"))) +#define DNNL_HELPER_DLL_EXPORT __attribute__((visibility("default"))) +#else +#define DNNL_HELPER_DLL_IMPORT +#define DNNL_HELPER_DLL_EXPORT +#endif +#endif + +#ifdef DNNL_DLL +#ifdef DNNL_DLL_EXPORTS +#define DNNL_API DNNL_HELPER_DLL_EXPORT +#else +#define DNNL_API DNNL_HELPER_DLL_IMPORT +#endif +#else +#define DNNL_API +#endif + +#if defined(__GNUC__) +#define DNNL_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define DNNL_DEPRECATED __declspec(deprecated) +#else +#define DNNL_DEPRECATED +#endif + +/// @endcond + +// clang-format off + +/// @addtogroup dnnl_api_service +/// @{ + +/// No runtime (disabled) +#define DNNL_RUNTIME_NONE 0u + +/// Sequential runtime (CPU only) +#define DNNL_RUNTIME_SEQ 1u + +/// OpenMP runtime (CPU only) +#define DNNL_RUNTIME_OMP 2u + +/// TBB runtime (CPU only) +#define DNNL_RUNTIME_TBB 4u + +/// Threadpool runtime (CPU only) +#define DNNL_RUNTIME_THREADPOOL 8u + +/// OpenCL runtime +#define DNNL_RUNTIME_OCL 256u + +/// SYCL runtime +#define DNNL_RUNTIME_SYCL 512u + +/// DPC++ runtime +#define DNNL_RUNTIME_DPCPP DNNL_RUNTIME_SYCL + +/// @} dnnl_api_service + +// oneDNN CPU threading runtime +#define DNNL_CPU_THREADING_RUNTIME DNNL_RUNTIME_THREADPOOL + +// oneDNN CPU engine runtime +#define DNNL_CPU_RUNTIME DNNL_RUNTIME_THREADPOOL + +// oneDNN GPU engine runtime +#define DNNL_GPU_RUNTIME DNNL_RUNTIME_NONE + +// clang-format on + +#if defined(DNNL_CPU_RUNTIME) && defined(DNNL_GPU_RUNTIME) +#if (DNNL_CPU_RUNTIME == DNNL_RUNTIME_OCL) +#error "Unexpected DNNL_CPU_RUNTIME" +#endif +#if (DNNL_GPU_RUNTIME != DNNL_RUNTIME_NONE) \ + && (DNNL_GPU_RUNTIME != DNNL_RUNTIME_OCL) \ + && (DNNL_GPU_RUNTIME != DNNL_RUNTIME_SYCL) +#error "Unexpected DNNL_GPU_RUNTIME" +#endif +#if (DNNL_CPU_RUNTIME == DNNL_RUNTIME_NONE \ + && DNNL_GPU_RUNTIME == DNNL_RUNTIME_NONE) +#error "At least one runtime must be specified" +#endif +#else +#error "BOTH DNNL_CPU_RUNTIME and DNNL_GPU_RUNTIME must be defined" +#endif + +// For SYCL CPU, a primitive may be created and executed in different threads +// hence the global scratchpad does not work. This enables concurrent execution +// when CPU runtime is SYCL to avoid the issue. +#if DNNL_CPU_RUNTIME == DNNL_RUNTIME_SYCL +#ifndef DNNL_ENABLE_CONCURRENT_EXEC +#define DNNL_ENABLE_CONCURRENT_EXEC +#endif +#endif + +// When defined, primitive cache stores runtime objects. +#undef DNNL_USE_RT_OBJECTS_IN_PRIMITIVE_CACHE + +// When defined, DPCPP is supported. +#undef DNNL_WITH_SYCL + +// When defined, Level Zero is supported. +#undef DNNL_WITH_LEVEL_ZERO + +// When defined, SYCL CUDA backend is used. +#undef DNNL_SYCL_CUDA + +// When defined, SYCL HIP backend is used. +#undef DNNL_SYCL_HIP + +// When defined, stack checker is enabled. +#undef DNNL_ENABLE_STACK_CHECKER + +// When defined, experimental features are enabled. +#undef DNNL_EXPERIMENTAL + +// When defined, experimental functionality for sparse domain is enabled. +#define DNNL_EXPERIMENTAL_SPARSE + +// When defined, experimental functionality for ukernels is enabled. +#undef DNNL_EXPERIMENTAL_UKERNEL + +// When defined, graph component is enabled. +#define ONEDNN_BUILD_GRAPH + +// When defined, experimental profiling capabilities are enabled. +#undef DNNL_EXPERIMENTAL_PROFILING + +// List of configurating build controls +// Workload controls +#define BUILD_TRAINING 1 +#define BUILD_INFERENCE 0 +// Primitive controls +#define BUILD_PRIMITIVE_ALL 1 +#define BUILD_BATCH_NORMALIZATION 0 +#define BUILD_BINARY 0 +#define BUILD_CONCAT 0 +#define BUILD_CONVOLUTION 0 +#define BUILD_DECONVOLUTION 0 +#define BUILD_ELTWISE 0 +#define BUILD_GROUP_NORMALIZATION 1 +#define BUILD_INNER_PRODUCT 0 +#define BUILD_LAYER_NORMALIZATION 0 +#define BUILD_LRN 0 +#define BUILD_MATMUL 0 +#define BUILD_POOLING 0 +#define BUILD_PRELU 0 +#define BUILD_REDUCTION 0 +#define BUILD_REORDER 0 +#define BUILD_RESAMPLING 0 +#define BUILD_RNN 0 +#define BUILD_SHUFFLE 0 +#define BUILD_SOFTMAX 0 +#define BUILD_SUM 0 +// Primitives CPU ISA controls +#define BUILD_PRIMITIVE_CPU_ISA_ALL 1 +#define BUILD_SSE41 0 +#define BUILD_AVX2 0 +#define BUILD_AVX512 0 +#define BUILD_AMX 0 +// Primitives GPU ISA controls +#define BUILD_PRIMITIVE_GPU_ISA_ALL 0 +#define BUILD_GEN9 0 +#define BUILD_GEN11 0 +#define BUILD_XELP 0 +#define BUILD_XEHP 0 +#define BUILD_XEHPG 0 +#define BUILD_XEHPC 0 +#define BUILD_XE2 0 +// GeMM kernels ISA controls +#define BUILD_GEMM_KERNELS_ALL 1 +#define BUILD_GEMM_KERNELS_NONE 0 +#define BUILD_GEMM_SSE41 1 +#define BUILD_GEMM_AVX2 1 +#define BUILD_GEMM_AVX512 1 +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_config.h.in b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_config.h.in new file mode 100644 index 0000000000000000000000000000000000000000..1699d9f78998da2d4d83109c580e9f380306ea3b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_config.h.in @@ -0,0 +1,204 @@ +/******************************************************************************* +* Copyright 2019-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_CONFIG_H +#define ONEAPI_DNNL_DNNL_CONFIG_H + +/// @cond DO_NOT_DOCUMENT_THIS + +// All symbols shall be internal unless marked as DNNL_API +#if defined _WIN32 || defined __CYGWIN__ +#define DNNL_HELPER_DLL_IMPORT __declspec(dllimport) +#define DNNL_HELPER_DLL_EXPORT __declspec(dllexport) +#else +#if __GNUC__ >= 4 +#define DNNL_HELPER_DLL_IMPORT __attribute__((visibility("default"))) +#define DNNL_HELPER_DLL_EXPORT __attribute__((visibility("default"))) +#else +#define DNNL_HELPER_DLL_IMPORT +#define DNNL_HELPER_DLL_EXPORT +#endif +#endif + +#ifdef DNNL_DLL +#ifdef DNNL_DLL_EXPORTS +#define DNNL_API DNNL_HELPER_DLL_EXPORT +#else +#define DNNL_API DNNL_HELPER_DLL_IMPORT +#endif +#else +#define DNNL_API +#endif + +#if defined(__GNUC__) +#define DNNL_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define DNNL_DEPRECATED __declspec(deprecated) +#else +#define DNNL_DEPRECATED +#endif + +/// @endcond + +// clang-format off + +/// @addtogroup dnnl_api_service +/// @{ + +/// No runtime (disabled) +#define DNNL_RUNTIME_NONE 0u + +/// Sequential runtime (CPU only) +#define DNNL_RUNTIME_SEQ 1u + +/// OpenMP runtime (CPU only) +#define DNNL_RUNTIME_OMP 2u + +/// TBB runtime (CPU only) +#define DNNL_RUNTIME_TBB 4u + +/// Threadpool runtime (CPU only) +#define DNNL_RUNTIME_THREADPOOL 8u + +/// OpenCL runtime +#define DNNL_RUNTIME_OCL 256u + +/// SYCL runtime +#define DNNL_RUNTIME_SYCL 512u + +/// DPC++ runtime +#define DNNL_RUNTIME_DPCPP DNNL_RUNTIME_SYCL + +/// @} dnnl_api_service + +// oneDNN CPU threading runtime +#cmakedefine DNNL_CPU_THREADING_RUNTIME DNNL_RUNTIME_${DNNL_CPU_THREADING_RUNTIME} + +// oneDNN CPU engine runtime +#cmakedefine DNNL_CPU_RUNTIME DNNL_RUNTIME_${DNNL_CPU_RUNTIME} + +// oneDNN GPU engine runtime +#cmakedefine DNNL_GPU_RUNTIME DNNL_RUNTIME_${DNNL_GPU_RUNTIME} + +// clang-format on + +#if defined(DNNL_CPU_RUNTIME) && defined(DNNL_GPU_RUNTIME) +#if (DNNL_CPU_RUNTIME == DNNL_RUNTIME_OCL) +#error "Unexpected DNNL_CPU_RUNTIME" +#endif +#if (DNNL_GPU_RUNTIME != DNNL_RUNTIME_NONE) \ + && (DNNL_GPU_RUNTIME != DNNL_RUNTIME_OCL) \ + && (DNNL_GPU_RUNTIME != DNNL_RUNTIME_SYCL) +#error "Unexpected DNNL_GPU_RUNTIME" +#endif +#if (DNNL_CPU_RUNTIME == DNNL_RUNTIME_NONE \ + && DNNL_GPU_RUNTIME == DNNL_RUNTIME_NONE) +#error "At least one runtime must be specified" +#endif +#else +#error "BOTH DNNL_CPU_RUNTIME and DNNL_GPU_RUNTIME must be defined" +#endif + +// For SYCL CPU, a primitive may be created and executed in different threads +// hence the global scratchpad does not work. This enables concurrent execution +// when CPU runtime is SYCL to avoid the issue. +#if DNNL_CPU_RUNTIME == DNNL_RUNTIME_SYCL +#ifndef DNNL_ENABLE_CONCURRENT_EXEC +#define DNNL_ENABLE_CONCURRENT_EXEC +#endif +#endif + +// When defined, primitive cache stores runtime objects. +#cmakedefine DNNL_USE_RT_OBJECTS_IN_PRIMITIVE_CACHE + +// When defined, DPCPP is supported. +#cmakedefine DNNL_WITH_SYCL + +// When defined, Level Zero is supported. +#cmakedefine DNNL_WITH_LEVEL_ZERO + +// When defined, SYCL CUDA backend is used. +#cmakedefine DNNL_SYCL_CUDA + +// When defined, SYCL HIP backend is used. +#cmakedefine DNNL_SYCL_HIP + +// When defined, stack checker is enabled. +#cmakedefine DNNL_ENABLE_STACK_CHECKER + +// When defined, experimental features are enabled. +#cmakedefine DNNL_EXPERIMENTAL + +// When defined, experimental functionality for sparse domain is enabled. +#cmakedefine DNNL_EXPERIMENTAL_SPARSE + +// When defined, experimental functionality for ukernels is enabled. +#cmakedefine DNNL_EXPERIMENTAL_UKERNEL + +// When defined, graph component is enabled. +#cmakedefine ONEDNN_BUILD_GRAPH + +// When defined, experimental profiling capabilities are enabled. +#cmakedefine DNNL_EXPERIMENTAL_PROFILING + +// List of configurating build controls +// Workload controls +#cmakedefine01 BUILD_TRAINING +#cmakedefine01 BUILD_INFERENCE +// Primitive controls +#cmakedefine01 BUILD_PRIMITIVE_ALL +#cmakedefine01 BUILD_BATCH_NORMALIZATION +#cmakedefine01 BUILD_BINARY +#cmakedefine01 BUILD_CONCAT +#cmakedefine01 BUILD_CONVOLUTION +#cmakedefine01 BUILD_DECONVOLUTION +#cmakedefine01 BUILD_ELTWISE +#cmakedefine01 BUILD_GROUP_NORMALIZATION +#cmakedefine01 BUILD_INNER_PRODUCT +#cmakedefine01 BUILD_LAYER_NORMALIZATION +#cmakedefine01 BUILD_LRN +#cmakedefine01 BUILD_MATMUL +#cmakedefine01 BUILD_POOLING +#cmakedefine01 BUILD_PRELU +#cmakedefine01 BUILD_REDUCTION +#cmakedefine01 BUILD_REORDER +#cmakedefine01 BUILD_RESAMPLING +#cmakedefine01 BUILD_RNN +#cmakedefine01 BUILD_SHUFFLE +#cmakedefine01 BUILD_SOFTMAX +#cmakedefine01 BUILD_SUM +// Primitives CPU ISA controls +#cmakedefine01 BUILD_PRIMITIVE_CPU_ISA_ALL +#cmakedefine01 BUILD_SSE41 +#cmakedefine01 BUILD_AVX2 +#cmakedefine01 BUILD_AVX512 +#cmakedefine01 BUILD_AMX +// Primitives GPU ISA controls +#cmakedefine01 BUILD_PRIMITIVE_GPU_ISA_ALL +#cmakedefine01 BUILD_GEN9 +#cmakedefine01 BUILD_GEN11 +#cmakedefine01 BUILD_XELP +#cmakedefine01 BUILD_XEHP +#cmakedefine01 BUILD_XEHPG +#cmakedefine01 BUILD_XEHPC +#cmakedefine01 BUILD_XE2 +// GeMM kernels ISA controls +#cmakedefine01 BUILD_GEMM_KERNELS_ALL +#cmakedefine01 BUILD_GEMM_KERNELS_NONE +#cmakedefine01 BUILD_GEMM_SSE41 +#cmakedefine01 BUILD_GEMM_AVX2 +#cmakedefine01 BUILD_GEMM_AVX512 +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_debug.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_debug.h new file mode 100644 index 0000000000000000000000000000000000000000..26a3d3f8517015bce7e7cff928ad6d09fca43918 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_debug.h @@ -0,0 +1,60 @@ +/******************************************************************************* +* Copyright 2018-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +// DO NOT EDIT, AUTO-GENERATED +// Use this script to update the file: scripts/generate_dnnl_debug.py + +// clang-format off + +#ifndef ONEAPI_DNNL_DNNL_DEBUG_H +#define ONEAPI_DNNL_DNNL_DEBUG_H + +/// @file +/// Debug capabilities + +#include "oneapi/dnnl/dnnl_config.h" +#include "oneapi/dnnl/dnnl_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +const char DNNL_API *dnnl_status2str(dnnl_status_t v); +const char DNNL_API *dnnl_dt2str(dnnl_data_type_t v); +const char DNNL_API *dnnl_fpmath_mode2str(dnnl_fpmath_mode_t v); +const char DNNL_API *dnnl_accumulation_mode2str(dnnl_accumulation_mode_t v); +const char DNNL_API *dnnl_engine_kind2str(dnnl_engine_kind_t v); +#ifdef DNNL_EXPERIMENTAL_SPARSE +const char DNNL_API *dnnl_sparse_encoding2str(dnnl_sparse_encoding_t v); +#endif +const char DNNL_API *dnnl_fmt_tag2str(dnnl_format_tag_t v); +const char DNNL_API *dnnl_prop_kind2str(dnnl_prop_kind_t v); +const char DNNL_API *dnnl_prim_kind2str(dnnl_primitive_kind_t v); +const char DNNL_API *dnnl_alg_kind2str(dnnl_alg_kind_t v); +const char DNNL_API *dnnl_rnn_flags2str(dnnl_rnn_flags_t v); +const char DNNL_API *dnnl_rnn_direction2str(dnnl_rnn_direction_t v); +const char DNNL_API *dnnl_scratchpad_mode2str(dnnl_scratchpad_mode_t v); +const char DNNL_API *dnnl_cpu_isa2str(dnnl_cpu_isa_t v); +const char DNNL_API *dnnl_cpu_isa_hints2str(dnnl_cpu_isa_hints_t v); + +const char DNNL_API *dnnl_runtime2str(unsigned v); +const char DNNL_API *dnnl_fmt_kind2str(dnnl_format_kind_t v); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..a5160dea3512511392fd861a7ea98d60a27cfc72 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph.h @@ -0,0 +1,735 @@ +/******************************************************************************* +* Copyright 2020-2023 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C API + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_H +#define ONEAPI_DNNL_DNNL_GRAPH_H + +#include "oneapi/dnnl/dnnl_common.h" +#include "oneapi/dnnl/dnnl_config.h" +#include "oneapi/dnnl/dnnl_graph_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_graph_api +/// @{ + +/// @addtogroup dnnl_graph_api_allocator +/// @{ + +/// Creates a host allocator with the given allocation and deallocation +/// call-back function pointers. +/// +/// @param allocator Output allocator. +/// @param host_malloc A pointer to malloc function for host. +/// @param host_free A pointer to free function for host. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_allocator_create( + dnnl_graph_allocator_t *allocator, + dnnl_graph_host_allocate_f host_malloc, + dnnl_graph_host_deallocate_f host_free); + +/// Destroys an allocator. +/// +/// @param allocator The allocator to be destroyed. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_allocator_destroy( + dnnl_graph_allocator_t allocator); + +/// @} dnnl_graph_api_allocator + +/// @addtogroup dnnl_graph_api_engine +/// @{ + +/// This API is a supplement for existing onednn engine API. +dnnl_status_t DNNL_API dnnl_graph_make_engine_with_allocator( + dnnl_engine_t *engine, dnnl_engine_kind_t kind, size_t index, + const_dnnl_graph_allocator_t alloc); + +/// @} dnnl_graph_api_engine + +/// @addtogroup dnnl_graph_api_logical_tensor +/// @{ + +/// Initializes a logical tensor with id, data type, number of dimensions, +/// layout type, and property. The logical tensor's dims are unknown with this +/// interface. +/// +/// @param logical_tensor Output logical tensor. +/// @param tid The unique id of the output logical tensor. +/// @param dtype Elements data type. +/// @param ndims Number of dimensions. +/// @param ltype Layout type of the underlying tensor buffer. +/// @param ptype Tensor property type. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_logical_tensor_init( + dnnl_graph_logical_tensor_t *logical_tensor, size_t tid, + dnnl_data_type_t dtype, int32_t ndims, dnnl_graph_layout_type_t ltype, + dnnl_graph_tensor_property_t ptype); + +/// Initializes a logical tensor with basic information and dims. The logical +/// tensor's dimensions and layout will be initialized according to the input +/// arguments. +/// +/// @note +/// If dims contains all valid values and layout type is +/// #dnnl_graph_layout_type_strided. The strides field in +/// #dnnl_graph_logical_tensor_t will be calculated in a row major and +/// contiguous way. Otherwise, Accessing the strides field is an undefined +/// behavior. +/// +/// Eg. dims (2, 3, 4, 5) will get strides (60, 20, 5, 1) +/// +/// @param logical_tensor Output logical tensor. +/// @param tid The unique id of output logical tensor. +/// @param dtype Elements data type. +/// @param ndims Number of dimensions. +/// @param dims Array of dimensions. +/// @param ltype Layout type of the underlying tensor memory. +/// @param ptype Tensor property type. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_logical_tensor_init_with_dims( + dnnl_graph_logical_tensor_t *logical_tensor, size_t tid, + dnnl_data_type_t dtype, int32_t ndims, const dnnl_dims_t dims, + dnnl_graph_layout_type_t ltype, dnnl_graph_tensor_property_t ptype); + +/// Initializes a logical tensor with dimensions and strides provided by user. +/// +/// @note +/// Once strides are explicitly provided through the API, the `layout_type` +/// in #dnnl_graph_logical_tensor_t can only be +/// #dnnl_graph_layout_type_strided or #dnnl_graph_layout_type_any. +/// +/// @param logical_tensor Output logical tensor. +/// @param tid The unique id of output logical tensor. +/// @param dtype Elements data type. +/// @param ndims Number of dimensions. +/// @param dims Array of dimensions. +/// @param strides Array of strides. +/// @param ptype Tensor property type. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_logical_tensor_init_with_strides( + dnnl_graph_logical_tensor_t *logical_tensor, size_t tid, + dnnl_data_type_t dtype, int32_t ndims, const dnnl_dims_t dims, + const dnnl_dims_t strides, dnnl_graph_tensor_property_t ptype); + +/// Returns the memory size described by the logical tensor. If it's a strided +/// layout, the size will be calculated by `dims` and `strides`. If it's an +/// opaque layout, the size will be decided by `layout_id`. +/// +/// @param logical_tensor Logical tensor. +/// @param size Output memory size in bytes. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_logical_tensor_get_mem_size( + const dnnl_graph_logical_tensor_t *logical_tensor, size_t *size); + +/// Compares if two logical tenors are equal. Users can decide accordingly +/// if layout reordering is needed for two logical tensors. The method will +/// return true for below two circumstances: +/// +/// 1. the two logical tensors are equal regarding each field in the struct, +/// eg. id, ndims, dims, layout type, property, etc. +/// 2. If all other fields are equal but the layout types in two logical +/// tensors are different, the method will return true when the underlying +/// memory layout is the same. For example, one logical tensor has strided +/// layout type while the other one has opaque layout type, but underneath, +/// both layouts are NHWC, the method will still return true for this case. +/// +/// @param lt1 The handle of first logical tensor. +/// @param lt2 The handle of second logical tensor. +/// @param is_equal 1 if these two logical tensors are equal, 0 otherwise. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_logical_tensor_is_equal( + const dnnl_graph_logical_tensor_t *lt1, + const dnnl_graph_logical_tensor_t *lt2, uint8_t *is_equal); + +/// @} dnnl_graph_api_logical_tensor + +/// @addtogroup dnnl_graph_api_tensor +/// @{ + +/// Creates a tensor with logical tensor, engine, and data handle. +/// +/// @param tensor Output tensor. +/// @param logical_tensor Description for this tensor. +/// @param engine Engine to use. +/// @param handle Handle of the memory buffer to use as an underlying storage. +/// - A pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer for the tensor. In this case the library +/// owns the buffer. +/// - DNNL_MEMORY_NONE to create tensor without an underlying buffer. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_tensor_create(dnnl_graph_tensor_t *tensor, + const dnnl_graph_logical_tensor_t *logical_tensor, dnnl_engine_t engine, + void *handle); + +/// Destroys a tensor. +/// +/// @param tensor The tensor to be destroyed. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_tensor_destroy(dnnl_graph_tensor_t tensor); + +/// Gets the data handle of a tensor. +/// +/// @param tensor The input tensor. +/// @param handle Pointer to the data of input tensor. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_tensor_get_data_handle( + const_dnnl_graph_tensor_t tensor, void **handle); + +/// Set data handle for a tensor. +/// +/// @param tensor The input tensor. +/// @param handle New data handle for tensor. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_tensor_set_data_handle( + dnnl_graph_tensor_t tensor, void *handle); + +/// Returns the engine of a tensor object. +/// +/// @param tensor The input tensor. +/// @param engine Output engine on which the tensor is located. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_tensor_get_engine( + const_dnnl_graph_tensor_t tensor, dnnl_engine_t *engine); + +/// @} dnnl_graph_api_tensor + +/// @addtogroup dnnl_graph_api_op +/// @{ + +/// Initializes an op with unique id, kind, and name. +/// +/// @param op Output op +/// @param id The unique id of the output op. +/// @param kind The op kind. +/// @param verbose_name The string added as the op name. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_create(dnnl_graph_op_t *op, size_t id, + dnnl_graph_op_kind_t kind, const char *verbose_name); + +/// Destroys an op. +/// +/// @param op The op to be destroyed. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_destroy(dnnl_graph_op_t op); + +/// Adds input logical tensor to the op. +/// +/// @param op Input op. +/// @param input The input logical tensor to be added. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_add_input( + dnnl_graph_op_t op, const dnnl_graph_logical_tensor_t *input); + +/// Adds output logical tensor to the op. +/// +/// @param op Input op. +/// @param output The output logical tensor to be added. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_add_output( + dnnl_graph_op_t op, const dnnl_graph_logical_tensor_t *output); + +/// Sets floating point attribute to an op. +/// +/// @param op Input op. +/// @param name The attribute's name. +/// @param value The attribute's value. +/// @param value_len The number of value element. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_set_attr_f32(dnnl_graph_op_t op, + dnnl_graph_op_attr_t name, const float *value, size_t value_len); + +/// Sets boolean attribute to an op. +/// +/// @param op Input op. +/// @param name The attribute's name. +/// @param value The attribute's value. +/// @param value_len The number of value element. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_set_attr_bool(dnnl_graph_op_t op, + dnnl_graph_op_attr_t name, const uint8_t *value, size_t value_len); + +/// Sets integer attribute to an op. +/// +/// @param op Input op. +/// @param name The attribute's name. +/// @param value The attribute's value. +/// @param value_len The number of value element. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_set_attr_s64(dnnl_graph_op_t op, + dnnl_graph_op_attr_t name, const int64_t *value, size_t value_len); + +/// Sets string attribute to an op. +/// +/// @param op Input op. +/// @param name The attribute's name. +/// @param value The attribute's value. +/// @param value_len The length of the string value. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_set_attr_str(dnnl_graph_op_t op, + dnnl_graph_op_attr_t name, const char *value, size_t value_len); + +/// Returns the unique id of an op. +/// +/// @param op Input op. +/// @param id Output the unique id. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_get_id( + const_dnnl_graph_op_t op, size_t *id); + +/// Returns the kind of an op. +/// +/// @param op Input op. +/// @param kind Output op kind. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_op_get_kind( + const_dnnl_graph_op_t op, dnnl_graph_op_kind_t *kind); + +/// @} dnnl_graph_api_op + +/// @addtogroup dnnl_graph_api_partition +/// @{ + +/// Creates a new partition with a given operator and engine kind. The API is +/// used to create a partition from an operation directly without creating the +/// graph and calling `get_partitions()`. The output partition contains only one +/// operation specified by the parameter. The output partition instance should +/// be destroyed via #dnnl_graph_partition_destroy after use. +/// +/// @param partition The handle of output partition. +/// @param op The operation used to create partition. +/// @param ekind The engine kind used to create partition. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_create_with_op( + dnnl_graph_partition_t *partition, const_dnnl_graph_op_t op, + dnnl_engine_kind_t ekind); + +/// Destroys a partition. +/// +/// @param partition The partition to be destroyed. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_destroy( + dnnl_graph_partition_t partition); + +/// Returns the number of operations in a partition. +/// +/// @param partition The target partition. +/// @param num Output the number of operations. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_op_num( + const_dnnl_graph_partition_t partition, size_t *num); + +/// Returns the list of op IDs of the partition. +/// +/// @param partition The target partition. +/// @param num The number of ops. +/// @param ids Output the op IDs. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_ops( + dnnl_graph_partition_t partition, size_t num, size_t *ids); + +/// Returns the ID of a partition. +/// +/// @param partition The target partition. +/// @param id Output the ID of the partition. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_id( + const_dnnl_graph_partition_t partition, size_t *id); + +/// Compiles a partition with given input and output logical tensors. The output +/// logical tensors can contain unknown dimensions. For this case, the +/// compilation will deduce the output shapes according to input shapes. The +/// output logical tensors can also have layout type `any`. The compilation will +/// choose the optimal layout for output tensors. The optimal layout will be +/// represented as an opaque layout ID saved in the output logical tensor. +/// +/// @param partition The target partition. +/// @param compiled_partition Output compiled partition. +/// @param in_num The number of input logical tensors. +/// @param inputs A list of input logical tensors. +/// @param out_num The number of output logical tensors. +/// @param outputs A list of output logical tensors. +/// @param engine The target engine of the compilation. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_compile( + dnnl_graph_partition_t partition, + dnnl_graph_compiled_partition_t compiled_partition, size_t in_num, + const dnnl_graph_logical_tensor_t **inputs, size_t out_num, + const dnnl_graph_logical_tensor_t **outputs, dnnl_engine_t engine); + +/// Returns the number of input logical tensors of a partition. +/// +/// @param partition The target partition. +/// @param num Output the number of input logical tensors. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_input_ports_num( + const_dnnl_graph_partition_t partition, size_t *num); + +/// Returns a list of input logical tensors from a partition. +/// +/// @param partition The target partition. +/// @param num The number of input logical tensors. +/// @param inputs The list of input logical tensors. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_input_ports( + const_dnnl_graph_partition_t partition, size_t num, + dnnl_graph_logical_tensor_t *inputs); + +/// Returns the number of output logical tensors of a partition. +/// +/// @param partition The target partition. +/// @param num Output the number of output logical tensors. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_output_ports_num( + const_dnnl_graph_partition_t partition, size_t *num); + +/// Returns a list of output logical tensors from a partition. +/// +/// @param partition The target partition. +/// @param num The number of output logical tensors. +/// @param outputs The list of output logical tensors. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_output_ports( + const_dnnl_graph_partition_t partition, size_t num, + dnnl_graph_logical_tensor_t *outputs); + +/// Returns the supporting status of a partition. Some operations may not be +/// supported by the library under certain circumstances. During partitioning +/// stage, unsupported partitions will be returned to users with each containing +/// an unsupported operation. Users should check the supporting status of a +/// partition before transforming the computation graph or compiling the +/// partition. +/// +/// @param partition The target partition. +/// @param is_supported Output flag to indicate the supporting status. 0 means +/// unsupported while 1 means supported. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_is_supported( + const_dnnl_graph_partition_t partition, uint8_t *is_supported); + +/// Returns the engine kind of a partition. +/// +/// @param partition The target partition. +/// @param kind The output engine kind. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_partition_get_engine_kind( + const_dnnl_graph_partition_t partition, dnnl_engine_kind_t *kind); + +/// @} dnnl_graph_api_partition + +/// @addtogroup dnnl_graph_api_compiled_partition +/// @{ + +/// Creates a new compiled partition handle. +/// +/// @param compiled_partition The handle of output compiled partition. +/// @param partition The handle of input partition. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_compiled_partition_create( + dnnl_graph_compiled_partition_t *compiled_partition, + dnnl_graph_partition_t partition); + +/// Executes a compiled partition. +/// +/// @param compiled_partition The handle of target compiled partition. +/// @param stream The stream used for execution. +/// @param num_inputs The number of input tensors. +/// @param inputs A list of input tensors. +/// @param num_outputs The number of output tensors. +/// @param outputs A non-empty list of output tensors. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_compiled_partition_execute( + const_dnnl_graph_compiled_partition_t compiled_partition, + dnnl_stream_t stream, size_t num_inputs, + const_dnnl_graph_tensor_t *inputs, size_t num_outputs, + const_dnnl_graph_tensor_t *outputs); + +/// Destroys a compiled partition. +/// +/// @param compiled_partition The compiled partition to be destroyed. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_compiled_partition_destroy( + dnnl_graph_compiled_partition_t compiled_partition); + +/// Queries an input or output logical tensor according to tensor ID. If the +/// tensor ID doesn't belong to any input or output of the compiled partition, +/// an error status #dnnl_invalid_arguments will be returned by the API. +/// +/// @param compiled_partition The handle of target compiled_partition. +/// @param tid The unique id of required tensor. +/// @param lt The output logical tensor. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_compiled_partition_query_logical_tensor( + const_dnnl_graph_compiled_partition_t compiled_partition, size_t tid, + dnnl_graph_logical_tensor_t *lt); + +/// Returns the hint of in-place pairs from a compiled partition. It indicates +/// that an input and an output of the partition can share the same memory +/// buffer for computation. In-place computation helps to reduce the memory +/// footprint and improves cache locality. But since the library may not have a +/// global view of user's application, it's possible that the tensor with +/// `input_id` is used at other places in user's computation graph. In this +/// case, the user should take the in-place pair as a hint and pass a different +/// memory buffer for output tensor to avoid overwriting the input memory buffer +/// which will probably cause unexpected incorrect results. +/// +/// @param compiled_partition The handle of target compiled_partition. +/// @param num_inplace_pairs The number of in-place pairs. +/// @param inplace_pairs The handle of in-place pairs. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_compiled_partition_get_inplace_ports( + const_dnnl_graph_compiled_partition_t compiled_partition, + size_t *num_inplace_pairs, + const dnnl_graph_inplace_pair_t **inplace_pairs); + +/// @} dnnl_graph_api_compiled_partition + +/// @addtogroup dnnl_graph_api_graph +/// @{ + +/// Creates a new empty graph. A graph is associated to a specific engine kind. +/// The partitions returned from the graph will inherit the engine kind of the +/// graph. +/// +/// @param graph The handle of output graph. +/// @param engine_kind The target engine kind. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_create( + dnnl_graph_graph_t *graph, dnnl_engine_kind_t engine_kind); + +/// Creates a new empty graph with an engine kind and a floating-point math +/// mode. All partitions returned from the graph will inherit the engine kind +/// and floating-point math mode. +/// +/// @param graph The handle of output graph. +/// @param engine_kind The kind for engine. +/// @param mode The floating-point math mode. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_create_with_fpmath_mode( + dnnl_graph_graph_t *graph, dnnl_engine_kind_t engine_kind, + dnnl_fpmath_mode_t mode); + +/// Destroys a graph. +/// +/// @param graph The graph to be destroyed. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_destroy(dnnl_graph_graph_t graph); + +/// Adds an operation into a graph. The API will return failure if the operator +/// has already been added to the graph or the operation cannot pass the schema +/// check in the library (eg. input and output numbers and data types, the +/// attributes of the operation, etc.). +/// +/// @param graph The target graph. +/// @param op The operation to be added. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_add_op( + dnnl_graph_graph_t graph, dnnl_graph_op_t op); + +/// Finalizes a graph. It means users have finished adding operations into the +/// graph and the graph is ready for partitioning. Adding a new operation into a +/// finalized graph will return failures. Similarly, partitioning on a +/// un-finalized graph will also return failures. +/// +/// @param graph The target graph to be finalized. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_finalize(dnnl_graph_graph_t graph); + +/// Checks if a graph is finalized. +/// +/// @param graph The target graph to be finalized. +/// @param finalized Output the finalization status. 0 means then graph is not +/// finalized. Other values means the graph is finalized. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_is_finalized( + dnnl_graph_graph_t graph, uint8_t *finalized); + +/// Filters a graph. Partitions will be claimed internally according to the +/// capability of the library, the engine kind, and the policy. +/// +/// @param graph The target graph. +/// @param policy The partition policy. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_filter( + dnnl_graph_graph_t graph, dnnl_graph_partition_policy_t policy); + +/// Returns the number of partitions of a graph. The API should be called after +/// a partition is already filtered. Otherwise, the output number is zero. +/// +/// @param graph The graph. +/// @param num Output the number of partitions. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_get_partition_num( + const_dnnl_graph_graph_t graph, size_t *num); + +/// Returns the partitions from a filtered graph. Output partition instances +/// will be written into the parameter `partitions`. Users need to make sure +/// `partitions` is valid and has enough space to accept the partition +/// instances. Each output partition instance should be destroyed via +/// #dnnl_graph_partition_destroy explicitly after use. +/// +/// @param graph The target graph. +/// @param num The number of partitions. +/// @param partitions Output the partitions. +/// @returns #dnnl_success on success or a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_graph_get_partitions(dnnl_graph_graph_t graph, + size_t num, dnnl_graph_partition_t *partitions); + +/// @} dnnl_graph_api_graph + +/// @addtogroup dnnl_graph_api_compiled_partition_cache +/// @{ + +/// Returns the number of compiled partitions that can be held in the compiled +/// partition cache at the same time. +/// +/// @param capacity Compiled partition cache capacity to query. Concurrently +/// accessing @p capacity is safe. +/// @returns #dnnl_invalid_arguments if the @p capacity value +/// is invalid, and #dnnl_success on success. +dnnl_status_t DNNL_API dnnl_graph_get_compiled_partition_cache_capacity( + int *capacity); + +/// Sets a number of compiled partitions that can be held in the compiled +/// partition cache at the same time. The default capacity of compiled partition +/// cache is 1024. +/// +/// @param capacity Compiled partition cache capacity to set. The default cache +/// capacity is 1024. If a new @p capacity is less than a number of compiled +/// partition that the compiled partition cache already has, then the excess +/// entries will be evicted. Setting the @p capacity to 0 clears the compiled +/// partition cache and disables it. Concurrently modifying @p capacity is safe. +/// @returns #dnnl_invalid_arguments if the @p capacity value +/// is invalid, and #dnnl_success on success. +dnnl_status_t DNNL_API dnnl_graph_set_compiled_partition_cache_capacity( + int capacity); + +/// @} dnnl_graph_api_compiled_partition_cache + +/// @addtogroup dnnl_graph_api_constant_tensor_cache +/// @{ + +/// Control the enabling or disabling of constant tensor cache. This API must +/// be called once before compilation stage. By default, constant tensor cache is +/// disabled in the library. +/// +/// @param flag Set to positive value to enable the cache and set to 0 to +/// disable the cache. Negative values are invalid. +/// @returns #dnnl_invalid_arguments if the @p flag value is +/// invalid, and #dnnl_success on success. +/// @note This API is deprecated and will be removed in future release, please +/// use the dnnl_graph_set_constant_tensor_cache_capacity API to disable +/// constant tensor cache by setting it's capacity to zero. +dnnl_status_t DNNL_API dnnl_graph_set_constant_tensor_cache(int flag); + +/// Return the enabling or disabling status of constant tensor cache. +/// +/// @param flag The constant tensor cache enabling status to query. +/// @returns #dnnl_invalid_arguments if the @p flag value is +/// nullptr, and #dnnl_success on success. +/// @note This API is deprecated and will be removed in future release, please +/// use the dnnl_graph_get_constant_tensor_cache_capacity API to check the +/// enabling status by checking it's capacity. +dnnl_status_t DNNL_API dnnl_graph_get_constant_tensor_cache(int *flag); + +/// Control the capacity for the constant tensor cache that used for specific +/// engine kind. This API is thread safe and can be called multiple times at +/// runtime. The capacity is set to zero by default which means the cache is +/// disabled. When calling this API, the corresponding cache will be flushed. +/// Setting capacity to 0 means to clear all cached tensors and disable cache. +/// Once the capacity limit is reached, no new tensors will be cached. If there +/// are multiple devices for an engine kind, the capacity set here is for each +/// device. +/// +/// @param eng_kind The engine kind that the constant tensor cache used for. +/// @param size The constant tensor cache capacity size to set. +/// @returns #dnnl_invalid_arguments if the @p eng_kind value is invalid, and +/// #dnnl_success on success. +dnnl_status_t DNNL_API dnnl_graph_set_constant_tensor_cache_capacity( + dnnl_engine_kind_t eng_kind, size_t size); + +/// Return the current capacity of constant tensor cache. +/// +/// @param eng_kind The engine kind that the constant tensor cache used for. +/// @param size The constant tensor cache capacity size to query. +/// @returns #dnnl_invalid_arguments if the @p eng_kind value is +/// nullptr or the @p size is nullptr, and #dnnl_success on success. +dnnl_status_t DNNL_API dnnl_graph_get_constant_tensor_cache_capacity( + dnnl_engine_kind_t eng_kind, size_t *size); + +/// @} dnnl_graph_api_constant_tensor_cache + +/// @} dnnl_graph_api + +#ifdef __cplusplus +} +#endif +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4161a46b277452dc58e0ae2962b56bee03cdc460 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph.hpp @@ -0,0 +1,1569 @@ +/******************************************************************************* +* Copyright 2020-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_HPP +#define ONEAPI_DNNL_DNNL_GRAPH_HPP + +#include "oneapi/dnnl/dnnl_common.hpp" +#include "oneapi/dnnl/dnnl_graph.h" + +#include +#include +#include +#include +#include + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_graph_api Graph API +/// @{ + +namespace dnnl { +namespace graph { + +/// @cond DO_NOT_DOCUMENT_THIS + +// Alias for common engine and stream API. +using engine = dnnl::engine; +using stream = dnnl::stream; +using fpmath_mode = dnnl::fpmath_mode; + +/// @endcond + +/// @addtogroup dnnl_graph_api_utils Utilities +/// Utility types and definitions +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS + +/// A class that provides the destructor for a oneDNN graph C API handle. +template +struct graph_handle_traits : public dnnl::handle_traits {}; + +template <> +struct graph_handle_traits { + static dnnl_status_t destructor(dnnl_graph_op_t p) { + return dnnl_graph_op_destroy(p); + } +}; + +template <> +struct graph_handle_traits { + static dnnl_status_t destructor(dnnl_graph_graph_t p) { + return dnnl_graph_graph_destroy(p); + } +}; + +template <> +struct graph_handle_traits { + static dnnl_status_t destructor(dnnl_graph_tensor_t p) { + return dnnl_graph_tensor_destroy(p); + } +}; + +template <> +struct graph_handle_traits { + static dnnl_status_t destructor(dnnl_graph_partition_t p) { + return dnnl_graph_partition_destroy(p); + } +}; + +template <> +struct graph_handle_traits { + static dnnl_status_t destructor(dnnl_graph_compiled_partition_t p) { + return dnnl_graph_compiled_partition_destroy(p); + } +}; + +template <> +struct graph_handle_traits { + static dnnl_status_t destructor(dnnl_graph_allocator_t p) { + return dnnl_graph_allocator_destroy(p); + } +}; + +#define DNNL_GRAPH_HANDLE_ALIAS(type) \ + using type##_handle = dnnl::handle> + +DNNL_GRAPH_HANDLE_ALIAS(allocator); +DNNL_GRAPH_HANDLE_ALIAS(graph); +DNNL_GRAPH_HANDLE_ALIAS(op); +DNNL_GRAPH_HANDLE_ALIAS(tensor); +DNNL_GRAPH_HANDLE_ALIAS(compiled_partition); +DNNL_GRAPH_HANDLE_ALIAS(partition); + +#undef DNNL_GRAPH_HANDLE_ALIAS + +template +using req = typename std::enable_if::type; + +/// @endcond + +/// @} dnnl_graph_api_utils + +/// @addtogroup dnnl_graph_api_status Status +/// Definitions of status values returned by the library functions. +/// +/// @{ + +/// Status values returned by the library functions. +enum class status { + /// The operation was successful + success = dnnl_success, + /// The operation failed due to an out-of-memory condition + out_of_memory = dnnl_out_of_memory, + /// The operation failed because of incorrect function arguments + invalid_arguments = dnnl_invalid_arguments, + /// The operation failed because requested functionality is not implemented + unimplemented = dnnl_unimplemented, + /// The last available implementation is reached + last_impl_reached = dnnl_last_impl_reached, + /// Primitive or engine failed on execution + runtime_error = dnnl_runtime_error, + /// Queried element is not required for given primitive + not_required = dnnl_not_required, + /// The graph is not legitimate + invalid_graph = dnnl_invalid_graph, + /// The operation is not legitimate according to op schema + invalid_graph_op = dnnl_invalid_graph_op, + /// The shape cannot be inferred or compiled + invalid_shape = dnnl_invalid_shape, + /// The data type cannot be inferred or compiled + invalid_data_type = dnnl_invalid_data_type, +}; + +/// @} dnnl_api_status + +/// @addtogroup dnnl_graph_api_allocator Allocator +/// +/// Definitions of allocator which is used to acquire memory resources in +/// partition compilation and execution. SYCL allocator +/// (#dnnl::graph::sycl_interop::make_allocator) should be used for SYCL runtime +/// and host allocator should be used for non-SYCL. +/// +/// @{ + +/// Allocator +class allocator : public allocator_handle { +public: + using allocator_handle::handle; + + /// Constructs an allocator according to given function pointers + /// + /// @param host_malloc A pointer to malloc function for CPU + /// @param host_free A pointer to free function for CPU + allocator(dnnl_graph_host_allocate_f host_malloc, + dnnl_graph_host_deallocate_f host_free) { + dnnl_graph_allocator_t a = nullptr; + error::wrap_c_api( + dnnl_graph_allocator_create(&a, host_malloc, host_free), + "could not create allocator for cpu"); + reset(a); + } + + /// Default constructor + allocator() { + dnnl_graph_allocator_t a = nullptr; + error::wrap_c_api(dnnl_graph_allocator_create(&a, nullptr, nullptr), + "could not create allocator"); + reset(a); + } +}; + +/// @} dnnl_graph_api_allocator + +/// @addtogroup dnnl_graph_api_engine Engine +/// @{ + +/// This API is a supplement for existing onednn engine API. +inline engine make_engine_with_allocator( + engine::kind kind, size_t index, const allocator &alloc) { + dnnl_engine_t c_engine; + error::wrap_c_api( + dnnl_graph_make_engine_with_allocator(&c_engine, + static_cast(kind), index, alloc.get()), + "could not make an engine with allocator"); + return engine(c_engine); +} + +/// @} dnnl_graph_api_engine + +/// @addtogroup dnnl_graph_api_logical_tensor Logical Tensor +/// +/// Logical tensor describes the meta-data of the input or output tensor, like +/// elements data type, number of dimensions, size for each dimension (shape), +/// layout, and the property of the tensor. +/// +/// Each logical tensor has an unique ID. The library uses logical tensor IDs to +/// build up the connections between operations if the output of one operation +/// has the same ID as the input of another operation. The meta-data in a +/// logical tensor may be enriched in the framework graph as it progresses +/// toward final execution. For example, the library doesn't require detailed +/// shape information at the operation and graph creation stage. But shape +/// information of input logical tensor will be required at partition +/// compilation stage. Logical tensor is not mutable. Users must create a new +/// logical tensor with the same ID to pass any new additional information to +/// oneDNN Graph API. Please note that the library also has unique IDs for +/// operations. The ID should be unique among different logical tensors, but it +/// can have the same value between a logical tensor and an operation. +/// +/// @{ + +/// Logical tensor object +class logical_tensor { + friend class op; + friend class tensor; + friend class partition; + friend class compiled_partition; + + dnnl_graph_logical_tensor_t data; + +public: + /// Integer type for representing dimension sizes and indices. + using dim = dnnl_dim_t; + /// Vector of dimensions. Implementations are free to force a limit on the + /// vector's length. + using dims = std::vector; + + /// Data Type + enum class data_type { + undef = dnnl_data_type_undef, + /// 16-bit/half-precision floating point. + f16 = dnnl_f16, + /// non-standard 16-bit (bfloat16 w/ 7 bit mantissa) floating point. + bf16 = dnnl_bf16, + /// 32-bit/single-precision floating point. + f32 = dnnl_f32, + /// 32-bit signed integer. + s32 = dnnl_s32, + /// 8-bit signed integer. + s8 = dnnl_s8, + /// 8-bit unsigned integer. + u8 = dnnl_u8, + /// Boolean data type. Size is C++ implementation defined. + boolean = dnnl_boolean, + /// [OFP8 standard 8-bit + /// floating-point](https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-06-20-pdf) + /// with a 5-bit exponent and a 2-bit mantissa. + f8_e5m2 = dnnl_f8_e5m2, + /// [OFP8 standard 8-bit + /// floating-point](https://www.opencompute.org/documents/ocp-8-bit-floating-point-specification-ofp8-revision-1-0-2023-06-20-pdf) + /// with a 4-bit exponent and a 3-bit mantissa. + f8_e4m3 = dnnl_f8_e4m3, + }; + + /// Layout type + enum class layout_type { + /// Undefined layout type. + undef = dnnl_graph_layout_type_undef, + /// Any means to let the library to decide the layout for a tensor + /// during partition compilation. + any = dnnl_graph_layout_type_any, + /// Strided means that the layout of a tensor is determined by the + /// strides field in the logical tensor. + strided = dnnl_graph_layout_type_strided, + /// Opaque means that the layout of a tensor is the library specific. + /// Usually, an opaque layout is generated by a partition which is + /// compiled with layout type any. + opaque = dnnl_graph_layout_type_opaque, + }; + + /// Tensor property + enum class property_type { + /// Undefined tensor property. + undef = dnnl_graph_tensor_property_undef, + /// Variable means the tensor may be changed during computation or + /// between different iterations. + variable = dnnl_graph_tensor_property_variable, + /// Constant means the tensor will keep unchanged during computation and + /// between different iterations. It's useful for the library to apply + /// optimizations for constant tensors or cache constant tensors inside + /// the library. For example, constant weight tensors in inference + /// scenarios. + constant = dnnl_graph_tensor_property_constant, + }; + + /// default constructor + /// construct an empty object + logical_tensor() = default; + + /// Constructs a logical tensor object + explicit logical_tensor(const dnnl_graph_logical_tensor_t &c_data) + : data(c_data) {} + + /// Copy + logical_tensor(const logical_tensor &other) = default; + + /// Assign + logical_tensor &operator=(const logical_tensor &other) = default; + + /// Constructs a logical tensor object with ID, data type, ndims, layout + /// type, and property type. + /// + /// @param tid Logical tensor ID. + /// @param dtype Elements data type. + /// @param ndims Number of dimensions. -1 means unknown (see + /// #DNNL_GRAPH_UNKNOWN_NDIMS) and 0 means a scalar tensor. + /// @param ltype Layout type. + /// @param ptype Property type. + logical_tensor(size_t tid, data_type dtype, int32_t ndims, + layout_type ltype, property_type ptype = property_type::undef) { + dnnl_graph_logical_tensor_t val; + error::wrap_c_api( + dnnl_graph_logical_tensor_init(&val, tid, convert_to_c(dtype), + ndims, convert_to_c(ltype), convert_to_c(ptype)), + "could not create logical_tensor with property"); + data = val; + } + + /// Delegated constructor. + /// + /// @param tid Logical tensor ID. + /// @param dtype Elements data type. + /// @param ltype Layout type. + logical_tensor( + size_t tid, data_type dtype, layout_type ltype = layout_type::undef) + : logical_tensor(tid, dtype, DNNL_GRAPH_UNKNOWN_NDIMS, ltype) {} + + /// Constructs a logical tensor object with basic information and detailed + /// dims. + /// + /// @param tid Logical tensor ID. + /// @param dtype Elements data type. + /// @param adims Logical tensor dimensions. #DNNL_GRAPH_UNKNOWN_DIM means + /// the size of that dimension is unknown. 0 is used to define + /// zero-dimension tensor. + /// @param ltype Layout type. If it's strided, the strides field in the + /// output logical tensor will be deduced accordingly. + /// @param ptype Property type. + logical_tensor(size_t tid, data_type dtype, const dims &adims, + layout_type ltype, property_type ptype = property_type::undef) { + dnnl_graph_logical_tensor_t val; + // if dimension size equals to 0, it's a scalar + if (adims.size() == 0) + error::wrap_c_api(dnnl_graph_logical_tensor_init(&val, tid, + convert_to_c(dtype), 0, + convert_to_c(ltype), convert_to_c(ptype)), + "could not create logical_tensor with property"); + else + error::wrap_c_api( + dnnl_graph_logical_tensor_init_with_dims(&val, tid, + convert_to_c(dtype), + static_cast(adims.size()), adims.data(), + convert_to_c(ltype), convert_to_c(ptype)), + "could not create logical_tensor with dims and property"); + data = val; + } + + /// Constructs a logical tensor object with detailed dims and strides. The + /// layout_type of the output logical tensor object will always be strided. + /// + /// @param tid Logical tensor ID. + /// @param dtype Elements data type. + /// @param adims Logical tensor dimensions. #DNNL_GRAPH_UNKNOWN_DIM means + /// the size of that dimension is unknown. 0 is used to define + /// zero-dimension tensor. + /// @param strides Logical tensor strides. #DNNL_GRAPH_UNKNOWN_DIM means + /// the stride of the dimension is unknown. The library currently + /// doesn't support other negative stride values. + /// @param ptype Property type. + logical_tensor(size_t tid, data_type dtype, const dims &adims, + const dims &strides, property_type ptype = property_type::undef) { + dnnl_graph_logical_tensor_t val; + // TODO(lvtao): check the size of adims and strides. + // They should be same. + error::wrap_c_api( + dnnl_graph_logical_tensor_init_with_strides(&val, tid, + convert_to_c(dtype), static_cast(adims.size()), + adims.data(), strides.data(), convert_to_c(ptype)), + "could not create logical_tensor with strides and property"); + data = val; + } + + /// Constructs a logical tensor object with detailed dims and an opaque + /// layout ID. layout_type of the output logical tensor object will always + /// be opaque. + /// + /// @param tid Logical tensor ID. + /// @param dtype Elements data type. + /// @param adims Logical tensor dimensions. #DNNL_GRAPH_UNKNOWN_DIM means + /// the size of that dimension is unknown. 0 is used to define + /// zero-dimension tensor. + /// @param lid Opaque layout id. + /// @param ptype Property type + logical_tensor(size_t tid, data_type dtype, const dims &adims, size_t lid, + property_type ptype = property_type::undef) { + dnnl_graph_logical_tensor_t val; + + if (adims.size() == 0) { + error::wrap_c_api(dnnl_graph_logical_tensor_init(&val, tid, + convert_to_c(dtype), 0, + convert_to_c(layout_type::opaque), + convert_to_c(ptype)), + "could not create logical_tensor"); + } else { + error::wrap_c_api( + dnnl_graph_logical_tensor_init_with_dims(&val, tid, + convert_to_c(dtype), + static_cast(adims.size()), adims.data(), + convert_to_c(layout_type::opaque), + convert_to_c(ptype)), + "could not create logical_tensor with dims"); + } + + val.layout.layout_id = lid; + data = val; + } + + /// Returns dimensions of a logical tensor. + /// + /// @returns A vector describing the size of each dimension. + dims get_dims() const { + if (data.ndims < 0) { + error::wrap_c_api(dnnl_invalid_arguments, + "cannot return dims when ndims < 0"); + } + + return {data.dims, data.dims + data.ndims}; + } + + /// Returns the unique id of a logical tensor. + /// + /// @returns An integer value describing the ID. + size_t get_id() const { return data.id; } + + /// Returns the data type of a logical tensor. + /// + /// @returns The data type. + data_type get_data_type() const { + return static_cast(data.data_type); + } + + /// Returns the property type of a logical tensor. + /// + /// @returns The property type. + property_type get_property_type() const { + return static_cast(data.property); + } + + /// Returns the layout type of a logical tensor. + /// + /// @returns The layout type. + layout_type get_layout_type() const { + return static_cast(data.layout_type); + } + + /// Returns the layout ID of a logical tensor. The API should be called on a + /// logical tensor with opaque layout type. Otherwise, an exception will be + /// raised. + /// + /// @returns Layout ID. + size_t get_layout_id() const { + if (get_layout_type() != layout_type::opaque) { + error::wrap_c_api( + dnnl_invalid_arguments, "layout type should be opaque"); + } + + return data.layout.layout_id; + } + + /// Returns the strides of a logical tensor. The API should be called on a + /// logical tensor with strided layout type. Otherwise, an exception will be + /// raised. + /// + /// @returns A vector describing the stride size of each dimension. + dims get_strides() const { + if (get_layout_type() != layout_type::strided) { + error::wrap_c_api( + dnnl_invalid_arguments, "layout type should be strided"); + } + + if (data.ndims < 0) { + error::wrap_c_api(dnnl_invalid_arguments, + "cannot return strides when ndims < 0"); + } + + return {data.layout.strides, data.layout.strides + data.ndims}; + } + + /// Returns memory size in bytes required by this logical tensor. + /// + /// @returns The memory size in bytes. + size_t get_mem_size() const { + size_t size = 0; + error::wrap_c_api(dnnl_graph_logical_tensor_get_mem_size(&data, &size), + "could not get memory size from the logical_tensor"); + return size; + } + + /// Compares if two logical tenors are equal. Users can decide accordingly + /// if layout reordering is needed for two logical tensors. The method will + /// return true for below two circumstances: + /// + /// 1. the two logical tensors are equal regarding each field in the struct, + /// eg. id, ndims, dims, layout type, property, etc. + /// 2. If all other fields are equal but the layout types in two logical + /// tensors are different, the method will return true when the underlying + /// memory layout is the same. For example, one logical tensor has strided + /// layout type while the other one has opaque layout type, but underneath, + /// both layouts are NHWC, the method will still return true for this case. + /// + /// @param lt The input logical tensor to be compared. + /// @returns @c true if the two logical tensors are equal. @c false otherwise + bool is_equal(const logical_tensor <) const { + uint8_t equal = 0; + error::wrap_c_api( + dnnl_graph_logical_tensor_is_equal(&data, <.data, &equal), + "could not compare between the two logical tensors"); + return equal != 0; + } + +private: + static dnnl_data_type_t convert_to_c(data_type dtype) { + return static_cast(dtype); + } + + static dnnl_graph_layout_type_t convert_to_c(layout_type ltype) { + return static_cast(ltype); + } + + static dnnl_graph_tensor_property_t convert_to_c(property_type ptype) { + return static_cast(ptype); + } +}; + +/// @} dnnl_graph_api_logical_tensor + +/// @addtogroup dnnl_graph_api_tensor Tensor +/// +/// Tensor is an abstraction for multi-dimensional input and output data needed +/// in the execution of a compiled partition. A tensor object encapsulates a +/// handle to a memory buffer allocated on a specific engine and a logical +/// tensor which describes the dimensions, elements data type, and memory +/// layout. +/// +/// @{ + +/// A tensor object +class tensor : public tensor_handle { +public: + /// Default constructor. Constructs an empty object. + tensor() = default; + + /// Constructs a tensor object according to a given logical tensor, an + /// engine, and a memory handle. + /// + /// @param lt The given logical tensor + /// @param aengine Engine to store the data on. + /// @param handle Handle of memory buffer to use as an underlying storage. + /// - A pointer to the user-allocated buffer. In this case the library + /// doesn't own the buffer. + /// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to + /// allocate the buffer for the tensor. In this case the library + /// owns the buffer. + /// - DNNL_MEMORY_NONE to create tensor without an underlying buffer. + tensor(const logical_tensor <, const engine &aengine, void *handle) { + dnnl_graph_tensor_t t = nullptr; + error::wrap_c_api( + dnnl_graph_tensor_create(&t, &(lt.data), aengine.get(), handle), + "could not create tensor object with the logical_tensor, " + "engine, and handle"); + reset(t); + } + + /// Constructs a tensor object. + /// The underlying buffer for the memory will be allocated by the library. + /// + /// @param lt The given logical tensor + /// @param aengine Engine to store the data on. + tensor(const logical_tensor <, const engine &aengine) + : tensor(lt, aengine, DNNL_MEMORY_ALLOCATE) {} + + /// Returns the underlying memory buffer. + /// + /// On the CPU engine, or when using USM, this is a pointer to the + /// allocated memory. + void *get_data_handle() const { + void *handle = nullptr; + error::wrap_c_api(dnnl_graph_tensor_get_data_handle(get(), &handle), + "could not get data handle from the tensor"); + return handle; + } + + /// Sets the underlying memory handle. + /// + /// @param handle Memory handle. + void set_data_handle(void *handle) { + error::wrap_c_api(dnnl_graph_tensor_set_data_handle(get(), handle), + "setting data handle to the tensor failed"); + } + + /// Returns the associated engine. + /// + /// @returns An engine object + engine get_engine() const { + dnnl_engine_t c_engine = nullptr; + error::wrap_c_api(dnnl_graph_tensor_get_engine(get(), &c_engine), + "could not get an engine from a tensor object"); + return engine(c_engine, true); + } +}; + +/// @} dnnl_graph_api_tensor + +/// @addtogroup dnnl_graph_api_compiled_partition Compiled Partition +/// +/// A compiled partition represents the generated kernels specialized for a +/// partition on a target hardware (engine) with input and output information +/// specified by the logical tensors. +/// +/// @{ + +/// A compiled partition object. +class compiled_partition : public compiled_partition_handle { +public: + /// Default constructor. Constructs an empty object. + compiled_partition() = default; + + /// Constructs a compiled partition object + compiled_partition(dnnl_graph_compiled_partition_t compiled_partition) { + reset(compiled_partition, false); + } + + /// Queries an input or output logical tensor according to tensor ID. If the + /// tensor ID doesn't belong to any input or output of the compiled + /// partition, an exception will be raised by the API. + /// + /// @param tid The unique id of required tensor. + /// @returns The logical tensor. + logical_tensor query_logical_tensor(size_t tid) const { + dnnl_graph_logical_tensor_t lt; + error::wrap_c_api(dnnl_graph_compiled_partition_query_logical_tensor( + get(), tid, <), + "query logical tensor from compiled_partition failed"); + return logical_tensor {lt}; + } + + /// Returns the hint of in-place pairs from a compiled partition. It + /// indicates that an input and an output of the partition can share the + /// same memory buffer for computation. In-place computation helps to reduce + /// the memory footprint and improves cache locality. But since the library + /// may not have a global view of user's application, it's possible that the + /// input tensor is used at other places in user's computation graph. In + /// this case, the user should take the in-place pair as a hint and pass a + /// different memory buffer for output tensor to avoid overwriting the input + /// memory buffer which will probably cause unexpected incorrect results. + /// + /// @returns A list of pairs of input and output IDs. + std::vector> get_inplace_ports() const { + size_t num = 0; + const dnnl_graph_inplace_pair_t *inplace_pairs; + + error::wrap_c_api(dnnl_graph_compiled_partition_get_inplace_ports( + get(), &num, &inplace_pairs), + "could not get the in-place pairs from a compiled partition"); + if (num == 0) return {}; + + std::vector> inplace_options; + inplace_options.reserve(num); + for (size_t i = 0; i < num; ++i) { + const dnnl_graph_inplace_pair_t *inplace_pair = inplace_pairs + i; + inplace_options.emplace_back( + inplace_pair->input_id, inplace_pair->output_id); + } + return inplace_options; + } + + /// Execute a compiled partition. + /// + /// @param astream Stream object to run over. + /// @param inputs A list of input tensors. + /// @param outputs A list of output tensors. + void execute(stream &astream, const std::vector &inputs, + const std::vector &outputs) const { + std::vector c_inputs; + c_inputs.reserve(inputs.size()); + for (auto &in : inputs) { + c_inputs.push_back(in.get()); + } + std::vector c_outputs; + c_outputs.reserve(outputs.size()); + for (auto &out : outputs) { + c_outputs.push_back(out.get()); + } + + error::wrap_c_api( + dnnl_graph_compiled_partition_execute(get(), astream.get(), + c_inputs.size(), c_inputs.data(), c_outputs.size(), + c_outputs.data()), + "could not execute the compiled_partition"); + } +}; + +/// @} dnnl_graph_api_compiled_partition + +/// @addtogroup dnnl_graph_api_op Op +/// +/// OP is an abstraction of computation logic for deep neural network +/// operations. An op object encapsulates an operation kind which describes the +/// computation logic, an unique ID which differentiates operations with the +/// same kind, and logical tensors which describes the input and output of the +/// operation and its connections to other operations in the graph. +/// +/// @{ + +/// An op object. +class op : public op_handle { +public: + /// Kinds of operations + enum class kind { + Abs = dnnl_graph_op_abs, + AbsBackward = dnnl_graph_op_abs_backward, + Add = dnnl_graph_op_add, + AvgPool = dnnl_graph_op_avg_pool, + AvgPoolBackward = dnnl_graph_op_avg_pool_backward, + BatchNormForwardTraining = dnnl_graph_op_batch_norm_forward_training, + BatchNormInference = dnnl_graph_op_batch_norm_inference, + BatchNormTrainingBackward = dnnl_graph_op_batch_norm_backward, + BiasAdd = dnnl_graph_op_bias_add, + BiasAddBackward = dnnl_graph_op_bias_add_backward, + Clamp = dnnl_graph_op_clamp, + ClampBackward = dnnl_graph_op_clamp_backward, + Concat = dnnl_graph_op_concat, + Convolution = dnnl_graph_op_convolution, + ConvolutionBackwardData = dnnl_graph_op_convolution_backward_data, + ConvolutionBackwardWeights = dnnl_graph_op_convolution_backward_weights, + ConvTranspose = dnnl_graph_op_conv_transpose, + ConvTransposeBackwardData = dnnl_graph_op_conv_transpose_backward_data, + ConvTransposeBackwardWeights + = dnnl_graph_op_conv_transpose_backward_weights, + Dequantize = dnnl_graph_op_dequantize, + Divide = dnnl_graph_op_divide, + DynamicDequantize = dnnl_graph_op_dynamic_dequantize, + DynamicQuantize = dnnl_graph_op_dynamic_quantize, + Elu = dnnl_graph_op_elu, + EluBackward = dnnl_graph_op_elu_backward, + End = dnnl_graph_op_end, + Exp = dnnl_graph_op_exp, + GELU = dnnl_graph_op_gelu, + GELUBackward = dnnl_graph_op_gelu_backward, + HardSigmoid = dnnl_graph_op_hard_sigmoid, + HardSigmoidBackward = dnnl_graph_op_hard_sigmoid_backward, + HardSwish = dnnl_graph_op_hard_swish, + HardSwishBackward = dnnl_graph_op_hard_swish_backward, + Interpolate = dnnl_graph_op_interpolate, + InterpolateBackward = dnnl_graph_op_interpolate_backward, + LayerNorm = dnnl_graph_op_layer_norm, + LayerNormBackward = dnnl_graph_op_layer_norm_backward, + LeakyReLU = dnnl_graph_op_leaky_relu, + Log = dnnl_graph_op_log, + LogSoftmax = dnnl_graph_op_log_softmax, + LogSoftmaxBackward = dnnl_graph_op_log_softmax_backward, + MatMul = dnnl_graph_op_matmul, + Maximum = dnnl_graph_op_maximum, + MaxPool = dnnl_graph_op_max_pool, + MaxPoolBackward = dnnl_graph_op_max_pool_backward, + Minimum = dnnl_graph_op_minimum, + Mish = dnnl_graph_op_mish, + MishBackward = dnnl_graph_op_mish_backward, + Multiply = dnnl_graph_op_multiply, + Pow = dnnl_graph_op_pow, + PReLU = dnnl_graph_op_prelu, + PReLUBackward = dnnl_graph_op_prelu_backward, + Quantize = dnnl_graph_op_quantize, + Reciprocal = dnnl_graph_op_reciprocal, + ReduceL1 = dnnl_graph_op_reduce_l1, + ReduceL2 = dnnl_graph_op_reduce_l2, + ReduceMax = dnnl_graph_op_reduce_max, + ReduceMean = dnnl_graph_op_reduce_mean, + ReduceMin = dnnl_graph_op_reduce_min, + ReduceProd = dnnl_graph_op_reduce_prod, + ReduceSum = dnnl_graph_op_reduce_sum, + ReLU = dnnl_graph_op_relu, + ReLUBackward = dnnl_graph_op_relu_backward, + Reorder = dnnl_graph_op_reorder, + Round = dnnl_graph_op_round, + Select = dnnl_graph_op_select, + Sigmoid = dnnl_graph_op_sigmoid, + SigmoidBackward = dnnl_graph_op_sigmoid_backward, + SoftMax = dnnl_graph_op_softmax, + SoftMaxBackward = dnnl_graph_op_softmax_backward, + SoftPlus = dnnl_graph_op_softplus, + SoftPlusBackward = dnnl_graph_op_softplus_backward, + Sqrt = dnnl_graph_op_sqrt, + SqrtBackward = dnnl_graph_op_sqrt_backward, + Square = dnnl_graph_op_square, + SquaredDifference = dnnl_graph_op_squared_difference, + StaticReshape = dnnl_graph_op_static_reshape, + StaticTranspose = dnnl_graph_op_static_transpose, + Subtract = dnnl_graph_op_subtract, + Tanh = dnnl_graph_op_tanh, + TanhBackward = dnnl_graph_op_tanh_backward, + TypeCast = dnnl_graph_op_type_cast, + Wildcard = dnnl_graph_op_wildcard, + // Sentinel + LastSymbol = dnnl_graph_op_last_symbol, + }; + + /// Attributes of operations. Different operations support different + /// attributes. Check the document of each operation for what attributes are + /// supported and what are the potential values for them. Missing required + /// attribute or illegal attribute value may lead to failure when adding the + /// operation to a graph. + enum class attr { + /// Undefined op attribute. + undef = dnnl_graph_op_attr_undef, + + // float32 attributes. The value of these attributes can be any single + // float32 number. + + /// Specifies an alpha attribute to an op. + alpha = dnnl_graph_op_attr_alpha, + /// Specifies an beta attribute to an op. + beta = dnnl_graph_op_attr_beta, + /// Specifies an epsilon attribute to an op. + epsilon = dnnl_graph_op_attr_epsilon, + /// Specifies a max attribute to an op. + max = dnnl_graph_op_attr_max, + /// Specifies a min attribute to an op. + min = dnnl_graph_op_attr_min, + /// Specifies a momentum attribute to an op. + momentum = dnnl_graph_op_attr_momentum, + + // float32 vector attributes. The value of these attributes can be a + // vector of float32 numbers. + + /// Specifies a scales attribute to an op. + scales = dnnl_graph_op_attr_scales, + + // int64_t attributes. The value of these attributes can be any single + // int64 number. + + /// Specifies an axis attribute to an op. + axis = dnnl_graph_op_attr_axis, + /// Specifies a begin_norm_axis attribute to an op. + begin_norm_axis = dnnl_graph_op_attr_begin_norm_axis, + /// Specifies a groups attribute to an op. + groups = dnnl_graph_op_attr_groups, + + // int64_t vector attributes. The value of these attributes can be a + // vector of int64 numbers. + + /// Specifies an axes attribute to an op. + axes = dnnl_graph_op_attr_axes, + /// Specifies a dilations attribute to an op. + dilations = dnnl_graph_op_attr_dilations, + /// Specifies an dst_shape attribute to an op. + dst_shape = dnnl_graph_op_attr_dst_shape, + /// Specifies a kernel attribute to an op. + kernel = dnnl_graph_op_attr_kernel, + /// Specifies an order attribute to an op. + order = dnnl_graph_op_attr_order, + /// Specifies an output_padding attribute to an op. + output_padding = dnnl_graph_op_attr_output_padding, + /// Specifies a pads_begin attribute to an op. + pads_begin = dnnl_graph_op_attr_pads_begin, + /// Specifies a pads_end attribute to an op. + pads_end = dnnl_graph_op_attr_pads_end, + /// Specifies a shape attribute to an op. + shape = dnnl_graph_op_attr_shape, + /// Specifies a sizes attribute to an op. + sizes = dnnl_graph_op_attr_sizes, + /// Specifies an src_shape attribute to an op. + src_shape = dnnl_graph_op_attr_src_shape, + /// Specifies a strides attribute to an op. + strides = dnnl_graph_op_attr_strides, + /// Specifies a weight_shape attribute to an op. + weights_shape = dnnl_graph_op_attr_weights_shape, + /// Specifies a zps attribute to an op. + zps = dnnl_graph_op_attr_zps, + + // bool attributes. The value of these attributes can be any single bool + // value. + + /// Specifies an exclude_pad attribute to an op. + exclude_pad = dnnl_graph_op_attr_exclude_pad, + /// Specifies a keep_dims attribute to an op. + keep_dims = dnnl_graph_op_attr_keep_dims, + /// Specifies a keep_stats attribute to an op. + keep_stats = dnnl_graph_op_attr_keep_stats, + /// Specifies a per_channel_broadcast attribute to an op. + per_channel_broadcast = dnnl_graph_op_attr_per_channel_broadcast, + /// Specifies a special_zero attribute to an op. + special_zero = dnnl_graph_op_attr_special_zero, + /// Specifies a transpose_a attribute to an op. + transpose_a = dnnl_graph_op_attr_transpose_a, + /// Specifies a transpose_b attribute to an op. + transpose_b = dnnl_graph_op_attr_transpose_b, + /// Specifies an use_affine attribute to an op. + use_affine = dnnl_graph_op_attr_use_affine, + /// Specifies an use_dst attribute to an op. + use_dst = dnnl_graph_op_attr_use_dst, + + // string attributes. The value of these attributes can be a string. + + /// Specifies an auto_broadcast attribute to an op. The value can be + /// "none" or "numpy". + auto_broadcast = dnnl_graph_op_attr_auto_broadcast, + /// Specifies an auto_pad attribute to an op. The value can be "none", + /// "same_upper", "same_lower", or "valid". + auto_pad = dnnl_graph_op_attr_auto_pad, + /// Specifies an coordinate_transformation_mode attribute to an op. The + /// value can be "half_pixel" or "align_corners". The attribute is + /// defined for Interpolate operations. + coordinate_transformation_mode + = dnnl_graph_op_attr_coordinate_transformation_mode, + /// Specifies a data_format of an op. The value can be "NCX" or "NXC". + data_format = dnnl_graph_op_attr_data_format, + /// Specifies a mode attribute of an op. The value can be "nearest", + /// "linear", "bilinear", or "trilinear". The attribute is defined for + /// Interpolate operations. + mode = dnnl_graph_op_attr_mode, + /// Specifies a qtype attribute to an op. The value can be "per_channel" + /// or "per_tensor". The attribute is defined for quantization + /// operations. + qtype = dnnl_graph_op_attr_qtype, + /// Specifies a rounding_type attribute to an op. The value can be + /// "ceil" or "floor". + rounding_type = dnnl_graph_op_attr_rounding_type, + /// Specifies a weights_format of an op. The value can be "OIX", "XIO", + /// "IOX", or "XOI". Different operations may support different values. + weights_format = dnnl_graph_op_attr_weights_format, + + /// Specifies the end of all above exteral attributes for check. + end = dnnl_graph_op_attr_end, + }; + + /// Constructs an op object with an unique ID, an operation kind, and a name + /// string. + /// + /// @param id The unique ID of the op. + /// @param akind The op kind specifies which computation is represented by + /// the op, such as Convolution or ReLU. + /// @param verbose_name The string added as the op name. + op(size_t id, kind akind, const std::string &verbose_name = "") { + dnnl_graph_op_t op = nullptr; + error::wrap_c_api(dnnl_graph_op_create(&op, id, convert_to_c(akind), + verbose_name.c_str()), + "could not create op with id and op kind"); + reset(op); + } + + /// Constructs an op object with an unique ID, an operation kind, and + /// input/output logical tensors. + /// + /// @param id The unique ID of this op. + /// @param akind The op kind specifies which computation is represented by + /// this op, such as Convolution or ReLU. + /// @param inputs Input logical tensor to be bound to this op. + /// @param outputs Output logical tensor to be bound to this op. + /// @param verbose_name The string added as the op name. + op(size_t id, kind akind, const std::vector &inputs, + const std::vector &outputs, + const std::string &verbose_name = "") + : op(id, akind, verbose_name) { + for (const auto &input : inputs) { + error::wrap_c_api(dnnl_graph_op_add_input(get(), &(input.data)), + "adding input to the op failed"); + } + for (const auto &output : outputs) { + error::wrap_c_api(dnnl_graph_op_add_output(get(), &(output.data)), + "adding output to the op failed"); + } + } + + /// Adds an input logical tensor to the op. + /// + /// @param t Input logical tensor. + void add_input(const logical_tensor &t) { + error::wrap_c_api(dnnl_graph_op_add_input(get(), &(t.data)), + "adding input to the op failed"); + } + + /// Adds a vector of input logical tensors to the op. + /// + /// @param ts The list of input logical tensors. + void add_inputs(const std::vector &ts) { + for (const auto &t : ts) { + error::wrap_c_api(dnnl_graph_op_add_input(get(), &(t.data)), + "adding input to the op failed"); + } + } + + /// Adds an output logical tensor to the op. + /// + /// @param t Output logical tensor. + void add_output(const logical_tensor &t) { + error::wrap_c_api(dnnl_graph_op_add_output(get(), &(t.data)), + "adding output to the op failed"); + } + + /// Adds a vector of output logical tensors to the op. + /// + /// @param ts The list of output logical tensors. + void add_outputs(const std::vector &ts) { + for (const auto &t : ts) { + error::wrap_c_api(dnnl_graph_op_add_output(get(), &(t.data)), + "adding output to the op failed"); + } + } + + /// Sets the attribute according to the name and type (int64_t). + /// + /// @tparam Type Attribute's type. + /// @param name Attribute's name. + /// @param value The attribute's value. + /// @returns The Op self. + template ::value> = true> + op &set_attr(attr name, const Type &value) { + dnnl_graph_op_attr_t attr = convert_to_c(name); + error::wrap_c_api(dnnl_graph_op_set_attr_s64(get(), attr, &value, 1), + "could not set attribute to the op"); + return *this; + } + + /// Sets the attribute according to the name and type (float). + /// + /// @tparam Type Attribute's type. + /// @param name Attribute's name. + /// @param value The attribute's value. + /// @returns The Op self. + template ::value> = true> + op &set_attr(attr name, const Type &value) { + dnnl_graph_op_attr_t attr = convert_to_c(name); + error::wrap_c_api(dnnl_graph_op_set_attr_f32(get(), attr, &value, 1), + "could not set attribute to the op"); + return *this; + } + + /// Sets the attribute according to the name and type (bool). + /// + /// @tparam Type Attribute's type. + /// @param name Attribute's name. + /// @param value The attribute's value. + /// @returns The Op self. + template ::value> = true> + op &set_attr(attr name, const Type &value) { + dnnl_graph_op_attr_t attr = convert_to_c(name); + const uint8_t val = value; + error::wrap_c_api(dnnl_graph_op_set_attr_bool(get(), attr, &val, 1), + "could not set attribute to the op"); + return *this; + } + + /// Sets the attribute according to the name and type (string). + /// + /// @tparam Type Attribute's type. + /// @param name Attribute's name. + /// @param value The attribute's value. + /// @returns The Op self. + template ::value> = true> + op &set_attr(attr name, const Type &value) { + dnnl_graph_op_attr_t attr = convert_to_c(name); + error::wrap_c_api(dnnl_graph_op_set_attr_str( + get(), attr, value.c_str(), value.size()), + "could not set attribute to the op"); + return *this; + } + + /// Sets the attribute according to the name and type + /// (std::vector). + /// + /// @tparam Type Attribute's type. + /// @param name Attribute's name. + /// @param value The attribute's value. + /// @returns The Op self. + template >::value> = true> + op &set_attr(attr name, const Type &value) { + dnnl_graph_op_attr_t attr = convert_to_c(name); + error::wrap_c_api(dnnl_graph_op_set_attr_s64( + get(), attr, value.data(), value.size()), + "could not set attribute to the op"); + return *this; + } + + /// Sets the attribute according to the name and type (std::vector). + /// + /// @tparam Type Attribute's type. + /// @param name Attribute's name. + /// @param value The attribute's value. + /// @returns The Op self. + template >::value> = true> + op &set_attr(attr name, const Type &value) { + dnnl_graph_op_attr_t attr = convert_to_c(name); + error::wrap_c_api(dnnl_graph_op_set_attr_f32( + get(), attr, value.data(), value.size()), + "could not set attribute to the op"); + return *this; + } + +private: + dnnl_graph_op_kind_t convert_to_c(kind akind) { + return static_cast(akind); + } + + dnnl_graph_op_attr_t convert_to_c(attr aattr) { + return static_cast(aattr); + } +}; + +/// @} dnnl_graph_api_op + +/// @addtogroup dnnl_graph_api_partition Partition +/// +/// Partition represents a collection of operations and their input and output +/// logical tensors identified by library as the basic unit for compilation and +/// execution. +/// +/// @{ + +/// A partition object. +class partition : public partition_handle { +public: + /// Policy specifications for partitioning. + enum class policy { + /// Fusion policy returns partitions with typical post-op fusions, eg. + /// Convolution + ReLU or other element-wise operations or a chian of + /// post-ops. + fusion = dnnl_graph_partition_policy_fusion, + /// Debug policy doesn't not apply any fusions. It returns partitions + /// with single operations in each partition. The policy is useful when + /// users notice any bug or correctness issue in fusion policy. + debug = dnnl_graph_partition_policy_debug, + }; + + partition() = default; + + /// Constructs a partition object + /// + /// @param p A raw pointer to the C API handle + partition(dnnl_graph_partition_t p) { reset(p, false); } + + /// Creates a new partition with a given operator and engine kind. The API + /// is used to create a partition from an operation directly without + /// creating the graph and calling `get_partitions()`. The output partition + /// contains only one operation. + /// + /// @param aop An operation used to create the partition. + /// @param ekind Engine kind. + partition(const op &aop, engine::kind ekind) { + dnnl_graph_partition_t p = nullptr; + error::wrap_c_api(dnnl_graph_partition_create_with_op(&p, aop.get(), + static_cast(ekind)), + "could not create a partition with the op and engine kind"); + reset(p); + } + + /// Returns the number of operations contained in the partition. + /// + /// @returns Number of operations. + size_t get_ops_num() const { + size_t num {0}; + error::wrap_c_api(dnnl_graph_partition_get_op_num(get(), &num), + "could not get number of ops from the partition"); + return num; + } + + /// Returns all operation IDs contained in the partition. + /// + /// @returns An unordered set of operation IDs. + std::vector get_ops() const { + auto num = get_ops_num(); + std::vector ops(num); + + error::wrap_c_api(dnnl_graph_partition_get_ops(get(), num, ops.data()), + "could not get op ids from the partition"); + return ops; + } + + /// Returns the unique ID of the partition. Partition ID is generated by the + /// library internally. The ID can be used for debugging purpose or verbose. + /// + /// @returns ID of the partition. + size_t get_id() const { + size_t id {}; + error::wrap_c_api(dnnl_graph_partition_get_id(get(), &id), + "could not get id of the partition"); + return id; + } + + /// Compiles a partition with given input and output logical tensors. The + /// output logical tensors can contain unknown dimensions. For this case, + /// the compilation will deduce the output shapes according to input shapes. + /// The output logical tensors can also have layout type `any`. The + /// compilation will choose the optimal layout for output tensors. The + /// optimal layout will be represented as an opaque layout ID saved in the + /// output logical tensor. + /// + /// @param inputs A list of input logical tensors. + /// @param outputs A list of output logical tensors. + /// @param e The engine used to compile the partition. + /// @returns A compiled partition. + compiled_partition compile(const std::vector &inputs, + const std::vector &outputs, const engine &e) const { + if (!is_supported()) { + error::wrap_c_api(dnnl_invalid_arguments, + "could not compile an unsupported partition"); + } + + return compile_(inputs, outputs, e); + } + + /// Returns the supporting status of a partition. Some operations may not be + /// supported by the library under certain circumstances. During + /// partitioning stage, unsupported partitions will be returned to users + /// with each containing an unsupported operation. Users should check the + /// supporting status of a partition before transforming the computation + /// graph or compiling the partition. + /// + /// @returns @c true if this partition is supported or @c false if this + /// partition isn't supported by the library + bool is_supported() const { + uint8_t supported {0}; + error::wrap_c_api(dnnl_graph_partition_is_supported(get(), &supported), + "could not get supporting status of the partition"); + return supported != 0; + } + + /// Returns a list of input logical tensors from the partition. + /// + /// @returns A list of input logical tensors. + std::vector get_input_ports() const { + size_t num = 0; + error::wrap_c_api(dnnl_graph_partition_get_input_ports_num(get(), &num), + "could not get number of inputs of the partition"); + if (num == 0) return {}; + + std::vector c_inputs(num); + error::wrap_c_api(dnnl_graph_partition_get_input_ports( + get(), num, c_inputs.data()), + "could not get input logical tensors of the partition"); + + std::vector inputs; + inputs.reserve(num); + for (auto &c_lt : c_inputs) + inputs.emplace_back(c_lt); + return inputs; + } + + /// Returns a list of output logical tensors from the partition. + /// + /// @returns A list of output logical tensor. + std::vector get_output_ports() const { + size_t num = 0; + error::wrap_c_api( + dnnl_graph_partition_get_output_ports_num(get(), &num), + "cannot get number of outputs of the partition"); + if (num == 0) return {}; + + std::vector c_outputs(num); + error::wrap_c_api(dnnl_graph_partition_get_output_ports( + get(), num, c_outputs.data()), + "could not get output logical tensors of the partition"); + + std::vector outputs; + outputs.reserve(num); + for (auto &c_lt : c_outputs) + outputs.emplace_back(c_lt); + return outputs; + } + + /// Returns the engine kind of the partition + /// + /// @returns The engine kind + engine::kind get_engine_kind() const { + dnnl_engine_kind_t akind; + error::wrap_c_api(dnnl_graph_partition_get_engine_kind(get(), &akind), + "cannot get the engine kind from the partition"); + + return static_cast(akind); + } + +private: + compiled_partition compile_(const std::vector &inputs, + const std::vector &outputs, const engine &e) const { + std::vector c_inputs; + std::vector c_outputs; + + c_inputs.reserve(inputs.size()); + for (const auto &in : inputs) { + c_inputs.push_back(&(in.data)); + } + + c_outputs.reserve(outputs.size()); + for (const auto &out : outputs) { + c_outputs.push_back(&(out.data)); + } + + dnnl_graph_compiled_partition_t cpartitions = nullptr; + error::wrap_c_api( + dnnl_graph_compiled_partition_create(&cpartitions, get()), + "could not create compiled_partition"); + error::wrap_c_api(dnnl_graph_partition_compile(get(), cpartitions, + c_inputs.size(), c_inputs.data(), + c_outputs.size(), c_outputs.data(), e.get()), + "partition compile failed"); + + return compiled_partition(cpartitions); + } +}; + +/// @} dnnl_graph_api_partition + +/// @addtogroup dnnl_graph_api_graph Graph +/// +/// Graph represents a computational DAG with a set of operations. +/// #dnnl::graph::graph::add_op() adds an operation and its input and output +/// logical tensors into a graph. The library accumulates the operations and +/// logical tensors and constructs and validates the graph as an internal state. +/// A graph object is associated to a specific engine kind. The partitions +/// returned from the graph will inherit the engine kind of the graph. +/// +/// @{ + +/// A graph object. +class graph : public graph_handle { +public: + /// Constructs a graph with an engine kind. + /// + /// @param engine_kind Engine kind. + graph(engine::kind engine_kind) { + dnnl_graph_graph_t g = nullptr; + error::wrap_c_api( + dnnl_graph_graph_create(&g, convert_to_c(engine_kind)), + "could not create graph with engine kind"); + reset(g); + } + + /// Creates a new empty graph with an engine kind and a floating-point math + /// mode. All partitions returned from the graph will inherit the engine + /// kind and floating-point math mode. + /// + /// @param engine_kind Engine kind. + /// @param mode Floating-point math mode. + graph(engine::kind engine_kind, fpmath_mode mode) { + dnnl_graph_graph_t g = nullptr; + error::wrap_c_api( + dnnl_graph_graph_create_with_fpmath_mode( + &g, convert_to_c(engine_kind), convert_to_c(mode)), + "could not create graph with engine kind and math mode"); + reset(g); + } + + /// Adds an op into the graph to construct a computational DAG. The API will + /// return failure if the operator has already been added to the graph or + /// the operation cannot pass the schema check in the library (eg. input and + /// output numbers and data types, the attributes of the operation, etc.). + /// + /// @param op An operation to be added. + /// @param allow_exception A flag indicating whether the method is allowed + /// to throw an exception if it fails to add the op to the graph. + /// @returns #status::success or a status describing the error otherwise. + status add_op(const op &op, bool allow_exception = true) { + dnnl_status_t ret = dnnl_graph_add_op(get(), op.get()); + + if (allow_exception) { + error::wrap_c_api(ret, "could not add op to the graph"); + } + + return static_cast(ret); + } + + /// Finalizes a graph. It means users have finished adding operations into + /// the graph and the graph is ready for partitioning. Adding a new + /// operation into a finalized graph will return failures. Similarly, + /// partitioning on a un-finalized graph will also return failures. + void finalize() { + error::wrap_c_api(dnnl_graph_graph_finalize(get()), + "could not finalize the graph"); + } + + /// Checks if a graph is finalized. + /// + /// @return True if the graph is finalized or false if the graph is not + /// finalized. + bool is_finalized() const { + uint8_t ret = 0; + error::wrap_c_api(dnnl_graph_graph_is_finalized(get(), &ret), + "could not get the finalization status of the graph"); + + return ret != 0; + } + + /// Gets filtered partitions from a graph. Partitions will be claimed + /// internally according to the capability of the library, the engine kind + /// of the graph, and the policy. + /// + /// @param policy Partition policy, defaults to policy + /// #dnnl::graph::partition::policy::fusion. + /// @return A vector storing the partitions. + std::vector get_partitions( + partition::policy policy = partition::policy::fusion) { + if (!is_finalized()) { + error::wrap_c_api( + dnnl_invalid_graph, "the graph is not finalized yet"); + } + + error::wrap_c_api( + dnnl_graph_graph_filter(get(), + static_cast(policy)), + "could not filter the graph"); + + size_t num = 0; + error::wrap_c_api(dnnl_graph_graph_get_partition_num(get(), &num), + "could not get number of partitions from the graph"); + + // return early if there is no partitions in the graph. + if (num == 0) return {}; + + std::vector out_list; + out_list.reserve(num); + + std::vector partitions(num); + error::wrap_c_api( + dnnl_graph_graph_get_partitions(get(), num, partitions.data()), + "could not get partitions from the graph"); + + for (auto p : partitions) { + out_list.emplace_back(p); + } + + return out_list; + } + +private: + static dnnl_fpmath_mode_t convert_to_c(fpmath_mode mode) { + return static_cast(mode); + } + + static dnnl_engine_kind_t convert_to_c(engine::kind akind) { + return static_cast(akind); + } +}; + +/// @} dnnl_graph_api_graph + +/// @addtogroup dnnl_graph_api_compiled_partition_cache Compiled Partition Cache +/// +/// A set of functions that provide compiled partition cache control. +/// +/// @{ + +/// Returns the number of compiled partition that can be held in the compiled +/// partition cache at the same time. +inline int get_compiled_partition_cache_capacity() { + int result = 0; + error::wrap_c_api(dnnl_graph_get_compiled_partition_cache_capacity(&result), + "could not get compiled partition cache capacity"); + return result; +} + +/// @copydoc dnnl_graph_set_compiled_partition_cache_capacity(int capacity) +inline void set_compiled_partition_cache_capacity(int capacity) { + error::wrap_c_api( + dnnl_graph_set_compiled_partition_cache_capacity(capacity), + "could not set compiled partition cache capacity"); +} + +/// @} dnnl_graph_api_compiled_partition_cache + +/// @addtogroup dnnl_graph_api_constant_tensor_cache Constant Tensor Cache +/// +/// A set of functions that provide constant tensor cache control +/// +/// @{ + +/// Control the enabling or disabling of constant tensor cache. This API must be +/// called once before compilation stage. By default, constant tensor cache is +/// disabled in the library. +/// @note This API is deprecated and will be removed in future release, please +/// use the set_constant_tensor_cache_capacity API to disable +/// constant tensor cache by setting it's capacity to zero. +/// +/// @param flag Set to positive value to enable the cache and set to 0 to +/// disable the cache. Negative values are invalid. +inline void set_constant_tensor_cache(int flag) { + error::wrap_c_api(dnnl_graph_set_constant_tensor_cache(flag), + "fail to set constant tensor cache"); +} + +/// Return the enabling status of constant tensor cache. +/// @note This API is deprecated and will be removed in future release, please +/// use the get_constant_tensor_cache_capacity API to check the +/// enabling status by checking it's capacity. +inline int get_constant_tensor_cache() { + int result = 0; + error::wrap_c_api(dnnl_graph_get_constant_tensor_cache(&result), + "fail to get constant tensor cache"); + return result; +} + +/// Control the capacity for the constant tensor cache that used for specific +/// engine kind. This API is thread safe and can be called multiple times at +/// runtime. The capacity is set to zero by default which means the cache is +/// disabled. When calling this API, the corresponding cache will be flushed. +/// Setting capacity to 0 means to clear all cached tensors and disable cache. +/// Once the capacity limit is reached, no new tensors will be cached. If there +/// are multiple devices for an engine kind, the capacity set here is for each +/// device. +/// +/// @param kind The engine kind that the constant tensor cache used for. +/// @param size The constant tensor cache capacity size to set. +inline void set_constant_tensor_cache_capacity(engine::kind kind, size_t size) { + error::wrap_c_api(dnnl_graph_set_constant_tensor_cache_capacity( + static_cast(kind), size), + "fail to set constant tensor cache capacity"); +} + +/// Return the current capacity of constant tensor cache. +/// +/// @param kind The engine kind that the constant tensor cache used for. +inline size_t get_constant_tensor_cache_capacity(engine::kind kind) { + size_t size = 0; + error::wrap_c_api(dnnl_graph_get_constant_tensor_cache_capacity( + static_cast(kind), &size), + "fail to get constant tensor cache capacity"); + return size; +} + +/// @} dnnl_graph_constant_tensor_cache + +} // namespace graph +} // namespace dnnl + +/// @cond DO_NOT_DOCUMENT_THIS + +/// oneAPI namespace +// Contains the oneapi::dnnl namespace as an alias to the ::dnnl namespace. +namespace oneapi { +// Note: without this guard, doxygen warns of potentially recursive namespace +#ifndef DOXYGEN_SHOULD_SKIP_THIS +/// oneDNN alias namespace +namespace dnnl = ::dnnl; +#endif +} // namespace oneapi + +/// @endcond + +/// @} dnnl_graph_api + +/// @} dnnl_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_ocl.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_ocl.h new file mode 100644 index 0000000000000000000000000000000000000000..5183c8c9b8fcceba0ab0a9bdeaa0a1398696a744 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_ocl.h @@ -0,0 +1,144 @@ +/******************************************************************************* +* Copyright 2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_OCL_H +#define ONEAPI_DNNL_DNNL_GRAPH_OCL_H + +#include "oneapi/dnnl/dnnl_graph.h" + +/// @cond DO_NOT_DOCUMENT_THIS +// Set target version for OpenCL explicitly to suppress a compiler warning. +#ifndef CL_TARGET_OPENCL_VERSION +#define CL_TARGET_OPENCL_VERSION 120 +#endif + +#include +/// @endcond + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_graph_api +/// @{ + +/// @addtogroup dnnl_graph_api_interop +/// @{ + +/// @addtogroup dnnl_graph_api_ocl_interop +/// @{ + +/// Allocation call-back function interface for OpenCL. OpenCL allocator should +/// be used for OpenCL GPU runtime. The call-back should return a USM device +/// memory pointer. +/// +/// @param size Memory size in bytes for requested allocation +/// @param alignment The minimum alignment in bytes for the requested allocation +/// @param device A valid OpenCL device used to allocate +/// @param context A valid OpenCL context used to allocate +/// @returns The memory address of the requested USM allocation. +typedef void *(*dnnl_graph_ocl_allocate_f)( + size_t size, size_t alignment, cl_device_id device, cl_context context); + +/// Deallocation call-back function interface for OpenCL. OpenCL allocator +/// should be used for OpenCL runtime. The call-back should deallocate a USM +/// device memory returned by #dnnl_graph_ocl_allocate_f. The event should be +/// completed before deallocate the USM. +/// +/// @param buf The USM allocation to be released +/// @param device A valid OpenCL device the USM associated with +/// @param context A valid OpenCL context used to free the USM allocation +/// @param event A event which the USM deallocation depends on +typedef void (*dnnl_graph_ocl_deallocate_f)( + void *buf, cl_device_id device, cl_context context, cl_event event); + +/// Creates an allocator with the given allocation and deallocation call-back +/// function pointers. +/// +/// @param allocator Output allocator +/// @param ocl_malloc A pointer to OpenCL malloc function +/// @param ocl_free A pointer to OpenCL free function +/// @returns #dnnl_success on success and a status describing the +/// error otherwise. +dnnl_status_t DNNL_API dnnl_graph_ocl_interop_allocator_create( + dnnl_graph_allocator_t *allocator, dnnl_graph_ocl_allocate_f ocl_malloc, + dnnl_graph_ocl_deallocate_f ocl_free); + +/// This API is a supplement for existing oneDNN engine API: +/// dnnl_status_t DNNL_API dnnl_ocl_interop_engine_create( +/// dnnl_engine_t *engine, cl_device_id device, cl_context context); +/// +/// @param engine Output engine. +/// @param device Underlying OpenCL device to use for the engine. +/// @param context Underlying OpenCL context to use for the engine. +/// @param alloc Underlying allocator to use for the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_graph_ocl_interop_make_engine_with_allocator( + dnnl_engine_t *engine, cl_device_id device, cl_context context, + const_dnnl_graph_allocator_t alloc); + +/// This API is a supplement for existing oneDNN engine API: +/// dnnl_status_t DNNL_API dnnl_ocl_interop_engine_create_from_cache_blob( +/// dnnl_engine_t *engine, cl_device_id device, cl_context context, +/// size_t size, const uint8_t *cache_blob); +/// +/// @param engine Output engine. +/// @param device The OpenCL device that this engine will encapsulate. +/// @param context The OpenCL context (containing the device) that this +/// engine will use for all operations. +/// @param alloc Underlying allocator to use for the engine. +/// @param size Size of the cache blob in bytes. +/// @param cache_blob Cache blob of size @p size. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API +dnnl_graph_ocl_interop_make_engine_from_cache_blob_with_allocator( + dnnl_engine_t *engine, cl_device_id device, cl_context context, + const_dnnl_graph_allocator_t alloc, size_t size, + const uint8_t *cache_blob); + +/// Execute a compiled partition with OpenCL runtime. +/// +/// @param compiled_partition The handle of target compiled_partition. +/// @param stream The stream used for execution +/// @param num_inputs The number of input tensors +/// @param inputs A list of input tensors +/// @param num_outputs The number of output tensors +/// @param outputs A non-empty list of output tensors +/// @param deps Optional handle of list with `cl_event` dependencies. +/// @param ndeps Number of dependencies. +/// @param return_event The handle of cl_event. +/// @returns #dnnl_success on success and a status describing the +/// error otherwise. +dnnl_status_t DNNL_API dnnl_graph_ocl_interop_compiled_partition_execute( + const_dnnl_graph_compiled_partition_t compiled_partition, + dnnl_stream_t stream, size_t num_inputs, + const_dnnl_graph_tensor_t *inputs, size_t num_outputs, + const_dnnl_graph_tensor_t *outputs, const cl_event *deps, int ndeps, + cl_event *return_event); + +/// @} dnnl_graph_api_ocl_interop + +/// @} dnnl_graph_api_interop + +/// @} dnnl_graph_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_ocl.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_ocl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ba5b34a24405e5187e7b676f659c89627a1d2ef5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_ocl.hpp @@ -0,0 +1,147 @@ +/******************************************************************************* +* Copyright 2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_OCL_HPP +#define ONEAPI_DNNL_DNNL_GRAPH_OCL_HPP + +/// @cond DO_NOT_DOCUMENT_THIS +#include + +#include + +#include "oneapi/dnnl/dnnl_graph.hpp" +#include "oneapi/dnnl/dnnl_graph_ocl.h" +#include "oneapi/dnnl/dnnl_ocl.hpp" +/// @endcond + +/// @addtogroup dnnl_graph_api +/// @{ + +namespace dnnl { +namespace graph { + +/// @addtogroup dnnl_graph_api_interop Runtime interoperability API +/// API extensions to interact with the underlying run-time. +/// @{ + +/// @addtogroup dnnl_graph_api_ocl_interop OpenCL interoperability API API +/// extensions to interact with the underlying OpenCL run-time. +/// +/// @{ + +/// OpenCL interoperability namespace +namespace ocl_interop { + +/// Constructs an allocator from OpenCL malloc and free function pointer. OpenCL +/// allocator should be used for OpenCL GPU runtime. Currently, only device USM +/// allocator is supported. +/// +/// @param ocl_malloc The pointer to OpenCL malloc function +/// @param ocl_free The pointer to OpenCL free function +/// @returns Created allocator +inline allocator make_allocator(dnnl_graph_ocl_allocate_f ocl_malloc, + dnnl_graph_ocl_deallocate_f ocl_free) { + dnnl_graph_allocator_t c_allocator = nullptr; + error::wrap_c_api(dnnl_graph_ocl_interop_allocator_create( + &c_allocator, ocl_malloc, ocl_free), + "could not create allocator for opencl device"); + return allocator(c_allocator); +} + +/// Constructs an engine from an OpenCL device, an OpenCL context, and an +/// allocator. +/// +/// @param device A valid OpenCL device to construct the engine +/// @param context A valid OpenCL context to construct the engine +/// @param alloc An allocator to associate with the engine +/// @returns Created engine +inline engine make_engine_with_allocator( + cl_device_id device, cl_context context, const allocator &alloc) { + dnnl_engine_t c_engine; + error::wrap_c_api(dnnl_graph_ocl_interop_make_engine_with_allocator( + &c_engine, device, context, alloc.get()), + "could not make an engine with allocator"); + return engine(c_engine); +} + +/// Constructs an engine from an OpenCL device, an OpenCL context, an +/// allocator, and a serialized engine cache blob. +/// +/// @param device A valid OpenCL device to construct the engine +/// @param context A valid OpenCL context to construct the engine +/// @param alloc An allocator to associate with the engine +/// @param cache_blob Cache blob serialized beforehand +/// @returns Created engine +inline engine make_engine_with_allocator(cl_device_id device, + cl_context context, const allocator &alloc, + const std::vector &cache_blob) { + dnnl_engine_t c_engine; + error::wrap_c_api( + dnnl_graph_ocl_interop_make_engine_from_cache_blob_with_allocator( + &c_engine, device, context, alloc.get(), cache_blob.size(), + cache_blob.data()), + "could not make an engine with allocator from cache blob"); + return engine(c_engine); +} + +/// Executes a compiled partition in a specified stream and returns a OpenCL +/// event. +/// +/// @param c_partition Compiled partition to execute. +/// @param astream Stream object to run over +/// @param inputs Arguments map. +/// @param outputs Arguments map. +/// @param deps Optional vector with `cl_event` dependencies. +/// @returns Output event. +inline cl_event execute(compiled_partition &c_partition, stream &astream, + const std::vector &inputs, std::vector &outputs, + const std::vector &deps = {}) { + std::vector c_inputs; + c_inputs.reserve(inputs.size()); + for (auto &in : inputs) { + c_inputs.push_back(in.get()); + } + std::vector c_outputs; + c_outputs.reserve(outputs.size()); + for (auto &out : outputs) { + c_outputs.push_back(out.get()); + } + + const cl_event *c_deps = deps.empty() ? nullptr : deps.data(); + + cl_event ocl_event; + error::wrap_c_api( + dnnl_graph_ocl_interop_compiled_partition_execute(c_partition.get(), + astream.get(), c_inputs.size(), c_inputs.data(), + c_outputs.size(), c_outputs.data(), c_deps, + (int)deps.size(), &ocl_event), + "could not execute the compiled_partition on a specified opencl " + "stream"); + return ocl_event; +} + +} // namespace ocl_interop + +/// @} dnnl_graph_api_ocl_interop + +/// @} dnnl_graph_api_interop + +} // namespace graph +} // namespace dnnl + +/// @} dnnl_graph_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_sycl.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_sycl.h new file mode 100644 index 0000000000000000000000000000000000000000..cf247624feae9992417380f7c77d6f499e51d0a2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_sycl.h @@ -0,0 +1,94 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_SYCL_H +#define ONEAPI_DNNL_DNNL_GRAPH_SYCL_H + +#include "oneapi/dnnl/dnnl_graph.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_graph_api +/// @{ + +/// @addtogroup dnnl_graph_api_interop +/// @{ + +/// @addtogroup dnnl_graph_api_sycl_interop +/// @{ + +/// Allocation call-back function interface for SYCL. SYCL allocator should be +/// used for SYCL runtime and host allocator should be used for non-SYCL. The +/// call-back should return a USM device memory pointer. +typedef void *(*dnnl_graph_sycl_allocate_f)( + size_t size, size_t alignment, const void *dev, const void *context); + +/// Deallocation call-back function interface for SYCL. SYCL allocator should be +/// used for SYCL runtime and host allocator should be used for non-SYCL. The +/// call-back should deallocate a USM device memory returned by +/// #dnnl_graph_sycl_allocate_f. +typedef void (*dnnl_graph_sycl_deallocate_f)( + void *buf, const void *dev, const void *context, void *event); + +/// Creates an allocator with the given allocation and deallocation call-back +/// function pointers. +/// +/// @param allocator Output allocator +/// @param sycl_malloc A pointer to SYCL malloc function +/// @param sycl_free A pointer to SYCL free function +/// @returns #dnnl_success on success and a status describing the +/// error otherwise. +dnnl_status_t DNNL_API dnnl_graph_sycl_interop_allocator_create( + dnnl_graph_allocator_t *allocator, + dnnl_graph_sycl_allocate_f sycl_malloc, + dnnl_graph_sycl_deallocate_f sycl_free); + +/// This API is a supplement for existing onednn engine API. +dnnl_status_t DNNL_API dnnl_graph_sycl_interop_make_engine_with_allocator( + dnnl_engine_t *engine, const void *device, const void *context, + const_dnnl_graph_allocator_t alloc); + +/// Execute a compiled partition with sycl runtime. +/// +/// @param compiled_partition The handle of target compiled_partition. +/// @param stream The stream used for execution +/// @param num_inputs The number of input tensors +/// @param inputs A list of input tensors +/// @param num_outputs The number of output tensors +/// @param outputs A non-empty list of output tensors +/// @param deps Optional handle of list with `sycl::event` dependencies. +/// @param sycl_event The handle of sycl event. +/// @returns #dnnl_success on success and a status describing the +/// error otherwise. +dnnl_status_t DNNL_API dnnl_graph_sycl_interop_compiled_partition_execute( + const_dnnl_graph_compiled_partition_t compiled_partition, + dnnl_stream_t stream, size_t num_inputs, + const_dnnl_graph_tensor_t *inputs, size_t num_outputs, + const_dnnl_graph_tensor_t *outputs, const void *deps, void *sycl_event); + +/// @} dnnl_graph_api_sycl_interop + +/// @} dnnl_graph_api_interop + +/// @} dnnl_graph_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_sycl.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_sycl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b0824b4f366a34912b78db2929a90acc690a431d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_sycl.hpp @@ -0,0 +1,124 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_SYCL_HPP +#define ONEAPI_DNNL_DNNL_GRAPH_SYCL_HPP + +/// @cond DO_NOT_DOCUMENT_THIS +#include + +#if __has_include() +#include +#elif __has_include() +#include +#else +#error "Unsupported compiler" +#endif + +#include "oneapi/dnnl/dnnl_graph.hpp" +#include "oneapi/dnnl/dnnl_graph_sycl.h" +/// @endcond + +/// @addtogroup dnnl_graph_api +/// @{ + +namespace dnnl { +namespace graph { + +/// @addtogroup dnnl_graph_api_interop Runtime interoperability API +/// API extensions to interact with the underlying run-time. +/// @{ + +/// @addtogroup dnnl_graph_api_sycl_interop SYCL interoperability API +/// API extensions to interact with the underlying SYCL run-time. +/// +/// @{ + +/// SYCL interoperability namespace +namespace sycl_interop { + +/// Constructs an allocator from SYCL malloc and free function pointer. SYCL +/// allocator should be used for SYCL runtime and host allocator should be used +/// for non-SYCL. Currently, only device USM allocator is supported. +/// +/// @param sycl_malloc The pointer to SYCL malloc function +/// @param sycl_free The pointer to SYCL free function +/// @returns Created allocator +inline allocator make_allocator(dnnl_graph_sycl_allocate_f sycl_malloc, + dnnl_graph_sycl_deallocate_f sycl_free) { + dnnl_graph_allocator_t c_allocator = nullptr; + error::wrap_c_api(dnnl_graph_sycl_interop_allocator_create( + &c_allocator, sycl_malloc, sycl_free), + "could not create allocator for sycl device"); + return allocator(c_allocator); +} + +inline engine make_engine_with_allocator(const sycl::device &adevice, + const sycl::context &acontext, const allocator &alloc) { + dnnl_engine_t c_engine; + error::wrap_c_api( + dnnl_graph_sycl_interop_make_engine_with_allocator(&c_engine, + static_cast(&adevice), + static_cast(&acontext), alloc.get()), + "could not make an engine with allocator"); + return engine(c_engine); +} + +/// Executes a compiled partition in a specified stream and returns a SYCL +/// event. +/// +/// @param c_partition Compiled partition to execute. +/// @param astream Stream object to run over +/// @param inputs Arguments map. +/// @param outputs Arguments map. +/// @param deps Optional vector with `sycl::event` dependencies. +/// @returns Output event. +inline sycl::event execute(compiled_partition &c_partition, stream &astream, + const std::vector &inputs, std::vector &outputs, + const std::vector &deps = {}) { + std::vector c_inputs; + c_inputs.reserve(inputs.size()); + for (auto &in : inputs) { + c_inputs.push_back(in.get()); + } + std::vector c_outputs; + c_outputs.reserve(outputs.size()); + for (auto &out : outputs) { + c_outputs.push_back(out.get()); + } + + sycl::event sycl_event; + error::wrap_c_api(dnnl_graph_sycl_interop_compiled_partition_execute( + c_partition.get(), astream.get(), c_inputs.size(), + c_inputs.data(), c_outputs.size(), + c_outputs.data(), &deps, &sycl_event), + "could not execute the compiled_partition on a specified sycl " + "stream"); + return sycl_event; +} + +} // namespace sycl_interop + +/// @} dnnl_graph_api_sycl_interop + +/// @} dnnl_graph_api_interop + +} // namespace graph +} // namespace dnnl + +/// @} dnnl_graph_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_types.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_types.h new file mode 100644 index 0000000000000000000000000000000000000000..e77e27706c064352a0c87d1b8b5a703be8003412 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_graph_types.h @@ -0,0 +1,465 @@ +/******************************************************************************* + * Copyright 2020-2024 Intel Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *******************************************************************************/ + +/// @file +/// C API definitions + +#ifndef ONEAPI_DNNL_DNNL_GRAPH_TYPES_H +#define ONEAPI_DNNL_DNNL_GRAPH_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include + +#include "oneapi/dnnl/dnnl_common_types.h" +/// @endcond + +/// @addtogroup dnnl_graph_api +/// @{ + +/// @addtogroup dnnl_graph_api_logical_tensor +/// @{ + +/// A wildcard value for number of dimensions which is unknown at a tensor or +/// operation creation time. +#define DNNL_GRAPH_UNKNOWN_NDIMS -1 + +/// A wildcard value for dimensions that are unknown at a tensor or operation +/// creation time. +#define DNNL_GRAPH_UNKNOWN_DIM INT64_MIN + +/// Layout type specification +typedef enum { + /// Undefined layout type + dnnl_graph_layout_type_undef = 0, + /// Any means to let the library to decide the layout for a tensor during + /// partition compilation. + dnnl_graph_layout_type_any = 1, + /// Strided means that the layout of a tensor is determined by the strides + /// field in the logical tensor. + dnnl_graph_layout_type_strided = 2, + /// Opaque means that the layout of a tensor is the library specific. + /// Usually, an opaque layout is generated by a partition which is compiled + /// with layout type any. + dnnl_graph_layout_type_opaque = 3, +} dnnl_graph_layout_type_t; + +/// Logical tensor property +typedef enum { + /// Undefined tensor property + dnnl_graph_tensor_property_undef = 0, + /// Variable means the tensor may be changed during computation or between + /// different iterations. + dnnl_graph_tensor_property_variable = 1, + /// Constant means the tensor will keep unchanged during computation and + /// between different iterations. It's useful for the library to apply + /// optimizations for constant tensors or cache constant tensors inside the + /// library. For example, constant weight tensors in inference scenarios. + dnnl_graph_tensor_property_constant = 2, +} dnnl_graph_tensor_property_t; + +/// Logical tensor. It is based on an ID, a number of dimensions, dimensions +/// themselves, element data type, tensor property and tensor memory layout. +typedef struct { + /// Unique id of each logical tensor. The library uses logical tensor IDs to + /// build up the connections between operations if the output of one + /// operation has the same ID as the input of another operation. + size_t id; + + /// Number of dimensions. -1 means unknown (DNNL_GRAPH_UNKNOWN_NDIMS). 0 is + /// used to define scalar tensor. + int ndims; + + /// Size of each dimension. #DNNL_GRAPH_UNKNOWN_DIM means the size of that + /// dimension is unknown. 0 is used to define zero-dimension tensor. The + /// library supports to deduce output shapes according to input shapes + /// during compilation. Unlike memory descriptor in oneDNN primitive API, + /// the order of dimensions is not defined in logical tensor. It is defined + /// by the operations which respect the order through the attributes + /// #dnnl_graph_op_attr_data_format or #dnnl_graph_op_attr_weights_format. + /// For example, for a Convolution with `data_format=NXC`, it means the + /// first element of dims of activation tensor is mini-batch size, the last + /// effective element of dims is channel size, and other elements between + /// them are spatial dimensions. + dnnl_dims_t dims; + + /// Data type of the tensor elements. + dnnl_data_type_t data_type; + + /// Property type of the tensor. + dnnl_graph_tensor_property_t property; + + /// Layout type of the tensor. + dnnl_graph_layout_type_t layout_type; + union { + /// The field is valid when `layout_type` is + /// #dnnl_graph_layout_type_strided. #DNNL_GRAPH_UNKNOWN_DIM means the + /// stride of the dimension is unknown. The library currently doesn't + /// support other negative stride values. + dnnl_dims_t strides; + + /// The field is valid when `layout_type` is + /// #dnnl_graph_layout_type_opaque. An opaque layout ID is usually + /// generated by a partition which is compiled with layout type any. + size_t layout_id; + } layout; +} dnnl_graph_logical_tensor_t; + +/// @} dnnl_graph_api_logical_tensor + +/// @addtogroup dnnl_graph_api_partition +/// @{ + +/// Policy specifications for partitioning +typedef enum { + /// Fusion policy returns partitions with typical post-op fusions, eg. + /// Convolution + ReLU or other element-wise operations or a chian of + /// post-ops. + dnnl_graph_partition_policy_fusion = 1, + /// Debug policy doesn't not apply any fusions. It returns partitions with + /// single operation in each partition. The policy is useful when users + /// notice any bug or correctness issue in fusion policy. + dnnl_graph_partition_policy_debug = 2, +} dnnl_graph_partition_policy_t; + +/// An opaque structure to describe a partition. +struct dnnl_graph_partition; + +/// A partition handle. +typedef struct dnnl_graph_partition *dnnl_graph_partition_t; + +/// A constant partition handle. +typedef const struct dnnl_graph_partition *const_dnnl_graph_partition_t; + +/// @} dnnl_graph_api_partition + +/// @addtogroup dnnl_graph_api_graph +/// @{ + +/// An opaque structure to describe a graph. +struct dnnl_graph_graph; + +/// A graph handle. +typedef struct dnnl_graph_graph *dnnl_graph_graph_t; + +/// A constant graph handle. +typedef const struct dnnl_graph_graph *const_dnnl_graph_graph_t; + +/// @} + +/// @addtogroup dnnl_graph_api_op +/// @{ + +/// Kinds of operations +typedef enum { + dnnl_graph_op_abs, + dnnl_graph_op_abs_backward, + dnnl_graph_op_add, + dnnl_graph_op_avg_pool, + dnnl_graph_op_avg_pool_backward, + dnnl_graph_op_batch_norm_backward, + dnnl_graph_op_batch_norm_forward_training, + dnnl_graph_op_batch_norm_inference, + dnnl_graph_op_bias_add, + dnnl_graph_op_bias_add_backward, + dnnl_graph_op_clamp, + dnnl_graph_op_clamp_backward, + dnnl_graph_op_concat, + dnnl_graph_op_convolution, + dnnl_graph_op_convolution_backward_data, + dnnl_graph_op_convolution_backward_weights, + dnnl_graph_op_conv_transpose, + dnnl_graph_op_conv_transpose_backward_data, + dnnl_graph_op_conv_transpose_backward_weights, + dnnl_graph_op_dequantize, + dnnl_graph_op_divide, + dnnl_graph_op_dynamic_dequantize, + dnnl_graph_op_dynamic_quantize, + dnnl_graph_op_elu, + dnnl_graph_op_elu_backward, + dnnl_graph_op_end, + dnnl_graph_op_exp, + dnnl_graph_op_gelu, + dnnl_graph_op_gelu_backward, + dnnl_graph_op_hard_swish, + dnnl_graph_op_hard_swish_backward, + dnnl_graph_op_interpolate, + dnnl_graph_op_interpolate_backward, + dnnl_graph_op_layer_norm, + dnnl_graph_op_layer_norm_backward, + dnnl_graph_op_leaky_relu, + dnnl_graph_op_log, + dnnl_graph_op_log_softmax, + dnnl_graph_op_log_softmax_backward, + dnnl_graph_op_matmul, + dnnl_graph_op_maximum, + dnnl_graph_op_max_pool, + dnnl_graph_op_max_pool_backward, + dnnl_graph_op_minimum, + dnnl_graph_op_mish, + dnnl_graph_op_mish_backward, + dnnl_graph_op_multiply, + dnnl_graph_op_prelu, + dnnl_graph_op_prelu_backward, + dnnl_graph_op_quantize, + dnnl_graph_op_reciprocal, + dnnl_graph_op_reduce_l1, + dnnl_graph_op_reduce_l2, + dnnl_graph_op_reduce_max, + dnnl_graph_op_reduce_mean, + dnnl_graph_op_reduce_min, + dnnl_graph_op_reduce_prod, + dnnl_graph_op_reduce_sum, + dnnl_graph_op_relu, + dnnl_graph_op_relu_backward, + dnnl_graph_op_reorder, + dnnl_graph_op_round, + dnnl_graph_op_sigmoid, + dnnl_graph_op_sigmoid_backward, + dnnl_graph_op_softmax, + dnnl_graph_op_softmax_backward, + dnnl_graph_op_softplus, + dnnl_graph_op_softplus_backward, + dnnl_graph_op_sqrt, + dnnl_graph_op_sqrt_backward, + dnnl_graph_op_square, + dnnl_graph_op_squared_difference, + dnnl_graph_op_static_reshape, + dnnl_graph_op_static_transpose, + dnnl_graph_op_subtract, + dnnl_graph_op_tanh, + dnnl_graph_op_tanh_backward, + dnnl_graph_op_type_cast, + dnnl_graph_op_wildcard, + dnnl_graph_op_hard_sigmoid, + dnnl_graph_op_hard_sigmoid_backward, + dnnl_graph_op_select, + dnnl_graph_op_pow, + dnnl_graph_op_last_symbol, +} dnnl_graph_op_kind_t; + +/// Attributes of operations +typedef enum { + /// Undefined op attribute. + dnnl_graph_op_attr_undef = 0, + + // float32 attributes. The value of these attributes can be any single + // float32 number. + + /// Specifies an alpha attribute to an op. + dnnl_graph_op_attr_alpha = 0x1, + /// Specifies an beta attribute to an op. + dnnl_graph_op_attr_beta, + /// Specifies an epsilon attribute to an op. + dnnl_graph_op_attr_epsilon, + /// Specifies a max attribute to an op. + dnnl_graph_op_attr_max, + ///Specifies a min attribute to an op. + dnnl_graph_op_attr_min, + /// Specifies a momentum attribute to an op. + dnnl_graph_op_attr_momentum, + + // float32 vector attributes. The value of these attributes can be a vector + // of float32 numbers. + + /// Specifies a scales attribute to an op. + dnnl_graph_op_attr_scales = 0x20, + + // int64_t attributes. The value of these attributes can be any single int64 + // number. + + /// Specifies an axis attribute to an op. + dnnl_graph_op_attr_axis = 0x30, + /// Specifies a begin_norm_axis attribute to an op. + dnnl_graph_op_attr_begin_norm_axis, + /// Specifies a groups attribute to an op. + dnnl_graph_op_attr_groups, + + // int64_t vector attributes. The value of these attributes can be a vector + // of int64 numbers. + + /// Specifies an axes attribute to an op. + dnnl_graph_op_attr_axes = 0x40, + /// Specifies a dilations attribute to an op. + dnnl_graph_op_attr_dilations, + /// Specifies an dst_shape attribute to an op. + dnnl_graph_op_attr_dst_shape, + /// Specifies a kernel attribute to an op. + dnnl_graph_op_attr_kernel, + /// Specifies an order attribute to an op. + dnnl_graph_op_attr_order, + /// Specifies an output_padding attribute to an op. + dnnl_graph_op_attr_output_padding, + /// Specifies a pads_begin attribute to an op. + dnnl_graph_op_attr_pads_begin, + /// Specifies a pads_end attribute to an op. + dnnl_graph_op_attr_pads_end, + /// Specifies a shape attribute to an op. + dnnl_graph_op_attr_shape, + /// Specifies a sizes attribute to an op. + dnnl_graph_op_attr_sizes, + /// Specifies a input_shape attribute to an op. + dnnl_graph_op_attr_src_shape, + /// Specifies a strides attribute to an op. + dnnl_graph_op_attr_strides, + /// Specifies a weight_shape attribute to an op. + dnnl_graph_op_attr_weights_shape, + /// Specifies a zps attribute to an op. + dnnl_graph_op_attr_zps, + + // bool attributes. The value of these attributes can be any single bool + // value. + + /// Specifies an exclude_pad attribute to an op. + dnnl_graph_op_attr_exclude_pad = 0x60, + /// Specifies a keep_dims attribute to an op. + dnnl_graph_op_attr_keep_dims, + /// Specifies a keep_stats attribute to an op. + dnnl_graph_op_attr_keep_stats, + /// Specifies a per_channel_broadcast attribute to an op. + dnnl_graph_op_attr_per_channel_broadcast, + /// Specifies a special_zero attribute to an op. + dnnl_graph_op_attr_special_zero, + /// Specifies a transpose_a attribute to an op. + dnnl_graph_op_attr_transpose_a, + /// Specifies a transpose_b attribute to an op. + dnnl_graph_op_attr_transpose_b, + /// Specifies an use_affine attribute to an op. + dnnl_graph_op_attr_use_affine, + /// Specifies an use_dst attribute to an op. + dnnl_graph_op_attr_use_dst, + + // string attributes. The value of these attributes can be a string. + + /// Specifies an auto_broadcast attribute to an op. The value can be "none" + /// or "numpy". + dnnl_graph_op_attr_auto_broadcast = 0x80, + /// Specifies an auto_pad attribute to an op. The value can be "none", + /// "same_upper", "same_lower", or "valid". + dnnl_graph_op_attr_auto_pad, + /// Specifies an coordinate_transformation_mode attribute to an op. The + /// value can be "half_pixel" or "align_corners". The attribute is defined + /// for Interpolate operations. + dnnl_graph_op_attr_coordinate_transformation_mode, + /// Specifies a data_format of an op. The value can be "NCX" or "NXC". + dnnl_graph_op_attr_data_format, + /// Specifies a mode attribute of an op. The value can be "nearest", + /// "linear", "bilinear", or "trilinear". The attribute is defined for + /// Interpolate operations. + dnnl_graph_op_attr_mode, + /// Specifies a qtype attribute to an op. The value can be "per_channel" or + /// "per_tensor". The attribute is defined for quantization operations. + dnnl_graph_op_attr_qtype, + /// Specifies a rounding_type attribute to an op. The value can be "ceil" or + /// "floor". + dnnl_graph_op_attr_rounding_type, + /// Specifies a weights_format of an op. The value can be "OIX", "XIO", + /// "IOX", or "XOI". Different operations may support different values. + dnnl_graph_op_attr_weights_format, + + /// Specifies the end of all above exteral attributes for check. + dnnl_graph_op_attr_end = 0xFF, +} dnnl_graph_op_attr_t; + +/// An opaque structure to describe an operation. +struct dnnl_graph_op; + +/// An operation handle. +typedef struct dnnl_graph_op *dnnl_graph_op_t; + +/// A constant operation handle. +typedef const struct dnnl_graph_op *const_dnnl_graph_op_t; + +/// @} dnnl_graph_api_op + +/// @addtogroup dnnl_graph_api_allocator +/// @{ + +/// Allocation call-back function interface for host. For SYCL allocator, see +/// #dnnl_graph_sycl_allocate_f. +typedef void *(*dnnl_graph_host_allocate_f)(size_t size, size_t alignment); + +/// Deallocation call-back function interface for host. For SYCL allocator, see +/// #dnnl_graph_sycl_deallocate_f. +typedef void (*dnnl_graph_host_deallocate_f)(void *); + +/// An opaque structure to describe an allocator. +struct dnnl_graph_allocator; + +/// An allocator handle. +typedef struct dnnl_graph_allocator *dnnl_graph_allocator_t; + +/// A constant allocator handle. +typedef const struct dnnl_graph_allocator *const_dnnl_graph_allocator_t; + +/// @} dnnl_graph_api_allocator + +/// @addtogroup dnnl_graph_api_compiled_partition +/// @{ + +/// In-place pair definition. It can queried from a compiled partition +/// indicating that an input and an output of the partition can share the same +/// memory buffer for computation. In-place computation helps to reduce the +/// memory footprint and improves cache locality. But since the library may not +/// have a global view of user's application, it's possible that the tensor with +/// `input_id` is used at other places in user's computation graph. In this +/// case, the user should take the in-place pair as a hint and pass a different +/// memory buffer for output tensor to avoid overwriting the input memory buffer +/// which will probably cause unexpected incorrect results. +typedef struct { + /// The id of input tensor + size_t input_id; + + /// The id of output tensor + size_t output_id; +} dnnl_graph_inplace_pair_t; + +/// An opaque structure to describe a compiled partition. +struct dnnl_graph_compiled_partition; + +/// A compiled partition handle. +typedef struct dnnl_graph_compiled_partition *dnnl_graph_compiled_partition_t; + +/// A constant compiled partition handle. +typedef const struct dnnl_graph_compiled_partition + *const_dnnl_graph_compiled_partition_t; + +/// @} dnnl_graph_api_compiled_partition + +/// @addtogroup dnnl_graph_api_tensor +/// @{ + +/// An opaque structure to describe a tensor. +struct dnnl_graph_tensor; + +/// A tensor handle. +typedef struct dnnl_graph_tensor *dnnl_graph_tensor_t; + +/// A constant tensor handle. +typedef const struct dnnl_graph_tensor *const_dnnl_graph_tensor_t; + +/// @} dnnl_graph_api_tensor + +/// @} dnnl_graph_api + +#ifdef __cplusplus +} +#endif +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl.h new file mode 100644 index 0000000000000000000000000000000000000000..6300bb7459fbd6d4504d9dda7a2a3b42709a0877 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl.h @@ -0,0 +1,247 @@ +/******************************************************************************* +* Copyright 2020-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_OCL_H +#define ONEAPI_DNNL_DNNL_OCL_H + +#include "oneapi/dnnl/dnnl.h" + +#include "oneapi/dnnl/dnnl_ocl_types.h" + +/// @cond DO_NOT_DOCUMENT_THIS +// Set target version for OpenCL explicitly to suppress a compiler warning. +#ifndef CL_TARGET_OPENCL_VERSION +#define CL_TARGET_OPENCL_VERSION 120 +#endif + +#include +/// @endcond + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_ocl_interop +/// @{ + +/// Creates a memory object. +/// +/// Unless @p handle is equal to DNNL_MEMORY_NONE or DNNL_MEMORY_ALLOCATE, the +/// constructed memory object will have the underlying buffer set. In this +/// case, the buffer will be initialized as if: +/// - dnnl_memory_set_data_handle() has been called, if @p memory_kind is equal +/// to dnnl_ocl_interop_usm, or +/// - dnnl_ocl_interop_memory_set_mem_object() has been called, if @p memory_kind +/// is equal to dnnl_ocl_interop_buffer. +/// +/// @param memory Output memory object. +/// @param memory_desc Memory descriptor. +/// @param engine Engine to use. +/// @param memory_kind Memory allocation kind to specify the type of handle. +/// @param handle Handle of the memory buffer to use as an underlying storage. +/// - A USM pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. Requires @p memory_kind to be equal to +/// dnnl_ocl_interop_usm. +/// - An OpenCL buffer. In this case the library doesn't own the buffer. +/// Requires @p memory_kind be equal to be equal to dnnl_ocl_interop_buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer that corresponds to the memory allocation kind +/// @p memory_kind for the memory object. In this case the library +/// owns the buffer. +/// - The DNNL_MEMORY_NONE specific value. Instructs the library to +/// create memory object without an underlying buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_memory_create(dnnl_memory_t *memory, + const_dnnl_memory_desc_t memory_desc, dnnl_engine_t engine, + dnnl_ocl_interop_memory_kind_t memory_kind, void *handle); + +/// Returns the memory allocation kind associated with a memory object. +/// +/// @param memory Memory to query. +/// @param memory_kind Output underlying memory allocation kind of the memory +/// object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_memory_get_memory_kind( + const_dnnl_memory_t memory, + dnnl_ocl_interop_memory_kind_t *memory_kind); + +/// Returns an OpenCL memory object associated with a memory object. +/// +/// @param memory Memory object. +/// @param mem_object Output OpenCL memory object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_memory_get_mem_object( + const_dnnl_memory_t memory, cl_mem *mem_object); + +/// Sets OpenCL memory object associated with a memory object. +/// +/// For behavioral details, see dnnl_memory_set_data_handle(). +/// +/// @param memory Memory object. +/// @param mem_object OpenCL memory object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_memory_set_mem_object( + dnnl_memory_t memory, cl_mem mem_object); + +/// Retrieves a cache blob ID for the OpenCL device. +/// +/// @warning +/// This API is intended to be used with +/// #dnnl_ocl_interop_engine_get_cache_blob() and +/// #dnnl_ocl_interop_engine_create_from_cache_blob(). The returned cache +/// blob ID can only be used as an ID of the cache blob returned by +/// #dnnl_ocl_interop_engine_get_cache_blob(). +/// +/// @note The cache blob ID can be empty (@p size will be 0 and +/// @p cache_blob_id will be nullptr) if oneDNN doesn't have anything to +/// put in the cache blob. (#dnnl_ocl_interop_engine_get_cache_blob will +/// return an empty cache blob). +/// +/// @param device An OpenCL device. +/// @param size Size of the cache blob ID in bytes. +/// @param cache_blob_id Cache blob id of size @p size. If +/// the @p cache_blob_id is nullptr then the size of the cache blob ID is +/// returned in @p size. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_engine_get_cache_blob_id( + cl_device_id device, size_t *size, uint8_t *cache_blob_id); + +/// Retrieves a cache blob associated with the given engine. +/// +/// @note The cache blob can be empty (@p size will be 0 and @p cache_blob +/// will be nullptr) if oneDNN doesn't have anything to put in the cache +/// blob. It's the user's responsibility to check whether it's empty +/// prior to passing it to +/// #dnnl_ocl_interop_engine_create_from_cache_blob(). +/// +/// @param engine Engine to query for the cache blob. +/// @param size Size of the cache blob in bytes. +/// @param cache_blob Cache blob of size @p size. If the @p cache_blob is +/// nullptr then the size of the cache blob is returned in @p size. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_engine_get_cache_blob( + dnnl_engine_t engine, size_t *size, uint8_t *cache_blob); + +/// Creates an engine from the given cache blob. +/// +/// @param engine Output engine. +/// @param device The OpenCL device that this engine will encapsulate. +/// @param context The OpenCL context (containing the device) that this +/// engine will use for all operations. +/// @param size Size of the cache blob in bytes. +/// @param cache_blob Cache blob of size @p size. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_engine_create_from_cache_blob( + dnnl_engine_t *engine, cl_device_id device, cl_context context, + size_t size, const uint8_t *cache_blob); + +/// Creates an engine associated with an OpenCL device and an OpenCL context. +/// +/// @param engine Output engine. +/// @param device Underlying OpenCL device to use for the engine. +/// @param context Underlying OpenCL context to use for the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_engine_create( + dnnl_engine_t *engine, cl_device_id device, cl_context context); + +/// Returns the OpenCL context associated with an engine. +/// +/// @param engine Engine to query. +/// @param context Output underlying OpenCL context of the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_engine_get_context( + dnnl_engine_t engine, cl_context *context); + +/// Returns the OpenCL device associated with an engine. +/// +/// @param engine Engine to query. +/// @param device Output underlying OpenCL device of the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_get_device( + dnnl_engine_t engine, cl_device_id *device); + +/// Creates an execution stream for a given engine associated with +/// an OpenCL command queue. +/// +/// @param stream Output execution stream. +/// @param engine Engine to create the execution stream on. +/// @param queue OpenCL command queue to use. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_stream_create( + dnnl_stream_t *stream, dnnl_engine_t engine, cl_command_queue queue); + +/// Returns the OpenCL command queue associated with an execution stream. +/// +/// @param stream Execution stream to query. +/// @param queue Output OpenCL command queue. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_stream_get_command_queue( + dnnl_stream_t stream, cl_command_queue *queue); + +/// Executes computations specified by the primitive in a specified stream and +/// returns an OpenCL event. +/// +/// @param primitive Primitive to execute. +/// @param stream Stream to use. +/// @param nargs Number of arguments. +/// @param args Array of arguments. Each argument is an +/// pair. The index is one of the `DNNL_ARG_*` +/// values such as `DNNL_ARG_SRC`. Unless runtime shapes are used (see +/// #DNNL_RUNTIME_DIM_VAL), the memory object must have the same memory +/// descriptor as that returned by +/// #dnnl_primitive_desc_query_md(#dnnl_query_exec_arg_md, index). +/// @param deps A pointer to a vector of size @p ndeps that contains +/// dependencies. +/// @param ndeps Number of dependencies. +/// @param return_event Output event. It's the user's responsibility to +/// manage lifetime of the event. Can be NULL. When @p stream is in-order +/// NULL will be returned. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_ocl_interop_primitive_execute( + const_dnnl_primitive_t primitive, dnnl_stream_t stream, int nargs, + const dnnl_exec_arg_t *args, const cl_event *deps, int ndeps, + cl_event *return_event); + +/// @} dnnl_api_ocl_interop + +/// @} dnnl_api_interop + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c2466bc82760ae852e13a6d36cdb4017e8172dc2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl.hpp @@ -0,0 +1,338 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_OCL_HPP +#define ONEAPI_DNNL_DNNL_OCL_HPP + +#include "oneapi/dnnl/dnnl.hpp" + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include +#include +#include +#include +#include +#include + +#include "oneapi/dnnl/dnnl_ocl.h" + +#include +/// @endcond + +/// @addtogroup dnnl_api +/// @{ + +namespace dnnl { + +/// @addtogroup dnnl_api_interop Runtime interoperability API +/// API extensions to interact with the underlying run-time. +/// @{ + +/// @addtogroup dnnl_api_ocl_interop OpenCL interoperability API +/// API extensions to interact with the underlying OpenCL run-time. +/// +/// @sa @ref dev_guide_opencl_interoperability in developer guide +/// @{ + +/// OpenCL interoperability namespace +namespace ocl_interop { + +/// Memory allocation kind. +enum class memory_kind { + /// USM (device, shared, host, or unknown) memory allocation kind. + usm = dnnl_ocl_interop_usm, + /// Buffer memory allocation kind - default. + buffer = dnnl_ocl_interop_buffer, +}; + +/// Converts a memory allocation kind enum value from C++ API to C API type. +/// +/// @param akind C++ API memory allocation kind enum value. +/// @returns Corresponding C API memory allocation kind enum value. +inline dnnl_ocl_interop_memory_kind_t convert_to_c(memory_kind akind) { + return static_cast(akind); +} + +/// Returns the cache blob ID of the OpenCL device. +/// +/// @warning +/// This API is intended to be used with +/// #dnnl::ocl_interop::get_engine_cache_blob() and +/// #dnnl::ocl_interop::make_engine(cl_device_id, cl_context, const std::vector &). +/// The returned cache blob ID can only be used as an ID of the cache blob +/// returned by #dnnl::ocl_interop::get_engine_cache_blob(). +/// +/// @note The cache blob ID can be empty (@p size will be 0 and +/// @p cache_blob_id will be nullptr) if oneDNN doesn't have anything to +/// put in the cache blob. (#dnnl_ocl_interop_engine_get_cache_blob will +/// return an empty cache blob). +/// +/// @param device An OpenCL device. +/// @returns A vector containing the cache blob ID. +inline std::vector get_engine_cache_blob_id(cl_device_id device) { + size_t size = 0; + error::wrap_c_api( + dnnl_ocl_interop_engine_get_cache_blob_id(device, &size, nullptr), + "could not get an engine cache blob id size"); + + std::vector cache_blob_id(size); + error::wrap_c_api(dnnl_ocl_interop_engine_get_cache_blob_id( + device, &size, cache_blob_id.data()), + "could not get an engine cache blob id"); + return cache_blob_id; +} + +/// Returns a cache blob for the engine. +/// +/// @note The cache blob vector can be empty if oneDNN doesn't have anything +/// to put in the cache blob. It's the user's responsibility to check +/// whether it's empty prior to passing it to +/// #dnnl::ocl_interop::make_engine(cl_device_id, cl_context, const std::vector &) +/// +/// @param aengine Engine to query for the cache blob. +/// @returns Vector containing the cache blob. +inline std::vector get_engine_cache_blob(const engine &aengine) { + size_t size = 0; + error::wrap_c_api(dnnl_ocl_interop_engine_get_cache_blob( + aengine.get(), &size, nullptr), + "could not get an engine cache blob size"); + + std::vector cache_blob(size); + error::wrap_c_api(dnnl_ocl_interop_engine_get_cache_blob( + aengine.get(), &size, cache_blob.data()), + "could not get an engine cache blob"); + return cache_blob; +} + +/// Constructs an engine from the given cache blob. +/// +/// @param device The OpenCL device that this engine will encapsulate. +/// @param context The OpenCL context (containing the device) that this +/// engine will use for all operations. +/// @param cache_blob Cache blob. +/// @returns An engine. +inline engine make_engine(cl_device_id device, cl_context context, + const std::vector &cache_blob) { + dnnl_engine_t c_engine; + error::wrap_c_api( + dnnl_ocl_interop_engine_create_from_cache_blob(&c_engine, device, + context, cache_blob.size(), cache_blob.data()), + "could not create an engine from cache blob"); + return engine(c_engine); +} + +/// Constructs an engine from OpenCL device and context objects. +/// +/// @param device The OpenCL device that this engine will encapsulate. +/// @param context The OpenCL context (containing the device) that this +/// engine will use for all operations. +/// @returns An engine. +inline engine make_engine(cl_device_id device, cl_context context) { + dnnl_engine_t c_engine; + error::wrap_c_api( + dnnl_ocl_interop_engine_create(&c_engine, device, context), + "could not create an engine"); + return engine(c_engine); +} + +/// Returns OpenCL context associated with the engine. +/// +/// @param aengine An engine. +/// @returns Underlying OpenCL context. +inline cl_context get_context(const engine &aengine) { + cl_context context = nullptr; + error::wrap_c_api( + dnnl_ocl_interop_engine_get_context(aengine.get(), &context), + "could not get an OpenCL context from an engine"); + return context; +} + +/// Returns OpenCL device associated with the engine. +/// +/// @param aengine An engine. +/// @returns Underlying OpenCL device. +inline cl_device_id get_device(const engine &aengine) { + cl_device_id device = nullptr; + error::wrap_c_api(dnnl_ocl_interop_get_device(aengine.get(), &device), + "could not get an OpenCL device from an engine"); + return device; +} + +/// Constructs an execution stream for the specified engine and OpenCL queue. +/// +/// @param aengine Engine to create the stream on. +/// @param queue OpenCL queue to use for the stream. +/// @returns An execution stream. +inline stream make_stream(const engine &aengine, cl_command_queue queue) { + dnnl_stream_t c_stream; + error::wrap_c_api( + dnnl_ocl_interop_stream_create(&c_stream, aengine.get(), queue), + "could not create a stream"); + return stream(c_stream); +} + +/// Returns OpenCL queue object associated with the execution stream. +/// +/// @param astream An execution stream. +/// @returns Underlying OpenCL queue. +inline cl_command_queue get_command_queue(const stream &astream) { + cl_command_queue queue = nullptr; + error::wrap_c_api( + dnnl_ocl_interop_stream_get_command_queue(astream.get(), &queue), + "could not get an OpenCL command queue from a stream"); + return queue; +} + +/// Returns the OpenCL memory object associated with the memory object. +/// +/// @param amemory A memory object. +/// @returns Underlying OpenCL memory object. +inline cl_mem get_mem_object(const memory &amemory) { + cl_mem mem_object; + error::wrap_c_api( + dnnl_ocl_interop_memory_get_mem_object(amemory.get(), &mem_object), + "could not get OpenCL buffer object from a memory object"); + return mem_object; +} + +/// Sets the OpenCL memory object associated with the memory object. +/// +/// For behavioral details see memory::set_data_handle(). +/// +/// @param amemory A memory object. +/// @param mem_object OpenCL cl_mem object to use as the underlying +/// storage. It must have at least get_desc().get_size() bytes +/// allocated. +inline void set_mem_object(memory &amemory, cl_mem mem_object) { + error::wrap_c_api( + dnnl_ocl_interop_memory_set_mem_object(amemory.get(), mem_object), + "could not set OpenCL buffer object from a memory object"); +} + +/// Returns the memory allocation kind associated with a memory object. +/// +/// @param amemory A memory object. +/// +/// @returns The underlying memory allocation kind of the memory object. +inline memory_kind get_memory_kind(const memory &amemory) { + dnnl_ocl_interop_memory_kind_t ckind; + error::wrap_c_api( + dnnl_ocl_interop_memory_get_memory_kind(amemory.get(), &ckind), + "could not get memory kind"); + return static_cast(ckind); +} + +/// Creates a memory object. +/// +/// Unless @p handle is equal to DNNL_MEMORY_NONE or DNNL_MEMORY_ALLOCATE, the +/// constructed memory object will have the underlying buffer set. In this +/// case, the buffer will be initialized as if: +/// - dnnl::memory::set_data_handle() had been called, if @p memory_kind is +/// equal to dnnl::ocl_interop::memory_kind::usm, or +/// - dnnl::ocl_interop::set_mem_object() has been called, if @p memory_kind is +/// equal to dnnl::ocl_interop::memory_kind::buffer. +/// +/// @param memory_desc Memory descriptor. +/// @param aengine Engine to use. +/// @param kind Memory allocation kind to specify the type of handle. +/// @param handle Handle of the memory buffer to use as an underlying storage. +/// - A USM pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. Requires @p memory_kind to be equal to +/// dnnl::ocl_interop::memory_kind::usm. +/// - An OpenCL buffer. In this case the library doesn't own the buffer. +/// Requires @p memory_kind be equal to be equal to +/// dnnl::ocl_interop::memory_kind::buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer that corresponds to the memory allocation kind +/// @p memory_kind for the memory object. In this case the library +/// owns the buffer. +/// - The DNNL_MEMORY_NONE specific value. Instructs the library to +/// create memory object without an underlying buffer. +/// +/// @returns Created memory object. +inline memory make_memory(const memory::desc &memory_desc, + const engine &aengine, memory_kind kind, + void *handle = DNNL_MEMORY_ALLOCATE) { + dnnl_memory_t c_memory; + error::wrap_c_api( + dnnl_ocl_interop_memory_create(&c_memory, memory_desc.get(), + aengine.get(), convert_to_c(kind), handle), + "could not create a memory"); + return memory(c_memory); +} + +/// Constructs a memory object from an OpenCL buffer. +/// +/// @param memory_desc Memory descriptor. +/// @param aengine Engine to use. +/// @param mem_object An OpenCL buffer to use. +/// +/// @returns Created memory object. +inline memory make_memory(const memory::desc &memory_desc, + const engine &aengine, cl_mem mem_object) { + memory amemory(memory_desc, aengine, DNNL_MEMORY_NONE); + set_mem_object(amemory, mem_object); + return amemory; +} + +/// Executes computations specified by the primitive in a specified stream and +/// returns a SYCL event. +/// +/// Arguments are passed via an arguments map containing +/// pairs. The index must be one of the `DNNL_ARG_*` +/// values such as `DNNL_ARG_SRC`, and the memory must have a memory descriptor +/// matching the one returned by +/// #dnnl::primitive_desc::query_md(#query::exec_arg_md, index) unless using +/// dynamic shapes (see #DNNL_RUNTIME_DIM_VAL). +/// +/// @param aprimitive Primitive to execute. +/// @param astream Stream object. The stream must belong to the same engine +/// as the primitive. +/// @param args Arguments map. +/// @param deps Optional vector with `cl_event` dependencies. +/// +/// @returns Output event. It's the user's responsibility to manage lifetime +/// of the event. +inline cl_event execute(const dnnl::primitive &aprimitive, + const stream &astream, const std::unordered_map &args, + const std::vector &deps = {}) { + std::vector c_args; + c_args.reserve(args.size()); + for (const auto &a : args) + c_args.push_back({a.first, a.second.get()}); + + const cl_event *c_deps = deps.empty() ? nullptr : deps.data(); + + cl_event return_event; + error::wrap_c_api(dnnl_ocl_interop_primitive_execute(aprimitive.get(), + astream.get(), (int)c_args.size(), c_args.data(), + c_deps, (int)deps.size(), &return_event), + "could not execute a primitive"); + return return_event; +} + +} // namespace ocl_interop + +/// @} dnnl_api_ocl_interop + +/// @} dnnl_api_interop + +} // namespace dnnl + +/// @} dnnl_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl_types.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..39a216650a6894152a5b3d7af84d157ca283a202 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ocl_types.h @@ -0,0 +1,51 @@ +/******************************************************************************* +* Copyright 2021 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_OCL_TYPES_H +#define ONEAPI_DNNL_DNNL_OCL_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_ocl_interop +/// @{ + +/// Memory allocation kind. +typedef enum { + /// USM (device, shared, host, or unknown) memory allocation kind. + dnnl_ocl_interop_usm, + /// Buffer memory allocation kind - default. + dnnl_ocl_interop_buffer, +} dnnl_ocl_interop_memory_kind_t; + +/// @} dnnl_api_ocl_interop + +/// @} dnnl_api_interop + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl.h new file mode 100644 index 0000000000000000000000000000000000000000..ed61d92435bb78b56b88a975732303101a26c086 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl.h @@ -0,0 +1,169 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_SYCL_H +#define ONEAPI_DNNL_DNNL_SYCL_H + +#include "oneapi/dnnl/dnnl.h" + +#include "oneapi/dnnl/dnnl_sycl_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_sycl_interop +/// @{ + +/// Creates an engine associated with a SYCL device and a SYCL context. +/// +/// @param engine Output engine. +/// @param device Pointer to the SYCL device to use for the engine. +/// @param context Pointer to the SYCL context to use for the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_engine_create( + dnnl_engine_t *engine, const void *device, const void *context); + +/// Returns the SYCL context associated with an engine. +/// +/// @param engine Engine to query. +/// @param context Pointer to the underlying SYCL context of the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_engine_get_context( + dnnl_engine_t engine, void **context); + +/// Returns the SYCL device associated with an engine. +/// +/// @param engine Engine to query. +/// @param device Pointer to the underlying SYCL device of the engine. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_engine_get_device( + dnnl_engine_t engine, void **device); + +/// Creates a memory object. +/// +/// Unless @p handle is equal to DNNL_MEMORY_NONE or DNNL_MEMORY_ALLOCATE, the +/// constructed memory object will have the underlying buffer set. In this +/// case, the buffer will be initialized as if: +/// - dnnl_memory_set_data_handle() had been called, if @p memory_kind is equal +/// to dnnl_sycl_interop_usm, or +/// - dnnl_sycl_interop_memory_set_buffer() has been called, if @p memory_kind +/// is equal to dnnl_sycl_interop_buffer. +/// +/// @param memory Output memory object. +/// @param memory_desc Memory descriptor. +/// @param engine Engine to use. +/// @param memory_kind Memory allocation kind to specify the type of handle. +/// @param handle Handle of the memory buffer to use as an underlying storage. +/// - A USM pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. Requires @p memory_kind to be equal to +/// dnnl_sycl_interop_usm. +/// - A pointer to SYCL buffer. In this case the library doesn't own the +/// buffer. Requires @p memory_kind be equal to be equal to +/// dnnl_sycl_interop_buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer that corresponds to the memory allocation kind +/// @p memory_kind for the memory object. In this case the library +/// owns the buffer. +/// - The DNNL_MEMORY_NONE specific value. Instructs the library to +/// create memory object without an underlying buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_memory_create(dnnl_memory_t *memory, + const_dnnl_memory_desc_t memory_desc, dnnl_engine_t engine, + dnnl_sycl_interop_memory_kind_t memory_kind, void *handle); + +/// Returns the memory allocation kind associated with a memory object. +/// +/// @param memory Memory to query. +/// @param memory_kind Output underlying memory allocation kind of the memory +/// object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_memory_get_memory_kind( + const_dnnl_memory_t memory, + dnnl_sycl_interop_memory_kind_t *memory_kind); + +/// Sets a SYCL buffer for a memory object. +/// +/// @param memory Memory object. +/// @param buffer SYCL buffer to be set in the memory object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_memory_set_buffer( + dnnl_memory_t memory, void *buffer); + +/// Creates an execution stream for a given engine associated with a SYCL +/// queue. +/// +/// @param stream Output execution stream. +/// @param engine Engine to create the execution stream on. +/// @param queue SYCL queue to use. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_stream_create( + dnnl_stream_t *stream, dnnl_engine_t engine, void *queue); + +/// Returns the SYCL queue associated with an execution stream. +/// +/// @param stream Execution stream to query. +/// @param queue Output SYCL command queue. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_stream_get_queue( + dnnl_stream_t stream, void **queue); + +/// Executes computations specified by the primitive in a specified stream and +/// returns a SYCL event. +/// +/// @param primitive Primitive to execute. +/// @param stream Stream to use. +/// @param nargs Number of arguments. +/// @param args Array of arguments. Each argument is an +/// pair. The index is one of the `DNNL_ARG_*` +/// values such as `DNNL_ARG_SRC`. Unless runtime shapes are used (see +/// #DNNL_RUNTIME_DIM_VAL), the memory object must have the same memory +/// descriptor as that returned by +/// #dnnl_primitive_desc_query_md(#dnnl_query_exec_arg_md, index). +/// @param deps A pointer to std::vector that contains +/// dependencies. +/// @param return_event Output event. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_sycl_interop_primitive_execute( + const_dnnl_primitive_t primitive, dnnl_stream_t stream, int nargs, + const dnnl_exec_arg_t *args, const void *deps, void *return_event); + +/// @} dnnl_api_sycl_interop + +/// @} dnnl_api_interop + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b9ddc876ed850882360e05831a4214537a99aff0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl.hpp @@ -0,0 +1,308 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_SYCL_HPP +#define ONEAPI_DNNL_DNNL_SYCL_HPP + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#elif __has_include() +#include +#else +#error "Unsupported compiler" +#endif + +#include "oneapi/dnnl/dnnl.hpp" +#include "oneapi/dnnl/dnnl_sycl.h" + +/// @endcond + +/// @addtogroup dnnl_api +/// @{ + +namespace dnnl { + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_sycl_interop SYCL interoperability API +/// API extensions to interact with the underlying SYCL run-time. +/// +/// @sa @ref dev_guide_dpcpp_interoperability in developer guide +/// @{ + +/// SYCL interoperability namespace +namespace sycl_interop { + +/// Memory allocation kind. +enum class memory_kind { + /// USM (device, shared, host, or unknown) memory allocation kind - default. + usm = dnnl_sycl_interop_usm, + /// Buffer memory allocation kind. + buffer = dnnl_sycl_interop_buffer, +}; + +/// Converts a memory allocation kind enum value from C++ API to C API type. +/// +/// @param akind C++ API memory allocation kind enum value. +/// @returns Corresponding C API memory allocation kind enum value. +inline dnnl_sycl_interop_memory_kind_t convert_to_c(memory_kind akind) { + return static_cast(akind); +} + +/// Constructs an engine from SYCL device and context objects. +/// +/// @param adevice SYCL device. +/// @param acontext SYCL context. +/// +/// @returns Created engine. +inline engine make_engine( + const sycl::device &adevice, const sycl::context &acontext) { + dnnl_engine_t aengine; + error::wrap_c_api(dnnl_sycl_interop_engine_create(&aengine, + static_cast(&adevice), + static_cast(&acontext)), + "could not create an engine"); + return engine(aengine); +} + +/// Returns the SYCL context associated with an engine. +/// +/// @param aengine Engine to query. +/// +/// @returns The underlying SYCL device of the engine. +inline sycl::context get_context(const engine &aengine) { + void *ctx_ptr; + error::wrap_c_api( + dnnl_sycl_interop_engine_get_context(aengine.get(), &ctx_ptr), + "could not get a context handle"); + auto ctx = *static_cast(ctx_ptr); + return ctx; +} + +/// Returns the SYCL device associated with an engine. +/// +/// @param aengine Engine to query. +/// +/// @returns The underlying SYCL context of the engine. +inline sycl::device get_device(const engine &aengine) { + void *dev_ptr; + error::wrap_c_api( + dnnl_sycl_interop_engine_get_device(aengine.get(), &dev_ptr), + "could not get a device handle"); + auto dev = *static_cast(dev_ptr); + return dev; +} + +/// Creates an execution stream for a given engine associated with a SYCL +/// queue. +/// +/// @param aengine Engine object to use for the stream. +/// @param aqueue SYCL queue to use for the stream. +/// +/// @returns An execution stream. +inline stream make_stream(const engine &aengine, sycl::queue &aqueue) { + dnnl_stream_t astream; + error::wrap_c_api( + dnnl_sycl_interop_stream_create(&astream, aengine.get(), &aqueue), + "could not create a stream"); + return stream(astream); +} + +/// Returns the SYCL queue associated with an execution stream. +/// +/// @param astream Execution stream to query. +/// +/// @returns SYCL queue object. +inline sycl::queue get_queue(const stream &astream) { + void *queue_ptr; + error::wrap_c_api( + dnnl_sycl_interop_stream_get_queue(astream.get(), &queue_ptr), + "could not get a stream handle"); + auto queue = *static_cast(queue_ptr); + return queue; +} + +/// Returns the SYCL buffer associated with a memory object. +/// +/// Throws an exception if the memory allocation kind associated with the +/// memory object is not equal to dnnl::sycl_interop::memory_kind::buffer. +/// +/// @tparam T Type of the requested buffer. +/// @tparam ndims Number of dimensions of the requested buffer. +/// @param amemory Memory object. +/// +/// @returns SYCL buffer associated with the memory object. +template +sycl::buffer get_buffer(const memory &amemory) { + static_assert(ndims == 1, "only 1D buffers supported"); + + // XXX: workaround: when CPU runtime is not SYCL and amemory was created + // for CPU engine `get_buffer` should return an error. Use interop API to + // implement the check. + dnnl_sycl_interop_memory_kind_t ckind; + error::wrap_c_api( + dnnl_sycl_interop_memory_get_memory_kind(amemory.get(), &ckind), + "could not get SYCL buffer object"); + + void *handle_ptr; + error::wrap_c_api(dnnl_memory_get_data_handle(amemory.get(), &handle_ptr), + "could not get SYCL buffer object"); + + // XXX: workaround: zero-range buffer cannot be constructed. + if (!handle_ptr) return sycl::buffer(sycl::range<1>(1)); + + auto &buf_u8 = *static_cast *>(handle_ptr); + + auto range = sycl::range<1>(buf_u8.byte_size() / sizeof(T)); + return buf_u8.reinterpret(range); +} + +/// Sets SYCL buffer associated with a memory object. +/// +/// @tparam T Type of the buffer. +/// @tparam ndims Number of dimensions of the buffer. +/// @param amemory Memory object to change. +/// @param abuffer SYCL buffer. +template +void set_buffer(memory &amemory, sycl::buffer &abuffer) { + auto range = sycl::range<1>(abuffer.byte_size()); + auto buf_u8 = abuffer.template reinterpret(range); + error::wrap_c_api(dnnl_sycl_interop_memory_set_buffer( + amemory.get(), static_cast(&buf_u8)), + "could not set SYCL buffer object"); +} + +/// Returns the memory allocation kind associated with a memory object. +/// +/// @param amemory A memory object. +/// +/// @returns The underlying memory allocation kind of the memory object. +inline memory_kind get_memory_kind(const memory &amemory) { + dnnl_sycl_interop_memory_kind_t ckind; + error::wrap_c_api( + dnnl_sycl_interop_memory_get_memory_kind(amemory.get(), &ckind), + "could not get memory kind"); + return static_cast(ckind); +} + +/// Creates a memory object. +/// +/// Unless @p handle is equal to DNNL_MEMORY_NONE or DNNL_MEMORY_ALLOCATE, the +/// constructed memory object will have the underlying buffer set. In this +/// case, the buffer will be initialized as if: +/// - dnnl::memory::set_data_handle() had been called, if @p memory_kind is +/// equal to dnnl::sycl_interop::memory_kind::usm, or +/// - dnnl::sycl_interop::set_buffer() has been called, if @p memory_kind is +/// equal to dnnl::sycl_interop::memory_kind::buffer. +/// +/// @param memory_desc Memory descriptor. +/// @param aengine Engine to use. +/// @param kind Memory allocation kind to specify the type of handle. +/// @param handle Handle of the memory buffer to use as an underlying storage. +/// - A USM pointer to the user-allocated buffer. In this case the library +/// doesn't own the buffer. Requires @p memory_kind to be equal to +/// dnnl::sycl_interop::memory_kind::usm. +/// - A pointer to SYCL buffer. In this case the library doesn't own the +/// buffer. Requires @p memory_kind be equal to be equal to +/// dnnl::sycl_interop::memory_kind::buffer. +/// - The DNNL_MEMORY_ALLOCATE special value. Instructs the library to +/// allocate the buffer that corresponds to the memory allocation kind +/// @p memory_kind for the memory object. In this case the library +/// owns the buffer. +/// - The DNNL_MEMORY_NONE specific value. Instructs the library to +/// create memory object without an underlying buffer. +/// +/// @returns Created memory object. +inline memory make_memory(const memory::desc &memory_desc, + const engine &aengine, memory_kind kind, + void *handle = DNNL_MEMORY_ALLOCATE) { + dnnl_memory_t c_memory; + error::wrap_c_api( + dnnl_sycl_interop_memory_create(&c_memory, memory_desc.get(), + aengine.get(), convert_to_c(kind), handle), + "could not create a memory"); + return memory(c_memory); +} + +/// Constructs a memory object from a SYCL buffer. +/// +/// @param memory_desc Memory descriptor. +/// @param aengine Engine to use. +/// @param abuffer A SYCL buffer to use. +/// +/// @returns Created memory object. +template +memory make_memory(const memory::desc &memory_desc, const engine &aengine, + sycl::buffer &abuffer) { + memory amemory(memory_desc, aengine, DNNL_MEMORY_NONE); + set_buffer(amemory, abuffer); + return amemory; +} + +/// Executes computations specified by the primitive in a specified stream and +/// returns a SYCL event. +/// +/// Arguments are passed via an arguments map containing +/// pairs. The index must be one of the `DNNL_ARG_*` +/// values such as `DNNL_ARG_SRC`, and the memory must have a memory descriptor +/// matching the one returned by +/// #dnnl::primitive_desc::query_md(#query::exec_arg_md, index) unless using +/// dynamic shapes (see #DNNL_RUNTIME_DIM_VAL). +/// +/// @param aprimitive Primitive to execute. +/// @param astream Stream object. The stream must belong to the same engine +/// as the primitive. +/// @param args Arguments map. +/// @param deps Optional vector with `sycl::event` dependencies. +/// +/// @returns Output event. +inline sycl::event execute(const dnnl::primitive &aprimitive, + const stream &astream, const std::unordered_map &args, + const std::vector &deps = {}) { + std::vector c_args; + c_args.reserve(args.size()); + for (const auto &a : args) + c_args.push_back({a.first, a.second.get()}); + + sycl::event return_event; + error::wrap_c_api( + dnnl_sycl_interop_primitive_execute(aprimitive.get(), astream.get(), + (int)c_args.size(), c_args.data(), &deps, &return_event), + "could not execute a primitive"); + return return_event; +} + +} // namespace sycl_interop + +/// @} dnnl_api_sycl_interop + +/// @} dnnl_api_interop + +} // namespace dnnl + +/// @} dnnl_api + +#endif // DNNL_SYCL_HPP diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl_types.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..8314075ef0007b1ea17d7826202232530085e9cb --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_sycl_types.h @@ -0,0 +1,51 @@ +/******************************************************************************* +* Copyright 2020-2021 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_SYCL_TYPES_H +#define ONEAPI_DNNL_DNNL_SYCL_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_sycl_interop +/// @{ + +/// Memory allocation kind. +typedef enum { + /// USM (device, shared, host, or unknown) memory allocation kind - default. + dnnl_sycl_interop_usm, + /// Buffer memory allocation kind. + dnnl_sycl_interop_buffer, +} dnnl_sycl_interop_memory_kind_t; + +/// @} dnnl_api_sycl_interop + +/// @} dnnl_api_interop + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool.h new file mode 100644 index 0000000000000000000000000000000000000000..d6110930cfeaf51834e6a44a2444253de1df3874 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool.h @@ -0,0 +1,118 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_THREADPOOL_H +#define ONEAPI_DNNL_DNNL_THREADPOOL_H + +#include "oneapi/dnnl/dnnl_config.h" +#include "oneapi/dnnl/dnnl_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_threadpool_interop +/// @{ + +/// Creates an execution stream with specified threadpool. +/// +/// @sa @ref dev_guide_threadpool +/// +/// @param stream Output execution stream. +/// @param engine Engine to create the execution stream on. +/// @param threadpool Pointer to an instance of a C++ class that implements +/// dnnl::threapdool_iface interface. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_threadpool_interop_stream_create( + dnnl_stream_t *stream, dnnl_engine_t engine, void *threadpool); + +/// Returns a threadpool to be used by the execution stream. +/// +/// @sa @ref dev_guide_threadpool +/// +/// @param astream Execution stream. +/// @param threadpool Output pointer to an instance of a C++ class that +/// implements dnnl::threapdool_iface interface. Set to NULL if the +/// stream was created without threadpool. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_threadpool_interop_stream_get_threadpool( + dnnl_stream_t astream, void **threadpool); + +/// Sets the maximum concurrency assumed by oneDNN when outside a +/// parallel call. +/// +/// @param max_concurrency The maximum concurrency assumed by oneDNN +/// when outside a parallel call. This is a threadlocal setting. +/// @returns #dnnl_success on success and a status describing the +/// error otherwise. +dnnl_status_t DNNL_API dnnl_threadpool_interop_set_max_concurrency( + int max_concurrency); + +/// Gets the maximum concurrency assumed by oneDNN when outside a +/// parallel call. +/// +/// @param max_concurrency The maximum concurrency assumed by oneDNN +/// when outside a parallel call. This is a threadlocal setting. +/// @returns #dnnl_success on success and a status describing the +/// error otherwise. +dnnl_status_t DNNL_API dnnl_threadpool_interop_get_max_concurrency( + int *max_concurrency); + +/// @copydoc dnnl_sgemm() +/// @param threadpool A pointer to a threadpool interface (only when built with +/// the THREADPOOL CPU runtime). +dnnl_status_t DNNL_API dnnl_threadpool_interop_sgemm(char transa, char transb, + dnnl_dim_t M, dnnl_dim_t N, dnnl_dim_t K, float alpha, const float *A, + dnnl_dim_t lda, const float *B, dnnl_dim_t ldb, float beta, float *C, + dnnl_dim_t ldc, void *threadpool); + +/// @copydoc dnnl_gemm_u8s8s32() +/// @param threadpool A pointer to a threadpool interface (only when built with +/// the THREADPOOL CPU runtime). +dnnl_status_t DNNL_API dnnl_threadpool_interop_gemm_u8s8s32(char transa, + char transb, char offsetc, dnnl_dim_t M, dnnl_dim_t N, dnnl_dim_t K, + float alpha, const uint8_t *A, dnnl_dim_t lda, uint8_t ao, + const int8_t *B, dnnl_dim_t ldb, int8_t bo, float beta, int32_t *C, + dnnl_dim_t ldc, const int32_t *co, void *threadpool); + +/// @copydoc dnnl_gemm_s8s8s32() +/// @param threadpool A pointer to a threadpool interface (only when built with +/// the THREADPOOL CPU runtime). +dnnl_status_t DNNL_API dnnl_threadpool_interop_gemm_s8s8s32(char transa, + char transb, char offsetc, dnnl_dim_t M, dnnl_dim_t N, dnnl_dim_t K, + float alpha, const int8_t *A, dnnl_dim_t lda, int8_t ao, + const int8_t *B, dnnl_dim_t ldb, int8_t bo, float beta, int32_t *C, + dnnl_dim_t ldc, const int32_t *co, void *threadpool); + +/// @} dnnl_api_threadpool_interop + +/// @} dnnl_api_interop + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e3ebd0ff251062dbaf9bb49772664a2928421878 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool.hpp @@ -0,0 +1,113 @@ +/******************************************************************************* +* Copyright 2020-2022 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_THREADPOOL_HPP +#define ONEAPI_DNNL_DNNL_THREADPOOL_HPP + +#include "oneapi/dnnl/dnnl.hpp" +#include "oneapi/dnnl/dnnl_threadpool.h" + +#include "oneapi/dnnl/dnnl_threadpool_iface.hpp" + +/// @addtogroup dnnl_api +/// @{ + +namespace dnnl { + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_threadpool_interop Threadpool interoperability API +/// API extensions to interact with the underlying Threadpool run-time. +/// @{ + +/// Threadpool interoperability namespace +namespace threadpool_interop { + +/// Constructs an execution stream for the specified engine and threadpool. +/// +/// @sa @ref dev_guide_threadpool +/// +/// @param aengine Engine to create the stream on. +/// @param threadpool Pointer to an instance of a C++ class that implements +/// dnnl::threapdool_iface interface. +/// @returns An execution stream. +inline dnnl::stream make_stream( + const dnnl::engine &aengine, threadpool_iface *threadpool) { + dnnl_stream_t c_stream; + dnnl::error::wrap_c_api(dnnl_threadpool_interop_stream_create( + &c_stream, aengine.get(), threadpool), + "could not create stream"); + return dnnl::stream(c_stream); +} + +/// Returns the pointer to a threadpool that is used by an execution stream. +/// +/// @sa @ref dev_guide_threadpool +/// +/// @param astream An execution stream. +/// @returns Output pointer to an instance of a C++ class that implements +/// dnnl::threapdool_iface interface or NULL if the stream was created +/// without threadpool. +inline threadpool_iface *get_threadpool(const dnnl::stream &astream) { + void *tp; + dnnl::error::wrap_c_api( + dnnl_threadpool_interop_stream_get_threadpool(astream.get(), &tp), + "could not get stream threadpool"); + return static_cast(tp); +} + +/// @copydoc dnnl_threadpool_interop_sgemm() +inline status sgemm(char transa, char transb, dnnl_dim_t M, dnnl_dim_t N, + dnnl_dim_t K, float alpha, const float *A, dnnl_dim_t lda, + const float *B, dnnl_dim_t ldb, float beta, float *C, dnnl_dim_t ldc, + threadpool_iface *threadpool) { + return static_cast(dnnl_threadpool_interop_sgemm(transa, transb, M, + N, K, alpha, A, lda, B, ldb, beta, C, ldc, threadpool)); +} +/// @copydoc dnnl_threadpool_interop_gemm_u8s8s32() +inline status gemm_u8s8s32(char transa, char transb, char offsetc, dnnl_dim_t M, + dnnl_dim_t N, dnnl_dim_t K, float alpha, const uint8_t *A, + dnnl_dim_t lda, uint8_t ao, const int8_t *B, dnnl_dim_t ldb, int8_t bo, + float beta, int32_t *C, dnnl_dim_t ldc, const int32_t *co, + threadpool_iface *threadpool) { + return static_cast(dnnl_threadpool_interop_gemm_u8s8s32(transa, + transb, offsetc, M, N, K, alpha, A, lda, ao, B, ldb, bo, beta, C, + ldc, co, threadpool)); +} + +/// @copydoc dnnl_threadpool_interop_gemm_s8s8s32() +inline status gemm_s8s8s32(char transa, char transb, char offsetc, dnnl_dim_t M, + dnnl_dim_t N, dnnl_dim_t K, float alpha, const int8_t *A, + dnnl_dim_t lda, int8_t ao, const int8_t *B, dnnl_dim_t ldb, int8_t bo, + float beta, int32_t *C, dnnl_dim_t ldc, const int32_t *co, + threadpool_iface *threadpool) { + return static_cast(dnnl_threadpool_interop_gemm_s8s8s32(transa, + transb, offsetc, M, N, K, alpha, A, lda, ao, B, ldb, bo, beta, C, + ldc, co, threadpool)); +} + +} // namespace threadpool_interop + +/// @} dnnl_api_threadpool_interop + +/// @} dnnl_api_interop + +} // namespace dnnl + +/// @} dnnl_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool_iface.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool_iface.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fb5b6084901bf7a641c4607a7576bf103eee4403 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_threadpool_iface.hpp @@ -0,0 +1,72 @@ +/******************************************************************************* +* Copyright 2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_THREADPOOL_IFACE_HPP +#define ONEAPI_DNNL_DNNL_THREADPOOL_IFACE_HPP + +#include + +/// @addtogroup dnnl_api +/// @{ + +namespace dnnl { + +/// @addtogroup dnnl_api_interop +/// @{ + +/// @addtogroup dnnl_api_threadpool_interop +/// @{ + +namespace threadpool_interop { + +/// Abstract threadpool interface. The users are expected to subclass this +/// interface and pass an object to the library during CPU stream creation or +/// directly in case of BLAS functions. +struct threadpool_iface { + /// Returns the number of worker threads. + virtual int get_num_threads() const = 0; + + /// Returns true if the calling thread belongs to this threadpool. + virtual bool get_in_parallel() const = 0; + + /// Submits n instances of a closure for execution in parallel: + /// + /// for (int i = 0; i < n; i++) fn(i, n); + /// + virtual void parallel_for(int n, const std::function &fn) + = 0; + + /// Returns threadpool behavior flags bit mask (see below). + virtual uint64_t get_flags() const = 0; + + /// If set, parallel_for() returns immediately and oneDNN needs implement + /// waiting for the submitted closures to finish execution on its own. + static constexpr uint64_t ASYNCHRONOUS = 1; + + virtual ~threadpool_iface() {} +}; + +} // namespace threadpool_interop + +/// @} dnnl_api_threadpool_interop + +/// @} dnnl_api_interop + +} // namespace dnnl + +/// @} dnnl_api + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_types.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_types.h new file mode 100644 index 0000000000000000000000000000000000000000..a8c819a5914e1ae7a1ba933b2672edddc4421c8a --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_types.h @@ -0,0 +1,2892 @@ +/******************************************************************************* +* Copyright 2016-2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// C API types definitions + +#ifndef ONEAPI_DNNL_DNNL_TYPES_H +#define ONEAPI_DNNL_DNNL_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/// @cond DO_NOT_DOCUMENT_THIS +#include +#include +/// @endcond + +#include "oneapi/dnnl/dnnl_config.h" + +#include "oneapi/dnnl/dnnl_common_types.h" + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_memory +/// @{ + +/// Memory format kind +typedef enum { + /// Undefined memory format kind, used for empty memory descriptors. + dnnl_format_kind_undef = 0, + /// A special format kind that indicates that the actual format will be + /// selected by a primitive automatically. + dnnl_format_kind_any, + /// A tensor in a generic format described by the stride and blocking + /// values in each dimension. + dnnl_blocked, + /// A special format kind that indicates that tensor format is opaque. + dnnl_format_kind_opaque, +#ifdef DNNL_EXPERIMENTAL_SPARSE + /// Format kind for sparse tensors. + dnnl_format_kind_sparse, +#endif + /// Parameter to allow internal only format kinds without undefined + /// behavior. This parameter is chosen to be valid for so long as + /// sizeof(int) >= 2. + dnnl_format_kind_max = 0x7fff, +} dnnl_format_kind_t; + +#ifdef DNNL_EXPERIMENTAL_SPARSE +/// Sparse encodings. +typedef enum { + /// Undefined sparse encoding kind, used for empty memory descriptors. + dnnl_sparse_encoding_undef = 0, + /// Compressed Sparse Row (CSR) encoding. + dnnl_csr, + /// An encoding that is used for an opaque storage schema for + /// tensors with unstructured sparsity. A memory descriptor with the + /// packed encoding cannot be used to create a memory object. It can + /// only be used to create a primitive descriptor to query the + /// actual memory descriptor (similar to the format tag `any`). + dnnl_packed, +} dnnl_sparse_encoding_t; +#endif + +#ifdef DNNL_EXPERIMENTAL_PROFILING +/// Profiling data kind. +typedef enum { + /// Undefined profiling data kind. + dnnl_profiling_data_kind_undef = 0, + /// Data kind to query an execution time in nanoseconds. + dnnl_profiling_data_kind_time, +} dnnl_profiling_data_kind_t; + +#endif + +/// Memory format tag specification. +/// +/// oneDNN formats describe physical data layout. The physical layout +/// is described as a sequence of the dimensions as they are laid out in the +/// memory (from the outer-most to the inner-most). Note that this order +/// doesn't affect the logical order of the dimensions that is kept in the +/// `dims` field of the dnnl_memory_desc_t structure. The logical order of the +/// dimensions is specified by the primitive that uses the tensor. +/// +/// For example, CNN 5D tensor always has its logical dimensions in the order +/// `(batch, channels, depth, height, width)`, while the physical layout might be +/// `NCDHW` (corresponds to #dnnl_ncdhw format tag) or +/// `NDHWC` (corresponds to #dnnl_ndhwc format tag). +/// +/// ~~~cpp +/// int batch = 2, channels = 16, depth = 13, height = 13, width = 13; +/// +/// int ndims = 5; // 5D tensor +/// dnnl_dims_t dims = {batch, channels, depth, height, width}; +/// dnnl_memory_desc_t data_in_ncdhw; +/// dnnl_memory_desc_create_with_tag( +/// &data_in_ncdhw, 5, dims, dnnl_f32, dnnl_ncdhw); +/// +/// // note that in both cases dims passed are the same +/// dnnl_memory_desc_t data_in_ndhwc; +/// dnnl_memory_desc_create_with_tag( +/// &data_in_ndhwc, 5, dims, dnnl_f32, dnnl_ndhwc); +/// +/// dnnl_memory_desc_destroy(data_in_ncdhw); +/// dnnl_memory_desc_destroy(data_in_ndhwc); +/// ~~~ +/// +/// Memory format tags can be further divided into two categories: +/// - Domain-agnostic names, i.e. names the do not depend on the tensor usage +/// in the specific primitive. These names use letters from `a` to `l` to +/// denote logical dimension from 1 to 12, and form the order in which the +/// dimensions are laid in memory. For instance, #dnnl_ab is used to denote +/// 2D tensor where the second logical dimension (aka `b`) is the innermost, +/// i.e. has stride = 1, and the first logical dimension (`a`) laid out in +/// memory with stride equal to the size of second dimension. On the other +/// hand, #dnnl_ba is just transposed version of the same tensor: the +/// first dimension (`a`) becomes the innermost one. +/// - Domain-specific names, i.e. names that make sense only in the context of +/// a certain domain, such as CNN. This names are just aliases to the +/// corresponding domain-agnostic tags and used mostly for the convenience. +/// For example, #dnnl_nc is used to denote 2D CNN activations tensor +/// memory format, where channels are the innermost dimension and batch is an +/// outermost one. Moreover, #dnnl_nc is just an alias to #dnnl_ab, +/// since for oneDNN CNN primitives the logical dimensions of +/// activations tensors come in order: batch, channels, spatial. +/// In other words, batch corresponds to the first logical dimension (`a`), +/// channels correspond to the second one (`b`). +/// +/// The following domain-specific notation applies to memory format tags: +/// - @c 'n' denotes the mini-batch dimension +/// - @c 'c' denotes a channels dimension +/// - When there are multiple channel dimensions (for example, in convolution +/// weights tensor), @c 'i' and @c 'o' denote dimensions of input and output +/// channels +/// - @c 'd', @c 'h', and @c 'w' denote spatial depth, height, and width +/// respectively +/// +/// Upper-case letters indicate that the data is laid out in blocks for a +/// particular dimension. In such cases, the format name contains both upper- +/// and lower-case letters for that dimension with a lower-case letter preceded +/// by the block size. For example: #dnnl_nChw8c describes a format where the +/// outermost dimension is mini-batch, followed by the channel block number, +/// followed by the spatial height and width, and finally followed by 8-element +/// channel blocks. +/// +/// @sa @ref dev_guide_understanding_memory_formats +typedef enum { + /// Undefined memory format tag + dnnl_format_tag_undef = 0, + /// Undefined memory format tag. + /// The primitive selects a format automatically. + dnnl_format_tag_any, + + // Semantic agnostic section + // The physical order of dimensions is defined by the permutation of the + // characters, assuming that ab..z defines the natural order. + + // Plain formats + + dnnl_a, ///< plain 1D tensor + dnnl_ab, ///< plain 2D tensor + dnnl_abc, ///< plain 3D tensor + dnnl_abcd, ///< plain 4D tensor + dnnl_abcde, ///< plain 5D tensor + dnnl_abcdef, ///< plain 6D tensor + dnnl_abcdefg, ///< plain 7D tensor + dnnl_abcdefgh, ///< plain 8D tensor + dnnl_abcdefghi, ///< plain 9D tensor + dnnl_abcdefghij, ///< plain 10D tensor + dnnl_abcdefghijk, ///< plain 11D tensor + dnnl_abcdefghijkl, ///< plain 12D tensor + + // Permuted plain formats + + dnnl_ba, ///< permuted 2D tensor + dnnl_acb, ///< permuted 3D tensor + dnnl_bac, ///< permuted 3D tensor + dnnl_bca, ///< permuted 3D tensor + dnnl_cab, ///< permuted 3D tensor + dnnl_cba, ///< permuted 3D tensor + dnnl_abdc, ///< permuted 4D tensor + dnnl_acbd, ///< permuted 4D tensor + dnnl_acdb, ///< permuted 4D tensor + dnnl_adbc, ///< permuted 4D tensor + dnnl_adcb, ///< permuted 4D tensor + dnnl_bacd, ///< permuted 4D tensor + dnnl_bcda, ///< permuted 4D tensor + dnnl_cdab, ///< permuted 4D tensor + dnnl_cdba, ///< permuted 4D tensor + dnnl_dcab, ///< permuted 4D tensor + dnnl_abced, ///< permuted 5D tensor + dnnl_abdec, ///< permuted 5D tensor + dnnl_acbde, ///< permuted 5D tensor + dnnl_acdeb, ///< permuted 5D tensor + dnnl_adecb, ///< permuted 5D tensor + dnnl_bacde, ///< permuted 5D tensor + dnnl_bcdea, ///< permuted 5D tensor + dnnl_cdeab, ///< permuted 5D tensor + dnnl_cdeba, ///< permuted 5D tensor + dnnl_decab, ///< permuted 5D tensor + dnnl_abcdfe, ///< permuted 6D tensor + dnnl_abdefc, ///< permuted 6D tensor + dnnl_abdfce, ///< permuted 6D tensor + dnnl_acbdef, ///< permuted 6D tensor + dnnl_adefcb, ///< permuted 6D tensor + dnnl_defcab, ///< permuted 6D tensor + dnnl_abcdegf, ///< permuted 7D tensor + dnnl_abcdefhg, ///< permuted 8D tensor + dnnl_abcdefgih, ///< permuted 9D tensor + dnnl_abcdefghji, ///< permuted 10D tensor + dnnl_abcdefghikj, ///< permuted 11D tensor + dnnl_abcdefghijlk, ///< permuted 12D tensor + + // Opaque blocked formats + + dnnl_Abc16a, + dnnl_ABc16a16b, + dnnl_ABc32a32b, + dnnl_ABc4a4b, + /// 3D tensor blocked by 2nd dimension with block size 16 + dnnl_aBc16b, + dnnl_ABc16b16a, + dnnl_Abc4a, + /// 3D tensor blocked by 2nd dimension with block size 32 + dnnl_aBc32b, + /// 3D tensor blocked by 2nd dimension with block size 4 + dnnl_aBc4b, + dnnl_ABc4b16a4b, + dnnl_ABc2b8a4b, + dnnl_ABc16b16a4b, + dnnl_ABc16b16a2b, + dnnl_ABc4b4a, + dnnl_ABc8a16b2a, + dnnl_ABc8a8b, + dnnl_ABc8a4b, + /// 3D tensor blocked by 2nd dimension with block size 8 + dnnl_aBc8b, + dnnl_ABc8b16a2b, + dnnl_BAc8a16b2a, + dnnl_ABc8b8a, + dnnl_Abcd16a, + dnnl_Abcd8a, + dnnl_ABcd16a16b, + dnnl_Abcd32a, + dnnl_ABcd32a32b, + /// 4D tensor blocked by 2nd dimension with block size 16 + dnnl_aBcd16b, + dnnl_ABcd16b16a, + dnnl_aBCd16b16c, + dnnl_aBCd16c16b, + dnnl_Abcd4a, + /// 4D tensor blocked by 2nd dimension with block size 32 + dnnl_aBcd32b, + /// 4D tensor blocked by 2nd dimension with block size 4 + dnnl_aBcd4b, + dnnl_ABcd4b16a4b, + dnnl_ABcd16b16a4b, + dnnl_ABcd16b16a2b, + dnnl_ABcd4b4a, + dnnl_ABcd4a4b, + dnnl_aBCd2c4b2c, + dnnl_aBCd4b8c2b, + dnnl_aBCd4c16b4c, + dnnl_aBCd2c8b4c, + dnnl_aBCd16c16b4c, + dnnl_aBCd16c16b2c, + dnnl_aBCd4c4b, + dnnl_aBCd4b4c, + dnnl_ABcd8a16b2a, + dnnl_ABcd2b8a4b, + dnnl_ABcd8a8b, + dnnl_ABcd8a4b, + /// 4D tensor blocked by 2nd dimension with block size 8 + dnnl_aBcd8b, + dnnl_aBCd4c8b2c, + dnnl_ABcd8b16a2b, + dnnl_aBCd8b16c2b, + dnnl_BAcd8a16b2a, + /// 4D tensor blocked by 1st and 2nd dimension with block size 8 + dnnl_ABcd8b8a, + dnnl_aBCd8b8c, + dnnl_aBCd8b4c, + dnnl_aBCd8c16b2c, + dnnl_ABcde8a16b2a, + dnnl_aCBd8b16c2b, + dnnl_aBCd8c8b, + dnnl_Abcde16a, + dnnl_Abcde32a, + dnnl_ABcde16a16b, + dnnl_BAcde8a16b2a, + /// 4D tensor blocked by 3rd dimension with block size 4 + dnnl_aBCd2b4c2b, + /// 5D tensor blocked by 1st dimension with block size 16 + dnnl_ABcde4b16a4b, + /// 5D tensor blocked by 1st dimension with block size 8 + dnnl_ABcde2b8a4b, + /// 5D tensor blocked by 2nd dimension with block size 16 + dnnl_aBcde16b, + dnnl_ABcde16b16a, + dnnl_aBCde16b16c, + dnnl_aBCde16c16b, + dnnl_aBCde2c8b4c, + dnnl_Abcde4a, + /// 5D tensor blocked by 2nd dimension with block size 32 + dnnl_aBcde32b, + /// 5D tensor blocked by 2nd dimension with block size 4 + dnnl_aBcde4b, + dnnl_ABcde4b4a, + dnnl_ABcde4a4b, + dnnl_aBCde4b4c, + dnnl_aBCde2c4b2c, + dnnl_aBCde4b8c2b, + dnnl_aBCde4c16b4c, + dnnl_aBCde16c16b4c, + dnnl_aBCde16c16b2c, + dnnl_aBCde4c4b, + dnnl_Abcde8a, + dnnl_ABcde8a8b, + dnnl_ABcde8a4b, + dnnl_BAcde16b16a, + /// 5D tensor blocked by 2nd dimension with block size 8 + dnnl_aBcde8b, + dnnl_ABcde8b16a2b, + dnnl_aBCde8b16c2b, + dnnl_aBCde4c8b2c, + dnnl_aCBde8b16c2b, + dnnl_ABcde8b8a, + dnnl_ABcde32a32b, + dnnl_aBCde8b8c, + dnnl_aBCde8b4c, + dnnl_ABc4a8b8a4b, + dnnl_ABcd4a8b8a4b, + dnnl_ABcde4a8b8a4b, + dnnl_BAc4b8a8b4a, + dnnl_BAcd4b8a8b4a, + dnnl_BAcde4b8a8b4a, + dnnl_ABcd2a8b8a2b, + dnnl_aBCd4b8c8b4c, + dnnl_aBCde4b8c8b4c, + dnnl_aBCde2b8c8b2c, + dnnl_aBCde8c16b2c, + dnnl_aBCde8c8b, + /// 5D tensor blocked by 3rd dimension with block size 4 + dnnl_aBCde2b4c2b, + /// 6D tensor blocked by 2nd dimension with block size 16 + dnnl_aBcdef16b, + dnnl_aBCdef16b16c, + dnnl_aBCdef16c16b, + dnnl_aBCdef4c16b4c, + /// 6D tensor blocked by 2nd dimension with block size 8 + dnnl_aBCdef2c8b4c, + dnnl_aBCdef4c8b2c, + /// 6D tensor blocked by 3rd dimension with block size 4 + dnnl_aBCdef2b4c2b, + /// 6D tensor blocked by 2nd dimension with block size 4 + dnnl_aBcdef4b, + dnnl_aBCdef4c4b, + dnnl_aBCdef4b4c, + dnnl_aBCdef2c4b2c, + dnnl_aBCdef4b8c2b, + dnnl_aBCdef8b8c, + dnnl_aBCdef8b4c, + dnnl_aBCdef8c16b2c, + dnnl_aBCdef4b8c8b4c, + dnnl_aBCdef8b16c2b, + dnnl_aCBdef8b16c2b, + dnnl_aBCdef8c8b, + dnnl_aBdc16b, + dnnl_aBdC16b2c, + dnnl_aBdC16b4c, + dnnl_aBdc4b, + dnnl_aBdc8b, + dnnl_aBdec16b, + dnnl_aBdeC16b2c, + dnnl_aBdeC16b4c, + dnnl_aBdec32b, + dnnl_aBdec4b, + dnnl_aBdec8b, + dnnl_aBdefc16b, + dnnl_aBdefC16b2c, + dnnl_aCBdef16c16b, + dnnl_aBdefc4b, + dnnl_aBdefc8b, + dnnl_Abcdef16a, + dnnl_Abcdef32a, + dnnl_aBedc16b, + dnnl_Acb16a, + dnnl_AcB16a2b, + dnnl_AcB16a4b, + dnnl_Acb4a, + dnnl_Acb8a, + dnnl_aCBd16b16c, + dnnl_aCBd16c16b, + dnnl_aCBde16b16c, + dnnl_aCBde16c16b, + dnnl_Acdb16a, + dnnl_AcdB16a2b, + dnnl_AcdB16a4b, + dnnl_Acdb32a, + dnnl_Acdb4a, + dnnl_Acdb8a, + dnnl_Acdeb16a, + dnnl_AcdeB16a2b, + dnnl_Acdeb4a, + dnnl_Acdeb8a, + dnnl_Adcb16a, + dnnl_BAc16a16b, + dnnl_BAc16b16a, + dnnl_BAcd16a16b, + dnnl_BAcd16b16a, + dnnl_aCBd4c8b8c4b, + dnnl_aCBde4c8b8c4b, + dnnl_aCBdef4c8b8c4b, + dnnl_BAcde16a16b, + dnnl_aCBdef16b16c, + dnnl_ABc16b32a, + dnnl_ABc16b64a, + dnnl_ABc4b32a4b, + dnnl_ABc4b64a4b, + dnnl_ABc8b32a2b, + dnnl_ABc8b64a2b, + dnnl_AB16b16a, + dnnl_AB16b32a, + dnnl_AB16b64a, + dnnl_AB8b16a2b, + dnnl_AB8b32a2b, + dnnl_AB8b64a2b, + dnnl_AB4b16a4b, + dnnl_AB4b32a4b, + dnnl_AB4b64a4b, + dnnl_AB16b16a4b, + dnnl_ABcd16b32a, + dnnl_ABcd16b64a, + dnnl_ABcd4b32a4b, + dnnl_ABcd4b64a4b, + dnnl_ABcd8b32a2b, + dnnl_ABcd8b64a2b, + dnnl_ABcde4b32a4b, + dnnl_ABcde4b64a4b, + dnnl_ABcde16b16a4b, + dnnl_ABcde16b16a2b, + dnnl_ABcde16b32a, + dnnl_ABcde16b64a, + dnnl_ABcde8b32a2b, + dnnl_ABcde8b64a2b, + dnnl_aBCdef16c16b4c, + dnnl_aBCdef16c16b2c, + dnnl_AB32a32b8a4b, + dnnl_AB8a4b, + dnnl_AB32a32b8a2b, + dnnl_AB8a2b, + dnnl_abDc32d, + dnnl_abDC32d4c, + dnnl_abdEc32e, + dnnl_abdEC32e2c, + dnnl_abdEC32e4c, + dnnl_aBdefC16b4c, + dnnl_AcdeB16a4b, + dnnl_ABcd16a16b2a, + dnnl_ABc16a16b2a, + dnnl_aBCd16b16c2b, + dnnl_aBCde16b16c2b, + dnnl_Acb32a, + dnnl_AcB32a2b, + dnnl_AcB32a4b, + dnnl_Acb48a, + dnnl_AcB48a2b, + dnnl_AcB48a4b, + dnnl_Acb64a, + dnnl_AcB64a2b, + dnnl_AcB64a4b, + dnnl_cBa2b, + dnnl_cBa4b, + dnnl_aBdc32b, + dnnl_aBdC32b2c, + dnnl_aBdC32b4c, + dnnl_aBdc48b, + dnnl_aBdC48b2c, + dnnl_aBdC48b4c, + dnnl_aBdc64b, + dnnl_aBdC64b2c, + dnnl_aBdC64b4c, + dnnl_adCb2c, + dnnl_adCb4c, + dnnl_AcdB32a2b, + dnnl_AcdB32a4b, + dnnl_Acdb48a, + dnnl_AcdB48a2b, + dnnl_AcdB48a4b, + dnnl_Acdb64a, + dnnl_AcdB64a2b, + dnnl_AcdB64a4b, + dnnl_cdBa2b, + dnnl_cdBa4b, + dnnl_aBdeC32b2c, + dnnl_aBdeC32b4c, + dnnl_aBdec48b, + dnnl_aBdeC48b2c, + dnnl_aBdeC48b4c, + dnnl_aBdec64b, + dnnl_aBdeC64b2c, + dnnl_aBdeC64b4c, + dnnl_adeCb2c, + dnnl_adeCb4c, + dnnl_Acdeb32a, + dnnl_AcdeB32a2b, + dnnl_AcdeB32a4b, + dnnl_Acdeb48a, + dnnl_AcdeB48a2b, + dnnl_AcdeB48a4b, + dnnl_Acdeb64a, + dnnl_AcdeB64a2b, + dnnl_AcdeB64a4b, + dnnl_cdeBa2b, + dnnl_cdeBa4b, + dnnl_aBdefc32b, + dnnl_aBdefC32b2c, + dnnl_aBdefC32b4c, + dnnl_aBdefc48b, + dnnl_aBdefC48b2c, + dnnl_aBdefC48b4c, + dnnl_aBdefc64b, + dnnl_aBdefC64b2c, + dnnl_aBdefC64b4c, + dnnl_adefCb2c, + dnnl_adefCb4c, + dnnl_AB16b32a4b, + dnnl_AB16b48a4b, + dnnl_AB16b64a4b, + dnnl_AB16b16a2b, + dnnl_AB16b32a2b, + dnnl_AB16b48a2b, + dnnl_AB16b64a2b, + dnnl_ABc16b32a4b, + dnnl_ABc16b48a4b, + dnnl_ABc16b64a4b, + dnnl_ABc16b32a2b, + dnnl_ABc16b48a2b, + dnnl_ABc16b64a2b, + dnnl_ABcd16b32a4b, + dnnl_ABcd16b48a4b, + dnnl_ABcd16b64a4b, + dnnl_ABcd16b32a2b, + dnnl_ABcd16b48a2b, + dnnl_ABcd16b64a2b, + dnnl_ABcde16b32a4b, + dnnl_ABcde16b48a4b, + dnnl_ABcde16b64a4b, + dnnl_ABcde16b32a2b, + dnnl_ABcde16b48a2b, + dnnl_ABcde16b64a2b, + dnnl_ABc32a16b, + dnnl_ABcd32a16b, + dnnl_ABcde32a16b, + dnnl_AB48a16b, + dnnl_AB48a32b, + dnnl_ABc40a16b, + dnnl_ABc40a32b, + dnnl_aBC48b16c, + dnnl_aBC48b32c, + dnnl_ABcd40a16b, + dnnl_ABcd40a32b, + dnnl_abCd32c, + dnnl_abdCe32c, + dnnl_abdCE32c2e, + dnnl_BA16a16b2a, + dnnl_BA16a32b2a, + dnnl_BA16a48b2a, + dnnl_BA16a64b2a, + dnnl_BA16a16b4a, + dnnl_BA16a32b4a, + dnnl_BA16a48b4a, + dnnl_BA16a64b4a, + dnnl_ABcd8a2b, + dnnl_aBdeC16c16b2c, + dnnl_aBdeC16c16b4c, + dnnl_aBdefC16c16b2c, + dnnl_AcB16b16a2b, + dnnl_AcB16b16a4b, + dnnl_AcdB16b16a2b, + dnnl_AcdB16b16a4b, + dnnl_AcdeB16b16a2b, + dnnl_aBdefC16c16b4c, + dnnl_AcdeB16b16a4b, + dnnl_AcB16b32a2b, + dnnl_AcB16b32a4b, + dnnl_AcB16b48a2b, + dnnl_AcB16b48a4b, + dnnl_AcB16b64a2b, + dnnl_AcB16b64a4b, + dnnl_aBdC16c16b2c, + dnnl_aBdC16c16b4c, + dnnl_aBdC16c32b2c, + dnnl_aBdC16c32b4c, + dnnl_aBdC16c48b2c, + dnnl_aBdC16c48b4c, + dnnl_aBdC16c64b2c, + dnnl_aBdC16c64b4c, + dnnl_AcdB16b32a2b, + dnnl_AcdB16b32a4b, + dnnl_AcdB16b48a2b, + dnnl_AcdB16b48a4b, + dnnl_AcdB16b64a2b, + dnnl_AcdB16b64a4b, + dnnl_aBdeC16c32b2c, + dnnl_aBdeC16c32b4c, + dnnl_aBdeC16c48b2c, + dnnl_aBdeC16c48b4c, + dnnl_aBdeC16c64b2c, + dnnl_aBdeC16c64b4c, + dnnl_AcdeB16b32a2b, + dnnl_AcdeB16b32a4b, + dnnl_AcdeB16b48a2b, + dnnl_AcdeB16b48a4b, + dnnl_AcdeB16b64a2b, + dnnl_AcdeB16b64a4b, + dnnl_aBdefC16c32b2c, + dnnl_aBdefC16c32b4c, + dnnl_aBdefC16c48b2c, + dnnl_aBdefC16c48b4c, + dnnl_aBdefC16c64b2c, + dnnl_aBdefC16c64b4c, + dnnl_decbA16a, + dnnl_ABc4a2b, + dnnl_ABc8a2b, + dnnl_aBCd8b2c, + dnnl_ABcde4a2b, + dnnl_ABcde8a2b, + dnnl_ABcde40a16b, + dnnl_ABcde40a32b, + dnnl_aBCde8b2c, + dnnl_ABcde4a8b8a2b, + dnnl_ABcd4a8b8a2b, + dnnl_ABc4a8b8a2b, + dnnl_aBCdef4b8c8b2c, + dnnl_aBCde4b8c8b2c, + dnnl_aBCd4b8c8b2c, + dnnl_BAcde4b8a8b2a, + dnnl_BAcd4b8a8b2a, + dnnl_BAc4b8a8b2a, + dnnl_aCBdef4c8b8c2b, + dnnl_aCBde4c8b8c2b, + dnnl_aCBd4c8b8c2b, + dnnl_aBCdef8b2c, + dnnl_AB32a16b, + dnnl_AB32a32b, + dnnl_BA4b8a8b2a, + dnnl_BA4b8a8b4a, + dnnl_aBC32b16c, + dnnl_aBC32b32c, + dnnl_aCB4c8b8c2b, + dnnl_aCB4c8b8c4b, + dnnl_ABcd4a2b, + dnnl_ABc2b8a16b4a, + dnnl_ABcd2b8a16b4a, + dnnl_ABcde2b8a16b4a, + dnnl_ABc2a8b16a4b, + dnnl_ABc2a8b16a2b, + dnnl_ABc2b32a8b, + dnnl_ABcd2a8b16a4b, + dnnl_ABcd2a8b16a2b, + dnnl_aCBd2c8b16c2b, + dnnl_ABcd2b32a8b, + dnnl_aBCd2c8b16c2b, + dnnl_ABcde2a8b16a4b, + dnnl_ABcde2a8b16a2b, + dnnl_aCBde2c8b16c2b, + dnnl_ABcde2b32a8b, + dnnl_aBC2b8c16b2c, + dnnl_aBCd2b8c16b2c, + dnnl_aBCde2b8c16b2c, + dnnl_aBCdef2b8c16b2c, + dnnl_BAcde2b8a16b4a, + dnnl_BAcd2b8a16b4a, + dnnl_BAc2b8a16b4a, + dnnl_BAcde2b8a16b2a, + dnnl_BAcd2b8a16b2a, + dnnl_BAc2b8a16b2a, + dnnl_aBCde2c8b16c2b, + dnnl_aBCdef2c8b16c2b, + dnnl_aCBdef2c8b16c2b, + dnnl_aBCd2b8c16b4c, + dnnl_aBCde2b8c16b4c, + dnnl_BA4b8a16b2a, + dnnl_BA4b8a16b4a, + dnnl_aCB4c8b16c2b, + dnnl_aCB4c8b16c4b, + dnnl_BA16a16b, + dnnl_BA16a32b, + dnnl_BA16a48b, + dnnl_BA16a64b, + dnnl_aCB16c2b, + dnnl_aCB16c4b, + dnnl_BA16b2a, + dnnl_BA16b4a, + dnnl_aBC16b16c, + dnnl_aBC16b32c, + dnnl_AB16a16b, + dnnl_AB16a32b, + dnnl_ABcde16a16b2a, + dnnl_aBCdef16b16c2b, + dnnl_Acedb16a, + dnnl_aBdfec16b, + dnnl_abdEC64e2c, + dnnl_abdEC64e4c, + dnnl_aCB16b16c, + dnnl_aCB16b32c, + dnnl_aCB16b48c, + dnnl_aCB16b64c, + dnnl_aCB16b16c2b, + dnnl_aCB16b32c2b, + dnnl_aCB16b48c2b, + dnnl_aCB16b64c2b, + dnnl_aCB16b16c4b, + dnnl_aCB16b32c4b, + dnnl_aCB16b48c4b, + dnnl_aCB16b64c4b, + dnnl_abCd4c, + dnnl_abCde4c, + dnnl_abCdef4c, + dnnl_abCde32c, + dnnl_abCdef32c, + dnnl_ABcd16a32b, + dnnl_decbA8a, + dnnl_aCdefB16b32c2b, + dnnl_aCdefB16b32c4b, + dnnl_aCdefB16b48c2b, + dnnl_aCdefB16b48c4b, + dnnl_aCdefB16b64c2b, + dnnl_aCdefB16b64c4b, + dnnl_BcdeA16a32b2a, + dnnl_BcdeA16a32b4a, + dnnl_BcdeA16a48b2a, + dnnl_BcdeA16a48b4a, + dnnl_BcdeA16a64b2a, + dnnl_BcdeA16a64b4a, + dnnl_aCdefb32c, + dnnl_aCdefB32c2b, + dnnl_aCdefB32c4b, + dnnl_aCdefb48c, + dnnl_aCdefB48c2b, + dnnl_aCdefB48c4b, + dnnl_aCdefb64c, + dnnl_aCdefB64c2b, + dnnl_aCdefB64c4b, + dnnl_Bcdea32b, + dnnl_BcdeA32b2a, + dnnl_BcdeA32b4a, + dnnl_Bcdea48b, + dnnl_BcdeA48b2a, + dnnl_BcdeA48b4a, + dnnl_Bcdea64b, + dnnl_BcdeA64b2a, + dnnl_BcdeA64b4a, + dnnl_Bca32b, + dnnl_BcA32b2a, + dnnl_BcA32b4a, + dnnl_Bca48b, + dnnl_BcA48b2a, + dnnl_BcA48b4a, + dnnl_Bca64b, + dnnl_BcA64b2a, + dnnl_BcA64b4a, + dnnl_aCdb32c, + dnnl_aCdB32c2b, + dnnl_aCdB32c4b, + dnnl_aCdb48c, + dnnl_aCdB48c2b, + dnnl_aCdB48c4b, + dnnl_aCdb64c, + dnnl_aCdB64c2b, + dnnl_aCdB64c4b, + dnnl_BcA16a16b2a, + dnnl_BcA16a16b4a, + dnnl_BcdA16a16b2a, + dnnl_BcdA16a16b4a, + dnnl_BcdeA16a16b2a, + dnnl_BcdeA16a16b4a, + dnnl_aCdB16b16c2b, + dnnl_aCdB16b16c4b, + dnnl_aCdeB16b16c2b, + dnnl_aCdeB16b16c4b, + dnnl_aCdefB16b16c2b, + dnnl_aCdefB16b16c4b, + dnnl_BcA16a32b2a, + dnnl_BcA16a32b4a, + dnnl_BcA16a48b2a, + dnnl_BcA16a48b4a, + dnnl_BcA16a64b2a, + dnnl_BcA16a64b4a, + dnnl_aCdB16b32c2b, + dnnl_aCdB16b32c4b, + dnnl_aCdB16b48c2b, + dnnl_aCdB16b48c4b, + dnnl_aCdB16b64c2b, + dnnl_aCdB16b64c4b, + dnnl_BcdA16a32b2a, + dnnl_BcdA16a32b4a, + dnnl_BcdA16a48b2a, + dnnl_BcdA16a48b4a, + dnnl_BcdA16a64b2a, + dnnl_BcdA16a64b4a, + dnnl_aCdeB16b32c2b, + dnnl_aCdeB16b32c4b, + dnnl_aCdeB16b48c2b, + dnnl_aCdeB16b48c4b, + dnnl_aCdeB16b64c2b, + dnnl_aCdeB16b64c4b, + dnnl_Bca16b, + dnnl_BcA16b2a, + dnnl_BcA16b4a, + dnnl_Bcda16b, + dnnl_BcdA16b2a, + dnnl_BcdA16b4a, + dnnl_Bcdea16b, + dnnl_BcdeA16b2a, + dnnl_BcdeA16b4a, + dnnl_aCdb16c, + dnnl_aCdB16c2b, + dnnl_aCdB16c4b, + dnnl_aCdeb16c, + dnnl_aCdeB16c2b, + dnnl_aCdeB16c4b, + dnnl_aCdefb16c, + dnnl_aCdefB16c2b, + dnnl_aCdefB16c4b, + dnnl_Bcda32b, + dnnl_BcdA32b2a, + dnnl_BcdA32b4a, + dnnl_Bcda48b, + dnnl_BcdA48b2a, + dnnl_BcdA48b4a, + dnnl_Bcda64b, + dnnl_BcdA64b2a, + dnnl_BcdA64b4a, + dnnl_aCdeb32c, + dnnl_aCdeB32c2b, + dnnl_aCdeB32c4b, + dnnl_aCdeb48c, + dnnl_aCdeB48c2b, + dnnl_aCdeB48c4b, + dnnl_aCdeb64c, + dnnl_aCdeB64c2b, + dnnl_aCdeB64c4b, + dnnl_Acb24a, + dnnl_Acdb24a, + dnnl_Acdeb24a, + dnnl_aBdc24b, + dnnl_aBdec24b, + dnnl_aBdefc24b, + dnnl_abDc16d, + dnnl_abdEc16e, + dnnl_abdCe16c, + dnnl_AcB24a2b, + dnnl_AcdB24a2b, + dnnl_AcdeB24a2b, + dnnl_aBdC24b2c, + dnnl_aBdeC24b2c, + dnnl_aBdefC24b2c, + dnnl_AcB8a2b, + dnnl_AcdB8a2b, + dnnl_AcdeB8a2b, + dnnl_aBdC8b2c, + dnnl_aBdeC8b2c, + dnnl_aBdefC8b2c, + dnnl_AB8b32a, + dnnl_ABc8b32a, + dnnl_ABcd8b32a, + dnnl_ABcde8b32a, + dnnl_AB8b24a, + dnnl_ABc8b24a, + dnnl_ABcd8b24a, + dnnl_ABcde8b24a, + dnnl_AB8b16a, + dnnl_ABc8b16a, + dnnl_ABcd8b16a, + dnnl_ABcde8b16a, + dnnl_AB8b8a, + dnnl_AB4b8a4b, + dnnl_AB4b24a4b, + dnnl_ABc4b8a4b, + dnnl_ABc4b24a4b, + dnnl_ABcd4b8a4b, + dnnl_ABcd4b24a4b, + dnnl_ABcde4b8a4b, + dnnl_ABcde4b24a4b, + dnnl_AB8b24a2b, + dnnl_ABc8b24a2b, + dnnl_ABcd8b24a2b, + dnnl_ABcde8b24a2b, + dnnl_AB8b8a2b, + dnnl_ABc8b8a2b, + dnnl_ABcd8b8a2b, + dnnl_ABcde8b8a2b, + dnnl_AcB24a4b, + dnnl_AcdB24a4b, + dnnl_AcdeB24a4b, + dnnl_aBdC24b4c, + dnnl_aBdeC24b4c, + dnnl_aBdefC24b4c, + dnnl_AcB8a4b, + dnnl_AcdB8a4b, + dnnl_AcdeB8a4b, + dnnl_aBdC8b4c, + dnnl_aBdeC8b4c, + dnnl_aBdefC8b4c, + dnnl_Bca8b, + dnnl_BcA8b2a, + dnnl_Bcda8b, + dnnl_BcdA8b2a, + dnnl_Bcdea8b, + dnnl_BcdeA8b2a, + dnnl_aCdb8c, + dnnl_aCdB8c2b, + dnnl_aCdeb8c, + dnnl_aCdeB8c2b, + dnnl_aCdefb8c, + dnnl_aCdefB8c2b, + dnnl_Bca24b, + dnnl_BcA24b2a, + dnnl_Bcda24b, + dnnl_BcdA24b2a, + dnnl_Bcdea24b, + dnnl_BcdeA24b2a, + dnnl_aCdb24c, + dnnl_aCdB24c2b, + dnnl_aCdeb24c, + dnnl_aCdeB24c2b, + dnnl_aCdefb24c, + dnnl_aCdefB24c2b, + dnnl_BcA8b4a, + dnnl_BcdA8b4a, + dnnl_BcdeA8b4a, + dnnl_aCdB8c4b, + dnnl_aCdeB8c4b, + dnnl_aCdefB8c4b, + dnnl_BcA24b4a, + dnnl_BcdA24b4a, + dnnl_BcdeA24b4a, + dnnl_aCdB24c4b, + dnnl_aCdeB24c4b, + dnnl_aCdefB24c4b, + dnnl_AB16b48a, + dnnl_ABc16b48a, + dnnl_ABcd16b48a, + dnnl_ABcde16b48a, + dnnl_ABc16a4b, + dnnl_ABcd16a4b, + dnnl_ABcde16a4b, + dnnl_defcbA16a, + dnnl_defcbA8a, + dnnl_AcB16b64a, + dnnl_AcdB16b64a, + dnnl_AcdeB16b64a, + dnnl_AcB16b48a, + dnnl_AcdB16b48a, + dnnl_AcdeB16b48a, + dnnl_AcB16b32a, + dnnl_AcdB16b32a, + dnnl_AcdeB16b32a, + dnnl_AcB16b16a, + dnnl_AcdB16b16a, + dnnl_AcdeB16b16a, + dnnl_AcB8b32a, + dnnl_AcdB8b32a, + dnnl_AcdeB8b32a, + dnnl_AcB8b24a, + dnnl_AcdB8b24a, + dnnl_AcdeB8b24a, + dnnl_AcB8b16a, + dnnl_AcdB8b16a, + dnnl_AcdeB8b16a, + dnnl_AcB8b8a, + dnnl_AcdB8b8a, + dnnl_AcdeB8b8a, + dnnl_AcB8b64a2b, + dnnl_AcdB8b64a2b, + dnnl_AcdeB8b64a2b, + dnnl_AcB8b32a2b, + dnnl_AcdB8b32a2b, + dnnl_AcdeB8b32a2b, + dnnl_AcB8b24a2b, + dnnl_AcdB8b24a2b, + dnnl_AcdeB8b24a2b, + dnnl_AcB8b16a2b, + dnnl_AcdB8b16a2b, + dnnl_AcdeB8b16a2b, + dnnl_AcB8b8a2b, + dnnl_AcdB8b8a2b, + dnnl_AcdeB8b8a2b, + dnnl_AcB4b64a4b, + dnnl_AcdB4b64a4b, + dnnl_AcdeB4b64a4b, + dnnl_AcB4b32a4b, + dnnl_AcdB4b32a4b, + dnnl_AcdeB4b32a4b, + dnnl_AcB4b24a4b, + dnnl_AcdB4b24a4b, + dnnl_AcdeB4b24a4b, + dnnl_AcB4b16a4b, + dnnl_AcdB4b16a4b, + dnnl_AcdeB4b16a4b, + dnnl_AcB4b8a4b, + dnnl_AcdB4b8a4b, + dnnl_AcdeB4b8a4b, + dnnl_Ab4a, + dnnl_Ab8a, + dnnl_BA4b4a, + dnnl_BA8b4a, + dnnl_BA2a24b, + dnnl_aCB2b24c, + dnnl_BA2a8b, + dnnl_aCB2b8c, + dnnl_BA8a24b, + dnnl_aCB8b24c, + dnnl_BA8a16b, + dnnl_aCB8b16c, + dnnl_BA8a8b, + dnnl_aCB8b8c, + dnnl_bcad, + dnnl_cabd, + dnnl_dabc, + + /// Just a sentinel, not real memory format tag. Must be changed after new + /// format tag is added. + dnnl_format_tag_last, + + // Aliases + + /// 1D tensor, an alias to #dnnl_a + dnnl_x = dnnl_a, + /// 2D CNN activations tensor, an alias to #dnnl_ab + dnnl_nc = dnnl_ab, + /// 2D CNN activations tensor, an alias to #dnnl_ba + dnnl_cn = dnnl_ba, + /// 2D RNN statistics tensor, an alias to #dnnl_ab + dnnl_tn = dnnl_ab, + /// 2D RNN statistics tensor, an alias to #dnnl_ba + dnnl_nt = dnnl_ba, + /// 3D CNN activations tensor, an alias to #dnnl_abc + dnnl_ncw = dnnl_abc, + /// 3D CNN activations tensor, an alias to #dnnl_acb + dnnl_nwc = dnnl_acb, + /// 4D CNN activations tensor, an alias to #dnnl_abcd + dnnl_nchw = dnnl_abcd, + /// 4D CNN activations tensor, an alias to #dnnl_acdb + dnnl_nhwc = dnnl_acdb, + /// 4D CNN activations tensor, an alias to #dnnl_bcda + dnnl_chwn = dnnl_bcda, + /// 5D CNN activations tensor, an alias to #dnnl_abcde + dnnl_ncdhw = dnnl_abcde, + /// 5D CNN activations tensor, an alias to #dnnl_acdeb + dnnl_ndhwc = dnnl_acdeb, + + /// 2D CNN weights tensor, an alias to #dnnl_ab + dnnl_oi = dnnl_ab, + /// 2D CNN weights tensor, an alias to #dnnl_ba + dnnl_io = dnnl_ba, + /// 3D CNN weights tensor, an alias to #dnnl_abc + dnnl_oiw = dnnl_abc, + /// 3D CNN weights tensor, an alias to #dnnl_acb + dnnl_owi = dnnl_acb, + /// 3D CNN weights tensor, an alias to #dnnl_cba + dnnl_wio = dnnl_cba, + /// 3D CNN weights tensor, an alias to #dnnl_cab + dnnl_woi = dnnl_cab, + /// 3D CNN weights tensor, an alias to #dnnl_bca + dnnl_iwo = dnnl_bca, + /// 4D CNN weights tensor, an alias to #dnnl_abcd + dnnl_oihw = dnnl_abcd, + /// 4D CNN weights tensor, an alias to #dnnl_cdba + dnnl_hwio = dnnl_cdba, + /// 4D CNN weights tensor, an alias to #dnnl_cdab + dnnl_hwoi = dnnl_cdab, + /// 4D CNN weights tensor, an alias to #dnnl_acdb + dnnl_ohwi = dnnl_acdb, + /// 4D CNN weights tensor, an alias to #dnnl_bcda + dnnl_ihwo = dnnl_bcda, + /// 4D CNN weights tensor, an alias to #dnnl_bacd + dnnl_iohw = dnnl_bacd, + /// 5D CNN weights tensor, an alias to #dnnl_abcde + dnnl_oidhw = dnnl_abcde, + /// 5D CNN weights tensor, an alias to #dnnl_bacde + dnnl_iodhw = dnnl_bacde, + /// 5D CNN weights tensor, an alias to #dnnl_cdeba + dnnl_dhwio = dnnl_cdeba, + /// 5D CNN weights tensor, an alias to #dnnl_cdeab + dnnl_dhwoi = dnnl_cdeab, + /// 5D CNN weights tensor, an alias to #dnnl_acdeb + dnnl_odhwi = dnnl_acdeb, + /// 5D CNN weights tensor, an alias to #dnnl_bcdea + dnnl_idhwo = dnnl_bcdea, + + /// 4D CNN weights tensor (incl. groups), an alias to #dnnl_abcd + dnnl_goiw = dnnl_abcd, + /// 4D CNN weights tensor (incl. groups), an alias to #dnnl_abdc + dnnl_gowi = dnnl_abdc, + /// 4D CNN weights tensor (incl. groups), an alias to #dnnl_dcab + dnnl_wigo = dnnl_dcab, + /// 5D CNN weights tensor (incl. groups), an alias to #dnnl_abcde + dnnl_goihw = dnnl_abcde, + /// 5D CNN weights tensor (incl. groups), an alias to #dnnl_abdec + dnnl_gohwi = dnnl_abdec, + /// 5D CNN weights tensor (incl. groups), an alias to #dnnl_decab + dnnl_hwigo = dnnl_decab, + /// 5D CNN weights tensor (incl. groups), an alias to #dnnl_acbde + dnnl_giohw = dnnl_acbde, + /// 6D CNN weights tensor (incl. groups), an alias to #dnnl_abcdef + dnnl_goidhw = dnnl_abcdef, + /// 6D CNN weights tensor (incl. groups), an alias to #dnnl_abdefc + dnnl_godhwi = dnnl_abdefc, + /// 6D CNN weights tensor (incl. groups), an alias to #dnnl_acbdef + dnnl_giodhw = dnnl_acbdef, + /// 6D CNN weights tensor (incl. groups), an alias to #dnnl_defcab + dnnl_dhwigo = dnnl_defcab, + + /// 3D RNN data tensor in the format (seq_length, batch, input channels), + /// an alias to #dnnl_abc. + dnnl_tnc = dnnl_abc, + /// 3D RNN data tensor in the format (batch, seq_length, input channels), + /// an alias to #dnnl_bac. + dnnl_ntc = dnnl_bac, + /// 4D RNN states tensor in the format (num_layers, num_directions, + /// batch, state channels), an alias to #dnnl_abcd. + dnnl_ldnc = dnnl_abcd, + /// 5D RNN weights tensor in the format (num_layers, num_directions, + /// input_channels, num_gates, output_channels), an alias to #dnnl_abcde. + /// + /// - For LSTM cells, the gates order is input, forget, candidate + /// and output gate. + /// - For GRU cells, the gates order is update, reset and output gate. + dnnl_ldigo = dnnl_abcde, + /// 5D RNN weights tensor in the format (num_layers, num_directions, + /// num_gates, output_channels, input_channels), an alias to #dnnl_abdec. + /// + /// - For LSTM cells, the gates order is input, forget, candidate + /// and output gate. + /// - For GRU cells, the gates order is update, reset and output gate. + dnnl_ldgoi = dnnl_abdec, + /// 4D LSTM projection tensor in the format (num_layers, num_directions, + /// num_channels_in_hidden_state, num_channels_in_recurrent_projection), + /// an alias to #dnnl_abcd. + dnnl_ldio = dnnl_abcd, + /// 4D LSTM projection tensor in the format (num_layers, num_directions, + /// num_channels_in_recurrent_projection, num_channels_in_hidden_state), + /// an alias to #dnnl_abdc. + dnnl_ldoi = dnnl_abdc, + /// 4D RNN bias tensor in the format (num_layers, num_directions, + /// num_gates, output_channels), an alias to #dnnl_abcd. + /// + /// - For LSTM cells, the gates order is input, forget, candidate + /// and output gate. + /// - For GRU cells, the gates order is update, reset and output gate. + dnnl_ldgo = dnnl_abcd, + /// 5D LSTM projection tensor + dnnl_ldOi16o = dnnl_abDc16d, + dnnl_ldOi32o = dnnl_abDc32d, + dnnl_ldOI32o4i = dnnl_abDC32d4c, + dnnl_ldIo32i = dnnl_abCd32c, + /// 6D RNN weights tensor + dnnl_ldgOi16o = dnnl_abdEc16e, + dnnl_ldgOi32o = dnnl_abdEc32e, + dnnl_ldgOI32o2i = dnnl_abdEC32e2c, + dnnl_ldgOI32o4i = dnnl_abdEC32e4c, + dnnl_ldgOI64o2i = dnnl_abdEC64e2c, + dnnl_ldgOI64o4i = dnnl_abdEC64e4c, + dnnl_ldgIo16i = dnnl_abdCe16c, + dnnl_ldgIo32i = dnnl_abdCe32c, + dnnl_ldgIO32i2o = dnnl_abdCE32c2e, + + // Opaque data types, are not to be used explicitly + + // data + /// 5D CNN activations tensor blocked by channels with block size 32, + /// an alias to #dnnl_aBcde32b + dnnl_nCdhw32c = dnnl_aBcde32b, + /// 5D CNN activations tensor blocked by channels with block size 16, + /// an alias to #dnnl_aBcde16b + dnnl_nCdhw16c = dnnl_aBcde16b, + /// 5D CNN activations tensor blocked by channels with block size 4, + /// an alias to #dnnl_aBcde4b + dnnl_nCdhw4c = dnnl_aBcde4b, + /// 5D CNN activations tensor blocked by channels with block size 8, + /// an alias to #dnnl_aBcde8b + dnnl_nCdhw8c = dnnl_aBcde8b, + /// 4D CNN activations tensor blocked by channels with block size 32, + /// an alias to #dnnl_aBcd32b + dnnl_nChw32c = dnnl_aBcd32b, + /// 4D CNN activations tensor blocked by channels with block size 16, + /// an alias to #dnnl_aBcd16b + dnnl_nChw16c = dnnl_aBcd16b, + /// 4D CNN activations tensor blocked by channels with block size 4, + /// an alias to #dnnl_aBcd4b + dnnl_nChw4c = dnnl_aBcd4b, + /// 4D CNN activations tensor blocked by channels with block size 8, + /// an alias to #dnnl_aBcd8b + dnnl_nChw8c = dnnl_aBcd8b, + /// 3D CNN activations tensor blocked by channels with block size 32, + /// an alias to #dnnl_aBc32b + dnnl_nCw32c = dnnl_aBc32b, + /// 3D CNN activations tensor blocked by channels with block size 16, + /// an alias to #dnnl_aBc16b + dnnl_nCw16c = dnnl_aBc16b, + /// 3D CNN activations tensor blocked by channels with block size 4, + /// an alias to #dnnl_aBc4b + dnnl_nCw4c = dnnl_aBc4b, + /// 3D CNN activations tensor blocked by channels with block size 8, + /// an alias to #dnnl_aBc8b + dnnl_nCw8c = dnnl_aBc8b, + dnnl_NCw16n16c = dnnl_ABc16a16b, + dnnl_NCdhw16n16c = dnnl_ABcde16a16b, + dnnl_NChw16n16c = dnnl_ABcd16a16b, + dnnl_NCw32n16c = dnnl_ABc32a16b, + dnnl_NChw32n16c = dnnl_ABcd32a16b, + dnnl_NChw16n32c = dnnl_ABcd16a32b, + dnnl_NCdhw32n16c = dnnl_ABcde32a16b, + dnnl_NCw32n32c = dnnl_ABc32a32b, + dnnl_NChw32n32c = dnnl_ABcd32a32b, + dnnl_NCdhw32n32c = dnnl_ABcde32a32b, + + // weights, 2D + dnnl_OI16i16o = dnnl_AB16b16a, + dnnl_OI16i32o = dnnl_AB16b32a, + dnnl_OI16i48o = dnnl_AB16b48a, + dnnl_OI16i64o = dnnl_AB16b64a, + dnnl_OI8i8o2i = dnnl_AB8b8a2b, + dnnl_OI8i16o2i = dnnl_AB8b16a2b, + dnnl_OI8i24o2i = dnnl_AB8b24a2b, + dnnl_OI8i32o2i = dnnl_AB8b32a2b, + dnnl_OI8i64o2i = dnnl_AB8b64a2b, + dnnl_OI4i8o4i = dnnl_AB4b8a4b, + dnnl_OI4i16o4i = dnnl_AB4b16a4b, + dnnl_OI4i24o4i = dnnl_AB4b24a4b, + dnnl_OI4i32o4i = dnnl_AB4b32a4b, + dnnl_OI4i64o4i = dnnl_AB4b64a4b, + dnnl_OI16i16o4i = dnnl_AB16b16a4b, + dnnl_OI8i32o = dnnl_AB8b32a, + dnnl_OI8i24o = dnnl_AB8b24a, + dnnl_OI8i16o = dnnl_AB8b16a, + dnnl_OI8i8o = dnnl_AB8b8a, + + // weights, 3D + dnnl_IOw16o16i = dnnl_BAc16a16b, + dnnl_IOw16i16o = dnnl_BAc16b16a, + dnnl_OIw16i16o = dnnl_ABc16b16a, + dnnl_OwI16i16o = dnnl_AcB16b16a, + dnnl_OIw16i32o = dnnl_ABc16b32a, + dnnl_OwI16i32o = dnnl_AcB16b32a, + dnnl_OIw16i48o = dnnl_ABc16b48a, + dnnl_OwI16i48o = dnnl_AcB16b48a, + dnnl_OIw16i64o = dnnl_ABc16b64a, + dnnl_OwI16i64o = dnnl_AcB16b64a, + dnnl_OIw16o16i = dnnl_ABc16a16b, + dnnl_Oiw16o = dnnl_Abc16a, + dnnl_OIw4i8o4i = dnnl_ABc4b8a4b, + dnnl_OwI4i8o4i = dnnl_AcB4b8a4b, + dnnl_OIw4i16o4i = dnnl_ABc4b16a4b, + dnnl_OwI4i16o4i = dnnl_AcB4b16a4b, + dnnl_OIw4i24o4i = dnnl_ABc4b24a4b, + dnnl_OwI4i24o4i = dnnl_AcB4b24a4b, + dnnl_OIw4i32o4i = dnnl_ABc4b32a4b, + dnnl_OwI4i32o4i = dnnl_AcB4b32a4b, + dnnl_OIw4i64o4i = dnnl_ABc4b64a4b, + dnnl_OwI4i64o4i = dnnl_AcB4b64a4b, + dnnl_OIw2i8o4i = dnnl_ABc2b8a4b, + dnnl_OIw16i16o4i = dnnl_ABc16b16a4b, + dnnl_OIw16i16o2i = dnnl_ABc16b16a2b, + dnnl_OIw16o16i2o = dnnl_ABc16a16b2a, + dnnl_OIw4i4o = dnnl_ABc4b4a, + dnnl_OIw4o4i = dnnl_ABc4a4b, + dnnl_Oiw4o = dnnl_Abc4a, + dnnl_OIw8i8o2i = dnnl_ABc8b8a2b, + dnnl_OwI8i8o2i = dnnl_AcB8b8a2b, + dnnl_OIw8i16o2i = dnnl_ABc8b16a2b, + dnnl_OwI8i16o2i = dnnl_AcB8b16a2b, + dnnl_OIw8i24o2i = dnnl_ABc8b24a2b, + dnnl_OwI8i24o2i = dnnl_AcB8b24a2b, + dnnl_OIw8i32o2i = dnnl_ABc8b32a2b, + dnnl_OwI8i32o2i = dnnl_AcB8b32a2b, + dnnl_OIw8i64o2i = dnnl_ABc8b64a2b, + dnnl_OwI8i64o2i = dnnl_AcB8b64a2b, + dnnl_OIw8i8o = dnnl_ABc8b8a, + dnnl_OwI8i8o = dnnl_AcB8b8a, + dnnl_OIw8o16i2o = dnnl_ABc8a16b2a, + dnnl_IOw8o16i2o = dnnl_BAc8a16b2a, + dnnl_OIw8o8i = dnnl_ABc8a8b, + dnnl_OIw8o4i = dnnl_ABc8a4b, + dnnl_Owi16o = dnnl_Acb16a, + dnnl_OwI16o2i = dnnl_AcB16a2b, + dnnl_OwI16o4i = dnnl_AcB16a4b, + dnnl_Iwo8i = dnnl_Bca8b, + dnnl_IwO8i2o = dnnl_BcA8b2a, + dnnl_IwO8i4o = dnnl_BcA8b4a, + dnnl_Iwo16i = dnnl_Bca16b, + dnnl_IwO16i2o = dnnl_BcA16b2a, + dnnl_IwO16i4o = dnnl_BcA16b4a, + dnnl_Iwo24i = dnnl_Bca24b, + dnnl_IwO24i2o = dnnl_BcA24b2a, + dnnl_IwO24i4o = dnnl_BcA24b4a, + dnnl_Owi4o = dnnl_Acb4a, + dnnl_Owi8o = dnnl_Acb8a, + dnnl_OwI8o2i = dnnl_AcB8a2b, + dnnl_OIw8i32o = dnnl_ABc8b32a, + dnnl_OwI8i32o = dnnl_AcB8b32a, + dnnl_OIw8i24o = dnnl_ABc8b24a, + dnnl_OwI8i24o = dnnl_AcB8b24a, + dnnl_OIw8i16o = dnnl_ABc8b16a, + dnnl_OwI8i16o = dnnl_AcB8b16a, + dnnl_OwI8o4i = dnnl_AcB8a4b, + + // weights, 4D + dnnl_IOhw16i16o = dnnl_BAcd16b16a, + dnnl_IOhw16o16i = dnnl_BAcd16a16b, + dnnl_Ohwi16o = dnnl_Acdb16a, + dnnl_OhwI16o2i = dnnl_AcdB16a2b, + dnnl_OhwI16o4i = dnnl_AcdB16a4b, + dnnl_Ihwo8i = dnnl_Bcda8b, + dnnl_IhwO8i2o = dnnl_BcdA8b2a, + dnnl_IhwO8i4o = dnnl_BcdA8b4a, + dnnl_Ihwo16i = dnnl_Bcda16b, + dnnl_IhwO16i2o = dnnl_BcdA16b2a, + dnnl_IhwO16i4o = dnnl_BcdA16b4a, + dnnl_Ihwo24i = dnnl_Bcda24b, + dnnl_IhwO24i2o = dnnl_BcdA24b2a, + dnnl_IhwO24i4o = dnnl_BcdA24b4a, + dnnl_Ohwi24o = dnnl_Acdb24a, + dnnl_Ohwi32o = dnnl_Acdb32a, + dnnl_Ohwi4o = dnnl_Acdb4a, + dnnl_Ohwi8o = dnnl_Acdb8a, + dnnl_OhwI8o2i = dnnl_AcdB8a2b, + dnnl_OhwI8o4i = dnnl_AcdB8a4b, + dnnl_OIhw16i16o = dnnl_ABcd16b16a, + dnnl_OhwI16i16o = dnnl_AcdB16b16a, + dnnl_OIhw16i32o = dnnl_ABcd16b32a, + dnnl_OhwI16i32o = dnnl_AcdB16b32a, + dnnl_OIhw16i48o = dnnl_ABcd16b48a, + dnnl_OhwI16i48o = dnnl_AcdB16b48a, + dnnl_OIhw16i64o = dnnl_ABcd16b64a, + dnnl_OhwI16i64o = dnnl_AcdB16b64a, + dnnl_OIhw16o16i = dnnl_ABcd16a16b, + dnnl_Oihw16o = dnnl_Abcd16a, + dnnl_OIhw4i8o4i = dnnl_ABcd4b8a4b, + dnnl_OhwI4i8o4i = dnnl_AcdB4b8a4b, + dnnl_OIhw4i16o4i = dnnl_ABcd4b16a4b, + dnnl_OhwI4i16o4i = dnnl_AcdB4b16a4b, + dnnl_OIhw4i24o4i = dnnl_ABcd4b24a4b, + dnnl_OhwI4i24o4i = dnnl_AcdB4b24a4b, + dnnl_OIhw4i32o4i = dnnl_ABcd4b32a4b, + dnnl_OhwI4i32o4i = dnnl_AcdB4b32a4b, + dnnl_OIhw4i64o4i = dnnl_ABcd4b64a4b, + dnnl_OhwI4i64o4i = dnnl_AcdB4b64a4b, + dnnl_OIhw16i16o4i = dnnl_ABcd16b16a4b, + dnnl_OIhw16i16o2i = dnnl_ABcd16b16a2b, + dnnl_OIhw16o16i2o = dnnl_ABcd16a16b2a, + dnnl_OIhw4i4o = dnnl_ABcd4b4a, + dnnl_OIhw4o4i = dnnl_ABcd4a4b, + dnnl_Oihw4o = dnnl_Abcd4a, + dnnl_OIhw8i8o2i = dnnl_ABcd8b8a2b, + dnnl_OhwI8i8o2i = dnnl_AcdB8b8a2b, + dnnl_OIhw8i16o2i = dnnl_ABcd8b16a2b, + dnnl_OhwI8i16o2i = dnnl_AcdB8b16a2b, + dnnl_OIhw8i32o2i = dnnl_ABcd8b32a2b, + dnnl_OhwI8i32o2i = dnnl_AcdB8b32a2b, + dnnl_OIhw8i24o2i = dnnl_ABcd8b24a2b, + dnnl_OhwI8i24o2i = dnnl_AcdB8b24a2b, + dnnl_OIhw8i64o2i = dnnl_ABcd8b64a2b, + dnnl_OhwI8i64o2i = dnnl_AcdB8b64a2b, + dnnl_OIhw8i8o = dnnl_ABcd8b8a, + dnnl_OhwI8i8o = dnnl_AcdB8b8a, + dnnl_OIhw8o16i2o = dnnl_ABcd8a16b2a, + dnnl_OIhw2i8o4i = dnnl_ABcd2b8a4b, + dnnl_IOhw8o16i2o = dnnl_BAcd8a16b2a, + dnnl_OIhw8o8i = dnnl_ABcd8a8b, + dnnl_OIhw8o4i = dnnl_ABcd8a4b, + dnnl_Owhi16o = dnnl_Adcb16a, + dnnl_OIhw8i32o = dnnl_ABcd8b32a, + dnnl_OhwI8i32o = dnnl_AcdB8b32a, + dnnl_OIhw8i24o = dnnl_ABcd8b24a, + dnnl_OhwI8i24o = dnnl_AcdB8b24a, + dnnl_OIhw8i16o = dnnl_ABcd8b16a, + dnnl_OhwI8i16o = dnnl_AcdB8b16a, + + // weights, 5D + dnnl_Odhwi16o = dnnl_Acdeb16a, + dnnl_OdhwI16o2i = dnnl_AcdeB16a2b, + dnnl_OdhwI16o4i = dnnl_AcdeB16a4b, + dnnl_Idhwo8i = dnnl_Bcdea8b, + dnnl_IdhwO8i2o = dnnl_BcdeA8b2a, + dnnl_IdhwO8i4o = dnnl_BcdeA8b4a, + dnnl_Idhwo16i = dnnl_Bcdea16b, + dnnl_IdhwO16i2o = dnnl_BcdeA16b2a, + dnnl_IdhwO16i4o = dnnl_BcdeA16b4a, + dnnl_Idhwo24i = dnnl_Bcdea24b, + dnnl_IdhwO24i2o = dnnl_BcdeA24b2a, + dnnl_IdhwO24i4o = dnnl_BcdeA24b4a, + dnnl_Odhwi4o = dnnl_Acdeb4a, + dnnl_Odhwi8o = dnnl_Acdeb8a, + dnnl_OdhwI8o2i = dnnl_AcdeB8a2b, + dnnl_OdhwI8o4i = dnnl_AcdeB8a4b, + dnnl_Odwhi16o = dnnl_Acedb16a, + dnnl_OIdhw16i16o = dnnl_ABcde16b16a, + dnnl_OdhwI16i16o = dnnl_AcdeB16b16a, + dnnl_OIdhw16i32o = dnnl_ABcde16b32a, + dnnl_OdhwI16i32o = dnnl_AcdeB16b32a, + dnnl_OIdhw16i48o = dnnl_ABcde16b48a, + dnnl_OdhwI16i48o = dnnl_AcdeB16b48a, + dnnl_OIdhw16i64o = dnnl_ABcde16b64a, + dnnl_OdhwI16i64o = dnnl_AcdeB16b64a, + dnnl_OIdhw16o16i = dnnl_ABcde16a16b, + dnnl_Oidhw16o = dnnl_Abcde16a, + dnnl_OIdhw4i4o = dnnl_ABcde4b4a, + dnnl_OIdhw4o4i = dnnl_ABcde4a4b, + dnnl_Oidhw4o = dnnl_Abcde4a, + dnnl_OIdhw8i8o2i = dnnl_ABcde8b8a2b, + dnnl_OdhwI8i8o2i = dnnl_AcdeB8b8a2b, + dnnl_OIdhw8i16o2i = dnnl_ABcde8b16a2b, + dnnl_OdhwI8i16o2i = dnnl_AcdeB8b16a2b, + dnnl_OIdhw8i32o2i = dnnl_ABcde8b32a2b, + dnnl_OdhwI8i32o2i = dnnl_AcdeB8b32a2b, + dnnl_OIdhw8i24o2i = dnnl_ABcde8b24a2b, + dnnl_OdhwI8i24o2i = dnnl_AcdeB8b24a2b, + dnnl_OIdhw8i64o2i = dnnl_ABcde8b64a2b, + dnnl_OdhwI8i64o2i = dnnl_AcdeB8b64a2b, + dnnl_OIdhw8i8o = dnnl_ABcde8b8a, + dnnl_OdhwI8i8o = dnnl_AcdeB8b8a, + dnnl_OIdhw8o16i2o = dnnl_ABcde8a16b2a, + dnnl_IOdhw8o16i2o = dnnl_BAcde8a16b2a, + dnnl_OIdhw4i8o4i = dnnl_ABcde4b8a4b, + dnnl_OdhwI4i8o4i = dnnl_AcdeB4b8a4b, + dnnl_OIdhw4i16o4i = dnnl_ABcde4b16a4b, + dnnl_OdhwI4i16o4i = dnnl_AcdeB4b16a4b, + dnnl_OIdhw4i24o4i = dnnl_ABcde4b24a4b, + dnnl_OdhwI4i24o4i = dnnl_AcdeB4b24a4b, + dnnl_OIdhw4i32o4i = dnnl_ABcde4b32a4b, + dnnl_OdhwI4i32o4i = dnnl_AcdeB4b32a4b, + dnnl_OIdhw4i64o4i = dnnl_ABcde4b64a4b, + dnnl_OdhwI4i64o4i = dnnl_AcdeB4b64a4b, + dnnl_OIdhw16i16o4i = dnnl_ABcde16b16a4b, + dnnl_OIdhw16i16o2i = dnnl_ABcde16b16a2b, + dnnl_OIdhw2i8o4i = dnnl_ABcde2b8a4b, + dnnl_OIdhw8o8i = dnnl_ABcde8a8b, + dnnl_OIdhw8o4i = dnnl_ABcde8a4b, + dnnl_IOdhw16i16o = dnnl_BAcde16b16a, + dnnl_OIdhw4o8i8o4i = dnnl_ABcde4a8b8a4b, + dnnl_IOdhw16o16i = dnnl_BAcde16a16b, + dnnl_OIdhw16o16i2o = dnnl_ABcde16a16b2a, + dnnl_OIdhw8i32o = dnnl_ABcde8b32a, + dnnl_OdhwI8i32o = dnnl_AcdeB8b32a, + dnnl_OIdhw8i24o = dnnl_ABcde8b24a, + dnnl_OdhwI8i24o = dnnl_AcdeB8b24a, + dnnl_OIdhw8i16o = dnnl_ABcde8b16a, + dnnl_OdhwI8i16o = dnnl_AcdeB8b16a, + + // weights w/ groups, 3D + dnnl_Goiw16g = dnnl_Abcd16a, + dnnl_Goiw8g = dnnl_Abcd8a, + dnnl_Goiw4g = dnnl_Abcd4a, + dnnl_gIOw16o16i = dnnl_aCBd16b16c, + dnnl_gIOw16i16o = dnnl_aCBd16c16b, + dnnl_gOIw16i16o = dnnl_aBCd16c16b, + dnnl_gOIw16o16i = dnnl_aBCd16b16c, + dnnl_gOiw16o = dnnl_aBcd16b, + dnnl_gOIw4i16o4i = dnnl_aBCd4c16b4c, + dnnl_gOIw2i8o4i = dnnl_aBCd2c8b4c, + dnnl_gOIw16i16o4i = dnnl_aBCd16c16b4c, + dnnl_gOIw16i16o2i = dnnl_aBCd16c16b2c, + dnnl_gOIw16o16i2o = dnnl_aBCd16b16c2b, + dnnl_gOIw4i4o = dnnl_aBCd4c4b, + dnnl_gOIw4o4i = dnnl_aBCd4b4c, + dnnl_gOiw4o = dnnl_aBcd4b, + dnnl_gOIw8i16o2i = dnnl_aBCd8c16b2c, + dnnl_gOIw8i8o = dnnl_aBCd8c8b, + dnnl_gOIw8o16i2o = dnnl_aBCd8b16c2b, + dnnl_gIOw8o16i2o = dnnl_aCBd8b16c2b, + dnnl_gOIw8o8i = dnnl_aBCd8b8c, + dnnl_gOIw8o4i = dnnl_aBCd8b4c, + dnnl_gOwi16o = dnnl_aBdc16b, + dnnl_gOwI16o2i = dnnl_aBdC16b2c, + dnnl_gOwI16o4i = dnnl_aBdC16b4c, + dnnl_gIwo8i = dnnl_aCdb8c, + dnnl_gIwO8i2o = dnnl_aCdB8c2b, + dnnl_gIwO8i4o = dnnl_aCdB8c4b, + dnnl_gIwo16i = dnnl_aCdb16c, + dnnl_gIwO16i2o = dnnl_aCdB16c2b, + dnnl_gIwO16i4o = dnnl_aCdB16c4b, + dnnl_gIwo24i = dnnl_aCdb24c, + dnnl_gIwO24i2o = dnnl_aCdB24c2b, + dnnl_gIwO24i4o = dnnl_aCdB24c4b, + dnnl_gOwi4o = dnnl_aBdc4b, + dnnl_gOwi8o = dnnl_aBdc8b, + dnnl_gOwI8o2i = dnnl_aBdC8b2c, + dnnl_gOwI8o4i = dnnl_aBdC8b4c, + dnnl_Goiw32g = dnnl_Abcd32a, + dnnl_gOIw2i4o2i = dnnl_aBCd2c4b2c, + dnnl_gOIw2o4i2o = dnnl_aBCd2b4c2b, + dnnl_gOIw4i8o2i = dnnl_aBCd4c8b2c, + dnnl_gOIw4o8i2o = dnnl_aBCd4b8c2b, + dnnl_goIw4i = dnnl_abCd4c, + dnnl_goIw32i = dnnl_abCd32c, + + // weights w/ groups, 4D + dnnl_gIOhw16i16o = dnnl_aCBde16c16b, + dnnl_gIOhw16o16i = dnnl_aCBde16b16c, + dnnl_gOhwi16o = dnnl_aBdec16b, + dnnl_gOhwI16o2i = dnnl_aBdeC16b2c, + dnnl_gOhwI16o4i = dnnl_aBdeC16b4c, + dnnl_gIhwo8i = dnnl_aCdeb8c, + dnnl_gIhwO8i2o = dnnl_aCdeB8c2b, + dnnl_gIhwO8i4o = dnnl_aCdeB8c4b, + dnnl_gIhwo16i = dnnl_aCdeb16c, + dnnl_gIhwO16i2o = dnnl_aCdeB16c2b, + dnnl_gIhwO16i4o = dnnl_aCdeB16c4b, + dnnl_gIhwo24i = dnnl_aCdeb24c, + dnnl_gIhwO24i2o = dnnl_aCdeB24c2b, + dnnl_gIhwO24i4o = dnnl_aCdeB24c4b, + dnnl_gOhwi32o = dnnl_aBdec32b, + dnnl_gOhwi24o = dnnl_aBdec24b, + dnnl_gOhwI24o2i = dnnl_aBdeC24b2c, + dnnl_gOhwI24o4i = dnnl_aBdeC24b4c, + dnnl_gOhwi4o = dnnl_aBdec4b, + dnnl_gOhwi8o = dnnl_aBdec8b, + dnnl_gOhwI8o2i = dnnl_aBdeC8b2c, + dnnl_gOhwI8o4i = dnnl_aBdeC8b4c, + dnnl_Goihw16g = dnnl_Abcde16a, + dnnl_gOIhw16i16o = dnnl_aBCde16c16b, + dnnl_gOIhw16o16i = dnnl_aBCde16b16c, + dnnl_gOihw16o = dnnl_aBcde16b, + dnnl_gOIhw2i8o4i = dnnl_aBCde2c8b4c, + dnnl_gOIhw4i16o4i = dnnl_aBCde4c16b4c, + dnnl_gOIhw16i16o4i = dnnl_aBCde16c16b4c, + dnnl_gOIhw16i16o2i = dnnl_aBCde16c16b2c, + dnnl_gOIhw16o16i2o = dnnl_aBCde16b16c2b, + dnnl_gOIhw4i4o = dnnl_aBCde4c4b, + dnnl_gOIhw4o4i = dnnl_aBCde4b4c, + dnnl_gOihw4o = dnnl_aBcde4b, + dnnl_Goihw8g = dnnl_Abcde8a, + dnnl_Goihw4g = dnnl_Abcde4a, + dnnl_gOIhw8i16o2i = dnnl_aBCde8c16b2c, + dnnl_gOIhw8i8o = dnnl_aBCde8c8b, + dnnl_gOIhw8o16i2o = dnnl_aBCde8b16c2b, + dnnl_gIOhw8o16i2o = dnnl_aCBde8b16c2b, + dnnl_gOIhw8o8i = dnnl_aBCde8b8c, + dnnl_gOIhw8o4i = dnnl_aBCde8b4c, + dnnl_Goihw32g = dnnl_Abcde32a, + dnnl_gOwhi16o = dnnl_aBedc16b, + dnnl_goIhw4i = dnnl_abCde4c, + dnnl_goIhw32i = dnnl_abCde32c, + + dnnl_OIw4o8i8o4i = dnnl_ABc4a8b8a4b, + dnnl_OIhw4o8i8o4i = dnnl_ABcd4a8b8a4b, + dnnl_IOw4i8o8i4o = dnnl_BAc4b8a8b4a, + dnnl_IOhw4i8o8i4o = dnnl_BAcd4b8a8b4a, + dnnl_IOdhw4i8o8i4o = dnnl_BAcde4b8a8b4a, + + dnnl_OIhw2o8i8o2i = dnnl_ABcd2a8b8a2b, + dnnl_gOIw4o8i8o4i = dnnl_aBCd4b8c8b4c, + dnnl_gOIhw4o8i8o4i = dnnl_aBCde4b8c8b4c, + dnnl_gOIdhw4o8i8o4i = dnnl_aBCdef4b8c8b4c, + dnnl_gIOw4i8o8i4o = dnnl_aCBd4c8b8c4b, + dnnl_gIOhw4i8o8i4o = dnnl_aCBde4c8b8c4b, + dnnl_gIOdhw4i8o8i4o = dnnl_aCBdef4c8b8c4b, + dnnl_gOIhw2o8i8o2i = dnnl_aBCde2b8c8b2c, + dnnl_gOIhw2i4o2i = dnnl_aBCde2c4b2c, + dnnl_gOIhw2o4i2o = dnnl_aBCde2b4c2b, + dnnl_gOIhw4i8o2i = dnnl_aBCde4c8b2c, + dnnl_gOIhw4o8i2o = dnnl_aBCde4b8c2b, + + // weights w/ groups, 6D + dnnl_gIOdhw16i16o = dnnl_aCBdef16c16b, + dnnl_gIOdhw16o16i = dnnl_aCBdef16b16c, + dnnl_gOdhwi16o = dnnl_aBdefc16b, + dnnl_gOdhwI16o2i = dnnl_aBdefC16b2c, + dnnl_gOdhwI16o4i = dnnl_aBdefC16b4c, + dnnl_gIdhwo8i = dnnl_aCdefb8c, + dnnl_gIdhwO8i2o = dnnl_aCdefB8c2b, + dnnl_gIdhwO8i4o = dnnl_aCdefB8c4b, + dnnl_gIdhwo16i = dnnl_aCdefb16c, + dnnl_gIdhwO16i2o = dnnl_aCdefB16c2b, + dnnl_gIdhwO16i4o = dnnl_aCdefB16c4b, + dnnl_gIdhwo24i = dnnl_aCdefb24c, + dnnl_gIdhwO24i2o = dnnl_aCdefB24c2b, + dnnl_gIdhwO24i4o = dnnl_aCdefB24c4b, + dnnl_gOdhwi4o = dnnl_aBdefc4b, + dnnl_gOdhwi8o = dnnl_aBdefc8b, + dnnl_gOdhwI8o2i = dnnl_aBdefC8b2c, + dnnl_gOdhwI8o4i = dnnl_aBdefC8b4c, + dnnl_gOdwhi16o = dnnl_aBdfec16b, + dnnl_gOIdhw16i16o = dnnl_aBCdef16c16b, + dnnl_gOIdhw4i16o4i = dnnl_aBCdef4c16b4c, + dnnl_gOIdhw16i16o4i = dnnl_aBCdef16c16b4c, + dnnl_gOIdhw2i8o4i = dnnl_aBCdef2c8b4c, + dnnl_gOIdhw16i16o2i = dnnl_aBCdef16c16b2c, + dnnl_gOIdhw16o16i = dnnl_aBCdef16b16c, + dnnl_gOIdhw16o16i2o = dnnl_aBCdef16b16c2b, + dnnl_gOidhw16o = dnnl_aBcdef16b, + dnnl_gOIdhw4i4o = dnnl_aBCdef4c4b, + dnnl_gOIdhw4o4i = dnnl_aBCdef4b4c, + dnnl_gOidhw4o = dnnl_aBcdef4b, + dnnl_gOIdhw8i16o2i = dnnl_aBCdef8c16b2c, + dnnl_gOIdhw8i8o = dnnl_aBCdef8c8b, + dnnl_gOIdhw8o16i2o = dnnl_aBCdef8b16c2b, + dnnl_gIOdhw8o16i2o = dnnl_aCBdef8b16c2b, + dnnl_gOIdhw8o8i = dnnl_aBCdef8b8c, + dnnl_gOIdhw8o4i = dnnl_aBCdef8b4c, + dnnl_Goidhw16g = dnnl_Abcdef16a, + dnnl_Goidhw32g = dnnl_Abcdef32a, + dnnl_gOIdhw2i4o2i = dnnl_aBCdef2c4b2c, + dnnl_gOIdhw4i8o2i = dnnl_aBCdef4c8b2c, + dnnl_gOIdhw2o4i2o = dnnl_aBCdef2b4c2b, + dnnl_gOIdhw4o8i2o = dnnl_aBCdef4b8c2b, + dnnl_goIdhw4i = dnnl_abCdef4c, + dnnl_goIdhw32i = dnnl_abCdef32c, + + // weights, 3D + dnnl_Owi24o = dnnl_Acb24a, + dnnl_OwI24o2i = dnnl_AcB24a2b, + dnnl_OwI24o4i = dnnl_AcB24a4b, + dnnl_Owi32o = dnnl_Acb32a, + dnnl_OwI32o2i = dnnl_AcB32a2b, + dnnl_OwI32o4i = dnnl_AcB32a4b, + dnnl_Owi48o = dnnl_Acb48a, + dnnl_OwI48o2i = dnnl_AcB48a2b, + dnnl_OwI48o4i = dnnl_AcB48a4b, + dnnl_Owi64o = dnnl_Acb64a, + dnnl_OwI64o2i = dnnl_AcB64a2b, + dnnl_OwI64o4i = dnnl_AcB64a4b, + dnnl_Iwo32i = dnnl_Bca32b, + dnnl_IwO32i2o = dnnl_BcA32b2a, + dnnl_IwO32i4o = dnnl_BcA32b4a, + dnnl_Iwo48i = dnnl_Bca48b, + dnnl_IwO48i2o = dnnl_BcA48b2a, + dnnl_IwO48i4o = dnnl_BcA48b4a, + dnnl_Iwo64i = dnnl_Bca64b, + dnnl_IwO64i2o = dnnl_BcA64b2a, + dnnl_IwO64i4o = dnnl_BcA64b4a, + dnnl_wIo2i = dnnl_cBa2b, + dnnl_wIo4i = dnnl_cBa4b, + dnnl_gOwi24o = dnnl_aBdc24b, + dnnl_gOwI24o2i = dnnl_aBdC24b2c, + dnnl_gOwI24o4i = dnnl_aBdC24b4c, + dnnl_gOwi32o = dnnl_aBdc32b, + dnnl_gOwI32o2i = dnnl_aBdC32b2c, + dnnl_gOwI32o4i = dnnl_aBdC32b4c, + dnnl_gOwi48o = dnnl_aBdc48b, + dnnl_gOwI48o2i = dnnl_aBdC48b2c, + dnnl_gOwI48o4i = dnnl_aBdC48b4c, + dnnl_gOwi64o = dnnl_aBdc64b, + dnnl_gOwI64o2i = dnnl_aBdC64b2c, + dnnl_gOwI64o4i = dnnl_aBdC64b4c, + dnnl_gIwo32i = dnnl_aCdb32c, + dnnl_gIwO32i2o = dnnl_aCdB32c2b, + dnnl_gIwO32i4o = dnnl_aCdB32c4b, + dnnl_gIwo48i = dnnl_aCdb48c, + dnnl_gIwO48i2o = dnnl_aCdB48c2b, + dnnl_gIwO48i4o = dnnl_aCdB48c4b, + dnnl_gIwo64i = dnnl_aCdb64c, + dnnl_gIwO64i2o = dnnl_aCdB64c2b, + dnnl_gIwO64i4o = dnnl_aCdB64c4b, + dnnl_gwio = dnnl_adcb, + dnnl_gwIo2i = dnnl_adCb2c, + dnnl_gwIo4i = dnnl_adCb4c, + // weights, 4D + dnnl_OhwI24o = dnnl_Acdb24a, + dnnl_OhwI24o2i = dnnl_AcdB24a2b, + dnnl_OhwI24o4i = dnnl_AcdB24a4b, + dnnl_OhwI32o = dnnl_Acdb32a, + dnnl_OhwI32o2i = dnnl_AcdB32a2b, + dnnl_OhwI32o4i = dnnl_AcdB32a4b, + dnnl_Ohwi48o = dnnl_Acdb48a, + dnnl_OhwI48o2i = dnnl_AcdB48a2b, + dnnl_OhwI48o4i = dnnl_AcdB48a4b, + dnnl_Ohwi64o = dnnl_Acdb64a, + dnnl_OhwI64o2i = dnnl_AcdB64a2b, + dnnl_OhwI64o4i = dnnl_AcdB64a4b, + dnnl_Ihwo32i = dnnl_Bcda32b, + dnnl_IhwO32i2o = dnnl_BcdA32b2a, + dnnl_IhwO32i4o = dnnl_BcdA32b4a, + dnnl_Ihwo48i = dnnl_Bcda48b, + dnnl_IhwO48i2o = dnnl_BcdA48b2a, + dnnl_IhwO48i4o = dnnl_BcdA48b4a, + dnnl_Ihwo64i = dnnl_Bcda64b, + dnnl_IhwO64i2o = dnnl_BcdA64b2a, + dnnl_IhwO64i4o = dnnl_BcdA64b4a, + dnnl_hwIo2i = dnnl_cdBa2b, + dnnl_hwIo4i = dnnl_cdBa4b, + dnnl_gOhwI24o = dnnl_aBdec24b, + dnnl_gOhwI32o = dnnl_aBdec32b, + dnnl_gOhwI32o2i = dnnl_aBdeC32b2c, + dnnl_gOhwI32o4i = dnnl_aBdeC32b4c, + dnnl_gOhwi48o = dnnl_aBdec48b, + dnnl_gOhwI48o2i = dnnl_aBdeC48b2c, + dnnl_gOhwI48o4i = dnnl_aBdeC48b4c, + dnnl_gOhwi64o = dnnl_aBdec64b, + dnnl_gOhwI64o2i = dnnl_aBdeC64b2c, + dnnl_gOhwI64o4i = dnnl_aBdeC64b4c, + dnnl_gIhwo32i = dnnl_aCdeb32c, + dnnl_gIhwO32i2o = dnnl_aCdeB32c2b, + dnnl_gIhwO32i4o = dnnl_aCdeB32c4b, + dnnl_gIhwo48i = dnnl_aCdeb48c, + dnnl_gIhwO48i2o = dnnl_aCdeB48c2b, + dnnl_gIhwO48i4o = dnnl_aCdeB48c4b, + dnnl_gIhwo64i = dnnl_aCdeb64c, + dnnl_gIhwO64i2o = dnnl_aCdeB64c2b, + dnnl_gIhwO64i4o = dnnl_aCdeB64c4b, + dnnl_ghwio = dnnl_adecb, + dnnl_ghwIo2i = dnnl_adeCb2c, + dnnl_ghwIo4i = dnnl_adeCb4c, + // weights, 5D + dnnl_Odhwi24o = dnnl_Acdeb24a, + dnnl_OdhwI24o2i = dnnl_AcdeB24a2b, + dnnl_OdhwI24o4i = dnnl_AcdeB24a4b, + dnnl_Odhwi32o = dnnl_Acdeb32a, + dnnl_OdhwI32o2i = dnnl_AcdeB32a2b, + dnnl_OdhwI32o4i = dnnl_AcdeB32a4b, + dnnl_Odhwi48o = dnnl_Acdeb48a, + dnnl_OdhwI48o2i = dnnl_AcdeB48a2b, + dnnl_OdhwI48o4i = dnnl_AcdeB48a4b, + dnnl_Odhwi64o = dnnl_Acdeb64a, + dnnl_OdhwI64o2i = dnnl_AcdeB64a2b, + dnnl_OdhwI64o4i = dnnl_AcdeB64a4b, + dnnl_Idhwo32i = dnnl_Bcdea32b, + dnnl_IdhwO32i2o = dnnl_BcdeA32b2a, + dnnl_IdhwO32i4o = dnnl_BcdeA32b4a, + dnnl_Idhwo48i = dnnl_Bcdea48b, + dnnl_IdhwO48i2o = dnnl_BcdeA48b2a, + dnnl_IdhwO48i4o = dnnl_BcdeA48b4a, + dnnl_Idhwo64i = dnnl_Bcdea64b, + dnnl_IdhwO64i2o = dnnl_BcdeA64b2a, + dnnl_IdhwO64i4o = dnnl_BcdeA64b4a, + dnnl_dhwIo2i = dnnl_cdeBa2b, + dnnl_dhwIo4i = dnnl_cdeBa4b, + dnnl_gOdhwi24o = dnnl_aBdefc24b, + dnnl_gOdhwI24o2i = dnnl_aBdefC24b2c, + dnnl_gOdhwI24o4i = dnnl_aBdefC24b4c, + dnnl_gOdhwi32o = dnnl_aBdefc32b, + dnnl_gOdhwI32o2i = dnnl_aBdefC32b2c, + dnnl_gOdhwI32o4i = dnnl_aBdefC32b4c, + dnnl_gOdhwi48o = dnnl_aBdefc48b, + dnnl_gOdhwI48o2i = dnnl_aBdefC48b2c, + dnnl_gOdhwI48o4i = dnnl_aBdefC48b4c, + dnnl_gOdhwi64o = dnnl_aBdefc64b, + dnnl_gOdhwI64o2i = dnnl_aBdefC64b2c, + dnnl_gOdhwI64o4i = dnnl_aBdefC64b4c, + dnnl_gIdhwo32i = dnnl_aCdefb32c, + dnnl_gIdhwO32i2o = dnnl_aCdefB32c2b, + dnnl_gIdhwO32i4o = dnnl_aCdefB32c4b, + dnnl_gIdhwo48i = dnnl_aCdefb48c, + dnnl_gIdhwO48i2o = dnnl_aCdefB48c2b, + dnnl_gIdhwO48i4o = dnnl_aCdefB48c4b, + dnnl_gIdhwo64i = dnnl_aCdefb64c, + dnnl_gIdhwO64i2o = dnnl_aCdefB64c2b, + dnnl_gIdhwO64i4o = dnnl_aCdefB64c4b, + dnnl_gdhwio = dnnl_adefcb, + dnnl_gdhwIo2i = dnnl_adefCb2c, + dnnl_gdhwIo4i = dnnl_adefCb4c, + dnnl_OI16i32o4i = dnnl_AB16b32a4b, + dnnl_OI16i48o4i = dnnl_AB16b48a4b, + dnnl_OI16i64o4i = dnnl_AB16b64a4b, + dnnl_OI16i16o2i = dnnl_AB16b16a2b, + dnnl_OI16i32o2i = dnnl_AB16b32a2b, + dnnl_OI16i48o2i = dnnl_AB16b48a2b, + dnnl_OI16i64o2i = dnnl_AB16b64a2b, + dnnl_OIw16i32o4i = dnnl_ABc16b32a4b, + dnnl_OIw16i48o4i = dnnl_ABc16b48a4b, + dnnl_OIw16i64o4i = dnnl_ABc16b64a4b, + dnnl_OIw16i32o2i = dnnl_ABc16b32a2b, + dnnl_OIw16i48o2i = dnnl_ABc16b48a2b, + dnnl_OIw16i64o2i = dnnl_ABc16b64a2b, + dnnl_OIhw16i32o4i = dnnl_ABcd16b32a4b, + dnnl_OIhw16i48o4i = dnnl_ABcd16b48a4b, + dnnl_OIhw16i64o4i = dnnl_ABcd16b64a4b, + dnnl_OIhw16i32o2i = dnnl_ABcd16b32a2b, + dnnl_OIhw16i48o2i = dnnl_ABcd16b48a2b, + dnnl_OIhw16i64o2i = dnnl_ABcd16b64a2b, + dnnl_OIdhw16i32o4i = dnnl_ABcde16b32a4b, + dnnl_OIdhw16i48o4i = dnnl_ABcde16b48a4b, + dnnl_OIdhw16i64o4i = dnnl_ABcde16b64a4b, + dnnl_OIdhw16i32o2i = dnnl_ABcde16b32a2b, + dnnl_OIdhw16i48o2i = dnnl_ABcde16b48a2b, + dnnl_OIdhw16i64o2i = dnnl_ABcde16b64a2b, + dnnl_OwI16i16o2i = dnnl_AcB16b16a2b, + dnnl_OwI16i16o4i = dnnl_AcB16b16a4b, + dnnl_OhwI16i16o2i = dnnl_AcdB16b16a2b, + dnnl_OhwI16i16o4i = dnnl_AcdB16b16a4b, + dnnl_OdhwI16i16o2i = dnnl_AcdeB16b16a2b, + dnnl_OdhwI16i16o4i = dnnl_AcdeB16b16a4b, + dnnl_IwO16o16i2o = dnnl_BcA16a16b2a, + dnnl_IwO16o16i4o = dnnl_BcA16a16b4a, + dnnl_IhwO16o16i2o = dnnl_BcdA16a16b2a, + dnnl_IhwO16o16i4o = dnnl_BcdA16a16b4a, + dnnl_IdhwO16o16i2o = dnnl_BcdeA16a16b2a, + dnnl_IdhwO16o16i4o = dnnl_BcdeA16a16b4a, + dnnl_gOwI16i16o2i = dnnl_aBdC16c16b2c, + dnnl_gOwI16i16o4i = dnnl_aBdC16c16b4c, + dnnl_gOhwI16i16o2i = dnnl_aBdeC16c16b2c, + dnnl_gOhwI16i16o4i = dnnl_aBdeC16c16b4c, + dnnl_gOdhwI16i16o2i = dnnl_aBdefC16c16b2c, + dnnl_gOdhwI16i16o4i = dnnl_aBdefC16c16b4c, + dnnl_gIwO16o16i2o = dnnl_aCdB16b16c2b, + dnnl_gIwO16o16i4o = dnnl_aCdB16b16c4b, + dnnl_gIhwO16o16i2o = dnnl_aCdeB16b16c2b, + dnnl_gIhwO16o16i4o = dnnl_aCdeB16b16c4b, + dnnl_gIdhwO16o16i2o = dnnl_aCdefB16b16c2b, + dnnl_gIdhwO16o16i4o = dnnl_aCdefB16b16c4b, + dnnl_OwI16i32o2i = dnnl_AcB16b32a2b, + dnnl_OwI16i32o4i = dnnl_AcB16b32a4b, + dnnl_OwI16i48o2i = dnnl_AcB16b48a2b, + dnnl_OwI16i48o4i = dnnl_AcB16b48a4b, + dnnl_OwI16i64o2i = dnnl_AcB16b64a2b, + dnnl_OwI16i64o4i = dnnl_AcB16b64a4b, + dnnl_IwO16o32i2o = dnnl_BcA16a32b2a, + dnnl_IwO16o32i4o = dnnl_BcA16a32b4a, + dnnl_IwO16o48i2o = dnnl_BcA16a48b2a, + dnnl_IwO16o48i4o = dnnl_BcA16a48b4a, + dnnl_IwO16o64i2o = dnnl_BcA16a64b2a, + dnnl_IwO16o64i4o = dnnl_BcA16a64b4a, + dnnl_gOwI16i32o2i = dnnl_aBdC16c32b2c, + dnnl_gOwI16i32o4i = dnnl_aBdC16c32b4c, + dnnl_gOwI16i48o2i = dnnl_aBdC16c48b2c, + dnnl_gOwI16i48o4i = dnnl_aBdC16c48b4c, + dnnl_gOwI16i64o2i = dnnl_aBdC16c64b2c, + dnnl_gOwI16i64o4i = dnnl_aBdC16c64b4c, + dnnl_gIwO16o32i2o = dnnl_aCdB16b32c2b, + dnnl_gIwO16o32i4o = dnnl_aCdB16b32c4b, + dnnl_gIwO16o48i2o = dnnl_aCdB16b48c2b, + dnnl_gIwO16o48i4o = dnnl_aCdB16b48c4b, + dnnl_gIwO16o64i2o = dnnl_aCdB16b64c2b, + dnnl_gIwO16o64i4o = dnnl_aCdB16b64c4b, + dnnl_OhwI16i32o2i = dnnl_AcdB16b32a2b, + dnnl_OhwI16i32o4i = dnnl_AcdB16b32a4b, + dnnl_OhwI16i48o2i = dnnl_AcdB16b48a2b, + dnnl_OhwI16i48o4i = dnnl_AcdB16b48a4b, + dnnl_OhwI16i64o2i = dnnl_AcdB16b64a2b, + dnnl_OhwI16i64o4i = dnnl_AcdB16b64a4b, + dnnl_IhwO16o32i2o = dnnl_BcdA16a32b2a, + dnnl_IhwO16o32i4o = dnnl_BcdA16a32b4a, + dnnl_IhwO16o48i2o = dnnl_BcdA16a48b2a, + dnnl_IhwO16o48i4o = dnnl_BcdA16a48b4a, + dnnl_IhwO16o64i2o = dnnl_BcdA16a64b2a, + dnnl_IhwO16o64i4o = dnnl_BcdA16a64b4a, + dnnl_gOhwI16i32o2i = dnnl_aBdeC16c32b2c, + dnnl_gOhwI16i32o4i = dnnl_aBdeC16c32b4c, + dnnl_gOhwI16i48o2i = dnnl_aBdeC16c48b2c, + dnnl_gOhwI16i48o4i = dnnl_aBdeC16c48b4c, + dnnl_gOhwI16i64o2i = dnnl_aBdeC16c64b2c, + dnnl_gOhwI16i64o4i = dnnl_aBdeC16c64b4c, + dnnl_gIhwO16o32i2o = dnnl_aCdeB16b32c2b, + dnnl_gIhwO16o32i4o = dnnl_aCdeB16b32c4b, + dnnl_gIhwO16o48i2o = dnnl_aCdeB16b48c2b, + dnnl_gIhwO16o48i4o = dnnl_aCdeB16b48c4b, + dnnl_gIhwO16o64i2o = dnnl_aCdeB16b64c2b, + dnnl_gIhwO16o64i4o = dnnl_aCdeB16b64c4b, + dnnl_OdhwI16i32o2i = dnnl_AcdeB16b32a2b, + dnnl_OdhwI16i32o4i = dnnl_AcdeB16b32a4b, + dnnl_OdhwI16i48o2i = dnnl_AcdeB16b48a2b, + dnnl_OdhwI16i48o4i = dnnl_AcdeB16b48a4b, + dnnl_OdhwI16i64o2i = dnnl_AcdeB16b64a2b, + dnnl_OdhwI16i64o4i = dnnl_AcdeB16b64a4b, + dnnl_IdhwO16o32i2o = dnnl_BcdeA16a32b2a, + dnnl_IdhwO16o32i4o = dnnl_BcdeA16a32b4a, + dnnl_IdhwO16o48i2o = dnnl_BcdeA16a48b2a, + dnnl_IdhwO16o48i4o = dnnl_BcdeA16a48b4a, + dnnl_IdhwO16o64i2o = dnnl_BcdeA16a64b2a, + dnnl_IdhwO16o64i4o = dnnl_BcdeA16a64b4a, + dnnl_gOdhwI16i32o2i = dnnl_aBdefC16c32b2c, + dnnl_gOdhwI16i32o4i = dnnl_aBdefC16c32b4c, + dnnl_gOdhwI16i48o2i = dnnl_aBdefC16c48b2c, + dnnl_gOdhwI16i48o4i = dnnl_aBdefC16c48b4c, + dnnl_gOdhwI16i64o2i = dnnl_aBdefC16c64b2c, + dnnl_gOdhwI16i64o4i = dnnl_aBdefC16c64b4c, + dnnl_gIdhwO16o32i2o = dnnl_aCdefB16b32c2b, + dnnl_gIdhwO16o32i4o = dnnl_aCdefB16b32c4b, + dnnl_gIdhwO16o48i2o = dnnl_aCdefB16b48c2b, + dnnl_gIdhwO16o48i4o = dnnl_aCdefB16b48c4b, + dnnl_gIdhwO16o64i2o = dnnl_aCdefB16b64c2b, + dnnl_gIdhwO16o64i4o = dnnl_aCdefB16b64c4b, + dnnl_hwioG16g = dnnl_decbA16a, + dnnl_hwioG8g = dnnl_decbA8a, + dnnl_dhwioG16g = dnnl_defcbA16a, + dnnl_dhwioG8g = dnnl_defcbA8a, + dnnl_NCdhw40n16c = dnnl_ABcde40a16b, + dnnl_NCw40n16c = dnnl_ABc40a16b, + dnnl_NChw40n16c = dnnl_ABcd40a16b, + dnnl_NCw40n32c = dnnl_ABc40a32b, + dnnl_NChw40n32c = dnnl_ABcd40a32b, + dnnl_NCdhw40n32c = dnnl_ABcde40a32b, + dnnl_OIdhw4o8i8o2i = dnnl_ABcde4a8b8a2b, + dnnl_OIhw4o8i8o2i = dnnl_ABcd4a8b8a2b, + dnnl_OIw4o8i8o2i = dnnl_ABc4a8b8a2b, + dnnl_gOIdhw4o8i8o2i = dnnl_aBCdef4b8c8b2c, + dnnl_gOIhw4o8i8o2i = dnnl_aBCde4b8c8b2c, + dnnl_gOIw4o8i8o2i = dnnl_aBCd4b8c8b2c, + dnnl_IOdhw4i8o8i2o = dnnl_BAcde4b8a8b2a, + dnnl_IOhw4i8o8i2o = dnnl_BAcd4b8a8b2a, + dnnl_IOw4i8o8i2o = dnnl_BAc4b8a8b2a, + dnnl_gIOdhw4i8o8i2o = dnnl_aCBdef4c8b8c2b, + dnnl_gIOhw4i8o8i2o = dnnl_aCBde4c8b8c2b, + dnnl_gIOw4i8o8i2o = dnnl_aCBd4c8b8c2b, + dnnl_NCw2c32n8c = dnnl_ABc2b32a8b, + dnnl_NChw2c32n8c = dnnl_ABcd2b32a8b, + dnnl_NCdhw2c32n8c = dnnl_ABcde2b32a8b, + dnnl_OIw2i8o16i4o = dnnl_ABc2b8a16b4a, + dnnl_OIhw2i8o16i4o = dnnl_ABcd2b8a16b4a, + dnnl_OIdhw2i8o16i4o = dnnl_ABcde2b8a16b4a, + dnnl_OIw2o8i16o4i = dnnl_ABc2a8b16a4b, + dnnl_OIw2o8i16o2i = dnnl_ABc2a8b16a2b, + dnnl_IOw2i8o16i4o = dnnl_BAc2b8a16b4a, + dnnl_IOw2i8o16i2o = dnnl_BAc2b8a16b2a, + dnnl_OIhw2o8i16o4i = dnnl_ABcd2a8b16a4b, + dnnl_OIhw2o8i16o2i = dnnl_ABcd2a8b16a2b, + dnnl_IOhw2i8o16i4o = dnnl_BAcd2b8a16b4a, + dnnl_IOhw2i8o16i2o = dnnl_BAcd2b8a16b2a, + dnnl_OIdhw2o8i16o4i = dnnl_ABcde2a8b16a4b, + dnnl_OIdhw2o8i16o2i = dnnl_ABcde2a8b16a2b, + dnnl_IOdhw2i8o16i4o = dnnl_BAcde2b8a16b4a, + dnnl_IOdhw2i8o16i2o = dnnl_BAcde2b8a16b2a, + dnnl_gOIw2o8i16o2i = dnnl_aBCd2b8c16b2c, + dnnl_gIOw2i8o16i2o = dnnl_aCBd2c8b16c2b, + dnnl_gIOhw2i8o16i2o = dnnl_aBCde2c8b16c2b, + dnnl_gIOdhw2i8o16i2o = dnnl_aBCdef2c8b16c2b, + dnnl_gOIhw2o8i16o2i = dnnl_aBCde2b8c16b2c, + dnnl_gOIdhw2o8i16o2i = dnnl_aBCdef2b8c16b2c, + dnnl_gOIw2o8i16o4i = dnnl_aBCd2b8c16b4c, + dnnl_gOIhw2o8i16o4i = dnnl_aBCde2b8c16b4c, +} dnnl_format_tag_t; + +/// @} dnnl_api_memory + +/// @addtogroup dnnl_api_primitives +/// @{ +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// Kinds of propagation. +typedef enum { + // TODO: suggest renames + /// Undefined propagation type. + dnnl_prop_kind_undef = 0, + /// Forward data propagation (training mode). In this mode primitives + /// perform computations necessary for subsequent backward propagation. + dnnl_forward_training = 64, + /// Forward data propagation (inference mode). In this mode primitives + /// perform only computations that are necessary for inference and omit + /// computations that are necessary only for backward propagation. + dnnl_forward_inference = 96, + /// Forward data propagation (alias for @c dnnl_forward_training). + dnnl_forward = dnnl_forward_training, + /// Backward propagation (with respect to all parameters). + dnnl_backward = 128, + /// Backward data propagation. + dnnl_backward_data = 160, + /// Backward weights propagation. + dnnl_backward_weights = 192, + /// Backward bias propagation. + dnnl_backward_bias = 193, +} dnnl_prop_kind_t; + +/// Kinds of primitives. Used to implement a way to extend the library with new +/// primitives without changing the ABI. +typedef enum { + /// Undefined primitive + dnnl_undefined_primitive, + /// A reorder primitive. + dnnl_reorder, + /// A shuffle primitive. + dnnl_shuffle, + /// A (out-of-place) concat primitive. + dnnl_concat, + /// A sum primitive. + dnnl_sum, + /// A convolution primitive. + dnnl_convolution, + /// A deconvolution primitive. + dnnl_deconvolution, + /// An element-wise primitive. + dnnl_eltwise, + /// An LRN primitive. + dnnl_lrn, + /// A batch normalization primitive. + dnnl_batch_normalization, + /// An inner product primitive. + dnnl_inner_product, + /// A rnn primitive. + dnnl_rnn, + /// A matrix multiplication primitive (internal). + dnnl_gemm, + /// A binary primitive. + dnnl_binary, + /// A matrix multiplication primitive. + dnnl_matmul, + /// A resampling primitive. + dnnl_resampling, + /// A pooling primitive. + dnnl_pooling, + /// A reduction primitive. + dnnl_reduction, + /// A PReLU primitive. + dnnl_prelu, + /// A softmax primitive. + dnnl_softmax, + /// A layer normalization primitive. + dnnl_layer_normalization, + /// A group normalization primitive. + dnnl_group_normalization, + + /// Parameter to allow internal only primitives without undefined behavior. + /// This parameter is chosen to be valid for so long as sizeof(int) >= 2. + dnnl_primitive_kind_max = 0x7fff, +} dnnl_primitive_kind_t; + +/// Kinds of algorithms. +typedef enum { + dnnl_alg_kind_undef, + /// Direct convolution + dnnl_convolution_direct = 0x1, + /// Winograd convolution + dnnl_convolution_winograd = 0x2, + /// Convolution algorithm(either direct or Winograd) is chosen just in time + dnnl_convolution_auto = 0x3, + /// Direct deconvolution + dnnl_deconvolution_direct = 0xa, + /// Winograd deconvolution + dnnl_deconvolution_winograd = 0xb, + /// Eltwise: ReLU + dnnl_eltwise_relu = 0x20, + /// Eltwise: hyperbolic tangent non-linearity (tanh) + dnnl_eltwise_tanh, + /// Eltwise: exponential linear unit (elu) + dnnl_eltwise_elu, + /// Eltwise: square + dnnl_eltwise_square, + /// Eltwise: abs + dnnl_eltwise_abs, + /// Eltwise: square root + dnnl_eltwise_sqrt, + /// Eltwise: linear + dnnl_eltwise_linear, + /// Eltwise: soft_relu + dnnl_eltwise_soft_relu, + /// Eltwise: hardsigmoid + dnnl_eltwise_hardsigmoid, + /// Eltwise: logistic + dnnl_eltwise_logistic, + /// Eltwise: exponent + dnnl_eltwise_exp, + /// Eltwise: gelu + /// + /// @note Tanh approximation formula is used to approximate + /// the cumulative distribution function of a Gaussian here + dnnl_eltwise_gelu_tanh, + /// Eltwise: swish + dnnl_eltwise_swish, + /// Eltwise: natural logarithm + dnnl_eltwise_log, + /// Eltwise: clip + dnnl_eltwise_clip, + /// Eltwise: clip version 2 + dnnl_eltwise_clip_v2, + /// Eltwise: pow + dnnl_eltwise_pow, + /// Eltwise: erf-based gelu + dnnl_eltwise_gelu_erf, + /// Eltwise: round + dnnl_eltwise_round, + /// Eltwise: mish + dnnl_eltwise_mish, + /// Eltwise: hardswish + dnnl_eltwise_hardswish, + /// Eltwise: ReLU (dst for backward) + dnnl_eltwise_relu_use_dst_for_bwd = 0x100, + /// Eltwise: hyperbolic tangent non-linearity (tanh) (dst for backward) + dnnl_eltwise_tanh_use_dst_for_bwd, + /// Eltwise: exponential linear unit (elu) (dst for backward) + dnnl_eltwise_elu_use_dst_for_bwd, + /// Eltwise: square root (dst for backward) + dnnl_eltwise_sqrt_use_dst_for_bwd, + /// Eltwise: logistic (dst for backward) + dnnl_eltwise_logistic_use_dst_for_bwd, + /// Eltwise: exp (dst for backward) + dnnl_eltwise_exp_use_dst_for_bwd, + /// Eltwise: clip version 2 (dst for backward) + dnnl_eltwise_clip_v2_use_dst_for_bwd, + /// Max pooling + dnnl_pooling_max = 0x1ff, + /// Average pooling include padding + dnnl_pooling_avg_include_padding = 0x2ff, + /// Average pooling exclude padding + dnnl_pooling_avg_exclude_padding = 0x3ff, + /// Local response normalization (LRN) across multiple channels + dnnl_lrn_across_channels = 0xaff, + /// LRN within a single channel + dnnl_lrn_within_channel = 0xbff, + /// RNN cell + dnnl_vanilla_rnn = 0x1fff, + /// LSTM cell + dnnl_vanilla_lstm = 0x2fff, + /// GRU cell + dnnl_vanilla_gru = 0x3fff, + /// GRU cell with linear before reset + /// + /// Modification of original GRU cell. Differs from #dnnl_vanilla_gru + /// in how the new memory gate is calculated: + /// \f[ c_t = tanh(W_c*x_t + b_{c_x} + r_t*(U_c*h_{t-1}+b_{c_h})) \f] + /// Primitive expects 4 biases on input: + /// \f$[b_{u}, b_{r}, b_{c_x}, b_{c_h}]\f$ + dnnl_lbr_gru = 0x4fff, + /// AUGRU cell + dnnl_vanilla_augru = 0x5fff, + /// AUGRU cell with linear before reset + dnnl_lbr_augru = 0x6fff, + /// Binary add + dnnl_binary_add = 0x1fff0, + /// Binary mul + dnnl_binary_mul = 0x1fff1, + /// Binary max + dnnl_binary_max = 0x1fff2, + /// Binary min + dnnl_binary_min = 0x1fff3, + /// Binary div + dnnl_binary_div = 0x1fff4, + /// Binary sub + dnnl_binary_sub = 0x1fff5, + /// Binary greater or equal + dnnl_binary_ge = 0x1fff6, + /// Binary greater than + dnnl_binary_gt = 0x1fff7, + /// Binary less or equal + dnnl_binary_le = 0x1fff8, + /// Binary less than + dnnl_binary_lt = 0x1fff9, + /// Binary equal + dnnl_binary_eq = 0x1fffa, + /// Binary not equal + dnnl_binary_ne = 0x1fffb, + /// Nearest Neighbor Resampling Method + dnnl_resampling_nearest = 0x2fff0, + /// Linear Resampling Method + dnnl_resampling_linear = 0x2fff1, + /// Reduction using max + dnnl_reduction_max, + /// Reduction using min + dnnl_reduction_min, + /// Reduction using sum + dnnl_reduction_sum, + /// Reduction using mul + dnnl_reduction_mul, + /// Reduction using mean + dnnl_reduction_mean, + /// Reduction using lp norm + dnnl_reduction_norm_lp_max, + /// Reduction using lp norm + dnnl_reduction_norm_lp_sum, + /// Reduction using lp norm without final pth-root + dnnl_reduction_norm_lp_power_p_max, + /// Reduction using lp norm without final pth-root + dnnl_reduction_norm_lp_power_p_sum, + /// Softmax + dnnl_softmax_accurate = 0x30000, + /// Logsoftmax + dnnl_softmax_log, +} dnnl_alg_kind_t; + +/// Flags for normalization primitives. +typedef enum { + /// Use no normalization flags + /// + /// If specified + /// - on forward training propagation mean and variance are computed and + /// stored as output + /// - on backward propagation compute full derivative wrt data + /// - on backward propagation prop_kind == #dnnl_backward_data has the same + /// behavior as prop_kind == #dnnl_backward + dnnl_normalization_flags_none = 0x0U, + + /// Use global statistics + /// + /// If specified + /// - on forward propagation use mean and variance provided by user (input) + /// - on backward propagation reduces the amount of computations, since + /// mean and variance are considered as constants + /// + /// If not specified: + /// - on forward propagation mean and variance are computed and stored as + /// output + /// - on backward propagation compute full derivative wrt data + dnnl_use_global_stats = 0x1U, + + /// Use scale parameter + /// + /// If specified: + /// - on forward propagation use scale for the normalization results + /// - on backward propagation (for prop_kind == #dnnl_backward) compute + /// diff wrt scale (hence one extra output used) + dnnl_use_scale = 0x2U, + + /// Use shift parameter + /// + /// If specified: + /// - on forward propagation use shift (aka bias) for the normalization + /// results + /// - on backward propagation (for prop_kind == #dnnl_backward) compute + /// diff wrt shift (hence one extra output used) + dnnl_use_shift = 0x4U, + + /// Fuse with ReLU + /// + /// The flag implies negative slope being 0. On training this is the only + /// configuration supported. For inference, to use non-zero negative slope + /// consider using @ref dev_guide_attributes_post_ops. + /// + /// If specified: + /// - on inference this option behaves the same as if the primitive were + /// fused with ReLU using post ops API with zero negative slope. + /// - on training primitive requires workspace (required to be able to + /// perform backward pass) + dnnl_fuse_norm_relu = 0x8U, + + /// Fuse with Add and then fuse with ReLU + /// + /// If specified: + /// + /// - on forward propagation apply element-wise binary Add operation to + /// to the normalization results with an additional input tensor and then + /// apply ReLU with negative slope being 0. + /// - on training primitive requires workspace (required to be able to + /// perform backward pass). + /// - on backward propagation save the result of backward ReLU operation + /// with input tensor and workspace from forward pass to extra output + /// tensor and then perform backward normalization. + dnnl_fuse_norm_add_relu = 0x10U, + +} dnnl_normalization_flags_t; + +/// @} dnnl_api_primitives_common +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_memory +/// @{ + +/// A wildcard value for dimensions that are unknown at a primitive creation +/// time. +#define DNNL_RUNTIME_DIM_VAL INT64_MIN + +/// A `size_t` counterpart of the DNNL_RUNTIME_DIM_VAL. +/// For instance, this value is returned by dnnl_memory_desc_get_size() if +/// either of the dimensions or strides equal to #DNNL_RUNTIME_DIM_VAL. +#define DNNL_RUNTIME_SIZE_VAL ((size_t)DNNL_RUNTIME_DIM_VAL) + +/// @cond DO_NOT_DOCUMENT_THIS +/// Hex representation for a **special** quiet NAN (!= NAN from math.h) +static const union { + unsigned u; + float f; +} DNNL_RUNTIME_F32_VAL_REP = {0x7fc000d0}; +/// @endcond + +/// A wildcard value for floating point values that are unknown at a primitive +/// creation time. +#define DNNL_RUNTIME_F32_VAL (DNNL_RUNTIME_F32_VAL_REP.f) + +/// @cond DO_NOT_DOCUMENT_THIS +static const int DNNL_RUNTIME_S32_VAL_REP = INT32_MIN; +/// @endcond + +/// A wildcard value for int32_t values that are unknown at a primitive creation +/// time. +#define DNNL_RUNTIME_S32_VAL DNNL_RUNTIME_S32_VAL_REP + +/// @struct dnnl_memory_desc +/// An opaque structure to describe a memory descriptor. +struct dnnl_memory_desc; + +/// A memory descriptor handle. +typedef struct dnnl_memory_desc *dnnl_memory_desc_t; + +/// A memory descriptor handle. +typedef const struct dnnl_memory_desc *const_dnnl_memory_desc_t; + +/// @struct dnnl_memory +/// An opaque structure to describe a memory. +struct dnnl_memory; + +/// A memory handle. +typedef struct dnnl_memory *dnnl_memory_t; + +/// A constant memory handle. +typedef const struct dnnl_memory *const_dnnl_memory_t; + +/// @} dnnl_api_memory + +/// @addtogroup dnnl_api_primitives +/// @{ + +/// @addtogroup dnnl_api_rnn +/// @{ + +/// Flags for RNN cell. +typedef enum { + /// Undefined RNN flags + dnnl_rnn_flags_undef = 0x0, + /// Do not add weights gradient to existing diff_weights memory + dnnl_rnn_flags_diff_weights_overwrite = 0x1, +} dnnl_rnn_flags_t; + +/// A direction of RNN primitive execution. +typedef enum { + /// Undefined RNN direction. + dnnl_rnn_direction_undef = 0, + /// Unidirectional execution of RNN primitive from left to right. + dnnl_unidirectional_left2right, + /// Unidirectional execution of RNN primitive from right to left. + dnnl_unidirectional_right2left, + /// Bidirectional execution of RNN primitive with concatenation of the + /// results. + dnnl_bidirectional_concat, + /// Bidirectional execution of RNN primitive with summation of the + /// results. + dnnl_bidirectional_sum, +} dnnl_rnn_direction_t; + +/// @} dnnl_api_rnn + +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_primitives +/// @{ +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// @struct dnnl_primitive_desc +/// @brief An opaque structure to describe a primitive descriptor. +struct dnnl_primitive_desc; + +/// @brief A primitive descriptor handle. +typedef struct dnnl_primitive_desc *dnnl_primitive_desc_t; + +/// @brief A constant primitive descriptor handle. +typedef const struct dnnl_primitive_desc *const_dnnl_primitive_desc_t; + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_attributes +/// @{ + +/// Scratchpad mode +typedef enum { + /// The library manages the scratchpad allocation according to the policy + /// specified by the `DNNL_ENABLE_CONCURRENT_EXEC` + /// [build option](@ref dev_guide_build_options) (default). + /// + /// When `DNNL_ENABLE_CONCURRENT_EXEC=OFF` (default), the library + /// scratchpad is common to all primitives to reduce the memory footprint. + /// This configuration comes with limited thread-safety properties, namely + /// primitives can be created and executed in parallel but cannot migrate + /// between threads (in other words, each primitive should be executed in + /// the same thread it was created in). + /// + /// When `DNNL_ENABLE_CONCURRENT_EXEC=ON`, the library scratchpad is + /// private to each primitive. The memory footprint is larger than when + /// using `DNNL_ENABLE_CONCURRENT_EXEC=OFF` but different primitives can be + /// created and run concurrently (the same primitive cannot be run + /// concurrently from two different threads though). + dnnl_scratchpad_mode_library, + /// The user manages the scratchpad allocation by querying and providing + /// the scratchpad memory to primitives. This mode is thread-safe as long + /// as the scratchpad buffers are not used concurrently by two primitive + /// executions. + dnnl_scratchpad_mode_user, +} dnnl_scratchpad_mode_t; + +/// @struct dnnl_primitive_attr +/// @brief An opaque structure for primitive descriptor attributes. +/// +/// Attributes may contain: +/// - output scales (to scale the result prior to storing it to the memory) +struct dnnl_primitive_attr; + +/// @brief A primitive descriptor attributes handle that controls primitive +/// behavior. +typedef struct dnnl_primitive_attr *dnnl_primitive_attr_t; + +/// @brief A constant primitive descriptor attributes handle. +typedef const struct dnnl_primitive_attr *const_dnnl_primitive_attr_t; + +/// @struct dnnl_post_ops +/// @brief An opaque structure for a chain of post operations. +/// +/// dnnl_post_ops can be used to perform some (trivial) operations like +/// accumulation or eltwise after certain primitives like convolution. +/// +/// Post operations might be combined together, making a chain of post +/// operations. For instance one can configure convolution followed by +/// accumulation followed by eltwise. This might be especially beneficial +/// for residual learning blocks. +/// +/// @warning +/// Of course not all combinations are supported, so the user should handle +/// errors accordingly. +/// +/// Supported post operations: +/// - accumulation (base primitive: convolution) +/// - eltwise (base primitive: convolution) +struct dnnl_post_ops; + +/// @brief A post operation chain handle. +typedef struct dnnl_post_ops *dnnl_post_ops_t; + +/// @brief A constant post operation chain handle. +typedef const struct dnnl_post_ops *const_dnnl_post_ops_t; + +/// @} dnnl_api_attributes + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// @struct dnnl_primitive +/// An opaque structure to describe a primitive. +struct dnnl_primitive; +/// A primitive handle. +typedef struct dnnl_primitive *dnnl_primitive_t; +/// A constant primitive handle. +typedef const struct dnnl_primitive *const_dnnl_primitive_t; + +/// Undefined argument. +#define DNNL_ARG_UNDEF 0 +/// Source argument #0. +#define DNNL_ARG_SRC_0 1 +/// A special mnemonic for source argument for primitives that have a +/// single source. An alias for #DNNL_ARG_SRC_0. +#define DNNL_ARG_SRC DNNL_ARG_SRC_0 +/// A special mnemonic for RNN input vector. An alias for +/// #DNNL_ARG_SRC_0. +#define DNNL_ARG_SRC_LAYER DNNL_ARG_SRC_0 +/// A special mnemonic for reorder source argument. An alias for +/// #DNNL_ARG_SRC_0. +#define DNNL_ARG_FROM DNNL_ARG_SRC_0 + +/// Source argument #1. +#define DNNL_ARG_SRC_1 2 +/// A special mnemonic for RNN input recurrent hidden state vector. An alias +/// for #DNNL_ARG_SRC_1. +#define DNNL_ARG_SRC_ITER DNNL_ARG_SRC_1 + +/// Source argument #2. +#define DNNL_ARG_SRC_2 3 +/// A special mnemonic for RNN input recurrent cell state vector. An alias for +/// #DNNL_ARG_SRC_2. +#define DNNL_ARG_SRC_ITER_C DNNL_ARG_SRC_2 + +/// Source argument #3. +#define DNNL_ARG_SRC_3 4 +/// A special mnemonic for RNN input recurrent cell attention vector. An alias for +/// #DNNL_ARG_SRC_3. +#define DNNL_ARG_AUGRU_ATTENTION DNNL_ARG_SRC_3 + +/// Destination argument #0. +#define DNNL_ARG_DST_0 17 +/// A special mnemonic for destination argument for primitives that have a +/// single destination. An alias for #DNNL_ARG_DST_0. +#define DNNL_ARG_DST DNNL_ARG_DST_0 +/// A special mnemonic for reorder destination argument. An alias for +/// #DNNL_ARG_DST_0. +#define DNNL_ARG_TO DNNL_ARG_DST_0 +/// A special mnemonic for RNN output vector. An alias for #DNNL_ARG_DST_0. +#define DNNL_ARG_DST_LAYER DNNL_ARG_DST_0 + +/// Destination argument #1. +#define DNNL_ARG_DST_1 18 +/// A special mnemonic for RNN input recurrent hidden state vector. An +/// alias for #DNNL_ARG_DST_1. +#define DNNL_ARG_DST_ITER DNNL_ARG_DST_1 + +/// Destination argument #2. +#define DNNL_ARG_DST_2 19 +/// A special mnemonic for LSTM output recurrent cell state vector. An +/// alias for #DNNL_ARG_DST_2. +#define DNNL_ARG_DST_ITER_C DNNL_ARG_DST_2 + +/// Weights argument #0. +#define DNNL_ARG_WEIGHTS_0 33 +/// A special mnemonic for primitives that have a single weights +/// argument. Alias for #DNNL_ARG_WEIGHTS_0. +#define DNNL_ARG_WEIGHTS DNNL_ARG_WEIGHTS_0 +/// A special mnemonic for RNN weights applied to the layer input. An +/// alias for #DNNL_ARG_WEIGHTS_0. +#define DNNL_ARG_WEIGHTS_LAYER DNNL_ARG_WEIGHTS_0 + +/// Weights argument #1. +#define DNNL_ARG_WEIGHTS_1 34 +/// A special mnemonic for RNN weights applied to the recurrent input. +/// An alias for #DNNL_ARG_WEIGHTS_1. +#define DNNL_ARG_WEIGHTS_ITER DNNL_ARG_WEIGHTS_1 + +/// Weights argument #2. +#define DNNL_ARG_WEIGHTS_2 35 +/// A special mnemonic for RNN weights applied to the peephole weights. +/// An alias for #DNNL_ARG_WEIGHTS_2. +#define DNNL_ARG_WEIGHTS_PEEPHOLE DNNL_ARG_WEIGHTS_2 + +/// Weights argument #3. +#define DNNL_ARG_WEIGHTS_3 36 +/// A special mnemonic for RNN weights applied to the projection weights. +/// An alias for #DNNL_ARG_WEIGHTS_3. +#define DNNL_ARG_WEIGHTS_PROJECTION DNNL_ARG_WEIGHTS_3 + +/// Bias tensor argument. +#define DNNL_ARG_BIAS 41 + +/// Mean values tensor argument. +#define DNNL_ARG_MEAN 49 +/// Variance values tensor argument. +#define DNNL_ARG_VARIANCE 50 + +/// A special mnemonic for scale argument of normalization primitives. +#define DNNL_ARG_SCALE 51 +/// A special mnemonic for shift argument of normalization primitives. +#define DNNL_ARG_SHIFT 52 + +/// Workspace tensor argument. Workspace is used to pass information +/// from forward propagation to backward propagation computations. +#define DNNL_ARG_WORKSPACE 64 +/// Scratchpad (temporary storage) tensor argument. +#define DNNL_ARG_SCRATCHPAD 80 + +/// Gradient (diff) of the source argument #0. +#define DNNL_ARG_DIFF_SRC_0 129 +/// A special mnemonic for primitives that have a single diff source argument. +/// An alias for #DNNL_ARG_DIFF_SRC_0. +#define DNNL_ARG_DIFF_SRC DNNL_ARG_DIFF_SRC_0 +/// A special mnemonic for gradient (diff) of RNN input vector. An alias for +/// #DNNL_ARG_DIFF_SRC_0. +#define DNNL_ARG_DIFF_SRC_LAYER DNNL_ARG_DIFF_SRC_0 + +/// Gradient (diff) of the source argument #1. +#define DNNL_ARG_DIFF_SRC_1 130 +/// A special mnemonic for gradient (diff) of RNN input recurrent hidden state +/// vector. An alias for #DNNL_ARG_DIFF_SRC_1. +#define DNNL_ARG_DIFF_SRC_ITER DNNL_ARG_DIFF_SRC_1 + +/// Gradient (diff) of the source argument #2. +#define DNNL_ARG_DIFF_SRC_2 131 +/// A special mnemonic for gradient (diff) of RNN input recurrent cell state +/// vector. An alias for #DNNL_ARG_DIFF_SRC_1. +#define DNNL_ARG_DIFF_SRC_ITER_C DNNL_ARG_DIFF_SRC_2 + +/// Gradient (diff) of the source argument #3. +#define DNNL_ARG_DIFF_SRC_3 132 +/// A special mnemonic for gradient (diff) of RNN input recurrent cell attention +/// vector. An alias for #DNNL_ARG_DIFF_SRC_3. +#define DNNL_ARG_DIFF_AUGRU_ATTENTION DNNL_ARG_DIFF_SRC_3 + +/// Gradient (diff) of the destination argument #0. +#define DNNL_ARG_DIFF_DST_0 145 +/// A special mnemonic for primitives that have a single diff destination +/// argument. An alias for #DNNL_ARG_DIFF_DST_0. +#define DNNL_ARG_DIFF_DST DNNL_ARG_DIFF_DST_0 +/// A special mnemonic for gradient (diff) of RNN output vector. An alias for +/// #DNNL_ARG_DIFF_DST_0. +#define DNNL_ARG_DIFF_DST_LAYER DNNL_ARG_DIFF_DST_0 + +/// Gradient (diff) of the destination argument #1. +#define DNNL_ARG_DIFF_DST_1 146 +/// A special mnemonic for gradient (diff) of RNN input recurrent hidden state +/// vector. An alias for #DNNL_ARG_DIFF_DST_1. +#define DNNL_ARG_DIFF_DST_ITER DNNL_ARG_DIFF_DST_1 + +/// Gradient (diff) of the destination argument #2. +#define DNNL_ARG_DIFF_DST_2 147 +/// A special mnemonic for gradient (diff) of RNN input recurrent cell state +/// vector. An alias for #DNNL_ARG_DIFF_DST_2. +#define DNNL_ARG_DIFF_DST_ITER_C DNNL_ARG_DIFF_DST_2 + +/// Gradient (diff) of the weights argument #0. +#define DNNL_ARG_DIFF_WEIGHTS_0 161 +/// A special mnemonic for primitives that have a single diff weights +/// argument. Alias for #DNNL_ARG_DIFF_WEIGHTS_0. +#define DNNL_ARG_DIFF_WEIGHTS DNNL_ARG_DIFF_WEIGHTS_0 +/// A special mnemonic for diff of RNN weights applied to the layer input. An +/// alias for #DNNL_ARG_DIFF_WEIGHTS_0. +#define DNNL_ARG_DIFF_WEIGHTS_LAYER DNNL_ARG_DIFF_WEIGHTS_0 + +/// Gradient (diff) of the weights argument #1. +#define DNNL_ARG_DIFF_WEIGHTS_1 162 +/// A special mnemonic for diff of RNN weights applied to the recurrent input. +/// An alias for #DNNL_ARG_DIFF_WEIGHTS_1. +#define DNNL_ARG_DIFF_WEIGHTS_ITER DNNL_ARG_DIFF_WEIGHTS_1 + +/// Gradient (diff) of the weights argument #2. +#define DNNL_ARG_DIFF_WEIGHTS_2 163 +/// A special mnemonic for diff of RNN weights applied to the peephole weights. +/// An alias for #DNNL_ARG_DIFF_WEIGHTS_2. +#define DNNL_ARG_DIFF_WEIGHTS_PEEPHOLE DNNL_ARG_DIFF_WEIGHTS_2 + +/// Gradient (diff) of the weights argument #3. +#define DNNL_ARG_DIFF_WEIGHTS_3 164 +/// A special mnemonic for diff of RNN weights applied to the projection +/// weights. An alias for #DNNL_ARG_DIFF_WEIGHTS_3. +#define DNNL_ARG_DIFF_WEIGHTS_PROJECTION DNNL_ARG_DIFF_WEIGHTS_3 + +/// Gradient (diff) of the bias tensor argument. +#define DNNL_ARG_DIFF_BIAS 169 + +/// A special mnemonic for scale argument of normalization primitives. +#define DNNL_ARG_DIFF_SCALE 255 +/// A special mnemonic for shift argument of normalization primitives. +#define DNNL_ARG_DIFF_SHIFT 256 + +/// Output scaling factors provided at execution time. +#define DNNL_ARG_ATTR_OUTPUT_SCALES 513 + +/// Starting index for source arguments for primitives that take a variable +/// number of source arguments. +#define DNNL_ARG_MULTIPLE_SRC 1024 +/// Starting index for destination arguments for primitives that produce a +/// variable number of destination arguments. +#define DNNL_ARG_MULTIPLE_DST 2048 + +/// Scaling factors provided at execution time. +#define DNNL_ARG_ATTR_SCALES 4096 + +/// Zero points provided at execution time. +#define DNNL_ARG_ATTR_ZERO_POINTS 8192 + +/// Arguments for fused depthwise convolution. +/// See @ref dev_guide_attributes_post_ops_depthwise_fusion +#define DNNL_ARG_ATTR_POST_OP_DW 16384 + +/// Starting point for a binary post operation. +#define DNNL_ARG_ATTR_MULTIPLE_POST_OP_BASE 32768 + +/// Arguments for a binary post operation. Up to 32 arguments are supported. +/// See @ref dev_guide_attributes_post_ops_binary_fusion +#define DNNL_ARG_ATTR_MULTIPLE_POST_OP(idx) \ + (DNNL_ARG_ATTR_MULTIPLE_POST_OP_BASE * ((idx) + 1)) + +/// A structure that contains an index and a memory object, and is used to pass +/// arguments to dnnl_primitive_execute(). +typedef struct { + int arg; ///< An argument index, e.g. DNNL_ARG_SRC + dnnl_memory_t memory; ///< Input/output memory +} dnnl_exec_arg_t; + +/// @} dnnl_api_primitives_common + +/// @addtogroup dnnl_api_primitives_common +/// @{ + +/// Primitive descriptor query specification +/// +/// For generic function dnnl_primitive_desc_query(), the type of result must +/// agree with the queried argument. The correspondence table: +/// +/// Query kind | Type of query result +/// --------------------------------|----------------------------- +/// dnnl_query_*_engine | #dnnl_engine_t * +/// #dnnl_query_primitive_kind | #dnnl_primitive_kind_t * +/// dnnl_query_*_s32 | int * +/// dnnl_query_*_s64 | #dnnl_dim_t * (same as int64_t *) +/// dnnl_query_*_f32 | float * +/// dnnl_query_*_f64 | double * +/// dnnl_query_*_str | const char ** +/// dnnl_query_*_md | #const_dnnl_memory_desc_t * +/// dnnl_query_*_pd | #const_dnnl_primitive_desc_t * +/// dnnl_query_cache_blob_id | const uint8_t ** +/// dnnl_query_strides | const #dnnl_dims_t ** +/// dnnl_query_dilations | const #dnnl_dims_t ** +/// dnnl_query_padding_l | const #dnnl_dims_t ** +/// dnnl_query_padding_r | const #dnnl_dims_t ** +/// dnnl_query_flags | unsigned * +/// dnnl_query_alg_kind | #dnnl_alg_kind_t * +/// dnnl_query_factors | const float ** +/// dnnl_query_cell_kind | #dnnl_alg_kind_t * +/// dnnl_query_direction | #dnnl_rnn_direction_t * +/// dnnl_query_activation_kind | #dnnl_alg_kind_t * +/// dnnl_query_kernel | const #dnnl_dims_t ** +/// dnnl_query_dims | const #dnnl_dims_t ** +/// dnnl_query_data_type | #dnnl_data_type_t * +/// dnnl_query_padded_dims | const #dnnl_dims_t ** +/// dnnl_query_padded_offsets | const #dnnl_dims_t ** +/// dnnl_query_format_kind | #dnnl_format_kind_t * +/// dnnl_query_inner_blks | const #dnnl_dims_t ** +/// dnnl_query_inner_idxs | const #dnnl_dims_t ** +/// dnnl_query_sparse_encoding | #dnnl_sparse_encoding_t * +/// +/// @note +/// Rule of thumb: all opaque types and structures are returned by +/// reference. All numbers are returned by value. +/// +/// @warning +/// All returned references point to constant objects and are valid only +/// during the lifetime of the queried primitive descriptor. Returned objects +/// must not be destroyed by the user. If you need to keep the object longer +/// than the lifetime of the queried primitive descriptor, use +/// dnnl_primitive_desc_clone() to make a copy. +typedef enum { + dnnl_query_undef = 0, ///< no query + + dnnl_query_engine, ///< execution engine + dnnl_query_primitive_kind, ///< primitive kind + + dnnl_query_num_of_inputs_s32, ///< number of inputs expected + dnnl_query_num_of_outputs_s32, ///< number of outputs expected + + dnnl_query_time_estimate_f64, ///< runtime estimation (seconds) + dnnl_query_memory_consumption_s64, ///< memory consumption -- extra + /// (scratch) memory, additional to + /// all inputs and outputs memory + /// (bytes) + + dnnl_query_scratchpad_engine, ///< scratchpad engine -- engine to be used + /// for creating scratchpad memory + + dnnl_query_impl_info_str, ///< implementation name + + dnnl_query_reorder_src_engine, ///< source engine + dnnl_query_reorder_dst_engine, ///< destination engine + + dnnl_query_prop_kind, ///< propagation kind + + dnnl_query_cache_blob_id_size_s64, ///< size of cache blob ID in bytes + dnnl_query_cache_blob_id, ///< cache blob ID (pointer to array) + + dnnl_query_strides, ///< strides + dnnl_query_dilations, ///< dilations + dnnl_query_padding_l, ///< left padding + dnnl_query_padding_r, ///< right padding + dnnl_query_epsilon_f32, ///< epsilon + dnnl_query_flags, ///< flags + dnnl_query_alg_kind, ///< algorithm kind + dnnl_query_alpha_f32, ///< alpha + dnnl_query_beta_f32, ///< beta + dnnl_query_axis_s32, ///< axis + dnnl_query_local_size_s64, ///< LRN parameter local size + dnnl_query_k_f32, ///< LRN parameter K + dnnl_query_p_f32, ///< Reduction parameter P + dnnl_query_factors, ///< Resampling parameter factors + dnnl_query_cell_kind, ///< RNN parameter cell kind + dnnl_query_direction, ///< RNN parameter direction + dnnl_query_activation_kind, ///< RNN parameter activation kind + dnnl_query_kernel, ///< Pooling parameter kernel + dnnl_query_group_size_s64, ///< Shuffle parameter group size + + // memory descriptor section + dnnl_query_some_md = 128, ///< stub + dnnl_query_src_md, ///< source memory desc + dnnl_query_diff_src_md, ///< source gradient memory desc + dnnl_query_weights_md, ///< weights memory descriptor desc + dnnl_query_diff_weights_md, ///< weights grad. memory desc + dnnl_query_dst_md, ///< destination memory desc + dnnl_query_diff_dst_md, ///< destination grad. memory desc + dnnl_query_workspace_md, ///< workspace memory desc + dnnl_query_scratchpad_md, ///< scratchpad memory desc + dnnl_query_exec_arg_md = 255, ///< memory desc of an execute argument + + dnnl_query_ndims_s32, ///< number of dimensions + dnnl_query_dims, ///< vector of dimensions + dnnl_query_data_type, ///< data type + dnnl_query_submemory_offset_s64, ///< submemory offset + dnnl_query_padded_dims, ///< vector of padded dimensions + dnnl_query_padded_offsets, ///< vector of padded offsets + dnnl_query_format_kind, ///< format kind + dnnl_query_inner_nblks_s32, ///< number of innermost blocks + dnnl_query_inner_blks, ///< vector of sizes of the innermost blocks + dnnl_query_inner_idxs, ///< vector of logical indices of the blocks +#ifdef DNNL_EXPERIMENTAL_SPARSE + dnnl_query_sparse_encoding, ///< Sparse encoding + dnnl_query_nnz_s64, ///< Number of non-zero entries + dnnl_query_num_handles_s32, ///< Number of buffers required for a memory +/// descriptor +#endif + // Max value to prevent UB for internal use only dnnl_query_t + dnnl_query_max = 0x7fff, +} dnnl_query_t; + +/// @} dnnl_api_primitives_common + +/// @} dnnl_api_primitives + +/// @addtogroup dnnl_api_service +/// @{ + +/// Disable profiling completely +#define DNNL_JIT_PROFILE_NONE 0u + +/// Enable VTune Profiler integration +#define DNNL_JIT_PROFILE_VTUNE 1u + +/// Enable Linux perf integration via perfmap files +#define DNNL_JIT_PROFILE_LINUX_PERFMAP 2u + +/// Enable Linux perf integration via jitdump files +#define DNNL_JIT_PROFILE_LINUX_JITDUMP 4u + +/// Instruct Linux perf integration via jitdump files to use TSC. @ref +/// DNNL_JIT_PROFILE_LINUX_JITDUMP must be set too for this to take effect. +#define DNNL_JIT_PROFILE_LINUX_JITDUMP_USE_TSC 8u + +/// Enable Linux perf integration (both jitdump and perfmap) +#define DNNL_JIT_PROFILE_LINUX_PERF \ + (DNNL_JIT_PROFILE_LINUX_JITDUMP | DNNL_JIT_PROFILE_LINUX_PERFMAP) + +/// CPU instruction set flags +typedef enum { + /// Library choice of ISA (excepting those listed as initial support) + dnnl_cpu_isa_default = 0x0, + + /// Intel Streaming SIMD Extensions 4.1 (Intel SSE4.1) + dnnl_cpu_isa_sse41 = 0x1, + + /// Intel Advanced Vector Extensions (Intel AVX) + dnnl_cpu_isa_avx = 0x3, + + /// Intel Advanced Vector Extensions 2 (Intel AVX2) + dnnl_cpu_isa_avx2 = 0x7, + + /// Intel AVX2 and Intel Deep Learning Boost (Intel DL Boost) support + dnnl_cpu_isa_avx2_vnni = 0xf, + + /// Intel AVX2 and Intel Deep Learning Boost (Intel DL Boost) + /// with 8-bit integer, float16 and bfloat16 support + dnnl_cpu_isa_avx2_vnni_2 = 0x1f, + + /// Intel AVX-512 subset for Intel Xeon Scalable processor family + /// and Intel Core processor family. + dnnl_cpu_isa_avx512_core = 0x27, + + /// Intel AVX-512 and Intel Deep Learning Boost (Intel DL Boost) support + /// for Intel Xeon Scalable processor family + /// and Intel Core processor family. + dnnl_cpu_isa_avx512_core_vnni = 0x67, + + /// Intel AVX-512, Intel DL Boost and bfloat16 support + /// for Intel Xeon Scalable processor family + /// and Intel Core processor family. + dnnl_cpu_isa_avx512_core_bf16 = 0xe7, + + /// Intel AVX-512 with float16, Intel DL Boost and bfloat16 support + /// for Intel Xeon Scalable processor family + /// and Intel Core processor family. + // TODO: Align avx10_1 values to internal representation. + dnnl_cpu_isa_avx10_1_512 = 0x1ef, + /// @copydoc dnnl_cpu_isa_avx10_1_512 + dnnl_cpu_isa_avx512_core_fp16 = dnnl_cpu_isa_avx10_1_512, + + /// Intel AVX-512 with float16, Intel DL Boost and bfloat16 support and + /// Intel AMX with 8-bit integer and bfloat16 support + // TODO: Align avx10_1 values to internal representation. + dnnl_cpu_isa_avx10_1_512_amx = 0xfef, + /// @copydoc dnnl_cpu_isa_avx10_1_512_amx + dnnl_cpu_isa_avx512_core_amx = dnnl_cpu_isa_avx10_1_512_amx, + + /// Intel AVX-512 with float16, Intel DL Boost and bfloat16 support and + /// Intel AMX with 8-bit integer, bfloat16 and float16 support + // TODO: Align avx10_1 values to internal representation. + dnnl_cpu_isa_avx10_1_512_amx_fp16 = 0x1fef, + /// @copydoc dnnl_cpu_isa_avx10_1_512_amx_fp16 + dnnl_cpu_isa_avx512_core_amx_fp16 = dnnl_cpu_isa_avx10_1_512_amx_fp16, +} dnnl_cpu_isa_t; + +/// CPU ISA hints flags +typedef enum { + /// No hints (use default features) + dnnl_cpu_isa_no_hints = 0x0, + + /// Prefer to exclusively use Ymm registers for computations + dnnl_cpu_isa_prefer_ymm = 0x1, +} dnnl_cpu_isa_hints_t; + +/// @} dnnl_api_service + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif /* ONEAPI_DNNL_TYPES_H */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3143c979ff78b3bed0ed1c595afbb5721916ff49 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel.h @@ -0,0 +1,217 @@ +/******************************************************************************* +* Copyright 2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// ukernel C API + +#ifndef ONEAPI_DNNL_DNNL_UKERNEL_H +#define ONEAPI_DNNL_DNNL_UKERNEL_H + +#include "oneapi/dnnl/dnnl.h" +#include "oneapi/dnnl/dnnl_ukernel_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_ukernel +/// @{ + +#ifdef DNNL_EXPERIMENTAL_UKERNEL + +/// @addtogroup dnnl_api_ukernel_brgemm +/// @{ + +/// Creates a BRGeMM ukernel object. Operates by the following formula: +/// `C = alpha * [A x B] + beta * C`. +/// `D = post-operations(C)`. +/// +/// Post-operations applies if one of the following holds: +/// * Non-empty attributes are specified. +/// * Output data type `d_dt` is different from accumulation data type `c_dt`. +/// +/// If any of conditions happens, the final call of the accumulation chain +/// must be `dnnl_brgemm_execute_postops`, and `dnnl_brgemm_execute`, otherwise. +/// +/// @param brgemm Output BRGeMM ukernel object. +/// @param M Dimension M of tensor A. +/// @param N Dimension N of tensor B. +/// @param K Dimension K of tensors A and B. +/// @param batch_size Number of batches to process. +/// @param lda Leading dimension of tensor A. +/// @param ldb Leading dimension of tensor B. +/// @param ldc Leading dimension of tensor C. +/// @param ldd Leading dimension of tensor D. +/// @param a_dt Data type of tensor A. +/// @param b_dt Data type of tensor B. +/// @param c_dt Data type of tensor C. Must be dnnl_f32. +/// @param d_dt Data type of tensor D. +/// @param alpha Scale for an accumulation output. +/// @param beta Scale for a tensor C to append on an accumulation output. +/// @param attr Primitive attributes to extend the kernel operations. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_create(dnnl_brgemm_t *brgemm, dnnl_dim_t M, + dnnl_dim_t N, dnnl_dim_t K, dnnl_dim_t batch_size, dnnl_dim_t lda, + dnnl_dim_t ldb, dnnl_dim_t ldc, dnnl_dim_t ldd, dnnl_data_type_t a_dt, + dnnl_data_type_t b_dt, dnnl_data_type_t c_dt, dnnl_data_type_t d_dt, + float alpha, float beta, const_dnnl_primitive_attr_t attr); + +/// Returns the size of a scratchpad memory needed for the BRGeMM ukernel +/// object. +/// +/// @param brgemm BRGeMM ukernel object. +/// @param size Output size of a buffer required for the BRGeMM ukernel object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_get_scratchpad_size( + const_dnnl_brgemm_t brgemm, size_t *size); + +/// Initializes the hardware-specific context. If no initialization required, +/// returns the success status. +/// +/// @param brgemm BRGeMM ukernel object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_set_hw_context(const_dnnl_brgemm_t brgemm); + +/// Releases the hardware-specific context. Must be used after all the execution +/// calls to BRGeMM ukernel objects. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_release_hw_context(); + +/// Generates an executable part of BRGeMM ukernel object. +/// @param brgemm BRGeMM ukernel object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_generate(dnnl_brgemm_t brgemm); + +/// Executes a BRGeMM ukernel object. +/// +/// @param brgemm BRGeMM ukernel object. +/// @param A_ptr Base pointer to a tensor A. +/// @param B_ptr Base pointer to a tensor B. +/// @param A_B_offsets Pointer to the set of tensor A and tensor B offsets for +/// each batch; the set must be contiguous in memory. Single batch should +/// supply offsets for both tensors A and B simultaneously. The number of +/// batches must coincide with the `batch_size` value passed at the creation +/// stage. +/// @param C_ptr Pointer to a tensor C (accumulation buffer). +/// @param scratchpad_ptr Pointer to a scratchpad buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_execute(const_dnnl_brgemm_t brgemm, + const void *A_ptr, const void *B_ptr, const dnnl_dim_t *A_B_offsets, + void *C_ptr, void *scratchpad_ptr); + +/// Executes a BRGeMM ukernel object with post operations. +/// +/// @param brgemm BRGeMM ukernel object. +/// @param A Base pointer to a tensor A. +/// @param B Base pointer to a tensor B. +/// @param A_B_offsets Pointer to a set of tensor A and tensor B offsets for +/// each batch. A set must be contiguous in memory. A single batch should +/// supply offsets for both tensors A and B simultaneously. The number of +/// batches must coincide with the `batch_size` value passed at the creation +/// stage. +/// @param C_ptr Pointer to a tensor C (accumulation buffer). +/// @param D_ptr Pointer to a tensor D (output buffer). +/// @param scratchpad_ptr Pointer to a scratchpad buffer. +/// @param binary_po_ptr Pointer to binary post-op data. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_execute_postops(const_dnnl_brgemm_t brgemm, + const void *A, const void *B, const dnnl_dim_t *A_B_offsets, + const void *C_ptr, void *D_ptr, void *scratchpad_ptr, + const void *binary_po_ptr); + +/// Destroys a BRGeMM ukernel object. +/// +/// @param brgemm BRGeMM ukernel object to destroy. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_destroy(dnnl_brgemm_t brgemm); + +/// Creates a BRGeMM ukernel packing tensor B object. +/// +/// @param brgemm_pack_B Output BRGeMM ukernel packing B object. +/// @param K Dimension K. +/// @param N Dimension N. +/// @param in_ld Input leading dimension. +/// @param out_ld Output leading dimension. Specifies a block by N dimension +/// during data packing. +/// @param in_dt Input data type. +/// @param out_dt Output data type. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_pack_B_create( + dnnl_brgemm_pack_B_t *brgemm_pack_B, dnnl_dim_t K, dnnl_dim_t N, + dnnl_dim_t in_ld, dnnl_dim_t out_ld, dnnl_data_type_t in_dt, + dnnl_data_type_t out_dt); + +/// Returns the flag if packing is expected by BRGeMM ukernel kernel. +/// +/// @param brgemm_pack_B BRGeMM ukernel packing B object. +/// @param need_pack Output flag specifying if packing is needed. +/// Possible values are 0 (not needed) and 1 (needed). +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_pack_B_need_pack( + const_dnnl_brgemm_pack_B_t brgemm_pack_B, int *need_pack); + +/// Generates an executable part of BRGeMM ukernel packing B object. +/// @param brgemm_pack_B BRGeMM ukernel packing B object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_pack_B_generate( + dnnl_brgemm_pack_B_t brgemm_pack_B); + +/// Executes a BRGeMM ukernel packing tensor B object. +/// +/// @param brgemm_pack_B BRGeMM ukernel packing B object. +/// @param in_ptr Pointer to an input buffer. +/// @param out_ptr Pointer to an output buffer. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_pack_B_execute( + const_dnnl_brgemm_pack_B_t brgemm_pack_B, const void *in_ptr, + void *out_ptr); + +/// Destroys a BRGeMM ukernel packing tensor B object. +/// +/// @param brgemm_pack_B BRGeMM ukernel packing B object. +/// @returns #dnnl_success on success and a status describing the error +/// otherwise. +dnnl_status_t DNNL_API dnnl_brgemm_pack_B_destroy( + dnnl_brgemm_pack_B_t brgemm_pack_B); + +/// @} dnnl_api_ukernel_brgemm + +#endif + +/// @} dnnl_api_ukernel + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif /* ONEAPI_DNNL_DNNL_UKERNEL_H */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel.hpp b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel.hpp new file mode 100644 index 0000000000000000000000000000000000000000..32cc8155696a2760afb7b8c23c6abf4f4bc7ab47 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel.hpp @@ -0,0 +1,309 @@ +/******************************************************************************* +* Copyright 2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// ukernel C++ API + +#ifndef ONEAPI_DNNL_DNNL_UKERNEL_HPP +#define ONEAPI_DNNL_DNNL_UKERNEL_HPP + +#include "oneapi/dnnl/dnnl.hpp" +#include "oneapi/dnnl/dnnl_ukernel.h" + +/// @addtogroup dnnl_api oneDNN API +/// @{ + +/// oneDNN namespace +namespace dnnl { + +/// @addtogroup dnnl_api_utils +/// @{ + +/// @cond DO_NOT_DOCUMENT_THIS + +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_brgemm_t p) { + return dnnl_brgemm_destroy(p); + } +}; + +template <> +struct handle_traits { + static dnnl_status_t destructor(dnnl_brgemm_pack_B_t p) { + return dnnl_brgemm_pack_B_destroy(p); + } +}; + +/// @endcond + +/// @} dnnl_api_utils + +/// @addtogroup dnnl_api_ukernel Ukernels +/// Collection of ukernels +/// @{ + +/// ukernel namespace +namespace ukernel { + +#ifdef DNNL_EXPERIMENTAL_UKERNEL + +/// @addtogroup dnnl_api_ukernel_brgemm BRGeMM ukernel +/// BRGeMM ukernel routines +/// @{ + +struct brgemm : public handle { + /// Default constructor. Produces an empty object. + brgemm() = default; + + /// Constructs a BRGeMM ukernel object. Operates by the following formula: + /// `C = alpha * [A x B] + beta * C`. + /// + /// @param M Dimension M of tensor A. + /// @param N Dimension N of tensor B. + /// @param K Dimension K of tensors A and B. + /// @param batch_size Number of batches to process. + /// @param lda Leading dimension of tensor A. + /// @param ldb Leading dimension of tensor B. + /// @param ldc Leading dimension of tensor C. + /// @param a_dt Data type of tensor A. + /// @param b_dt Data type of tensor B. + /// @param c_dt Data type of tensor C. + /// @param alpha Scale for an accumulation output. + /// @param beta Scale for a tensor C to append on an accumulated output. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + brgemm(memory::dim M, memory::dim N, memory::dim K, memory::dim batch_size, + memory::dim lda, memory::dim ldb, memory::dim ldc, + memory::data_type a_dt, memory::data_type b_dt, + memory::data_type c_dt, float alpha, float beta, + bool allow_empty = false) { + + dnnl_brgemm_t brgemm = nullptr; + dnnl_status_t status = dnnl_brgemm_create(&brgemm, M, N, K, batch_size, + lda, ldb, ldc, ldc, memory::convert_to_c(a_dt), + memory::convert_to_c(b_dt), memory::convert_to_c(c_dt), + memory::convert_to_c(c_dt), alpha, beta, nullptr); + + if (!allow_empty) + error::wrap_c_api( + status, "could not create a BRGeMM ukernel object"); + reset(brgemm); + } + + /// Constructs a BRGeMM ukernel object. Operates by the following formula: + /// `C = alpha * [A x B] + beta * C`; + /// `D = post-operations(C)`. + /// + /// @param M Dimension M of tensor A. + /// @param N Dimension N of tensor B. + /// @param K Dimension K of tensors A and B. + /// @param batch_size Number of batches to process. + /// @param lda Leading dimension of tensor A. + /// @param ldb Leading dimension of tensor B. + /// @param ldc Leading dimension of tensor C. + /// @param ldd Leading dimension of tensor D. + /// @param a_dt Data type of tensor A. + /// @param b_dt Data type of tensor B. + /// @param c_dt Data type of tensor C. Must be data_type::f32. + /// @param d_dt Data type of tensor D. + /// @param alpha Scale for an accumulation output. + /// @param beta Scale for a tensor C to append on an accumulated output. + /// @param attr Primitive attributes to extend the kernel operations. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + brgemm(memory::dim M, memory::dim N, memory::dim K, memory::dim batch_size, + memory::dim lda, memory::dim ldb, memory::dim ldc, memory::dim ldd, + memory::data_type a_dt, memory::data_type b_dt, + memory::data_type c_dt, memory::data_type d_dt, float alpha, + float beta, const primitive_attr &attr, bool allow_empty = false) { + + dnnl_brgemm_t brgemm = nullptr; + dnnl_status_t status = dnnl_brgemm_create(&brgemm, M, N, K, batch_size, + lda, ldb, ldc, ldd, memory::convert_to_c(a_dt), + memory::convert_to_c(b_dt), memory::convert_to_c(c_dt), + memory::convert_to_c(d_dt), alpha, beta, attr.get()); + + if (!allow_empty) + error::wrap_c_api( + status, "could not create a BRGeMM ukernel object"); + reset(brgemm); + } + + /// Returns the size of a scratchpad memory needed for the BRGeMM ukernel + /// object. + size_t get_scratchpad_size() const { + size_t size; + dnnl_status_t status = dnnl_brgemm_get_scratchpad_size(get(), &size); + if (status != dnnl_success) + error::wrap_c_api(status, + "could not query a scratchpad size from a BRGeMM ukernel " + "object"); + return size; + } + + /// Initializes the hardware-specific context. Affects the global state for + /// all BRGeMM ukernel objects. If no initialization required, returns. + void set_hw_context() const { + dnnl_status_t status = dnnl_brgemm_set_hw_context(get()); + if (status != dnnl_success) + error::wrap_c_api(status, "could not set hardware context"); + } + + /// Releases the hardware-specific context. Affects the global state for + /// all BRGeMM ukernel objects. Must be used after all the execution calls + /// to BRGeMM ukernel objects. + static void release_hw_context() { + dnnl_status_t status = dnnl_brgemm_release_hw_context(); + if (status != dnnl_success) + error::wrap_c_api(status, "could not release hardware context"); + } + + /// Generates an executable part of BRGeMM ukernel object. + void generate() { + dnnl_status_t status = dnnl_brgemm_generate(get()); + if (status != dnnl_success) + error::wrap_c_api(status, "could not generate a kernel"); + } + + /// Executes a BRGeMM ukernel object. + /// + /// @param A Base pointer to a tensor A. + /// @param B Base pointer to a tensor B. + /// @param A_B_offsets Vector of pairs of tensors A and B offsets for + /// each batch. The number of batches must coincide with the + /// `batch_size` value passed at object construction stage. + /// @param C Pointer to a tensor C (accumulation buffer). + /// @param scratchpad Pointer to a scratchpad buffer. + void execute(const void *A, const void *B, + const std::vector> &A_B_offsets, + void *C, void *scratchpad) const { + // TODO: export batch_element to C API later for user to fill it and + // pass directly to the call. + dnnl_status_t status = dnnl_brgemm_execute(get(), A, B, + (const dnnl_dim_t *)A_B_offsets.data(), C, scratchpad); + if (status != dnnl_success) + error::wrap_c_api( + status, "could not execute a BRGeMM ukernel object"); + } + + /// Executes a BRGeMM ukernel object with post operations. + /// + /// @param A Base pointer to a tensor A. + /// @param B Base pointer to a tensor B. + /// @param A_B_offsets Vector of pairs of tensors A and B offsets for + /// each batch. The number of batches must coincide with the + /// `batch_size` value passed at object construction stage. + /// @param C Pointer to a tensor C (accumulation buffer). + /// @param D Pointer to a tensor D (output buffer). + /// @param scratchpad Pointer to a scratchpad buffer. + /// @param binary_po Binary post-op memory buffer. Must be passed If binary + /// post-op was specified at construction call. + void execute(const void *A, const void *B, + const std::vector> &A_B_offsets, + void *C, void *D, void *scratchpad, + const void *binary_po = nullptr) const { + // TODO: export batch_element to C API later for user to fill it and + // pass directly to the call. + dnnl_status_t status = dnnl_brgemm_execute_postops(get(), A, B, + (const dnnl_dim_t *)A_B_offsets.data(), C, D, scratchpad, + binary_po); + if (status != dnnl_success) + error::wrap_c_api( + status, "could not execute a BRGeMM ukernel object"); + } +}; + +struct brgemm_pack_B : public handle { + /// Default constructor. Produces an empty object. + brgemm_pack_B() = default; + + /// Constructs a BRGeMM ukernel packing tensor B object. + /// + /// @param K Dimension K. + /// @param N Dimension N. + /// @param in_ld Input leading dimension. + /// @param out_ld Output leading dimension. Specifies a block by N dimension + /// during data packing. + /// @param in_dt Input data type. + /// @param out_dt Output data type. + /// @param allow_empty A flag signifying whether construction is + /// allowed to fail without throwing an exception. In this case an + /// empty object will be produced. This flag is optional and + /// defaults to false. + brgemm_pack_B(memory::dim K, memory::dim N, memory::dim in_ld, + memory::dim out_ld, memory::data_type in_dt, + memory::data_type out_dt, bool allow_empty = false) { + + dnnl_brgemm_pack_B_t brgemm_pack_B = nullptr; + dnnl_status_t status = dnnl_brgemm_pack_B_create(&brgemm_pack_B, K, N, + in_ld, out_ld, memory::convert_to_c(in_dt), + memory::convert_to_c(out_dt)); + + if (!allow_empty) + error::wrap_c_api(status, + "could not create a BRGeMM ukernel packing B object"); + reset(brgemm_pack_B); + } + + /// Returns the flag if packing is expected by BRGeMM ukernel kernel. + bool need_pack() const { + int flag; + dnnl_status_t status = dnnl_brgemm_pack_B_need_pack(get(), &flag); + if (status != dnnl_success) + error::wrap_c_api(status, + "could not query a need_pack flag from a BRGeMM ukernel " + "packing B object"); + return bool(flag); + } + + /// Generates an executable part of BRGeMM ukernel packing B object. + void generate() { + dnnl_status_t status = dnnl_brgemm_pack_B_generate(get()); + if (status != dnnl_success) + error::wrap_c_api(status, + "could not generate a BRGeMM ukernel packing B object"); + } + + /// Executes a BRGeMM ukernel packing tensor B object. + /// + /// @param in Pointer to an input buffer. + /// @param out Pointer to an output buffer. + void execute(const void *in, void *out) const { + dnnl_status_t status = dnnl_brgemm_pack_B_execute(get(), in, out); + if (status != dnnl_success) + error::wrap_c_api(status, + "could not execute a BRGeMM ukernel packing B object"); + } +}; + +/// @} dnnl_api_ukernel_brgemm + +#endif + +} // namespace ukernel + +/// @} dnnl_api_ukernel + +} // namespace dnnl + +/// @} dnnl_api + +#endif /* ONEAPI_DNNL_DNNL_UKERNEL_HPP */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel_types.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel_types.h new file mode 100644 index 0000000000000000000000000000000000000000..ca593b3d6aa6105d369cb76cb8975f2b4d20dff2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_ukernel_types.h @@ -0,0 +1,70 @@ +/******************************************************************************* +* Copyright 2024 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +/// @file +/// ukernel C API types definitions + +#ifndef ONEAPI_DNNL_DNNL_UKERNEL_TYPES_H +#define ONEAPI_DNNL_DNNL_UKERNEL_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "oneapi/dnnl/dnnl_types.h" + +/// @addtogroup dnnl_api +/// @{ + +/// @addtogroup dnnl_api_ukernel +/// @{ + +#ifdef DNNL_EXPERIMENTAL_UKERNEL +/// @addtogroup dnnl_api_ukernel_brgemm +/// @{ + +/// @struct dnnl_brgemm +/// An opaque structure to describe a brgemm ukernel. +struct dnnl_brgemm; + +/// A brgemm ukernel handle. +typedef struct dnnl_brgemm *dnnl_brgemm_t; + +/// A constant brgemm ukernel handle. +typedef const struct dnnl_brgemm *const_dnnl_brgemm_t; + +/// @struct dnnl_brgemm_pack_B +/// An opaque structure to describe a brgemm ukernel packing B routine. +struct dnnl_brgemm_pack_B; + +/// A brgemm ukernel packing B routine handle. +typedef struct dnnl_brgemm_pack_B *dnnl_brgemm_pack_B_t; + +/// A constant brgemm ukernel packing B routine handle. +typedef const struct dnnl_brgemm_pack_B *const_dnnl_brgemm_pack_B_t; + +/// @} dnnl_api_ukernel_brgemm +#endif + +/// @} dnnl_api_ukernel + +/// @} dnnl_api + +#ifdef __cplusplus +} +#endif + +#endif /* ONEAPI_DNNL_DNNL_UKERNEL_TYPES_H */ diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_version.h b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_version.h new file mode 100644 index 0000000000000000000000000000000000000000..3f3e98442f4963e44a2cc471ea40ac4523be848d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_version.h @@ -0,0 +1,36 @@ +/******************************************************************************* +* Copyright 2019-2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_VERSION_H +#define ONEAPI_DNNL_DNNL_VERSION_H + +// clang-format off + +/// Major version +#define DNNL_VERSION_MAJOR 3 + +/// Minor version +#define DNNL_VERSION_MINOR 5 + +/// Patch version +#define DNNL_VERSION_PATCH 0 + +/// Git commit hash +#define DNNL_VERSION_HASH "N/A" + +// clang-format on + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_version.h.in b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_version.h.in new file mode 100644 index 0000000000000000000000000000000000000000..479202b9a8367fdd7cf83111946d17991cf37b66 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/oneapi/dnnl/dnnl_version.h.in @@ -0,0 +1,36 @@ +/******************************************************************************* +* Copyright 2019-2020 Intel Corporation +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*******************************************************************************/ + +#ifndef ONEAPI_DNNL_DNNL_VERSION_H +#define ONEAPI_DNNL_DNNL_VERSION_H + +// clang-format off + +/// Major version +#define DNNL_VERSION_MAJOR @DNNL_VERSION_MAJOR@ + +/// Minor version +#define DNNL_VERSION_MINOR @DNNL_VERSION_MINOR@ + +/// Patch version +#define DNNL_VERSION_PATCH @DNNL_VERSION_PATCH@ + +/// Git commit hash +#define DNNL_VERSION_HASH "@DNNL_VERSION_HASH@" + +// clang-format on + +#endif diff --git a/deps/exla/cache/xla_extension/include/include/private/autogen/config.h b/deps/exla/cache/xla_extension/include/include/private/autogen/config.h new file mode 100644 index 0000000000000000000000000000000000000000..56779b25c1f9d30346c2f5999e4d3a973b770164 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/autogen/config.h @@ -0,0 +1,915 @@ +/* include/private/autogen/config.h.in. Generated from configure.ac by autoheader. */ + +/* -*- c -*- + * + * Copyright © 2009, 2011, 2012 CNRS, inria., Université Bordeaux All rights reserved. + * Copyright © 2009-2014 Cisco Systems, Inc. All rights reserved. + * Copyright © 2022 IBM Corporation. All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + * + * This file is automatically generated by configure. Edits will be lost + * the next time you run configure! + */ + +#ifndef HWLOC_CONFIGURE_H +#define HWLOC_CONFIGURE_H + + +/* Define to 1 if the system has the type `CACHE_DESCRIPTOR'. */ +#undef HAVE_CACHE_DESCRIPTOR + +/* Define to 1 if the system has the type `CACHE_RELATIONSHIP'. */ +#undef HAVE_CACHE_RELATIONSHIP + +/* Define to 1 if you have the `clock_gettime' function. */ +#define HAVE_CLOCK_GETTIME 1 + +/* Define to 1 if you have the `clz' function. */ +#undef HAVE_CLZ + +/* Define to 1 if you have the `clzl' function. */ +#undef HAVE_CLZL + +/* Define to 1 if you have the header file. */ +#undef HAVE_CL_CL_EXT_H + +/* Define to 1 if you have the `cpuset_setaffinity' function. */ +#undef HAVE_CPUSET_SETAFFINITY + +/* Define to 1 if you have the `cpuset_setid' function. */ +#undef HAVE_CPUSET_SETID + +/* Define to 1 if you have the header file. */ +#define HAVE_CTYPE_H 1 + +/* Define to 1 if we have -lcuda */ +#undef HAVE_CUDA + +/* Define to 1 if you have the header file. */ +#undef HAVE_CUDA_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_CUDA_RUNTIME_API_H + +/* Define to 1 if you have the declaration of `bind', and to 0 if you don't. + */ +#undef HAVE_DECL_BIND + +/* Define to 1 if you have the declaration of `CTL_HW', and to 0 if you don't. + */ +#define HAVE_DECL_CTL_HW 0 + +/* Define to 1 if you have the declaration of `fabsf', and to 0 if you don't. + */ +#define HAVE_DECL_FABSF 1 + +/* Define to 1 if you have the declaration of `getexecname', and to 0 if you + don't. */ +#define HAVE_DECL_GETEXECNAME 0 + +/* Define to 1 if you have the declaration of `GetModuleFileName', and to 0 if + you don't. */ +#define HAVE_DECL_GETMODULEFILENAME 0 + +/* Define to 1 if you have the declaration of `getprogname', and to 0 if you + don't. */ +#define HAVE_DECL_GETPROGNAME 0 + +/* Define to 1 if you have the declaration of `HW_MEMSIZE', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_MEMSIZE + +/* Define to 1 if you have the declaration of `HW_MEMSIZE64', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_MEMSIZE64 + +/* Define to 1 if you have the declaration of `HW_NCPU', and to 0 if you + don't. */ +#define HAVE_DECL_HW_NCPU 0 + +/* Define to 1 if you have the declaration of `HW_PHYSMEM', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_PHYSMEM + +/* Define to 1 if you have the declaration of `HW_PHYSMEM64', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_PHYSMEM64 + +/* Define to 1 if you have the declaration of `HW_REALMEM', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_REALMEM + +/* Define to 1 if you have the declaration of `HW_REALMEM64', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_REALMEM64 + +/* Define to 1 if you have the declaration of `HW_USERMEM', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_USERMEM + +/* Define to 1 if you have the declaration of `HW_USERMEM64', and to 0 if you + don't. */ +#undef HAVE_DECL_HW_USERMEM64 + +/* Define to 1 if you have the declaration of `lgrp_latency_cookie', and to 0 + if you don't. */ +#undef HAVE_DECL_LGRP_LATENCY_COOKIE + +/* Define to 1 if you have the declaration of `modff', and to 0 if you don't. + */ +#define HAVE_DECL_MODFF 1 + +/* Define to 1 if you have the declaration of + `nvmlDeviceGetMaxPcieLinkGeneration', and to 0 if you don't. */ +#undef HAVE_DECL_NVMLDEVICEGETMAXPCIELINKGENERATION + +/* Define to 1 if you have the declaration of `pthread_getaffinity_np', and to + 0 if you don't. */ +#define HAVE_DECL_PTHREAD_GETAFFINITY_NP 1 + +/* Define to 1 if you have the declaration of `pthread_setaffinity_np', and to + 0 if you don't. */ +#define HAVE_DECL_PTHREAD_SETAFFINITY_NP 1 + +/* Embedded mode; just assume we do not have Valgrind support */ +#define HAVE_DECL_RUNNING_ON_VALGRIND 0 + +/* Define to 1 if you have the declaration of `sched_getcpu', and to 0 if you + don't. */ +#define HAVE_DECL_SCHED_GETCPU 1 + +/* Define to 1 if you have the declaration of `snprintf', and to 0 if you + don't. */ +#define HAVE_DECL_SNPRINTF 1 + +/* Define to 1 if you have the declaration of `strtoull', and to 0 if you + don't. */ +#define HAVE_DECL_STRTOULL 1 + +/* Define to 1 if you have the declaration of `_putenv', and to 0 if you + don't. */ +#define HAVE_DECL__PUTENV 0 + +/* Define to 1 if you have the declaration of `_SC_LARGE_PAGESIZE', and to 0 + if you don't. */ +#define HAVE_DECL__SC_LARGE_PAGESIZE 0 + +/* Define to 1 if you have the declaration of `_SC_NPROCESSORS_CONF', and to 0 + if you don't. */ +#define HAVE_DECL__SC_NPROCESSORS_CONF 1 + +/* Define to 1 if you have the declaration of `_SC_NPROCESSORS_ONLN', and to 0 + if you don't. */ +#define HAVE_DECL__SC_NPROCESSORS_ONLN 1 + +/* Define to 1 if you have the declaration of `_SC_NPROC_CONF', and to 0 if + you don't. */ +#define HAVE_DECL__SC_NPROC_CONF 0 + +/* Define to 1 if you have the declaration of `_SC_NPROC_ONLN', and to 0 if + you don't. */ +#define HAVE_DECL__SC_NPROC_ONLN 0 + +/* Define to 1 if you have the declaration of `_SC_PAGESIZE', and to 0 if you + don't. */ +#define HAVE_DECL__SC_PAGESIZE 1 + +/* Define to 1 if you have the declaration of `_SC_PAGE_SIZE', and to 0 if you + don't. */ +#define HAVE_DECL__SC_PAGE_SIZE 1 + +/* Define to 1 if you have the declaration of `_strdup', and to 0 if you + don't. */ +#define HAVE_DECL__STRDUP 0 + +/* Define to 1 if you have the header file. */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the `ffs' function. */ +#define HAVE_FFS 1 + +/* Define to 1 if you have the `ffsl' function. */ +#define HAVE_FFSL 1 + +/* Define to 1 if you have the `fls' function. */ +#undef HAVE_FLS + +/* Define to 1 if you have the `flsl' function. */ +#undef HAVE_FLSL + +/* Define to 1 if you have the `getpagesize' function. */ +#define HAVE_GETPAGESIZE 1 + +/* Define to 1 if the system has the type `GROUP_AFFINITY'. */ +#undef HAVE_GROUP_AFFINITY + +/* Define to 1 if the system has the type `GROUP_RELATIONSHIP'. */ +#undef HAVE_GROUP_RELATIONSHIP + +/* Define to 1 if you have the `host_info' function. */ +#undef HAVE_HOST_INFO + +/* Define to 1 if you have the header file. */ +#undef HAVE_INFINIBAND_VERBS_H + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if the system has the type `KAFFINITY'. */ +#undef HAVE_KAFFINITY + +/* Define to 1 if you have the header file. */ +#undef HAVE_KSTAT_H + +/* Define to 1 if you have the header file. */ +#define HAVE_LANGINFO_H 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_LEVEL_ZERO_ZES_API_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_LEVEL_ZERO_ZE_API_H + +/* Define to 1 if we have -lgdi32 */ +#undef HAVE_LIBGDI32 + +/* Define to 1 if we have -libverbs */ +#undef HAVE_LIBIBVERBS + +/* Define to 1 if we have -lkstat */ +#undef HAVE_LIBKSTAT + +/* Define to 1 if we have -llgrp */ +#undef HAVE_LIBLGRP + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIBUDEV_H + +/* Define to 1 if you have the header file. */ +#define HAVE_LOCALE_H 1 + +/* Define to 1 if the system has the type `LOGICAL_PROCESSOR_RELATIONSHIP'. */ +#undef HAVE_LOGICAL_PROCESSOR_RELATIONSHIP + +/* Define to 1 if you have the header file. */ +#undef HAVE_MACH_INIT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_MACH_MACH_HOST_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_MACH_MACH_INIT_H + +/* Define to 1 if you have the header file. */ +#define HAVE_MALLOC_H 1 + +/* Define to 1 if you have the `memalign' function. */ +#define HAVE_MEMALIGN 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_MINIX_CONFIG_H + +/* Define to 1 if you have the `mkstemp' function. */ +#define HAVE_MKSTEMP 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_MPI_H + +/* Define to 1 if you have the `nl_langinfo' function. */ +#define HAVE_NL_LANGINFO 1 + +/* Define to 1 if the system has the type `NUMA_NODE_RELATIONSHIP'. */ +#undef HAVE_NUMA_NODE_RELATIONSHIP + +/* Define to 1 if you have the header file. */ +#undef HAVE_NVCTRL_NVCTRL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NVML_H + +/* Define to 1 if you have the `openat' function. */ +#define HAVE_OPENAT 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_OPENCL_CL_EXT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_PICL_H + +/* Define to 1 if you have the `posix_memalign' function. */ +#define HAVE_POSIX_MEMALIGN 1 + +/* Define to 1 if the system has the type `PROCESSOR_CACHE_TYPE'. */ +#undef HAVE_PROCESSOR_CACHE_TYPE + +/* Define to 1 if the system has the type `PROCESSOR_GROUP_INFO'. */ +#undef HAVE_PROCESSOR_GROUP_INFO + +/* Define to 1 if the system has the type `PROCESSOR_NUMBER'. */ +#undef HAVE_PROCESSOR_NUMBER + +/* Define to 1 if the system has the type `PROCESSOR_RELATIONSHIP'. */ +#undef HAVE_PROCESSOR_RELATIONSHIP + +/* Define to '1' if program_invocation_name is present and usable */ +#define HAVE_PROGRAM_INVOCATION_NAME 1 + +/* Define to 1 if the system has the type `PSAPI_WORKING_SET_EX_BLOCK'. */ +#undef HAVE_PSAPI_WORKING_SET_EX_BLOCK + +/* Define to 1 if the system has the type `PSAPI_WORKING_SET_EX_INFORMATION'. + */ +#undef HAVE_PSAPI_WORKING_SET_EX_INFORMATION + +/* Define to 1 if you have the header file. */ +#undef HAVE_PTHREAD_NP_H + +/* Define to 1 if the system has the type `pthread_t'. */ +#define HAVE_PTHREAD_T 1 + +/* Define to 1 if you have the `putwc' function. */ +#define HAVE_PUTWC 1 + +/* Define to 1 if the system has the type `RelationProcessorPackage'. */ +#undef HAVE_RELATIONPROCESSORPACKAGE + +/* Define to 1 if you have the header file. */ +#undef HAVE_ROCM_SMI_ROCM_SMI_H + +/* Define to 1 if you have the `setlocale' function. */ +#define HAVE_SETLOCALE 1 + +/* Define to 1 if the system has the type `ssize_t'. */ +#define HAVE_SSIZE_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDIO_H + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strcasecmp' function. */ +#define HAVE_STRCASECMP 1 + +/* Define to 1 if you have the `strftime' function. */ +#define HAVE_STRFTIME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strncasecmp' function. */ +#define HAVE_STRNCASECMP 1 + +/* Define to 1 if you have the `strtoull' function. */ +#undef HAVE_STRTOULL + +/* Define to '1' if sysctl is present and usable */ +#undef HAVE_SYSCTL + +/* Define to '1' if sysctlbyname is present and usable */ +#undef HAVE_SYSCTLBYNAME + +/* Define to 1 if the system has the type + `SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX'. */ +#undef HAVE_SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_CPUSET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_DOMAINSET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_LGRP_USER_H + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_MMAN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SYSCTL_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_THR_H + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UTSNAME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TIME_H 1 + +/* Define to 1 if you have the `uname' function. */ +#define HAVE_UNAME 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the `uselocale' function. */ +#define HAVE_USELOCALE 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_VALGRIND_VALGRIND_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_WCHAR_H + +/* Define to 1 if the system has the type `wchar_t'. */ +#define HAVE_WCHAR_T 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_X11_KEYSYM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_X11_XLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_X11_XUTIL_H 1 + +/* Define to 1 if you have the header file. */ +#undef HAVE_XLOCALE_H + +/* Define to '1' if __progname is present and usable */ +#define HAVE___PROGNAME 1 + +/* Define to 1 on AIX */ +#undef HWLOC_AIX_SYS + +/* Define to 1 on BlueGene/Q */ +#undef HWLOC_BGQ_SYS + +/* Define if the CUDA component is built statically inside libhwloc */ +#undef HWLOC_CUDA_COMPONENT_BUILTIN + +/* Whether C compiler supports symbol visibility or not */ +#define HWLOC_C_HAVE_VISIBILITY 1 + +/* Define to 1 on Darwin */ +#undef HWLOC_DARWIN_SYS + +/* Whether we are in debugging mode or not */ +#undef HWLOC_DEBUG + +/* Define to 1 on *FREEBSD */ +#undef HWLOC_FREEBSD_SYS + +/* Define if the GL component is built statically inside libhwloc */ +#undef HWLOC_GL_COMPONENT_BUILTIN + +/* Define to 1 if --enable-32bits-pci-domain is called. */ +#undef HWLOC_HAVE_32BITS_PCI_DOMAIN + +/* Whether your compiler has __attribute__ or not */ +#define HWLOC_HAVE_ATTRIBUTE 1 + +/* Whether your compiler has __attribute__ aligned or not */ +#define HWLOC_HAVE_ATTRIBUTE_ALIGNED 1 + +/* Whether your compiler has __attribute__ always_inline or not */ +#define HWLOC_HAVE_ATTRIBUTE_ALWAYS_INLINE 1 + +/* Whether your compiler has __attribute__ cold or not */ +#define HWLOC_HAVE_ATTRIBUTE_COLD 1 + +/* Whether your compiler has __attribute__ const or not */ +#define HWLOC_HAVE_ATTRIBUTE_CONST 1 + +/* Whether your compiler has __attribute__ constructor or not */ +#define HWLOC_HAVE_ATTRIBUTE_CONSTRUCTOR 1 + +/* Whether your compiler has __attribute__ deprecated or not */ +#define HWLOC_HAVE_ATTRIBUTE_DEPRECATED 1 + +/* Whether your compiler has __attribute__ format or not */ +#define HWLOC_HAVE_ATTRIBUTE_FORMAT 1 + +/* Whether your compiler has __attribute__ hot or not */ +#define HWLOC_HAVE_ATTRIBUTE_HOT 1 + +/* Whether your compiler has __attribute__ malloc or not */ +#define HWLOC_HAVE_ATTRIBUTE_MALLOC 1 + +/* Whether your compiler has __attribute__ may_alias or not */ +#define HWLOC_HAVE_ATTRIBUTE_MAY_ALIAS 1 + +/* Whether your compiler has __attribute__ nonnull or not */ +#define HWLOC_HAVE_ATTRIBUTE_NONNULL 1 + +/* Whether your compiler has __attribute__ noreturn or not */ +#define HWLOC_HAVE_ATTRIBUTE_NORETURN 1 + +/* Whether your compiler has __attribute__ no_instrument_function or not */ +#define HWLOC_HAVE_ATTRIBUTE_NO_INSTRUMENT_FUNCTION 1 + +/* Whether your compiler has __attribute__ packed or not */ +#define HWLOC_HAVE_ATTRIBUTE_PACKED 1 + +/* Whether your compiler has __attribute__ pure or not */ +#define HWLOC_HAVE_ATTRIBUTE_PURE 1 + +/* Whether your compiler has __attribute__ sentinel or not */ +#define HWLOC_HAVE_ATTRIBUTE_SENTINEL 1 + +/* Whether your compiler has __attribute__ unused or not */ +#define HWLOC_HAVE_ATTRIBUTE_UNUSED 1 + +/* Whether your compiler has __attribute__ warn unused result or not */ +#define HWLOC_HAVE_ATTRIBUTE_WARN_UNUSED_RESULT 1 + +/* Whether your compiler has __attribute__ weak alias or not */ +#define HWLOC_HAVE_ATTRIBUTE_WEAK_ALIAS 1 + +/* Define to 1 if your `ffs' function is known to be broken. */ +#undef HWLOC_HAVE_BROKEN_FFS + +/* Define to 1 if you have the `cairo' library. */ +#undef HWLOC_HAVE_CAIRO + +/* Define to 1 if you have the `clz' function. */ +#undef HWLOC_HAVE_CLZ + +/* Define to 1 if you have the `clzl' function. */ +#undef HWLOC_HAVE_CLZL + +/* Define to 1 if snprintf supports NULL output buffer and returns the correct + length on truncation */ +#undef HWLOC_HAVE_CORRECT_SNPRINTF + +/* Define to 1 if the CPU_SET macro works */ +#define HWLOC_HAVE_CPU_SET 1 + +/* Define to 1 if the CPU_SET_S macro works */ +#define HWLOC_HAVE_CPU_SET_S 1 + +/* Define to 1 if you have the `cudart' SDK. */ +#undef HWLOC_HAVE_CUDART + +/* `Define to 1 if you have the Foundation Darwin framework' */ +#undef HWLOC_HAVE_DARWIN_FOUNDATION + +/* `Define to 1 if you have the IOKit Darwin framework' */ +#undef HWLOC_HAVE_DARWIN_IOKIT + +/* Define to 1 if function `clz' is declared by system headers */ +#undef HWLOC_HAVE_DECL_CLZ + +/* Define to 1 if function `clzl' is declared by system headers */ +#undef HWLOC_HAVE_DECL_CLZL + +/* Define to 1 if function `ffs' is declared by system headers */ +#define HWLOC_HAVE_DECL_FFS 1 + +/* Define to 1 if function `ffsl' is declared by system headers */ +#define HWLOC_HAVE_DECL_FFSL 1 + +/* Define to 1 if function `fls' is declared by system headers */ +#undef HWLOC_HAVE_DECL_FLS + +/* Define to 1 if function `flsl' is declared by system headers */ +#undef HWLOC_HAVE_DECL_FLSL + +/* Define to 1 if function `strcasecmp' is declared by system headers */ +#define HWLOC_HAVE_DECL_STRCASECMP 1 + +/* Define to 1 if function `strncasecmp' is declared by system headers */ +#define HWLOC_HAVE_DECL_STRNCASECMP 1 + +/* Define to 1 if you have the `ffs' function. */ +#define HWLOC_HAVE_FFS 1 + +/* Define to 1 if you have the `ffsl' function. */ +#define HWLOC_HAVE_FFSL 1 + +/* Define to 1 if you have the `fls' function. */ +#undef HWLOC_HAVE_FLS + +/* Define to 1 if you have the `flsl' function. */ +#undef HWLOC_HAVE_FLSL + +/* Define to 1 if gcc -Wcast-function-type is supported and enabled */ +#undef HWLOC_HAVE_GCC_W_CAST_FUNCTION_TYPE + +/* Define to 1 if gcc -Wmissing-field-initializers is supported and enabled */ +#undef HWLOC_HAVE_GCC_W_MISSING_FIELD_INITIALIZERS + +/* Define to 1 if you have the GL module components. */ +#undef HWLOC_HAVE_GL + +/* Define to 1 if you have the `LevelZero' library. */ +#undef HWLOC_HAVE_LEVELZERO + +/* Define to 1 if you have a library providing the termcap interface */ +#define HWLOC_HAVE_LIBTERMCAP 1 + +/* Define to 1 if you have libudev. */ +#undef HWLOC_HAVE_LIBUDEV + +/* Define to 1 if you have the `libxml2' library. */ +#undef HWLOC_HAVE_LIBXML2 + +/* Define to 1 for I/O discovery in the Linux component */ +#define HWLOC_HAVE_LINUXIO 1 + +/* Define to 1 if enabling Linux-specific PCI discovery in the Linux I/O + component */ +#undef HWLOC_HAVE_LINUXPCI + +/* Define to 1 if the hwloc library should use ltdl for loading plugins */ +#undef HWLOC_HAVE_LTDL + +/* Define to 1 if you have the `NVML' library. */ +#undef HWLOC_HAVE_NVML + +/* Define to 1 if glibc provides the old prototype (without length) of + sched_setaffinity() */ +#undef HWLOC_HAVE_OLD_SCHED_SETAFFINITY + +/* Define to 1 if you have the `OpenCL' library. */ +#undef HWLOC_HAVE_OPENCL + +/* Define to 1 if the hwloc library should support dynamically-loaded plugins + */ +#undef HWLOC_HAVE_PLUGINS + +/* `Define to 1 if you have pthread_getthrds_np' */ +#undef HWLOC_HAVE_PTHREAD_GETTHRDS_NP + +/* Define to 1 if pthread mutexes are available */ +#define HWLOC_HAVE_PTHREAD_MUTEX 1 + +/* Define to 1 if you have the `RSMI' library. */ +#undef HWLOC_HAVE_RSMI + +/* Define to 1 if glibc provides a prototype of sched_setaffinity() */ +#define HWLOC_HAVE_SCHED_SETAFFINITY 1 + +/* Define to 1 if you have the header file. */ +#define HWLOC_HAVE_STDINT_H 1 + +/* Define to 1 if function `syscall' is available with 6 parameters */ +#define HWLOC_HAVE_SYSCALL 1 + +/* Define to 1 if you have the `windows.h' header. */ +#undef HWLOC_HAVE_WINDOWS_H + +/* Define to 1 if X11 headers including Xutil.h and keysym.h are available. */ +#define HWLOC_HAVE_X11_KEYSYM 1 + +/* Define to 1 if you have x86 cpuid */ +#define HWLOC_HAVE_X86_CPUID 1 + +/* Define to 1 on HP-UX */ +#undef HWLOC_HPUX_SYS + +/* Define to 1 on Irix */ +#undef HWLOC_IRIX_SYS + +/* Define if the LevelZero component is built statically inside libhwloc */ +#undef HWLOC_LEVELZERO_COMPONENT_BUILTIN + +/* Define to 1 on Linux */ +#define HWLOC_LINUX_SYS 1 + +/* Define to 1 on *NETBSD */ +#undef HWLOC_NETBSD_SYS + +/* Define if the NVML component is built statically inside libhwloc */ +#undef HWLOC_NVML_COMPONENT_BUILTIN + +/* Define if the OpenCL component is built statically inside libhwloc */ +#undef HWLOC_OPENCL_COMPONENT_BUILTIN + +/* Define if the PCI component is built statically inside libhwloc */ +#undef HWLOC_PCI_COMPONENT_BUILTIN + +/* Define if the RSMI component is built statically inside libhwloc */ +#undef HWLOC_RSMI_COMPONENT_BUILTIN + +/* The size of `unsigned int', as computed by sizeof */ +#define HWLOC_SIZEOF_UNSIGNED_INT 4 + +/* The size of `unsigned long', as computed by sizeof */ +#define HWLOC_SIZEOF_UNSIGNED_LONG 8 + +/* Define to 1 on Solaris */ +#undef HWLOC_SOLARIS_SYS + +/* The hwloc symbol prefix */ +#define HWLOC_SYM_PREFIX hwloc_ + +/* The hwloc symbol prefix in all caps */ +#define HWLOC_SYM_PREFIX_CAPS HWLOC_ + +/* Whether we need to re-define all the hwloc public symbols or not */ +#define HWLOC_SYM_TRANSFORM 0 + +/* Define to 1 on unsupported systems */ +#undef HWLOC_UNSUPPORTED_SYS + +/* Define to 1 if ncurses works, preferred over curses */ +#define HWLOC_USE_NCURSES 1 + +/* The library version, always available, even in embedded mode, contrary to + VERSION */ +#define HWLOC_VERSION "2.0.3" + +/* The library version optional greek suffix string */ +#define HWLOC_VERSION_GREEK "" + +/* The library version major number */ +#define HWLOC_VERSION_MAJOR 2 + +/* The library version minor number */ +#define HWLOC_VERSION_MINOR 0 + +/* The library version release number */ +#define HWLOC_VERSION_RELEASE 3 + +/* Define to 1 on WINDOWS */ +#undef HWLOC_WIN_SYS + +/* Define to 1 on x86_32 */ +#undef HWLOC_X86_32_ARCH + +/* Define to 1 on x86_64 */ +#define HWLOC_X86_64_ARCH 1 + +/* Define if the libxml XML component is built statically inside libhwloc */ +#undef HWLOC_XML_LIBXML_COMPONENT_BUILTIN + +/* Define if lstopo Cairo/X11 interactive graphical output is supported */ +#undef LSTOPO_HAVE_X11 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Define to 1 if scotch is netlocscotch is enabled */ +#undef NETLOC_SCOTCH + +/* Name of package */ +#define PACKAGE "hwloc" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "http://github.com/open-mpi/hwloc/issues + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "hwloc" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "hwloc 2.0.3" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "hwloc" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "2.0.3" + +/* The size of `unsigned int', as computed by sizeof. */ +#define SIZEOF_UNSIGNED_INT 4 + +/* The size of `unsigned long', as computed by sizeof. */ +#define SIZEOF_UNSIGNED_LONG 8 + +/* The size of `void *', as computed by sizeof. */ +#define SIZEOF_VOID_P 8 + +/* Define to 1 if all of the C90 standard headers exist (not just the ones + required in a freestanding environment). This macro is provided for + backward compatibility; new code need not use it. */ +#define STDC_HEADERS 1 + +/* Enable extensions on HP-UX. */ +#ifndef _HPUX_SOURCE +# define _HPUX_SOURCE 1 +#endif + + +/* Enable extensions on AIX 3, Interix. */ +#ifndef _ALL_SOURCE +# define _ALL_SOURCE 1 +#endif +/* Enable general extensions on macOS. */ +#ifndef _DARWIN_C_SOURCE +# undef _DARWIN_C_SOURCE +#endif +/* Enable general extensions on Solaris. */ +#ifndef __EXTENSIONS__ +# define __EXTENSIONS__ 1 +#endif +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif +/* Enable X/Open compliant socket functions that do not require linking + with -lxnet on HP-UX 11.11. */ +#ifndef _HPUX_ALT_XOPEN_SOCKET_API +# undef _HPUX_ALT_XOPEN_SOCKET_API +#endif +/* Identify the host operating system as Minix. + This macro does not affect the system headers' behavior. + A future release of Autoconf may stop defining this macro. */ +#ifndef _MINIX +# undef _MINIX +#endif +/* Enable general extensions on NetBSD. + Enable NetBSD compatibility extensions on Minix. */ +#ifndef _NETBSD_SOURCE +# undef _NETBSD_SOURCE +#endif +/* Enable OpenBSD compatibility extensions on NetBSD. + Oddly enough, this does nothing on OpenBSD. */ +#ifndef _OPENBSD_SOURCE +# undef _OPENBSD_SOURCE +#endif +/* Define to 1 if needed for POSIX-compatible behavior. */ +#ifndef _POSIX_SOURCE +# undef _POSIX_SOURCE +#endif +/* Define to 2 if needed for POSIX-compatible behavior. */ +#ifndef _POSIX_1_SOURCE +# undef _POSIX_1_SOURCE +#endif +/* Enable POSIX-compatible threading on Solaris. */ +#ifndef _POSIX_PTHREAD_SEMANTICS +# define _POSIX_PTHREAD_SEMANTICS 1 +#endif +/* Enable extensions specified by ISO/IEC TS 18661-5:2014. */ +#ifndef __STDC_WANT_IEC_60559_ATTRIBS_EXT__ +# undef __STDC_WANT_IEC_60559_ATTRIBS_EXT__ +#endif +/* Enable extensions specified by ISO/IEC TS 18661-1:2014. */ +#ifndef __STDC_WANT_IEC_60559_BFP_EXT__ +# undef __STDC_WANT_IEC_60559_BFP_EXT__ +#endif +/* Enable extensions specified by ISO/IEC TS 18661-2:2015. */ +#ifndef __STDC_WANT_IEC_60559_DFP_EXT__ +# undef __STDC_WANT_IEC_60559_DFP_EXT__ +#endif +/* Enable extensions specified by ISO/IEC TS 18661-4:2015. */ +#ifndef __STDC_WANT_IEC_60559_FUNCS_EXT__ +# undef __STDC_WANT_IEC_60559_FUNCS_EXT__ +#endif +/* Enable extensions specified by ISO/IEC TS 18661-3:2015. */ +#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__ +# undef __STDC_WANT_IEC_60559_TYPES_EXT__ +#endif +/* Enable extensions specified by ISO/IEC TR 24731-2:2010. */ +#ifndef __STDC_WANT_LIB_EXT2__ +# undef __STDC_WANT_LIB_EXT2__ +#endif +/* Enable extensions specified by ISO/IEC 24747:2009. */ +#ifndef __STDC_WANT_MATH_SPEC_FUNCS__ +# undef __STDC_WANT_MATH_SPEC_FUNCS__ +#endif +/* Enable extensions on HP NonStop. */ +#ifndef _TANDEM_SOURCE +# define _TANDEM_SOURCE 1 +#endif +/* Enable X/Open extensions. Define to 500 only if necessary + to make mbstate_t available. */ +#ifndef _XOPEN_SOURCE +# undef _XOPEN_SOURCE +#endif + + +/* Version number of package */ +#define VERSION "2.0.3" + +/* Define to 1 if the X Window System is missing or not being used. */ +#undef X_DISPLAY_MISSING + +/* Are we building for HP-UX? */ +#define _HPUX_SOURCE 1 + +/* Define this to the process ID type */ +#define hwloc_pid_t pid_t + +/* Define this to the thread ID type */ +#define hwloc_thread_t pthread_t + + +#endif /* HWLOC_CONFIGURE_H */ + diff --git a/deps/exla/cache/xla_extension/include/include/private/components.h b/deps/exla/cache/xla_extension/include/include/private/components.h new file mode 100644 index 0000000000000000000000000000000000000000..e28c00b1da41c4bd0f9924a50c77875b85ef32cd --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/components.h @@ -0,0 +1,45 @@ +/* + * Copyright © 2012-2019 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + + +#ifdef HWLOC_INSIDE_PLUGIN +/* + * these declarations are internal only, they are not available to plugins + * (many functions below are internal static symbols). + */ +#error This file should not be used in plugins +#endif + + +#ifndef PRIVATE_COMPONENTS_H +#define PRIVATE_COMPONENTS_H 1 + +#include "hwloc/plugins.h" + +struct hwloc_topology; + +extern int hwloc_disc_component_force_enable(struct hwloc_topology *topology, + int envvar_forced, /* 1 if forced through envvar, 0 if forced through API */ + const char *name, + const void *data1, const void *data2, const void *data3); +extern void hwloc_disc_components_enable_others(struct hwloc_topology *topology); + +/* Compute the topology is_thissystem flag and find some callbacks based on enabled backends */ +extern void hwloc_backends_is_thissystem(struct hwloc_topology *topology); +extern void hwloc_backends_find_callbacks(struct hwloc_topology *topology); + +/* Initialize the lists of components and backends used by a topology */ +extern void hwloc_topology_components_init(struct hwloc_topology *topology); +/* Disable and destroy all backends used by a topology */ +extern void hwloc_backends_disable_all(struct hwloc_topology *topology); +/* Cleanup the lists of components used by a topology */ +extern void hwloc_topology_components_fini(struct hwloc_topology *topology); + +/* Used by the core to setup/destroy the list of components */ +extern void hwloc_components_init(void); /* increases components refcount, should be called exactly once per topology (during init) */ +extern void hwloc_components_fini(void); /* decreases components refcount, should be called exactly once per topology (during destroy) */ + +#endif /* PRIVATE_COMPONENTS_H */ + diff --git a/deps/exla/cache/xla_extension/include/include/private/cpuid-x86.h b/deps/exla/cache/xla_extension/include/include/private/cpuid-x86.h new file mode 100644 index 0000000000000000000000000000000000000000..2758afe049531c9285135e9076af3b8d8e3bd69c --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/cpuid-x86.h @@ -0,0 +1,86 @@ +/* + * Copyright © 2010-2012, 2014 Université Bordeaux + * Copyright © 2010 Cisco Systems, Inc. All rights reserved. + * Copyright © 2014 Inria. All rights reserved. + * + * See COPYING in top-level directory. + */ + +/* Internals for x86's cpuid. */ + +#ifndef HWLOC_PRIVATE_CPUID_X86_H +#define HWLOC_PRIVATE_CPUID_X86_H + +#if (defined HWLOC_X86_32_ARCH) && (!defined HWLOC_HAVE_MSVC_CPUIDEX) +static __hwloc_inline int hwloc_have_x86_cpuid(void) +{ + int ret; + unsigned tmp, tmp2; + __asm__( + "mov $0,%0\n\t" /* Not supported a priori */ + + "pushfl \n\t" /* Save flags */ + + "pushfl \n\t" \ + "pop %1 \n\t" /* Get flags */ \ + +#define TRY_TOGGLE \ + "xor $0x00200000,%1\n\t" /* Try to toggle ID */ \ + "mov %1,%2\n\t" /* Save expected value */ \ + "push %1 \n\t" \ + "popfl \n\t" /* Try to toggle */ \ + "pushfl \n\t" \ + "pop %1 \n\t" \ + "cmp %1,%2\n\t" /* Compare with expected value */ \ + "jnz 0f\n\t" /* Unexpected, failure */ \ + + TRY_TOGGLE /* Try to set/clear */ + TRY_TOGGLE /* Try to clear/set */ + + "mov $1,%0\n\t" /* Passed the test! */ + + "0: \n\t" + "popfl \n\t" /* Restore flags */ + + : "=r" (ret), "=&r" (tmp), "=&r" (tmp2)); + return ret; +} +#endif /* !defined HWLOC_X86_32_ARCH && !defined HWLOC_HAVE_MSVC_CPUIDEX*/ +#if (defined HWLOC_X86_64_ARCH) || (defined HWLOC_HAVE_MSVC_CPUIDEX) +static __hwloc_inline int hwloc_have_x86_cpuid(void) { return 1; } +#endif /* HWLOC_X86_64_ARCH */ + +static __hwloc_inline void hwloc_x86_cpuid(unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) +{ +#ifdef HWLOC_HAVE_MSVC_CPUIDEX + int regs[4]; + __cpuidex(regs, *eax, *ecx); + *eax = regs[0]; + *ebx = regs[1]; + *ecx = regs[2]; + *edx = regs[3]; +#else /* HWLOC_HAVE_MSVC_CPUIDEX */ + /* Note: gcc might want to use bx or the stack for %1 addressing, so we can't + * use them :/ */ +#ifdef HWLOC_X86_64_ARCH + hwloc_uint64_t sav_rbx; + __asm__( + "mov %%rbx,%2\n\t" + "cpuid\n\t" + "xchg %2,%%rbx\n\t" + "movl %k2,%1\n\t" + : "+a" (*eax), "=m" (*ebx), "=&r"(sav_rbx), + "+c" (*ecx), "=&d" (*edx)); +#elif defined(HWLOC_X86_32_ARCH) + __asm__( + "mov %%ebx,%1\n\t" + "cpuid\n\t" + "xchg %%ebx,%1\n\t" + : "+a" (*eax), "=&SD" (*ebx), "+c" (*ecx), "=&d" (*edx)); +#else +#error unknown architecture +#endif +#endif /* HWLOC_HAVE_MSVC_CPUIDEX */ +} + +#endif /* HWLOC_PRIVATE_X86_CPUID_H */ diff --git a/deps/exla/cache/xla_extension/include/include/private/debug.h b/deps/exla/cache/xla_extension/include/include/private/debug.h new file mode 100644 index 0000000000000000000000000000000000000000..29dca70b073d1917d533d4c68b9681c3c553bb17 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/debug.h @@ -0,0 +1,95 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2020 Inria. All rights reserved. + * Copyright © 2009, 2011 Université Bordeaux + * Copyright © 2011 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/* The configuration file */ + +#ifndef HWLOC_DEBUG_H +#define HWLOC_DEBUG_H + +#include "private/autogen/config.h" +#include "private/misc.h" + +#ifdef HWLOC_DEBUG +#include +#include +#endif + +#ifdef ANDROID +extern void JNIDebug(char *text); +#endif + +/* Compile-time assertion */ +#define HWLOC_BUILD_ASSERT(condition) ((void)sizeof(char[1 - 2*!(condition)])) + +#ifdef HWLOC_DEBUG +static __hwloc_inline int hwloc_debug_enabled(void) +{ + static int checked = 0; + static int enabled = 1; + if (!checked) { + const char *env = getenv("HWLOC_DEBUG_VERBOSE"); + if (env) + enabled = atoi(env); + if (enabled) + fprintf(stderr, "hwloc verbose debug enabled, may be disabled with HWLOC_DEBUG_VERBOSE=0 in the environment.\n"); + checked = 1; + } + return enabled; +} +#endif + +static __hwloc_inline void hwloc_debug(const char *s __hwloc_attribute_unused, ...) __hwloc_attribute_format(printf, 1, 2); +static __hwloc_inline void hwloc_debug(const char *s __hwloc_attribute_unused, ...) +{ +#ifdef HWLOC_DEBUG + if (hwloc_debug_enabled()) { +#ifdef ANDROID + char buffer[256]; +#endif + va_list ap; + va_start(ap, s); +#ifdef ANDROID + vsprintf(buffer, s, ap); + JNIDebug(buffer); +#else + vfprintf(stderr, s, ap); +#endif + va_end(ap); + } +#endif +} + +#ifdef HWLOC_DEBUG +#define hwloc_debug_bitmap(fmt, bitmap) do { \ +if (hwloc_debug_enabled()) { \ + char *s; \ + hwloc_bitmap_asprintf(&s, bitmap); \ + hwloc_debug(fmt, s); \ + free(s); \ +} } while (0) +#define hwloc_debug_1arg_bitmap(fmt, arg1, bitmap) do { \ +if (hwloc_debug_enabled()) { \ + char *s; \ + hwloc_bitmap_asprintf(&s, bitmap); \ + hwloc_debug(fmt, arg1, s); \ + free(s); \ +} } while (0) +#define hwloc_debug_2args_bitmap(fmt, arg1, arg2, bitmap) do { \ +if (hwloc_debug_enabled()) { \ + char *s; \ + hwloc_bitmap_asprintf(&s, bitmap); \ + hwloc_debug(fmt, arg1, arg2, s); \ + free(s); \ +} } while (0) +#else +#define hwloc_debug_bitmap(s, bitmap) do { } while(0) +#define hwloc_debug_1arg_bitmap(s, arg1, bitmap) do { } while(0) +#define hwloc_debug_2args_bitmap(s, arg1, arg2, bitmap) do { } while(0) +#endif + +#endif /* HWLOC_DEBUG_H */ diff --git a/deps/exla/cache/xla_extension/include/include/private/internal-components.h b/deps/exla/cache/xla_extension/include/include/private/internal-components.h new file mode 100644 index 0000000000000000000000000000000000000000..65cfdd7d41ceb178a0f4bfbacafb8bea64e113b8 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/internal-components.h @@ -0,0 +1,42 @@ +/* + * Copyright © 2018-2020 Inria. All rights reserved. + * + * See COPYING in top-level directory. + */ + +/* List of components defined inside hwloc */ + +#ifndef PRIVATE_INTERNAL_COMPONENTS_H +#define PRIVATE_INTERNAL_COMPONENTS_H + +/* global discovery */ +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_xml_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_synthetic_component; + +/* CPU discovery */ +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_aix_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_bgq_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_darwin_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_freebsd_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_hpux_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_linux_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_netbsd_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_noos_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_solaris_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_windows_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_x86_component; + +/* I/O discovery */ +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_cuda_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_gl_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_nvml_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_rsmi_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_levelzero_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_opencl_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_pci_component; + +/* XML backend */ +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_xml_nolibxml_component; +HWLOC_DECLSPEC extern const struct hwloc_component hwloc_xml_libxml_component; + +#endif /* PRIVATE_INTERNAL_COMPONENTS_H */ diff --git a/deps/exla/cache/xla_extension/include/include/private/misc.h b/deps/exla/cache/xla_extension/include/include/private/misc.h new file mode 100644 index 0000000000000000000000000000000000000000..bc57e98ec8d9716c64dc2ec7341b0e997ef56512 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/misc.h @@ -0,0 +1,576 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2019 Inria. All rights reserved. + * Copyright © 2009-2012 Université Bordeaux + * Copyright © 2011 Cisco Systems, Inc. All rights reserved. + * See COPYING in top-level directory. + */ + +/* Misc macros and inlines. */ + +#ifndef HWLOC_PRIVATE_MISC_H +#define HWLOC_PRIVATE_MISC_H + +#include "hwloc/autogen/config.h" +#include "private/autogen/config.h" +#include "hwloc.h" + +#ifdef HWLOC_HAVE_DECL_STRNCASECMP +#ifdef HAVE_STRINGS_H +#include +#endif +#else +#ifdef HAVE_CTYPE_H +#include +#endif +#endif + +#define HWLOC_BITS_PER_LONG (HWLOC_SIZEOF_UNSIGNED_LONG * 8) +#define HWLOC_BITS_PER_INT (HWLOC_SIZEOF_UNSIGNED_INT * 8) + +#if (HWLOC_BITS_PER_LONG != 32) && (HWLOC_BITS_PER_LONG != 64) +#error "unknown size for unsigned long." +#endif + +#if (HWLOC_BITS_PER_INT != 16) && (HWLOC_BITS_PER_INT != 32) && (HWLOC_BITS_PER_INT != 64) +#error "unknown size for unsigned int." +#endif + +/* internal-use-only value for when we don't know the type or don't have any value */ +#define HWLOC_OBJ_TYPE_NONE ((hwloc_obj_type_t) -1) + +/** + * ffsl helpers. + */ + +#if defined(HWLOC_HAVE_BROKEN_FFS) + +/* System has a broken ffs(). + * We must check the before __GNUC__ or HWLOC_HAVE_FFSL + */ +# define HWLOC_NO_FFS + +#elif defined(__GNUC__) + +# if (__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)) + /* Starting from 3.4, gcc has a long variant. */ +# define hwloc_ffsl(x) __builtin_ffsl(x) +# else +# define hwloc_ffs(x) __builtin_ffs(x) +# define HWLOC_NEED_FFSL +# endif + +#elif defined(HWLOC_HAVE_FFSL) + +# ifndef HWLOC_HAVE_DECL_FFSL +extern int ffsl(long) __hwloc_attribute_const; +# endif + +# define hwloc_ffsl(x) ffsl(x) + +#elif defined(HWLOC_HAVE_FFS) + +# ifndef HWLOC_HAVE_DECL_FFS +extern int ffs(int) __hwloc_attribute_const; +# endif + +# define hwloc_ffs(x) ffs(x) +# define HWLOC_NEED_FFSL + +#else /* no ffs implementation */ + +# define HWLOC_NO_FFS + +#endif + +#ifdef HWLOC_NO_FFS + +/* no ffs or it is known to be broken */ +static __hwloc_inline int +hwloc_ffsl_manual(unsigned long x) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_ffsl_manual(unsigned long x) +{ + int i; + + if (!x) + return 0; + + i = 1; +#if HWLOC_BITS_PER_LONG >= 64 + if (!(x & 0xfffffffful)) { + x >>= 32; + i += 32; + } +#endif + if (!(x & 0xffffu)) { + x >>= 16; + i += 16; + } + if (!(x & 0xff)) { + x >>= 8; + i += 8; + } + if (!(x & 0xf)) { + x >>= 4; + i += 4; + } + if (!(x & 0x3)) { + x >>= 2; + i += 2; + } + if (!(x & 0x1)) { + x >>= 1; + i += 1; + } + + return i; +} +/* always define hwloc_ffsl as a macro, to avoid renaming breakage */ +#define hwloc_ffsl hwloc_ffsl_manual + +#elif defined(HWLOC_NEED_FFSL) + +/* We only have an int ffs(int) implementation, build a long one. */ + +/* First make it 32 bits if it was only 16. */ +static __hwloc_inline int +hwloc_ffs32(unsigned long x) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_ffs32(unsigned long x) +{ +#if HWLOC_BITS_PER_INT == 16 + int low_ffs, hi_ffs; + + low_ffs = hwloc_ffs(x & 0xfffful); + if (low_ffs) + return low_ffs; + + hi_ffs = hwloc_ffs(x >> 16); + if (hi_ffs) + return hi_ffs + 16; + + return 0; +#else + return hwloc_ffs(x); +#endif +} + +/* Then make it 64 bit if longs are. */ +static __hwloc_inline int +hwloc_ffsl_from_ffs32(unsigned long x) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_ffsl_from_ffs32(unsigned long x) +{ +#if HWLOC_BITS_PER_LONG == 64 + int low_ffs, hi_ffs; + + low_ffs = hwloc_ffs32(x & 0xfffffffful); + if (low_ffs) + return low_ffs; + + hi_ffs = hwloc_ffs32(x >> 32); + if (hi_ffs) + return hi_ffs + 32; + + return 0; +#else + return hwloc_ffs32(x); +#endif +} +/* always define hwloc_ffsl as a macro, to avoid renaming breakage */ +#define hwloc_ffsl hwloc_ffsl_from_ffs32 + +#endif + +/** + * flsl helpers. + */ +#ifdef __GNUC_____ + +# if (__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4)) +# define hwloc_flsl(x) ((x) ? (8*sizeof(long) - __builtin_clzl(x)) : 0) +# else +# define hwloc_fls(x) ((x) ? (8*sizeof(int) - __builtin_clz(x)) : 0) +# define HWLOC_NEED_FLSL +# endif + +#elif defined(HWLOC_HAVE_FLSL) + +# ifndef HWLOC_HAVE_DECL_FLSL +extern int flsl(long) __hwloc_attribute_const; +# endif + +# define hwloc_flsl(x) flsl(x) + +#elif defined(HWLOC_HAVE_CLZL) + +# ifndef HWLOC_HAVE_DECL_CLZL +extern int clzl(long) __hwloc_attribute_const; +# endif + +# define hwloc_flsl(x) ((x) ? (8*sizeof(long) - clzl(x)) : 0) + +#elif defined(HWLOC_HAVE_FLS) + +# ifndef HWLOC_HAVE_DECL_FLS +extern int fls(int) __hwloc_attribute_const; +# endif + +# define hwloc_fls(x) fls(x) +# define HWLOC_NEED_FLSL + +#elif defined(HWLOC_HAVE_CLZ) + +# ifndef HWLOC_HAVE_DECL_CLZ +extern int clz(int) __hwloc_attribute_const; +# endif + +# define hwloc_fls(x) ((x) ? (8*sizeof(int) - clz(x)) : 0) +# define HWLOC_NEED_FLSL + +#else /* no fls implementation */ + +static __hwloc_inline int +hwloc_flsl_manual(unsigned long x) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_flsl_manual(unsigned long x) +{ + int i = 0; + + if (!x) + return 0; + + i = 1; +#if HWLOC_BITS_PER_LONG >= 64 + if ((x & 0xffffffff00000000ul)) { + x >>= 32; + i += 32; + } +#endif + if ((x & 0xffff0000u)) { + x >>= 16; + i += 16; + } + if ((x & 0xff00)) { + x >>= 8; + i += 8; + } + if ((x & 0xf0)) { + x >>= 4; + i += 4; + } + if ((x & 0xc)) { + x >>= 2; + i += 2; + } + if ((x & 0x2)) { + x >>= 1; + i += 1; + } + + return i; +} +/* always define hwloc_flsl as a macro, to avoid renaming breakage */ +#define hwloc_flsl hwloc_flsl_manual + +#endif + +#ifdef HWLOC_NEED_FLSL + +/* We only have an int fls(int) implementation, build a long one. */ + +/* First make it 32 bits if it was only 16. */ +static __hwloc_inline int +hwloc_fls32(unsigned long x) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_fls32(unsigned long x) +{ +#if HWLOC_BITS_PER_INT == 16 + int low_fls, hi_fls; + + hi_fls = hwloc_fls(x >> 16); + if (hi_fls) + return hi_fls + 16; + + low_fls = hwloc_fls(x & 0xfffful); + if (low_fls) + return low_fls; + + return 0; +#else + return hwloc_fls(x); +#endif +} + +/* Then make it 64 bit if longs are. */ +static __hwloc_inline int +hwloc_flsl_from_fls32(unsigned long x) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_flsl_from_fls32(unsigned long x) +{ +#if HWLOC_BITS_PER_LONG == 64 + int low_fls, hi_fls; + + hi_fls = hwloc_fls32(x >> 32); + if (hi_fls) + return hi_fls + 32; + + low_fls = hwloc_fls32(x & 0xfffffffful); + if (low_fls) + return low_fls; + + return 0; +#else + return hwloc_fls32(x); +#endif +} +/* always define hwloc_flsl as a macro, to avoid renaming breakage */ +#define hwloc_flsl hwloc_flsl_from_fls32 + +#endif + +static __hwloc_inline int +hwloc_weight_long(unsigned long w) __hwloc_attribute_const; +static __hwloc_inline int +hwloc_weight_long(unsigned long w) +{ +#if HWLOC_BITS_PER_LONG == 32 +#if (__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__) >= 4) + return __builtin_popcount(w); +#else + unsigned int res = (w & 0x55555555) + ((w >> 1) & 0x55555555); + res = (res & 0x33333333) + ((res >> 2) & 0x33333333); + res = (res & 0x0F0F0F0F) + ((res >> 4) & 0x0F0F0F0F); + res = (res & 0x00FF00FF) + ((res >> 8) & 0x00FF00FF); + return (res & 0x0000FFFF) + ((res >> 16) & 0x0000FFFF); +#endif +#else /* HWLOC_BITS_PER_LONG == 32 */ +#if (__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__) >= 4) + return __builtin_popcountll(w); +#else + unsigned long res; + res = (w & 0x5555555555555555ul) + ((w >> 1) & 0x5555555555555555ul); + res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul); + res = (res & 0x0F0F0F0F0F0F0F0Ful) + ((res >> 4) & 0x0F0F0F0F0F0F0F0Ful); + res = (res & 0x00FF00FF00FF00FFul) + ((res >> 8) & 0x00FF00FF00FF00FFul); + res = (res & 0x0000FFFF0000FFFFul) + ((res >> 16) & 0x0000FFFF0000FFFFul); + return (res & 0x00000000FFFFFFFFul) + ((res >> 32) & 0x00000000FFFFFFFFul); +#endif +#endif /* HWLOC_BITS_PER_LONG == 64 */ +} + +#if !HAVE_DECL_STRTOULL && defined(HAVE_STRTOULL) +unsigned long long int strtoull(const char *nptr, char **endptr, int base); +#endif + +static __hwloc_inline int hwloc_strncasecmp(const char *s1, const char *s2, size_t n) +{ +#ifdef HWLOC_HAVE_DECL_STRNCASECMP + return strncasecmp(s1, s2, n); +#else + while (n) { + char c1 = tolower(*s1), c2 = tolower(*s2); + if (!c1 || !c2 || c1 != c2) + return c1-c2; + n--; s1++; s2++; + } + return 0; +#endif +} + +static __hwloc_inline hwloc_obj_type_t hwloc_cache_type_by_depth_type(unsigned depth, hwloc_obj_cache_type_t type) +{ + if (type == HWLOC_OBJ_CACHE_INSTRUCTION) { + if (depth >= 1 && depth <= 3) + return HWLOC_OBJ_L1ICACHE + depth-1; + else + return HWLOC_OBJ_TYPE_NONE; + } else { + if (depth >= 1 && depth <= 5) + return HWLOC_OBJ_L1CACHE + depth-1; + else + return HWLOC_OBJ_TYPE_NONE; + } +} + +#define HWLOC_BITMAP_EQUAL 0 /* Bitmaps are equal */ +#define HWLOC_BITMAP_INCLUDED 1 /* First bitmap included in second */ +#define HWLOC_BITMAP_CONTAINS 2 /* First bitmap contains second */ +#define HWLOC_BITMAP_INTERSECTS 3 /* Bitmaps intersect without any inclusion */ +#define HWLOC_BITMAP_DIFFERENT 4 /* Bitmaps do not intersect */ + +/* Compare bitmaps \p bitmap1 and \p bitmap2 from an inclusion point of view. */ +HWLOC_DECLSPEC int hwloc_bitmap_compare_inclusion(hwloc_const_bitmap_t bitmap1, hwloc_const_bitmap_t bitmap2) __hwloc_attribute_pure; + +/* Return a stringified PCI class. */ +HWLOC_DECLSPEC extern const char * hwloc_pci_class_string(unsigned short class_id); + +/* Parse a PCI link speed (GT/s) string from Linux sysfs */ +#ifdef HWLOC_LINUX_SYS +#include /* for atof() */ +static __hwloc_inline float +hwloc_linux_pci_link_speed_from_string(const char *string) +{ + /* don't parse Gen1 with atof() since it expects a localized string + * while the kernel sysfs files aren't. + */ + if (!strncmp(string, "2.5 ", 4)) + /* "2.5 GT/s" is Gen1 with 8/10 encoding */ + return 2.5 * .8; + + /* also hardwire Gen2 since it also has a specific encoding */ + if (!strncmp(string, "5 ", 2)) + /* "5 GT/s" is Gen2 with 8/10 encoding */ + return 5 * .8; + + /* handle Gen3+ in a generic way */ + return atof(string) * 128./130; /* Gen3+ encoding is 128/130 */ +} +#endif + +/* Traverse children of a parent */ +#define for_each_child(child, parent) for(child = parent->first_child; child; child = child->next_sibling) +#define for_each_memory_child(child, parent) for(child = parent->memory_first_child; child; child = child->next_sibling) +#define for_each_io_child(child, parent) for(child = parent->io_first_child; child; child = child->next_sibling) +#define for_each_misc_child(child, parent) for(child = parent->misc_first_child; child; child = child->next_sibling) + +/* Any object attached to normal children */ +static __hwloc_inline int hwloc__obj_type_is_normal (hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return type <= HWLOC_OBJ_GROUP || type == HWLOC_OBJ_DIE; +} + +/* Any object attached to memory children, currently NUMA nodes or Memory-side caches */ +static __hwloc_inline int hwloc__obj_type_is_memory (hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return type == HWLOC_OBJ_NUMANODE || type == HWLOC_OBJ_MEMCACHE; +} + +/* I/O or Misc object, without cpusets or nodesets. */ +static __hwloc_inline int hwloc__obj_type_is_special (hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return type >= HWLOC_OBJ_BRIDGE && type <= HWLOC_OBJ_MISC; +} + +/* Any object attached to io children */ +static __hwloc_inline int hwloc__obj_type_is_io (hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return type >= HWLOC_OBJ_BRIDGE && type <= HWLOC_OBJ_OS_DEVICE; +} + +/* Any CPU caches (not Memory-side caches) */ +static __hwloc_inline int +hwloc__obj_type_is_cache(hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return (type >= HWLOC_OBJ_L1CACHE && type <= HWLOC_OBJ_L3ICACHE); +} + +static __hwloc_inline int +hwloc__obj_type_is_dcache(hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return (type >= HWLOC_OBJ_L1CACHE && type <= HWLOC_OBJ_L5CACHE); +} + +/** \brief Check whether an object is a Instruction Cache. */ +static __hwloc_inline int +hwloc__obj_type_is_icache(hwloc_obj_type_t type) +{ + /* type contiguity is asserted in topology_check() */ + return (type >= HWLOC_OBJ_L1ICACHE && type <= HWLOC_OBJ_L3ICACHE); +} + +#ifdef HAVE_USELOCALE +#include "locale.h" +#ifdef HAVE_XLOCALE_H +#include "xlocale.h" +#endif +#define hwloc_localeswitch_declare locale_t __old_locale = (locale_t)0, __new_locale +#define hwloc_localeswitch_init() do { \ + __new_locale = newlocale(LC_ALL_MASK, "C", (locale_t)0); \ + if (__new_locale != (locale_t)0) \ + __old_locale = uselocale(__new_locale); \ +} while (0) +#define hwloc_localeswitch_fini() do { \ + if (__new_locale != (locale_t)0) { \ + uselocale(__old_locale); \ + freelocale(__new_locale); \ + } \ +} while(0) +#else /* HAVE_USELOCALE */ +#if HWLOC_HAVE_ATTRIBUTE_UNUSED +#define hwloc_localeswitch_declare int __dummy_nolocale __hwloc_attribute_unused +#define hwloc_localeswitch_init() +#else +#define hwloc_localeswitch_declare int __dummy_nolocale +#define hwloc_localeswitch_init() (void)__dummy_nolocale +#endif +#define hwloc_localeswitch_fini() +#endif /* HAVE_USELOCALE */ + +#if !HAVE_DECL_FABSF +#define fabsf(f) fabs((double)(f)) +#endif + +#if !HAVE_DECL_MODFF +#define modff(x,iptr) (float)modf((double)x,(double *)iptr) +#endif + +#if HAVE_DECL__SC_PAGE_SIZE +#define hwloc_getpagesize() sysconf(_SC_PAGE_SIZE) +#elif HAVE_DECL__SC_PAGESIZE +#define hwloc_getpagesize() sysconf(_SC_PAGESIZE) +#elif defined HAVE_GETPAGESIZE +#define hwloc_getpagesize() getpagesize() +#else +#undef hwloc_getpagesize +#endif + +#if HWLOC_HAVE_ATTRIBUTE_FORMAT +# define __hwloc_attribute_format(type, str, arg) __attribute__((__format__(type, str, arg))) +#else +# define __hwloc_attribute_format(type, str, arg) +#endif + +#define hwloc_memory_size_printf_value(_size, _verbose) \ + ((_size) < (10ULL<<20) || (_verbose) ? (((_size)>>9)+1)>>1 : (_size) < (10ULL<<30) ? (((_size)>>19)+1)>>1 : (_size) < (10ULL<<40) ? (((_size)>>29)+1)>>1 : (((_size)>>39)+1)>>1) +#define hwloc_memory_size_printf_unit(_size, _verbose) \ + ((_size) < (10ULL<<20) || (_verbose) ? "KB" : (_size) < (10ULL<<30) ? "MB" : (_size) < (10ULL<<40) ? "GB" : "TB") + +#ifdef HWLOC_WIN_SYS +# ifndef HAVE_SSIZE_T +typedef SSIZE_T ssize_t; +# endif +# if !HAVE_DECL_STRTOULL && !defined(HAVE_STRTOULL) +# define strtoull _strtoui64 +# endif +# ifndef S_ISREG +# define S_ISREG(m) ((m) & S_IFREG) +# endif +# ifndef S_ISDIR +# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +# endif +# ifndef S_IRWXU +# define S_IRWXU 00700 +# endif +# ifndef HWLOC_HAVE_DECL_STRCASECMP +# define strcasecmp _stricmp +# endif +# if !HAVE_DECL_SNPRINTF +# define snprintf _snprintf +# endif +# if HAVE_DECL__STRDUP +# define strdup _strdup +# endif +# if HAVE_DECL__PUTENV +# define putenv _putenv +# endif +#endif + +#endif /* HWLOC_PRIVATE_MISC_H */ diff --git a/deps/exla/cache/xla_extension/include/include/private/private.h b/deps/exla/cache/xla_extension/include/include/private/private.h new file mode 100644 index 0000000000000000000000000000000000000000..131b079650fd62630afc3b5b1e0a134360ab14da --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/private.h @@ -0,0 +1,535 @@ +/* + * Copyright © 2009 CNRS + * Copyright © 2009-2021 Inria. All rights reserved. + * Copyright © 2009-2012, 2020 Université Bordeaux + * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. + * + * See COPYING in top-level directory. + */ + +/* Internal types and helpers. */ + + +#ifdef HWLOC_INSIDE_PLUGIN +/* + * these declarations are internal only, they are not available to plugins + * (many functions below are internal static symbols). + */ +#error This file should not be used in plugins +#endif + + +#ifndef HWLOC_PRIVATE_H +#define HWLOC_PRIVATE_H + +#include "private/autogen/config.h" +#include "hwloc.h" +#include "hwloc/bitmap.h" +#include "private/components.h" +#include "private/misc.h" + +#include +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_STDINT_H +#include +#endif +#ifdef HAVE_SYS_UTSNAME_H +#include +#endif +#include + +#define HWLOC_TOPOLOGY_ABI 0x20400 /* version of the layout of struct topology */ + +struct hwloc_internal_location_s { + enum hwloc_location_type_e type; + union { + struct { + hwloc_obj_t obj; /* cached between refreshes */ + uint64_t gp_index; + hwloc_obj_type_t type; + } object; /* if type == HWLOC_LOCATION_TYPE_OBJECT */ + hwloc_cpuset_t cpuset; /* if type == HWLOC_LOCATION_TYPE_CPUSET */ + } location; +}; + +/***************************************************** + * WARNING: + * changes below in this structure (and its children) + * should cause a bump of HWLOC_TOPOLOGY_ABI. + *****************************************************/ + +struct hwloc_topology { + unsigned topology_abi; + + unsigned nb_levels; /* Number of horizontal levels */ + unsigned nb_levels_allocated; /* Number of levels allocated and zeroed in level_nbobjects and levels below */ + unsigned *level_nbobjects; /* Number of objects on each horizontal level */ + struct hwloc_obj ***levels; /* Direct access to levels, levels[l = 0 .. nblevels-1][0..level_nbobjects[l]] */ + unsigned long flags; + int type_depth[HWLOC_OBJ_TYPE_MAX]; + enum hwloc_type_filter_e type_filter[HWLOC_OBJ_TYPE_MAX]; + int is_thissystem; + int is_loaded; + int modified; /* >0 if objects were added/removed recently, which means a reconnect is needed */ + hwloc_pid_t pid; /* Process ID the topology is view from, 0 for self */ + void *userdata; + uint64_t next_gp_index; + + void *adopted_shmem_addr; + size_t adopted_shmem_length; + +#define HWLOC_NR_SLEVELS 6 +#define HWLOC_SLEVEL_NUMANODE 0 +#define HWLOC_SLEVEL_BRIDGE 1 +#define HWLOC_SLEVEL_PCIDEV 2 +#define HWLOC_SLEVEL_OSDEV 3 +#define HWLOC_SLEVEL_MISC 4 +#define HWLOC_SLEVEL_MEMCACHE 5 + /* order must match negative depth, it's asserted in setup_defaults() */ +#define HWLOC_SLEVEL_FROM_DEPTH(x) (HWLOC_TYPE_DEPTH_NUMANODE-(x)) +#define HWLOC_SLEVEL_TO_DEPTH(x) (HWLOC_TYPE_DEPTH_NUMANODE-(x)) + struct hwloc_special_level_s { + unsigned nbobjs; + struct hwloc_obj **objs; + struct hwloc_obj *first, *last; /* Temporarily used while listing object before building the objs array */ + } slevels[HWLOC_NR_SLEVELS]; + + hwloc_bitmap_t allowed_cpuset; + hwloc_bitmap_t allowed_nodeset; + + struct hwloc_binding_hooks { + /* These are actually rather OS hooks since some of them are not about binding */ + int (*set_thisproc_cpubind)(hwloc_topology_t topology, hwloc_const_cpuset_t set, int flags); + int (*get_thisproc_cpubind)(hwloc_topology_t topology, hwloc_cpuset_t set, int flags); + int (*set_thisthread_cpubind)(hwloc_topology_t topology, hwloc_const_cpuset_t set, int flags); + int (*get_thisthread_cpubind)(hwloc_topology_t topology, hwloc_cpuset_t set, int flags); + int (*set_proc_cpubind)(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_const_cpuset_t set, int flags); + int (*get_proc_cpubind)(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_cpuset_t set, int flags); +#ifdef hwloc_thread_t + int (*set_thread_cpubind)(hwloc_topology_t topology, hwloc_thread_t tid, hwloc_const_cpuset_t set, int flags); + int (*get_thread_cpubind)(hwloc_topology_t topology, hwloc_thread_t tid, hwloc_cpuset_t set, int flags); +#endif + + int (*get_thisproc_last_cpu_location)(hwloc_topology_t topology, hwloc_cpuset_t set, int flags); + int (*get_thisthread_last_cpu_location)(hwloc_topology_t topology, hwloc_cpuset_t set, int flags); + int (*get_proc_last_cpu_location)(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_cpuset_t set, int flags); + + int (*set_thisproc_membind)(hwloc_topology_t topology, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags); + int (*get_thisproc_membind)(hwloc_topology_t topology, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags); + int (*set_thisthread_membind)(hwloc_topology_t topology, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags); + int (*get_thisthread_membind)(hwloc_topology_t topology, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags); + int (*set_proc_membind)(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags); + int (*get_proc_membind)(hwloc_topology_t topology, hwloc_pid_t pid, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags); + int (*set_area_membind)(hwloc_topology_t topology, const void *addr, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags); + int (*get_area_membind)(hwloc_topology_t topology, const void *addr, size_t len, hwloc_nodeset_t nodeset, hwloc_membind_policy_t * policy, int flags); + int (*get_area_memlocation)(hwloc_topology_t topology, const void *addr, size_t len, hwloc_nodeset_t nodeset, int flags); + /* This has to return the same kind of pointer as alloc_membind, so that free_membind can be used on it */ + void *(*alloc)(hwloc_topology_t topology, size_t len); + /* alloc_membind has to always succeed if !(flags & HWLOC_MEMBIND_STRICT). + * see hwloc_alloc_or_fail which is convenient for that. */ + void *(*alloc_membind)(hwloc_topology_t topology, size_t len, hwloc_const_nodeset_t nodeset, hwloc_membind_policy_t policy, int flags); + int (*free_membind)(hwloc_topology_t topology, void *addr, size_t len); + + int (*get_allowed_resources)(hwloc_topology_t topology); + } binding_hooks; + + struct hwloc_topology_support support; + + void (*userdata_export_cb)(void *reserved, struct hwloc_topology *topology, struct hwloc_obj *obj); + void (*userdata_import_cb)(struct hwloc_topology *topology, struct hwloc_obj *obj, const char *name, const void *buffer, size_t length); + int userdata_not_decoded; + + struct hwloc_internal_distances_s { + char *name; /* FIXME: needs an API to set it from user */ + + unsigned id; /* to match the container id field of public distances structure + * not exported to XML, regenerated during _add() + */ + + /* if all objects have the same type, different_types is NULL and unique_type is valid. + * otherwise unique_type is HWLOC_OBJ_TYPE_NONE and different_types contains individual objects types. + */ + hwloc_obj_type_t unique_type; + hwloc_obj_type_t *different_types; + + /* add union hwloc_obj_attr_u if we ever support groups */ + unsigned nbobjs; + uint64_t *indexes; /* array of OS or GP indexes before we can convert them into objs. + * OS indexes for distances covering only PUs or only NUMAnodes. + */ +#define HWLOC_DIST_TYPE_USE_OS_INDEX(_type) ((_type) == HWLOC_OBJ_PU || (_type == HWLOC_OBJ_NUMANODE)) + uint64_t *values; /* distance matrices, ordered according to the above indexes/objs array. + * distance from i to j is stored in slot i*nbnodes+j. + */ + unsigned long kind; + +#define HWLOC_INTERNAL_DIST_FLAG_OBJS_VALID (1U<<0) /* if the objs array is valid below */ +#define HWLOC_INTERNAL_DIST_FLAG_NOT_COMMITTED (1U<<1) /* if the distances isn't in the list yet */ + unsigned iflags; + + /* objects are currently stored in physical_index order */ + hwloc_obj_t *objs; /* array of objects */ + + struct hwloc_internal_distances_s *prev, *next; + } *first_dist, *last_dist; + unsigned next_dist_id; + + /* memory attributes */ + unsigned nr_memattrs; + struct hwloc_internal_memattr_s { + /* memattr info */ + char *name; /* TODO unit is implicit, in the documentation of standard attributes, or in the name? */ + unsigned long flags; +#define HWLOC_IMATTR_FLAG_STATIC_NAME (1U<<0) /* no need to free name */ +#define HWLOC_IMATTR_FLAG_CACHE_VALID (1U<<1) /* target and initiator are valid */ +#define HWLOC_IMATTR_FLAG_CONVENIENCE (1U<<2) /* convenience attribute reporting values from non-memattr attributes (R/O and no actual targets stored) */ + unsigned iflags; + + /* array of values */ + unsigned nr_targets; + struct hwloc_internal_memattr_target_s { + /* target object */ + hwloc_obj_t obj; /* cached between refreshes */ + hwloc_obj_type_t type; + unsigned os_index; /* only used temporarily during discovery when there's no obj/gp_index yet */ + hwloc_uint64_t gp_index; + + /* value if there are no initiator for this attr */ + hwloc_uint64_t noinitiator_value; + /* initiators otherwise */ + unsigned nr_initiators; + struct hwloc_internal_memattr_initiator_s { + struct hwloc_internal_location_s initiator; + hwloc_uint64_t value; + } *initiators; + } *targets; + } *memattrs; + + /* hybridcpus */ + unsigned nr_cpukinds; + unsigned nr_cpukinds_allocated; + struct hwloc_internal_cpukind_s { + hwloc_cpuset_t cpuset; +#define HWLOC_CPUKIND_EFFICIENCY_UNKNOWN -1 + int efficiency; + int forced_efficiency; /* returned by the hardware or OS if any */ + hwloc_uint64_t ranking_value; /* internal value for ranking */ + unsigned nr_infos; + struct hwloc_info_s *infos; + } *cpukinds; + + int grouping; + int grouping_verbose; + unsigned grouping_nbaccuracies; + float grouping_accuracies[5]; + unsigned grouping_next_subkind; + + /* list of enabled backends. */ + struct hwloc_backend * backends; + struct hwloc_backend * get_pci_busid_cpuset_backend; /* first backend that provides get_pci_busid_cpuset() callback */ + unsigned backend_phases; + unsigned backend_excluded_phases; + + /* memory allocator for topology objects */ + struct hwloc_tma * tma; + +/***************************************************** + * WARNING: + * changes above in this structure (and its children) + * should cause a bump of HWLOC_TOPOLOGY_ABI. + *****************************************************/ + + /* + * temporary variables during discovery + */ + + /* machine-wide memory. + * temporarily stored there by OSes that only provide this without NUMA information, + * and actually used later by the core. + */ + struct hwloc_numanode_attr_s machine_memory; + + /* pci stuff */ + int pci_has_forced_locality; + unsigned pci_forced_locality_nr; + struct hwloc_pci_forced_locality_s { + unsigned domain; + unsigned bus_first, bus_last; + hwloc_bitmap_t cpuset; + } * pci_forced_locality; + + /* component blacklisting */ + unsigned nr_blacklisted_components; + struct hwloc_topology_forced_component_s { + struct hwloc_disc_component *component; + unsigned phases; + } *blacklisted_components; + + /* FIXME: keep until topo destroy and reuse for finding specific buses */ + struct hwloc_pci_locality_s { + unsigned domain; + unsigned bus_min; + unsigned bus_max; + hwloc_bitmap_t cpuset; + hwloc_obj_t parent; + struct hwloc_pci_locality_s *prev, *next; + } *first_pci_locality, *last_pci_locality; +}; + +extern void hwloc_alloc_root_sets(hwloc_obj_t root); +extern void hwloc_setup_pu_level(struct hwloc_topology *topology, unsigned nb_pus); +extern int hwloc_get_sysctlbyname(const char *name, int64_t *n); +extern int hwloc_get_sysctl(int name[], unsigned namelen, int64_t *n); + +/* returns the number of CPU from the OS (only valid if thissystem) */ +#define HWLOC_FALLBACK_NBPROCESSORS_INCLUDE_OFFLINE 1 /* by default we try to get only the online CPUs */ +extern int hwloc_fallback_nbprocessors(unsigned flags); +/* returns the memory size from the OS (only valid if thissystem) */ +extern int64_t hwloc_fallback_memsize(void); + +extern int hwloc__object_cpusets_compare_first(hwloc_obj_t obj1, hwloc_obj_t obj2); +extern void hwloc__reorder_children(hwloc_obj_t parent); + +extern void hwloc_topology_setup_defaults(struct hwloc_topology *topology); +extern void hwloc_topology_clear(struct hwloc_topology *topology); + +/* insert memory object as memory child of normal parent */ +extern struct hwloc_obj * hwloc__attach_memory_object(struct hwloc_topology *topology, hwloc_obj_t parent, + hwloc_obj_t obj, const char *reason); + +extern hwloc_obj_t hwloc_get_obj_by_type_and_gp_index(hwloc_topology_t topology, hwloc_obj_type_t type, uint64_t gp_index); + +extern void hwloc_pci_discovery_init(struct hwloc_topology *topology); +extern void hwloc_pci_discovery_prepare(struct hwloc_topology *topology); +extern void hwloc_pci_discovery_exit(struct hwloc_topology *topology); + +/* Look for an object matching complete cpuset exactly, or insert one. + * Return NULL on failure. + * Return a good fallback (object above) on failure to insert. + */ +extern hwloc_obj_t hwloc_find_insert_io_parent_by_complete_cpuset(struct hwloc_topology *topology, hwloc_cpuset_t cpuset); + +extern int hwloc__add_info(struct hwloc_info_s **infosp, unsigned *countp, const char *name, const char *value); +extern int hwloc__add_info_nodup(struct hwloc_info_s **infosp, unsigned *countp, const char *name, const char *value, int replace); +extern int hwloc__move_infos(struct hwloc_info_s **dst_infosp, unsigned *dst_countp, struct hwloc_info_s **src_infosp, unsigned *src_countp); +extern int hwloc__tma_dup_infos(struct hwloc_tma *tma, struct hwloc_info_s **dst_infosp, unsigned *dst_countp, struct hwloc_info_s *src_infos, unsigned src_count); +extern void hwloc__free_infos(struct hwloc_info_s *infos, unsigned count); + +/* set native OS binding hooks */ +extern void hwloc_set_native_binding_hooks(struct hwloc_binding_hooks *hooks, struct hwloc_topology_support *support); +/* set either native OS binding hooks (if thissystem), or dummy ones */ +extern void hwloc_set_binding_hooks(struct hwloc_topology *topology); + +#if defined(HWLOC_LINUX_SYS) +extern void hwloc_set_linuxfs_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_LINUX_SYS */ + +#if defined(HWLOC_BGQ_SYS) +extern void hwloc_set_bgq_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_BGQ_SYS */ + +#ifdef HWLOC_SOLARIS_SYS +extern void hwloc_set_solaris_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_SOLARIS_SYS */ + +#ifdef HWLOC_AIX_SYS +extern void hwloc_set_aix_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_AIX_SYS */ + +#ifdef HWLOC_WIN_SYS +extern void hwloc_set_windows_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_WIN_SYS */ + +#ifdef HWLOC_DARWIN_SYS +extern void hwloc_set_darwin_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_DARWIN_SYS */ + +#ifdef HWLOC_FREEBSD_SYS +extern void hwloc_set_freebsd_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_FREEBSD_SYS */ + +#ifdef HWLOC_NETBSD_SYS +extern void hwloc_set_netbsd_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_NETBSD_SYS */ + +#ifdef HWLOC_HPUX_SYS +extern void hwloc_set_hpux_hooks(struct hwloc_binding_hooks *binding_hooks, struct hwloc_topology_support *support); +#endif /* HWLOC_HPUX_SYS */ + +extern int hwloc_look_hardwired_fujitsu_k(struct hwloc_topology *topology); +extern int hwloc_look_hardwired_fujitsu_fx10(struct hwloc_topology *topology); +extern int hwloc_look_hardwired_fujitsu_fx100(struct hwloc_topology *topology); + +/* Insert uname-specific names/values in the object infos array. + * If cached_uname isn't NULL, it is used as a struct utsname instead of recalling uname. + * Any field that starts with \0 is ignored. + */ +extern void hwloc_add_uname_info(struct hwloc_topology *topology, void *cached_uname); + +/* Free obj and its attributes assuming it's not linked to a parent and doesn't have any child */ +extern void hwloc_free_unlinked_object(hwloc_obj_t obj); + +/* Free obj and its children, assuming it's not linked to a parent */ +extern void hwloc_free_object_and_children(hwloc_obj_t obj); + +/* Free obj, its next siblings, and their children, assuming they're not linked to a parent */ +extern void hwloc_free_object_siblings_and_children(hwloc_obj_t obj); + +/* This can be used for the alloc field to get allocated data that can be freed by free() */ +void *hwloc_alloc_heap(hwloc_topology_t topology, size_t len); + +/* This can be used for the alloc field to get allocated data that can be freed by munmap() */ +void *hwloc_alloc_mmap(hwloc_topology_t topology, size_t len); + +/* This can be used for the free_membind field to free data using free() */ +int hwloc_free_heap(hwloc_topology_t topology, void *addr, size_t len); + +/* This can be used for the free_membind field to free data using munmap() */ +int hwloc_free_mmap(hwloc_topology_t topology, void *addr, size_t len); + +/* Allocates unbound memory or fail, depending on whether STRICT is requested + * or not */ +static __hwloc_inline void * +hwloc_alloc_or_fail(hwloc_topology_t topology, size_t len, int flags) +{ + if (flags & HWLOC_MEMBIND_STRICT) + return NULL; + return hwloc_alloc(topology, len); +} + +extern void hwloc_internal_distances_init(hwloc_topology_t topology); +extern void hwloc_internal_distances_prepare(hwloc_topology_t topology); +extern void hwloc_internal_distances_destroy(hwloc_topology_t topology); +extern int hwloc_internal_distances_dup(hwloc_topology_t new, hwloc_topology_t old); +extern void hwloc_internal_distances_refresh(hwloc_topology_t topology); +extern void hwloc_internal_distances_invalidate_cached_objs(hwloc_topology_t topology); + +/* these distances_add() functions are higher-level than those in hwloc/plugins.h + * but they may change in the future, hence they are not exported to plugins. + */ +extern int hwloc_internal_distances_add_by_index(hwloc_topology_t topology, const char *name, hwloc_obj_type_t unique_type, hwloc_obj_type_t *different_types, unsigned nbobjs, uint64_t *indexes, uint64_t *values, unsigned long kind, unsigned long flags); +extern int hwloc_internal_distances_add(hwloc_topology_t topology, const char *name, unsigned nbobjs, hwloc_obj_t *objs, uint64_t *values, unsigned long kind, unsigned long flags); + +extern void hwloc_internal_memattrs_init(hwloc_topology_t topology); +extern void hwloc_internal_memattrs_prepare(hwloc_topology_t topology); +extern void hwloc_internal_memattrs_destroy(hwloc_topology_t topology); +extern void hwloc_internal_memattrs_need_refresh(hwloc_topology_t topology); +extern void hwloc_internal_memattrs_refresh(hwloc_topology_t topology); +extern int hwloc_internal_memattrs_dup(hwloc_topology_t new, hwloc_topology_t old); +extern int hwloc_internal_memattr_set_value(hwloc_topology_t topology, hwloc_memattr_id_t id, hwloc_obj_type_t target_type, hwloc_uint64_t target_gp_index, unsigned target_os_index, struct hwloc_internal_location_s *initiator, hwloc_uint64_t value); + +extern void hwloc_internal_cpukinds_init(hwloc_topology_t topology); +extern int hwloc_internal_cpukinds_rank(hwloc_topology_t topology); +extern void hwloc_internal_cpukinds_destroy(hwloc_topology_t topology); +extern int hwloc_internal_cpukinds_dup(hwloc_topology_t new, hwloc_topology_t old); +#define HWLOC_CPUKINDS_REGISTER_FLAG_OVERWRITE_FORCED_EFFICIENCY (1<<0) +extern int hwloc_internal_cpukinds_register(hwloc_topology_t topology, hwloc_cpuset_t cpuset, int forced_efficiency, const struct hwloc_info_s *infos, unsigned nr_infos, unsigned long flags); +extern void hwloc_internal_cpukinds_restrict(hwloc_topology_t topology); + +/* encode src buffer into target buffer. + * targsize must be at least 4*((srclength+2)/3)+1. + * target will be 0-terminated. + */ +extern int hwloc_encode_to_base64(const char *src, size_t srclength, char *target, size_t targsize); +/* decode src buffer into target buffer. + * src is 0-terminated. + * targsize must be at least srclength*3/4+1 (srclength not including \0) + * but only srclength*3/4 characters will be meaningful + * (the next one may be partially written during decoding, but it should be ignored). + */ +extern int hwloc_decode_from_base64(char const *src, char *target, size_t targsize); + +/* On some systems, snprintf returns the size of written data, not the actually + * required size. Sometimes it returns -1 on truncation too. + * And sometimes it doesn't like NULL output buffers. + * http://www.gnu.org/software/gnulib/manual/html_node/snprintf.html + * + * hwloc_snprintf behaves properly, but it's a bit overkill on the vast majority + * of platforms, so don't enable it unless really needed. + */ +#ifdef HWLOC_HAVE_CORRECT_SNPRINTF +#define hwloc_snprintf snprintf +#else +extern int hwloc_snprintf(char *str, size_t size, const char *format, ...) __hwloc_attribute_format(printf, 3, 4); +#endif + +/* Return the name of the currently running program, if supported. + * If not NULL, must be freed by the caller. + */ +extern char * hwloc_progname(struct hwloc_topology *topology); + +/* obj->attr->group.kind internal values. + * the core will keep the smallest ones when merging two groups, + * that's why user-given kinds are first. + */ +/* first, user-given groups, should remain as long as possible */ +#define HWLOC_GROUP_KIND_USER 0 /* user-given, user may use subkind too */ +#define HWLOC_GROUP_KIND_SYNTHETIC 10 /* subkind is group depth within synthetic description */ +/* then, hardware-specific groups */ +#define HWLOC_GROUP_KIND_INTEL_KNL_SUBNUMA_CLUSTER 100 /* no subkind */ +#define HWLOC_GROUP_KIND_INTEL_EXTTOPOENUM_UNKNOWN 101 /* subkind is unknown level */ +#define HWLOC_GROUP_KIND_INTEL_MODULE 102 /* no subkind */ +#define HWLOC_GROUP_KIND_INTEL_TILE 103 /* no subkind */ +#define HWLOC_GROUP_KIND_INTEL_DIE 104 /* no subkind */ +#define HWLOC_GROUP_KIND_S390_BOOK 110 /* subkind 0 is book, subkind 1 is drawer (group of books) */ +#define HWLOC_GROUP_KIND_AMD_COMPUTE_UNIT 120 /* no subkind */ +/* then, OS-specific groups */ +#define HWLOC_GROUP_KIND_SOLARIS_PG_HW_PERF 200 /* subkind is group width */ +#define HWLOC_GROUP_KIND_AIX_SDL_UNKNOWN 210 /* subkind is SDL level */ +#define HWLOC_GROUP_KIND_WINDOWS_PROCESSOR_GROUP 220 /* no subkind */ +#define HWLOC_GROUP_KIND_WINDOWS_RELATIONSHIP_UNKNOWN 221 /* no subkind */ +#define HWLOC_GROUP_KIND_LINUX_CLUSTER 222 /* no subkind */ +/* distance groups */ +#define HWLOC_GROUP_KIND_DISTANCE 900 /* subkind is round of adding these groups during distance based grouping */ +/* finally, hwloc-specific groups required to insert something else, should disappear as soon as possible */ +#define HWLOC_GROUP_KIND_IO 1000 /* no subkind */ +#define HWLOC_GROUP_KIND_MEMORY 1001 /* no subkind */ + +/* memory allocator for topology objects */ +struct hwloc_tma { + void * (*malloc)(struct hwloc_tma *, size_t); + void *data; + int dontfree; /* when set, free() or realloc() cannot be used, and tma->malloc() cannot fail */ +}; + +static __hwloc_inline void * +hwloc_tma_malloc(struct hwloc_tma *tma, + size_t size) +{ + if (tma) { + return tma->malloc(tma, size); + } else { + return malloc(size); + } +} + +static __hwloc_inline void * +hwloc_tma_calloc(struct hwloc_tma *tma, + size_t size) +{ + char *ptr = hwloc_tma_malloc(tma, size); + if (ptr) + memset(ptr, 0, size); + return ptr; +} + +static __hwloc_inline char * +hwloc_tma_strdup(struct hwloc_tma *tma, + const char *src) +{ + size_t len = strlen(src); + char *ptr = hwloc_tma_malloc(tma, len+1); + if (ptr) + memcpy(ptr, src, len+1); + return ptr; +} + +/* bitmap allocator to be used inside hwloc */ +extern hwloc_bitmap_t hwloc_bitmap_tma_dup(struct hwloc_tma *tma, hwloc_const_bitmap_t old); + +extern int hwloc__topology_dup(hwloc_topology_t *newp, hwloc_topology_t old, struct hwloc_tma *tma); +extern void hwloc__topology_disadopt(hwloc_topology_t topology); + +#endif /* HWLOC_PRIVATE_H */ diff --git a/deps/exla/cache/xla_extension/include/include/private/xml.h b/deps/exla/cache/xla_extension/include/include/private/xml.h new file mode 100644 index 0000000000000000000000000000000000000000..3af5ba1e535d37b17ec4015b50cbe9bc77d3a821 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/private/xml.h @@ -0,0 +1,107 @@ +/* + * Copyright © 2009-2017 Inria. All rights reserved. + * See COPYING in top-level directory. + */ + +#ifndef PRIVATE_XML_H +#define PRIVATE_XML_H 1 + +#include "hwloc.h" + +#include + +HWLOC_DECLSPEC int hwloc__xml_verbose(void); + +/************** + * XML import * + **************/ + +typedef struct hwloc__xml_import_state_s { + struct hwloc__xml_import_state_s *parent; + + /* globals shared because the entire stack of states during import */ + struct hwloc_xml_backend_data_s *global; + + /* opaque data used to store backend-specific data. + * statically allocated to allow stack-allocation by the common code without knowing actual backend needs. + */ + char data[32]; +} * hwloc__xml_import_state_t; + +struct hwloc__xml_imported_v1distances_s { + unsigned long kind; + unsigned nbobjs; + float *floats; + struct hwloc__xml_imported_v1distances_s *prev, *next; +}; + +HWLOC_DECLSPEC int hwloc__xml_import_diff(hwloc__xml_import_state_t state, hwloc_topology_diff_t *firstdiffp); + +struct hwloc_xml_backend_data_s { + /* xml backend parameters */ + int (*look_init)(struct hwloc_xml_backend_data_s *bdata, struct hwloc__xml_import_state_s *state); + void (*look_done)(struct hwloc_xml_backend_data_s *bdata, int result); + void (*backend_exit)(struct hwloc_xml_backend_data_s *bdata); + int (*next_attr)(struct hwloc__xml_import_state_s * state, char **namep, char **valuep); + int (*find_child)(struct hwloc__xml_import_state_s * state, struct hwloc__xml_import_state_s * childstate, char **tagp); + int (*close_tag)(struct hwloc__xml_import_state_s * state); /* look for an explicit closing tag */ + void (*close_child)(struct hwloc__xml_import_state_s * state); + int (*get_content)(struct hwloc__xml_import_state_s * state, const char **beginp, size_t expected_length); /* return 0 on empty content (and sets beginp to empty string), 1 on actual content, -1 on error or unexpected content length */ + void (*close_content)(struct hwloc__xml_import_state_s * state); + char * msgprefix; + void *data; /* libxml2 doc, or nolibxml buffer */ + unsigned version_major, version_minor; + unsigned nbnumanodes; + hwloc_obj_t first_numanode, last_numanode; /* temporary cousin-list for handling v1distances */ + struct hwloc__xml_imported_v1distances_s *first_v1dist, *last_v1dist; +}; + +/************** + * XML export * + **************/ + +typedef struct hwloc__xml_export_state_s { + struct hwloc__xml_export_state_s *parent; + + void (*new_child)(struct hwloc__xml_export_state_s *parentstate, struct hwloc__xml_export_state_s *state, const char *name); + void (*new_prop)(struct hwloc__xml_export_state_s *state, const char *name, const char *value); + void (*add_content)(struct hwloc__xml_export_state_s *state, const char *buffer, size_t length); + void (*end_object)(struct hwloc__xml_export_state_s *state, const char *name); + + struct hwloc__xml_export_data_s { + hwloc_obj_t v1_memory_group; /* if we need to insert intermediate group above memory children when exporting to v1 */ + } *global; + + /* opaque data used to store backend-specific data. + * statically allocated to allow stack-allocation by the common code without knowing actual backend needs. + */ + char data[40]; +} * hwloc__xml_export_state_t; + +HWLOC_DECLSPEC void hwloc__xml_export_topology(hwloc__xml_export_state_t parentstate, hwloc_topology_t topology, unsigned long flags); + +HWLOC_DECLSPEC void hwloc__xml_export_diff(hwloc__xml_export_state_t parentstate, hwloc_topology_diff_t diff); + +/****************** + * XML components * + ******************/ + +struct hwloc_xml_callbacks { + int (*backend_init)(struct hwloc_xml_backend_data_s *bdata, const char *xmlpath, const char *xmlbuffer, int xmlbuflen); + int (*export_file)(struct hwloc_topology *topology, struct hwloc__xml_export_data_s *edata, const char *filename, unsigned long flags); + int (*export_buffer)(struct hwloc_topology *topology, struct hwloc__xml_export_data_s *edata, char **xmlbuffer, int *buflen, unsigned long flags); + void (*free_buffer)(void *xmlbuffer); + int (*import_diff)(struct hwloc__xml_import_state_s *state, const char *xmlpath, const char *xmlbuffer, int xmlbuflen, hwloc_topology_diff_t *diff, char **refnamep); + int (*export_diff_file)(union hwloc_topology_diff_u *diff, const char *refname, const char *filename); + int (*export_diff_buffer)(union hwloc_topology_diff_u *diff, const char *refname, char **xmlbuffer, int *buflen); +}; + +struct hwloc_xml_component { + struct hwloc_xml_callbacks *nolibxml_callbacks; + struct hwloc_xml_callbacks *libxml_callbacks; +}; + +HWLOC_DECLSPEC void hwloc_xml_callbacks_register(struct hwloc_xml_component *component); +HWLOC_DECLSPEC void hwloc_xml_callbacks_reset(void); + +#endif /* PRIVATE_XML_H */ diff --git a/deps/exla/cache/xla_extension/include/include/pthreadpool.h b/deps/exla/cache/xla_extension/include/include/pthreadpool.h new file mode 100644 index 0000000000000000000000000000000000000000..9ec49d6b11080a821872f1343b210d98fe6c6fd0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/pthreadpool.h @@ -0,0 +1,3290 @@ +// Copyright (c) 2017 Facebook Inc. +// Copyright (c) 2015-2017 Georgia Institute of Technology +// All rights reserved. +// +// Copyright 2019 Google LLC +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#ifndef __PTHREADPOOL_INCLUDE_PTHREADPOOL_H_ +#define __PTHREADPOOL_INCLUDE_PTHREADPOOL_H_ + +#include +#include + +typedef struct pthreadpool* pthreadpool_t; + +typedef void (*pthreadpool_task_1d_t)(void*, size_t); +typedef void (*pthreadpool_task_1d_with_thread_t)(void*, size_t, size_t); +typedef void (*pthreadpool_task_1d_tile_1d_t)(void*, size_t, size_t); +typedef void (*pthreadpool_task_1d_tile_1d_dynamic_t)(void*, size_t, size_t); +typedef void (*pthreadpool_task_1d_tile_1d_dynamic_with_id_t)(void*, uint32_t, + size_t, size_t); +typedef void (*pthreadpool_task_2d_t)(void*, size_t, size_t); +typedef void (*pthreadpool_task_2d_with_thread_t)(void*, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_2d_tile_1d_t)(void*, size_t, size_t, size_t); +typedef void (*pthreadpool_task_2d_tile_1d_dynamic_t)(void*, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_2d_tile_2d_t)(void*, size_t, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_2d_tile_2d_dynamic_t)(void*, size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_3d_t)(void*, size_t, size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_1d_t)(void*, size_t, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_3d_tile_1d_with_thread_t)(void*, size_t, size_t, + size_t, size_t, + size_t); +typedef void (*pthreadpool_task_3d_tile_1d_dynamic_t)(void*, size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_2d_t)(void*, size_t, size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_2d_dynamic_t)(void*, size_t, size_t, + size_t, size_t, size_t); +typedef void (*pthreadpool_task_4d_t)(void*, size_t, size_t, size_t, size_t); +typedef void (*pthreadpool_task_4d_tile_1d_t)(void*, size_t, size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_4d_tile_2d_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t); +typedef void (*pthreadpool_task_4d_tile_2d_dynamic_t)(void*, size_t, size_t, + size_t, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_5d_t)(void*, size_t, size_t, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_5d_tile_1d_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t); +typedef void (*pthreadpool_task_5d_tile_2d_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t, size_t); +typedef void (*pthreadpool_task_6d_t)(void*, size_t, size_t, size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_6d_tile_1d_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t, size_t); +typedef void (*pthreadpool_task_6d_tile_2d_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t, size_t, + size_t); + +typedef void (*pthreadpool_task_1d_with_id_t)(void*, uint32_t, size_t); +typedef void (*pthreadpool_task_2d_tile_1d_with_id_t)(void*, uint32_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_2d_tile_1d_dynamic_with_id_t)(void*, uint32_t, + size_t, size_t, + size_t); +typedef void (*pthreadpool_task_2d_tile_2d_with_id_t)(void*, uint32_t, size_t, + size_t, size_t, size_t); +typedef void (*pthreadpool_task_2d_tile_2d_dynamic_with_id_t)(void*, uint32_t, + size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_1d_with_id_t)(void*, uint32_t, size_t, + size_t, size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_1d_dynamic_with_id_t)(void*, uint32_t, + size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_2d_with_id_t)(void*, uint32_t, size_t, + size_t, size_t, size_t, + size_t); +typedef void (*pthreadpool_task_3d_tile_2d_dynamic_with_id_t)(void*, uint32_t, + size_t, size_t, + size_t, size_t, + size_t); +typedef void (*pthreadpool_task_4d_tile_2d_with_id_t)(void*, uint32_t, size_t, + size_t, size_t, size_t, + size_t, size_t); +typedef void (*pthreadpool_task_4d_tile_2d_dynamic_with_id_t)(void*, uint32_t, + size_t, size_t, + size_t, size_t, + size_t, size_t); + +typedef void (*pthreadpool_task_1d_tile_1d_dynamic_with_id_with_thread_t)( + void*, uint32_t, size_t, size_t, size_t); +typedef void (*pthreadpool_task_2d_tile_1d_with_id_with_thread_t)( + void*, uint32_t, size_t, size_t, size_t, size_t); +typedef void (*pthreadpool_task_2d_tile_1d_dynamic_with_id_with_thread_t)( + void*, uint32_t, size_t, size_t, size_t, size_t); +typedef void (*pthreadpool_task_3d_tile_1d_with_id_with_thread_t)( + void*, uint32_t, size_t, size_t, size_t, size_t, size_t); + +/** + * Disable support for denormalized numbers to the maximum extent possible for + * the duration of the computation. + * + * Handling denormalized floating-point numbers is often implemented in + * microcode, and incurs significant performance degradation. This hint + * instructs the thread pool to disable support for denormalized numbers before + * running the computation by manipulating architecture-specific control + * registers, and restore the initial value of control registers after the + * computation is complete. The thread pool temporary disables denormalized + * numbers on all threads involved in the computation (i.e. the caller threads, + * and potentially worker threads). + * + * Disabling denormalized numbers may have a small negative effect on results' + * accuracy. As various architectures differ in capabilities to control + * processing of denormalized numbers, using this flag may also hurt results' + * reproducibility across different instruction set architectures. + */ +#define PTHREADPOOL_FLAG_DISABLE_DENORMALS 0x00000001 + +/** + * Yield worker threads to the system scheduler after the operation is finished. + * + * Force workers to use kernel wait (instead of active spin-wait by default) for + * new commands after this command is processed. This flag affects only the + * immediate next operation on this thread pool. To make the thread pool always + * use kernel wait, pass this flag to all parallelization functions. + */ +#define PTHREADPOOL_FLAG_YIELD_WORKERS 0x00000002 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Create a thread pool with the specified number of threads. + * + * @param threads_count the number of threads in the thread pool. + * A value of 0 has special interpretation: it creates a thread pool with as + * many threads as there are logical processors in the system. + * + * @returns A pointer to an opaque thread pool object if the call is + * successful, or NULL pointer if the call failed. + */ +pthreadpool_t pthreadpool_create(size_t threads_count); + +/** + * Query the number of threads in a thread pool. + * + * @param threadpool the thread pool to query. + * + * @returns The number of threads in the thread pool. + */ +size_t pthreadpool_get_threads_count(pthreadpool_t threadpool); + +/** + * Process items on a 1D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range; i++) + * function(context, i); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each item. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. The + * specified function will be called once for each item. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d(pthreadpool_t threadpool, + pthreadpool_task_1d_t function, void* context, + size_t range, uint32_t flags); + +/** + * Process items on a 1D grid passing along the current thread id. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range; i++) + * function(context, thread_index, i); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each item. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. The + * specified function will be called once for each item. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d_with_thread( + pthreadpool_t threadpool, pthreadpool_task_1d_with_thread_t function, + void* context, size_t range, uint32_t flags); + +/** + * Process items on a 1D grid using a microarchitecture-aware task function. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range; i++) + * function(context, uarch_index, i); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each item. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range the number of items on the 1D grid to process. + * The specified function will be called once for each item. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d_with_uarch( + pthreadpool_t threadpool, pthreadpool_task_1d_with_id_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range, uint32_t flags); + +/** + * Process items on a 1D grid with specified maximum tile size. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range; i += tile) + * function(context, i, min(range - i, tile)); + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. + * @param tile the maximum number of items on the 1D grid to process in + * one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d_tile_1d(pthreadpool_t threadpool, + pthreadpool_task_1d_tile_1d_t function, + void* context, size_t range, + size_t tile, uint32_t flags); + +/** + * Process items on a 1D grid with specified prefered tile size. + * + * The function repeatedly calls + * + * function(context, i, count) + * + * in parallel where `i` is in the range `[0, range)` and a multiple of the + * provided @a tile and `count` is an integer multiple of @a tile unless `i + * + count == range`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. + * @param tile the preferred multiple number of items on the 1D grid to + * process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d_tile_1d_dynamic( + pthreadpool_t threadpool, pthreadpool_task_1d_tile_1d_dynamic_t function, + void* context, size_t range, size_t tile, uint32_t flags); + +/** + * Process items on a 1D grid with specified prefered tile size, passing along + * the current thread id. + * + * The function repeatedly calls + * + * function(context, thread_id, i, count) + * + * in parallel where `i` is in the range `[0, range)` and a multiple of the + * provided @a tile and `count` is an integer multiple of @a tile unless `i + * + count == range`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. + * @param tile the preferred multiple number of items on the 1D grid to + * process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d_tile_1d_dynamic_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_1d_tile_1d_dynamic_with_id_t function, void* context, + size_t range, size_t tile, uint32_t flags); + +/** + * Process items on a 1D grid with specified prefered tile size, passing along + * the current uarch index and thread id. + * + * The function repeatedly calls + * + * function(context, uarch_index, thread_id, i, count) + * + * in parallel where `i` is in the range `[0, range)` and a multiple of the + * provided @a tile and `count` is an integer multiple of @a tile unless `i + * + count == range`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. + * @param tile the preferred multiple number of items on the 1D grid to + * process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_1d_tile_1d_dynamic_with_uarch_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_1d_tile_1d_dynamic_with_id_with_thread_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range, size_t tile, uint32_t flags); + +/** + * Process items on a 2D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * function(context, i, j); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each item. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d(pthreadpool_t threadpool, + pthreadpool_task_2d_t function, void* context, + size_t range_i, size_t range_j, uint32_t flags); + +/** + * Process items on a 2D grid passing along the current thread id. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * function(context, thread_index, i, j); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each item. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_with_thread( + pthreadpool_t threadpool, pthreadpool_task_2d_with_thread_t function, + void* context, size_t range_i, size_t range_j, uint32_t flags); + +/** + * Process items on a 2D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * function(context, i, j, min(range_j - j, tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param tile_j the maximum number of items along the second dimension of + * the 2D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_1d(pthreadpool_t threadpool, + pthreadpool_task_2d_tile_1d_t function, + void* context, size_t range_i, + size_t range_j, size_t tile_j, + uint32_t flags); + +/** + * Process items on a 2D grid with the specified maximum tile size along the + * last grid dimension using a microarchitecture-aware task function. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * function(context, uarch_index, i, j, min(range_j - j, tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param tile_j the maximum number of items along the second dimension of + * the 2D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_1d_with_uarch( + pthreadpool_t threadpool, pthreadpool_task_2d_tile_1d_with_id_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range_i, size_t range_j, size_t tile_j, uint32_t flags); + +/** + * Process items on a 2D grid with the specified maximum tile size along the + * last grid dimension using a microarchitecture-aware task function and passing + * along the current thread id. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * function(context, uarch_index, thread_index, i, j, min(range_j - j, + * tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param tile_j the maximum number of items along the second dimension of + * the 2D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_1d_with_uarch_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_2d_tile_1d_with_id_with_thread_t function, void* context, + uint32_t default_uarch_index, uint32_t max_uarch_index, size_t range_i, + size_t range_j, size_t tile_j, uint32_t flags); + +/** + * Process items on a 2D grid with specified prefered tile size along the + * last grid dimension. + * + * The function repeatedly calls + * + * function(context, i, j, count_j) + * + * in parallel where `i` is in the range `[0, range_i)`, `j` is in the range + * `[0, range_j)` and a multiple of the provided @a tile_j, and `count_j` is an + * integer multiple of @a tile_j unless `j + count_j == range_j`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 2D + * grid to process. + * @param range_j the number of items on the second dimension of the 2D + * grid to process. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 2D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_1d_dynamic( + pthreadpool_t threadpool, pthreadpool_task_2d_tile_1d_dynamic_t function, + void* context, size_t range_i, size_t range_j, size_t tile_j, + uint32_t flags); + +/** + * Process items on a 2D grid with specified prefered tile size along the + * last grid dimension, passing along the current thread id. + * + * The function repeatedly calls + * + * function(context, thread_id, i, j, count_j) + * + * in parallel where `i` is in the range `[0, range_i)`, `j` is in the range + * `[0, range_j)` and a multiple of the provided @a tile_j, and `count_j` is an + * integer multiple of @a tile_j unless `j + count_j == range_j`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 2D + * grid to process. + * @param range_j the number of items on the second dimension of the 2D + * grid to process. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 2D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_1d_dynamic_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_2d_tile_1d_dynamic_with_id_t function, void* context, + size_t range_i, size_t range_j, size_t tile_j, uint32_t flags); + +/** + * Process items on a 2D grid with specified prefered tile size along the + * last grid dimension, passing along the current uarch index and thread id. + * + * The function repeatedly calls + * + * function(context, uarch_index, thread_id, i, j, count_j) + * + * in parallel where `i` is in the range `[0, range_i)`, `j` is in the range + * `[0, range_j)` and a multiple of the provided @a tile_j, and `count_j` is an + * integer multiple of @a tile_j unless `j + count_j == range_j`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 2D + * grid to process. + * @param range_j the number of items on the second dimension of the 2D + * grid to process. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 2D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_1d_dynamic_with_uarch_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_2d_tile_1d_dynamic_with_id_with_thread_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range_i, size_t range_j, size_t tile_j, uint32_t flags); + +/** + * Process items on a 2D grid with the specified maximum tile size along each + * grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i += tile_i) + * for (size_t j = 0; j < range_j; j += tile_j) + * function(context, i, j, + * min(range_i - i, tile_i), min(range_j - j, tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param tile_j the maximum number of items along the first dimension of + * the 2D grid to process in one function call. + * @param tile_j the maximum number of items along the second dimension of + * the 2D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_2d(pthreadpool_t threadpool, + pthreadpool_task_2d_tile_2d_t function, + void* context, size_t range_i, + size_t range_j, size_t tile_i, + size_t tile_j, uint32_t flags); + +/** + * Process items on a 2D grid with specified prefered tile size along each grid + * dimension. + * + * The function repeatedly calls + * + * function(context, i, j, count_i, count_j) + * + * in parallel where `i` is in the range `[0, range_i)` and a multiple of the + * provided @a tile_i, `j` is in the range `[0, range_j)` and a multiple of the + * provided @a tile_j, and `count_i` and `count_j` are integer multiples of @a + * tile__i and @a tile_j, unless `i + count_i == range_i` or `j + count_j == + * range_j`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 2D + * grid to process. + * @param range_j the number of items on the second dimension of the 2D + * grid to process. + * @param tile_i the preferred multiple number of items on the first + * dimension of the 2D grid to process in each function call. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 2D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_2d_dynamic( + pthreadpool_t threadpool, pthreadpool_task_2d_tile_2d_dynamic_t function, + void* context, size_t range_i, size_t range_j, size_t tile_i, size_t tile_j, + uint32_t flags); + +/** + * Process items on a 2D grid with specified prefered tile size along each grid + * dimension using a microarchitecture-aware task function. + * + * The function repeatedly calls + * + * function(context, uarch_index, i, j, count_i, count_j) + * + * in parallel where `i` is in the range `[0, range_i)` and a multiple of the + * provided @a tile_i, `j` is in the range `[0, range_j)` and a multiple of the + * provided @a tile_j, and `count_i` and `count_j` are integer multiples of @a + * tile__i and @a tile_j, unless `i + count_i == range_i` or `j + count_j == + * range_j`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed + * serially on the calling thread. + * @param function the function to call for each interval of the + * given range. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, + * cpuinfo initialization failed, or index returned + * by cpuinfo_get_current_uarch_index() exceeds + * the max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected + * by the specified function. If the index returned + * by cpuinfo_get_current_uarch_index() exceeds this + * value, default_uarch_index will be used instead. + * default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items on the first dimension of the + * 2D grid to process. + * @param range_j the number of items on the second dimension of + * the 2D grid to process. + * @param tile_i the preferred multiple number of items on the + * first dimension of the 2D grid to process in each + * function call. + * @param tile_j the preferred multiple number of items on the + * second dimension of the 2D grid to process in + * each function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_2d_dynamic_with_uarch( + pthreadpool_t threadpool, + pthreadpool_task_2d_tile_2d_dynamic_with_id_t function, void* context, + uint32_t default_uarch_index, uint32_t max_uarch_index, size_t range_i, + size_t range_j, size_t tile_i, size_t tile_j, uint32_t flags); + +/** + * Process items on a 2D grid with specified prefered tile size along each grid + * dimension passing along the current thread id. + * + * The function repeatedly calls + * + * function(context, thread_id, i, j, count_i, count_j) + * + * in parallel where `i` is in the range `[0, range_i)` and a multiple of the + * provided @a tile_i, `j` is in the range `[0, range_j)` and a multiple of the + * provided @a tile_j, and `count_i` and `count_j` are integer multiples of @a + * tile__i and @a tile_j, unless `i + count_i == range_i` or `j + count_j == + * range_j`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed + * serially on the calling thread. + * @param function the function to call for each interval of the + * given range. + * @param context the first argument passed to the specified + * function. + * @param range_i the number of items on the first dimension of the + * 2D grid to process. + * @param range_j the number of items on the second dimension of + * the 2D grid to process. + * @param tile_i the preferred multiple number of items on the + * first dimension of the 2D grid to process in each + * function call. + * @param tile_j the preferred multiple number of items on the + * second dimension of the 2D grid to process in + * each function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_2d_dynamic_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_2d_tile_2d_dynamic_with_id_t function, void* context, + size_t range_i, size_t range_j, size_t tile_i, size_t tile_j, + uint32_t flags); + +/** + * Process items on a 2D grid with the specified maximum tile size along each + * grid dimension using a microarchitecture-aware task function. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i += tile_i) + * for (size_t j = 0; j < range_j; j += tile_j) + * function(context, uarch_index, i, j, + * min(range_i - i, tile_i), min(range_j - j, tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, + * cpuinfo initialization failed, or index returned + * by cpuinfo_get_current_uarch_index() exceeds + * the max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected + * by the specified function. If the index returned + * by cpuinfo_get_current_uarch_index() exceeds this + * value, default_uarch_index will be used instead. + * default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first + * dimension of the 2D grid. + * @param range_j the number of items to process along the second + * dimension of the 2D grid. + * @param tile_j the maximum number of items along the first + * dimension of the 2D grid to process in one function call. + * @param tile_j the maximum number of items along the second + * dimension of the 2D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_2d_tile_2d_with_uarch( + pthreadpool_t threadpool, pthreadpool_task_2d_tile_2d_with_id_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range_i, size_t range_j, size_t tile_i, size_t tile_j, + uint32_t flags); + +/** + * Process items on a 3D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * function(context, i, j, k); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d(pthreadpool_t threadpool, + pthreadpool_task_3d_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, + uint32_t flags); + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * function(context, i, j, k, min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param tile_k the maximum number of items along the third dimension of + * the 3D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_1d(pthreadpool_t threadpool, + pthreadpool_task_3d_tile_1d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t tile_k, uint32_t flags); + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last grid dimension and passing along the current thread id. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * function(context, thread_index, i, j, k, min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param tile_k the maximum number of items along the third dimension of + * the 3D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_1d_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_3d_tile_1d_with_thread_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, size_t tile_k, + uint32_t flags); + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last grid dimension using a microarchitecture-aware task function. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * function(context, uarch_index, i, j, k, min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first + * dimension of the 3D grid. + * @param range_j the number of items to process along the second + * dimension of the 3D grid. + * @param range_k the number of items to process along the third + * dimension of the 3D grid. + * @param tile_k the maximum number of items along the third + * dimension of the 3D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_1d_with_uarch( + pthreadpool_t threadpool, pthreadpool_task_3d_tile_1d_with_id_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range_i, size_t range_j, size_t range_k, size_t tile_k, + uint32_t flags); + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last grid dimension using a microarchitecture-aware task function and passing + * along the current thread id. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * function(context, uarch_index, thread_index, i, j, k, min(range_k - + * k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first + * dimension of the 3D grid. + * @param range_j the number of items to process along the second + * dimension of the 3D grid. + * @param range_k the number of items to process along the third + * dimension of the 3D grid. + * @param tile_k the maximum number of items along the third + * dimension of the 3D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_1d_with_uarch_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_3d_tile_1d_with_id_with_thread_t function, void* context, + uint32_t default_uarch_index, uint32_t max_uarch_index, size_t range_i, + size_t range_j, size_t range_k, size_t tile_k, uint32_t flags); + +/** + * Process items on a 3D grid with specified prefered tile size along the last + * grid dimension, passing along the thread ID. + * + * The function repeatedly calls + * + * function(context, thread_id, i, j, k, count_k) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)`, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `count_k` is an integer multiple of @a tile_k, unless `k + count_k == + * range_k`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed + * serially on the calling thread. + * @param function the function to call for each interval of the + * given range. + * @param context the first argument passed to the specified + * function. + * @param range_i the number of items on the first dimension of the + * 3D grid to process. + * @param range_j the number of items on the second dimension of + * the 3D grid to process. + * @param range_k the number of items on the third dimension of the + * 3D grid to process. + * @param tile_k the preferred multiple number of items on the + * third dimension of the 3D grid to process in each + * function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_1d_dynamic_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_3d_tile_1d_dynamic_with_id_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, size_t tile_k, + uint32_t flags); + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * for (size_t k = 0; k < range_k; k += tile_k) + * function(context, i, j, k, + * min(range_j - j, tile_j), min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param tile_j the maximum number of items along the second dimension of + * the 3D grid to process in one function call. + * @param tile_k the maximum number of items along the third dimension of + * the 3D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_2d(pthreadpool_t threadpool, + pthreadpool_task_3d_tile_2d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t tile_j, size_t tile_k, + uint32_t flags); + +/** + * Process items on a 3D grid with specified prefered tile size along the last + * two grid dimensions. + * + * The function repeatedly calls + * + * function(context, i, j, k, count_j, count_k) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)` and a multiple of the provided @a + * tile_j, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `count_j` and `count_k` are integer multiples of @a tile__j and @a tile_k, + * unless `j + count_j == range_j` or `k + count_k == range_k`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 3D + * grid to process. + * @param range_j the number of items on the second dimension of the 3D + * grid to process. + * @param range_k the number of items on the third dimension of the 3D + * grid to process. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 3D grid to process in each function call. + * @param tile_k the preferred multiple number of items on the third + * dimension of the 3D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_2d_dynamic( + pthreadpool_t threadpool, pthreadpool_task_3d_tile_2d_dynamic_t function, + void* context, size_t range_i, size_t range_j, size_t range_k, + size_t tile_j, size_t tile_k, uint32_t flags); + +/** + * Process items on a 3D grid with specified prefered tile size along the last + * two grid dimensions using a microarchitecture-aware task function. + * + * The function repeatedly calls + * + * function(context, uarch_index, i, j, k, count_j, count_k) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)` and a multiple of the provided @a + * tile_j, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `count_j` and `count_k` are integer multiples of @a tile__j and @a tile_k, + * unless `j + count_j == range_j` or `k + count_k == range_k`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed + * serially on the calling thread. + * @param function the function to call for each interval of the + * given range. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, + * cpuinfo initialization failed, or index returned + * by cpuinfo_get_current_uarch_index() exceeds + * the max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected + * by the specified function. If the index returned + * by cpuinfo_get_current_uarch_index() exceeds this + * value, default_uarch_index will be used instead. + * default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items on the first dimension of the + * 3D grid to process. + * @param range_j the number of items on the second dimension of + * the 3D grid to process. + * @param range_k the number of items on the third dimension of the + * 3D grid to process. + * @param tile_j the preferred multiple number of items on the + * second dimension of the 3D grid to process in + * each function call. + * @param tile_k the preferred multiple number of items on the + * third dimension of the 3D grid to process in each + * function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_2d_dynamic_with_uarch( + pthreadpool_t threadpool, + pthreadpool_task_3d_tile_2d_dynamic_with_id_t function, void* context, + uint32_t default_uarch_index, uint32_t max_uarch_index, size_t range_i, + size_t range_j, size_t range_k, size_t tile_j, size_t tile_k, + uint32_t flags); + +/** + * Process items on a 3D grid with specified prefered tile size along the last + * two grid dimensions passing along the thread ID. + * + * The function repeatedly calls + * + * function(context, thread_id, i, j, k, count_j, count_k) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)` and a multiple of the provided @a + * tile_j, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `count_j` and `count_k` are integer multiples of @a tile__j and @a tile_k, + * unless `j + count_j == range_j` or `k + count_k == range_k`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed + * serially on the calling thread. + * @param function the function to call for each interval of the + * given range. + * @param context the first argument passed to the specified + * function. + * @param range_i the number of items on the first dimension of the + * 3D grid to process. + * @param range_j the number of items on the second dimension of + * the 3D grid to process. + * @param range_k the number of items on the third dimension of the + * 3D grid to process. + * @param tile_j the preferred multiple number of items on the + * second dimension of the 3D grid to process in + * each function call. + * @param tile_k the preferred multiple number of items on the + * third dimension of the 3D grid to process in each + * function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_2d_dynamic_with_thread( + pthreadpool_t threadpool, + pthreadpool_task_3d_tile_2d_dynamic_with_id_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, size_t tile_j, + size_t tile_k, uint32_t flags); + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last two grid dimensions using a microarchitecture-aware task function. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * for (size_t k = 0; k < range_k; k += tile_k) + * function(context, uarch_index, i, j, k, + * min(range_j - j, tile_j), min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first + * dimension of the 3D grid. + * @param range_j the number of items to process along the second + * dimension of the 3D grid. + * @param range_k the number of items to process along the third + * dimension of the 3D grid. + * @param tile_j the maximum number of items along the second + * dimension of the 3D grid to process in one function call. + * @param tile_k the maximum number of items along the third + * dimension of the 3D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_3d_tile_2d_with_uarch( + pthreadpool_t threadpool, pthreadpool_task_3d_tile_2d_with_id_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range_i, size_t range_j, size_t range_k, size_t tile_j, + size_t tile_k, uint32_t flags); + +/** + * Process items on a 4D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * function(context, i, j, k, l); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 4D grid. + * @param range_j the number of items to process along the second dimension + * of the 4D grid. + * @param range_k the number of items to process along the third dimension + * of the 4D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 4D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_4d(pthreadpool_t threadpool, + pthreadpool_task_4d_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, + size_t range_l, uint32_t flags); + +/** + * Process items on a 4D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l += tile_l) + * function(context, i, j, k, l, min(range_l - l, tile_l)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 4D grid. + * @param range_j the number of items to process along the second dimension + * of the 4D grid. + * @param range_k the number of items to process along the third dimension + * of the 4D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 4D grid. + * @param tile_l the maximum number of items along the fourth dimension of + * the 4D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_4d_tile_1d(pthreadpool_t threadpool, + pthreadpool_task_4d_tile_1d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t tile_l, + uint32_t flags); + +/** + * Process items on a 4D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * for (size_t l = 0; l < range_l; l += tile_l) + * function(context, i, j, k, l, + * min(range_k - k, tile_k), min(range_l - l, tile_l)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 4D grid. + * @param range_j the number of items to process along the second dimension + * of the 4D grid. + * @param range_k the number of items to process along the third dimension + * of the 4D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 4D grid. + * @param tile_k the maximum number of items along the third dimension of + * the 4D grid to process in one function call. + * @param tile_l the maximum number of items along the fourth dimension of + * the 4D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_4d_tile_2d(pthreadpool_t threadpool, + pthreadpool_task_4d_tile_2d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t tile_k, + size_t tile_l, uint32_t flags); + +/** + * Process items on a 4D grid with the specified maximum tile size along the + * last two grid dimensions using a microarchitecture-aware task function. + * + * The function implements a parallel version of the following snippet: + * + * uint32_t uarch_index = cpuinfo_initialize() ? + * cpuinfo_get_current_uarch_index() : default_uarch_index; + * if (uarch_index > max_uarch_index) uarch_index = default_uarch_index; + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * for (size_t l = 0; l < range_l; l += tile_l) + * function(context, uarch_index, i, j, k, l, + * min(range_k - k, tile_k), min(range_l - l, tile_l)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, cpuinfo initialization failed, + * or index returned by cpuinfo_get_current_uarch_index() exceeds the + * max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected by + * the specified function. If the index returned by + * cpuinfo_get_current_uarch_index() exceeds this value, default_uarch_index + * will be used instead. default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items to process along the first + * dimension of the 4D grid. + * @param range_j the number of items to process along the second + * dimension of the 4D grid. + * @param range_k the number of items to process along the third + * dimension of the 4D grid. + * @param range_l the number of items to process along the fourth + * dimension of the 4D grid. + * @param tile_k the maximum number of items along the third + * dimension of the 4D grid to process in one function call. + * @param tile_l the maximum number of items along the fourth + * dimension of the 4D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_4d_tile_2d_with_uarch( + pthreadpool_t threadpool, pthreadpool_task_4d_tile_2d_with_id_t function, + void* context, uint32_t default_uarch_index, uint32_t max_uarch_index, + size_t range_i, size_t range_j, size_t range_k, size_t range_l, + size_t tile_k, size_t tile_l, uint32_t flags); + +/** + * Process items on a 4D grid with specified prefered tile size along the last + * two grid dimensions. + * + * The function repeatedly calls + * + * function(context, i, j, k, l, count_k, count_l) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)`, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `l` is in the range `[0, range_l)` and a multiple of the provided @a + * tile_l, + * - `count_k` and `count_l` are integer multiples of @a tile_k and @a tile_l, + * unless `k + count_k == range_k` or `l + count_l == range_l`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 4D + * grid to process. + * @param range_j the number of items on the second dimension of the 4D + * grid to process. + * @param range_k the number of items on the third dimension of the 4D + * grid to process. + * @param range_l the number of items on the fourth dimension of the 4D + * grid to process. + * @param tile_k the preferred multiple number of items on the third + * dimension of the 4D grid to process in each function call. + * @param tile_l the preferred multiple number of items on the fourth + * dimension of the 4D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_4d_tile_2d_dynamic( + pthreadpool_t threadpool, pthreadpool_task_4d_tile_2d_dynamic_t function, + void* context, size_t range_i, size_t range_j, size_t range_k, + size_t range_l, size_t tile_k, size_t tile_l, uint32_t flags); + +/** + * Process items on a 4D grid with specified prefered tile size along the last + * two grid dimensions using a microarchitecture-aware task function. + * + * The function repeatedly calls + * + * function(context, uarch_index, i, j, k, l, count_k, count_l) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)`, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `l` is in the range `[0, range_l)` and a multiple of the provided @a + * tile_l, + * - `count_k` and `count_l` are integer multiples of @a tile_k and @a tile_l, + * unless `k + count_k == range_k` or `l + count_l == range_l`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If + * threadpool is NULL, all items are processed + * serially on the calling thread. + * @param function the function to call for each interval of the + * given range. + * @param context the first argument passed to the specified + * function. + * @param default_uarch_index the microarchitecture index to use when + * pthreadpool is configured without cpuinfo, + * cpuinfo initialization failed, or index returned + * by cpuinfo_get_current_uarch_index() exceeds + * the max_uarch_index value. + * @param max_uarch_index the maximum microarchitecture index expected + * by the specified function. If the index returned + * by cpuinfo_get_current_uarch_index() exceeds this + * value, default_uarch_index will be used instead. + * default_uarch_index can exceed max_uarch_index. + * @param range_i the number of items on the first dimension of the + * 4D grid to process. + * @param range_j the number of items on the second dimension of + * the 4D grid to process. + * @param range_k the number of items on the third dimension of the + * 4D grid to process. + * @param range_l the number of items on the fourth dimension of + * the 4D grid to process. + * @param tile_k the preferred multiple number of items on the + * third dimension of the 4D grid to process in each + * function call. + * @param tile_l the preferred multiple number of items on the + * fourth dimension of the 4D grid to process in + * each function call. + * @param flags a bitwise combination of zero or more optional + * flags (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_4d_tile_2d_dynamic_with_uarch( + pthreadpool_t threadpool, + pthreadpool_task_4d_tile_2d_dynamic_with_id_t function, void* context, + uint32_t default_uarch_index, uint32_t max_uarch_index, size_t range_i, + size_t range_j, size_t range_k, size_t range_l, size_t tile_k, + size_t tile_l, uint32_t flags); + +/** + * Process items on a 5D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m++) + * function(context, i, j, k, l, m); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 5D grid. + * @param range_j the number of items to process along the second dimension + * of the 5D grid. + * @param range_k the number of items to process along the third dimension + * of the 5D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 5D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 5D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_5d(pthreadpool_t threadpool, + pthreadpool_task_5d_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, + size_t range_l, size_t range_m, uint32_t flags); + +/** + * Process items on a 5D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m += tile_m) + * function(context, i, j, k, l, m, min(range_m - m, tile_m)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 5D grid. + * @param range_j the number of items to process along the second dimension + * of the 5D grid. + * @param range_k the number of items to process along the third dimension + * of the 5D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 5D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 5D grid. + * @param tile_m the maximum number of items along the fifth dimension of + * the 5D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_5d_tile_1d(pthreadpool_t threadpool, + pthreadpool_task_5d_tile_1d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t tile_m, uint32_t flags); + +/** + * Process items on a 5D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l += tile_l) + * for (size_t m = 0; m < range_m; m += tile_m) + * function(context, i, j, k, l, m, + * min(range_l - l, tile_l), min(range_m - m, tile_m)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 5D grid. + * @param range_j the number of items to process along the second dimension + * of the 5D grid. + * @param range_k the number of items to process along the third dimension + * of the 5D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 5D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 5D grid. + * @param tile_l the maximum number of items along the fourth dimension of + * the 5D grid to process in one function call. + * @param tile_m the maximum number of items along the fifth dimension of + * the 5D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_5d_tile_2d(pthreadpool_t threadpool, + pthreadpool_task_5d_tile_2d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t tile_l, size_t tile_m, + uint32_t flags); + +/** + * Process items on a 6D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m++) + * for (size_t n = 0; n < range_n; n++) + * function(context, i, j, k, l, m, n); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 6D grid. + * @param range_j the number of items to process along the second dimension + * of the 6D grid. + * @param range_k the number of items to process along the third dimension + * of the 6D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 6D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 6D grid. + * @param range_n the number of items to process along the sixth dimension + * of the 6D grid. + * @param tile_n the maximum number of items along the sixth dimension of + * the 6D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_6d(pthreadpool_t threadpool, + pthreadpool_task_6d_t function, void* context, + size_t range_i, size_t range_j, size_t range_k, + size_t range_l, size_t range_m, size_t range_n, + uint32_t flags); + +/** + * Process items on a 6D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m++) + * for (size_t n = 0; n < range_n; n += tile_n) + * function(context, i, j, k, l, m, n, min(range_n - n, tile_n)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 6D grid. + * @param range_j the number of items to process along the second dimension + * of the 6D grid. + * @param range_k the number of items to process along the third dimension + * of the 6D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 6D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 6D grid. + * @param range_n the number of items to process along the sixth dimension + * of the 6D grid. + * @param tile_n the maximum number of items along the sixth dimension of + * the 6D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_6d_tile_1d(pthreadpool_t threadpool, + pthreadpool_task_6d_tile_1d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t range_n, size_t tile_n, + uint32_t flags); + +/** + * Process items on a 6D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m += tile_m) + * for (size_t n = 0; n < range_n; n += tile_n) + * function(context, i, j, k, l, m, n, + * min(range_m - m, tile_m), min(range_n - n, tile_n)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each tile. + * @param context the first argument passed to the specified function. + * @param range_i the number of items to process along the first dimension + * of the 6D grid. + * @param range_j the number of items to process along the second dimension + * of the 6D grid. + * @param range_k the number of items to process along the third dimension + * of the 6D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 6D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 6D grid. + * @param range_n the number of items to process along the sixth dimension + * of the 6D grid. + * @param tile_m the maximum number of items along the fifth dimension of + * the 6D grid to process in one function call. + * @param tile_n the maximum number of items along the sixth dimension of + * the 6D grid to process in one function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +void pthreadpool_parallelize_6d_tile_2d(pthreadpool_t threadpool, + pthreadpool_task_6d_tile_2d_t function, + void* context, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t range_n, size_t tile_m, + size_t tile_n, uint32_t flags); + +/** + * Terminates threads in the thread pool and releases associated resources. + * + * @warning Accessing the thread pool after a call to this function constitutes + * undefined behaviour and may cause data corruption. + * + * @param[in,out] threadpool The thread pool to destroy. + */ +void pthreadpool_destroy(pthreadpool_t threadpool); + +#ifndef PTHREADPOOL_NO_DEPRECATED_API + +/* Legacy API for compatibility with pre-existing users (e.g. NNPACK) */ +#if defined(__GNUC__) +#define PTHREADPOOL_DEPRECATED __attribute__((__deprecated__)) +#else +#define PTHREADPOOL_DEPRECATED +#endif + +typedef void (*pthreadpool_function_1d_t)(void*, size_t); +typedef void (*pthreadpool_function_1d_tiled_t)(void*, size_t, size_t); +typedef void (*pthreadpool_function_2d_t)(void*, size_t, size_t); +typedef void (*pthreadpool_function_2d_tiled_t)(void*, size_t, size_t, size_t, + size_t); +typedef void (*pthreadpool_function_3d_tiled_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t); +typedef void (*pthreadpool_function_4d_tiled_t)(void*, size_t, size_t, size_t, + size_t, size_t, size_t, size_t, + size_t); + +void pthreadpool_compute_1d(pthreadpool_t threadpool, + pthreadpool_function_1d_t function, void* argument, + size_t range) PTHREADPOOL_DEPRECATED; + +void pthreadpool_compute_1d_tiled(pthreadpool_t threadpool, + pthreadpool_function_1d_tiled_t function, + void* argument, size_t range, + size_t tile) PTHREADPOOL_DEPRECATED; + +void pthreadpool_compute_2d(pthreadpool_t threadpool, + pthreadpool_function_2d_t function, void* argument, + size_t range_i, + size_t range_j) PTHREADPOOL_DEPRECATED; + +void pthreadpool_compute_2d_tiled(pthreadpool_t threadpool, + pthreadpool_function_2d_tiled_t function, + void* argument, size_t range_i, + size_t range_j, size_t tile_i, + size_t tile_j) PTHREADPOOL_DEPRECATED; + +void pthreadpool_compute_3d_tiled(pthreadpool_t threadpool, + pthreadpool_function_3d_tiled_t function, + void* argument, size_t range_i, + size_t range_j, size_t range_k, size_t tile_i, + size_t tile_j, + size_t tile_k) PTHREADPOOL_DEPRECATED; + +void pthreadpool_compute_4d_tiled(pthreadpool_t threadpool, + pthreadpool_function_4d_tiled_t function, + void* argument, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t tile_i, size_t tile_j, + size_t tile_k, + size_t tile_l) PTHREADPOOL_DEPRECATED; + +#endif /* PTHREADPOOL_NO_DEPRECATED_API */ + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#ifdef __cplusplus + +namespace libpthreadpool { +namespace detail { +namespace { // NOLINT: Naming this namespace would expose it. + +template +void call_wrapper_1d(void* arg, size_t i) { + (*static_cast(arg))(i); +} + +template +void call_wrapper_1d_tile_1d(void* arg, size_t range_i, size_t tile_i) { + (*static_cast(arg))(range_i, tile_i); +} + +template +void call_wrapper_1d_tile_1d_dynamic(void* arg, size_t range_i, size_t tile_i) { + (*static_cast(arg))(range_i, tile_i); +} + +template +void call_wrapper_2d(void* functor, size_t i, size_t j) { + (*static_cast(functor))(i, j); +} + +template +void call_wrapper_2d_tile_1d(void* functor, size_t i, size_t range_j, + size_t tile_j) { + (*static_cast(functor))(i, range_j, tile_j); +} + +template +void call_wrapper_2d_tile_1d_dynamic(void* functor, size_t i, size_t range_j, + size_t tile_j) { + (*static_cast(functor))(i, range_j, tile_j); +} + +template +void call_wrapper_2d_tile_2d(void* functor, size_t range_i, size_t range_j, + size_t tile_i, size_t tile_j) { + (*static_cast(functor))(range_i, range_j, tile_i, tile_j); +} + +template +void call_wrapper_2d_tile_2d_dynamic(void* functor, size_t range_i, + size_t range_j, size_t tile_i, + size_t tile_j) { + (*static_cast(functor))(range_i, range_j, tile_i, tile_j); +} + +template +void call_wrapper_3d(void* functor, size_t i, size_t j, size_t k) { + (*static_cast(functor))(i, j, k); +} + +template +void call_wrapper_3d_tile_1d(void* functor, size_t i, size_t j, size_t range_k, + size_t tile_k) { + (*static_cast(functor))(i, j, range_k, tile_k); +} + +template +void call_wrapper_3d_tile_2d(void* functor, size_t i, size_t range_j, + size_t range_k, size_t tile_j, size_t tile_k) { + (*static_cast(functor))(i, range_j, range_k, tile_j, tile_k); +} + +template +void call_wrapper_3d_tile_2d_dynamic(void* functor, size_t i, size_t range_j, + size_t range_k, size_t tile_j, + size_t tile_k) { + (*static_cast(functor))(i, range_j, range_k, tile_j, tile_k); +} + +template +void call_wrapper_4d(void* functor, size_t i, size_t j, size_t k, size_t l) { + (*static_cast(functor))(i, j, k, l); +} + +template +void call_wrapper_4d_tile_1d(void* functor, size_t i, size_t j, size_t k, + size_t range_l, size_t tile_l) { + (*static_cast(functor))(i, j, k, range_l, tile_l); +} + +template +void call_wrapper_4d_tile_2d(void* functor, size_t i, size_t j, size_t range_k, + size_t range_l, size_t tile_k, size_t tile_l) { + (*static_cast(functor))(i, j, range_k, range_l, tile_k, tile_l); +} + +template +void call_wrapper_4d_tile_2d_dynamic(void* functor, size_t i, size_t j, + size_t range_k, size_t range_l, + size_t tile_k, size_t tile_l) { + (*static_cast(functor))(i, j, range_k, range_l, tile_k, tile_l); +} + +template +void call_wrapper_5d(void* functor, size_t i, size_t j, size_t k, size_t l, + size_t m) { + (*static_cast(functor))(i, j, k, l, m); +} + +template +void call_wrapper_5d_tile_1d(void* functor, size_t i, size_t j, size_t k, + size_t l, size_t range_m, size_t tile_m) { + (*static_cast(functor))(i, j, k, l, range_m, tile_m); +} + +template +void call_wrapper_5d_tile_2d(void* functor, size_t i, size_t j, size_t k, + size_t range_l, size_t range_m, size_t tile_l, + size_t tile_m) { + (*static_cast(functor))(i, j, k, range_l, range_m, tile_l, tile_m); +} + +template +void call_wrapper_6d(void* functor, size_t i, size_t j, size_t k, size_t l, + size_t m, size_t n) { + (*static_cast(functor))(i, j, k, l, m, n); +} + +template +void call_wrapper_6d_tile_1d(void* functor, size_t i, size_t j, size_t k, + size_t l, size_t m, size_t range_n, + size_t tile_n) { + (*static_cast(functor))(i, j, k, l, m, range_n, tile_n); +} + +template +void call_wrapper_6d_tile_2d(void* functor, size_t i, size_t j, size_t k, + size_t l, size_t range_m, size_t range_n, + size_t tile_m, size_t tile_n) { + (*static_cast(functor))(i, j, k, l, range_m, range_n, tile_m, + tile_n); +} + +} /* namespace */ +} /* namespace detail */ +} /* namespace libpthreadpool */ + +/** + * Process items on a 1D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range; i++) + * functor(i); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each item. + * @param range the number of items on the 1D grid to process. The + * specified functor will be called once for each item. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_1d(pthreadpool_t threadpool, + const T& functor, size_t range, + uint32_t flags = 0) { + pthreadpool_parallelize_1d( + threadpool, &libpthreadpool::detail::call_wrapper_1d, + const_cast(static_cast(&functor)), range, flags); +} + +/** + * Process items on a 1D grid with specified maximum tile size. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range; i += tile) + * functor(i, min(range - i, tile)); + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range the number of items on the 1D grid to process. + * @param tile the maximum number of items on the 1D grid to process in + * one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_1d_tile_1d(pthreadpool_t threadpool, + const T& functor, size_t range, + size_t tile, + uint32_t flags = 0) { + pthreadpool_parallelize_1d_tile_1d( + threadpool, &libpthreadpool::detail::call_wrapper_1d_tile_1d, + const_cast(static_cast(&functor)), range, tile, + flags); +} + +/** + * Process items on a 1D grid with specified prefered tile size. + * + * The function repeatedly calls + * + * function(context, i, count) + * + * in parallel where `i` is in the range `[0, range)` and a multiple of the + * provided @a tile and `count` is an integer multiple of @a tile unless `i + * + count == range`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range the number of items on the 1D grid to process. + * @param tile the preferred multiple number of items on the 1D grid to + * process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_1d_tile_1d_dynamic(pthreadpool_t threadpool, + const T& functor, + size_t range, + size_t tile, + uint32_t flags = 0) { + pthreadpool_parallelize_1d_tile_1d_dynamic( + threadpool, + &libpthreadpool::detail::call_wrapper_1d_tile_1d_dynamic, + const_cast(static_cast(&functor)), range, tile, + flags); +} + +/** + * Process items on a 2D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * functor(i, j); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each item. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_2d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, uint32_t flags = 0) { + pthreadpool_parallelize_2d( + threadpool, &libpthreadpool::detail::call_wrapper_2d, + const_cast(static_cast(&functor)), range_i, range_j, + flags); +} + +/** + * Process items on a 2D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * functor(i, j, min(range_j - j, tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param tile_j the maximum number of items along the second dimension of + * the 2D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_2d_tile_1d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t tile_j, + uint32_t flags = 0) { + pthreadpool_parallelize_2d_tile_1d( + threadpool, &libpthreadpool::detail::call_wrapper_2d_tile_1d, + const_cast(static_cast(&functor)), range_i, range_j, + tile_j, flags); +} + +/** + * Process items on a 2D grid with specified prefered tile size along the + * last grid dimension. + * + * The function repeatedly calls + * + * function(context, i, j, count_j) + * + * in parallel where `i` is in the range `[0, range_i)`, `j` is in the range + * `[0, range_j)` and a multiple of the provided @a tile_j, and `count_j` is an + * integer multiple of @a tile_j unless `j + count_j == range_j`. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 2D + * grid to process. + * @param range_j the number of items on the second dimension of the 2D + * grid to process. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 2D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_2d_tile_1d_dynamic( + pthreadpool_t threadpool, const T& functor, size_t range_i, size_t range_j, + size_t tile_j, uint32_t flags = 0) { + pthreadpool_parallelize_2d_tile_1d_dynamic( + threadpool, + &libpthreadpool::detail::call_wrapper_2d_tile_1d_dynamic, + const_cast(static_cast(&functor)), range_i, range_j, + tile_j, flags); +} + +/** + * Process items on a 2D grid with the specified maximum tile size along each + * grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i += tile_i) + * for (size_t j = 0; j < range_j; j += tile_j) + * functor(i, j, + * min(range_i - i, tile_i), min(range_j - j, tile_j)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 2D grid. + * @param range_j the number of items to process along the second dimension + * of the 2D grid. + * @param tile_j the maximum number of items along the first dimension of + * the 2D grid to process in one functor call. + * @param tile_j the maximum number of items along the second dimension of + * the 2D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_2d_tile_2d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t tile_i, + size_t tile_j, + uint32_t flags = 0) { + pthreadpool_parallelize_2d_tile_2d( + threadpool, &libpthreadpool::detail::call_wrapper_2d_tile_2d, + const_cast(static_cast(&functor)), range_i, range_j, + tile_i, tile_j, flags); +} + +/** + * Process items on a 2D grid with specified prefered tile size along each grid + * dimension. + * + * The function repeatedly calls + * + * function(context, i, j, count_i, count_j) + * + * in parallel where `i` is in the range `[0, range_i)` and a multiple of the + * provided @a tile_i, `j` is in the range `[0, range_j)` and a multiple of the + * provided @a tile_j, and `count_i` and `count_j` are integer multiples of @a + * tile__i and @a tile_j, unless `i + count_i == range_i` or `j + count_j == + * range_j`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 2D + * grid to process. + * @param range_j the number of items on the second dimension of the 2D + * grid to process. + * @param tile_i the preferred multiple number of items on the first + * dimension of the 2D grid to process in each function call. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 2D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_2d_tile_2d_dynamic( + pthreadpool_t threadpool, const T& functor, size_t range_i, size_t range_j, + size_t tile_i, size_t tile_j, uint32_t flags = 0) { + pthreadpool_parallelize_2d_tile_2d_dynamic( + threadpool, + &libpthreadpool::detail::call_wrapper_2d_tile_2d_dynamic, + const_cast(static_cast(&functor)), range_i, range_j, + tile_i, tile_j, flags); +} + +/** + * Process items on a 3D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * functor(i, j, k); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_3d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + uint32_t flags = 0) { + pthreadpool_parallelize_3d( + threadpool, &libpthreadpool::detail::call_wrapper_3d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, flags); +} + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * functor(i, j, k, min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param tile_k the maximum number of items along the third dimension of + * the 3D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_3d_tile_1d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t tile_k, + uint32_t flags = 0) { + pthreadpool_parallelize_3d_tile_1d( + threadpool, &libpthreadpool::detail::call_wrapper_3d_tile_1d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, tile_k, flags); +} + +/** + * Process items on a 3D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j += tile_j) + * for (size_t k = 0; k < range_k; k += tile_k) + * functor(i, j, k, + * min(range_j - j, tile_j), min(range_k - k, tile_k)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 3D grid. + * @param range_j the number of items to process along the second dimension + * of the 3D grid. + * @param range_k the number of items to process along the third dimension + * of the 3D grid. + * @param tile_j the maximum number of items along the second dimension of + * the 3D grid to process in one functor call. + * @param tile_k the maximum number of items along the third dimension of + * the 3D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_3d_tile_2d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t tile_j, size_t tile_k, + uint32_t flags = 0) { + pthreadpool_parallelize_3d_tile_2d( + threadpool, &libpthreadpool::detail::call_wrapper_3d_tile_2d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, tile_j, tile_k, flags); +} + +/** + * Process items on a 3D grid with specified prefered tile size along the last + * two grid dimensions. + * + * The function repeatedly calls + * + * function(context, i, j, k, count_j, count_k) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)` and a multiple of the provided @a + * tile_j, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `count_j` and `count_k` are integer multiples of @a tile__j and @a tile_k, + * unless `j + count_j == range_j` or `k + count_k == range_k`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 3D + * grid to process. + * @param range_j the number of items on the second dimension of the 3D + * grid to process. + * @param range_k the number of items on the third dimension of the 3D + * grid to process. + * @param tile_j the preferred multiple number of items on the second + * dimension of the 3D grid to process in each function call. + * @param tile_k the preferred multiple number of items on the third + * dimension of the 3D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_3d_tile_2d_dynamic( + pthreadpool_t threadpool, const T& functor, size_t range_i, size_t range_j, + size_t range_k, size_t tile_j, size_t tile_k, uint32_t flags = 0) { + pthreadpool_parallelize_3d_tile_2d_dynamic( + threadpool, + &libpthreadpool::detail::call_wrapper_3d_tile_2d_dynamic, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, tile_j, tile_k, flags); +} + +/** + * Process items on a 4D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * functor(i, j, k, l); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 4D grid. + * @param range_j the number of items to process along the second dimension + * of the 4D grid. + * @param range_k the number of items to process along the third dimension + * of the 4D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 4D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_4d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, uint32_t flags = 0) { + pthreadpool_parallelize_4d( + threadpool, &libpthreadpool::detail::call_wrapper_4d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, flags); +} + +/** + * Process items on a 4D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l += tile_l) + * functor(i, j, k, l, min(range_l - l, tile_l)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 4D grid. + * @param range_j the number of items to process along the second dimension + * of the 4D grid. + * @param range_k the number of items to process along the third dimension + * of the 4D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 4D grid. + * @param tile_l the maximum number of items along the fourth dimension of + * the 4D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_4d_tile_1d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t tile_l, + uint32_t flags = 0) { + pthreadpool_parallelize_4d_tile_1d( + threadpool, &libpthreadpool::detail::call_wrapper_4d_tile_1d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, tile_l, flags); +} + +/** + * Process items on a 4D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k += tile_k) + * for (size_t l = 0; l < range_l; l += tile_l) + * functor(i, j, k, l, + * min(range_k - k, tile_k), min(range_l - l, tile_l)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 4D grid. + * @param range_j the number of items to process along the second dimension + * of the 4D grid. + * @param range_k the number of items to process along the third dimension + * of the 4D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 4D grid. + * @param tile_k the maximum number of items along the third dimension of + * the 4D grid to process in one functor call. + * @param tile_l the maximum number of items along the fourth dimension of + * the 4D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_4d_tile_2d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t tile_k, + size_t tile_l, + uint32_t flags = 0) { + pthreadpool_parallelize_4d_tile_2d( + threadpool, &libpthreadpool::detail::call_wrapper_4d_tile_2d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, tile_k, tile_l, flags); +} + +/** + * Process items on a 4D grid with specified prefered tile size along the last + * two grid dimensions. + * + * The function repeatedly calls + * + * function(context, i, j, k, l, count_k, count_l) + * + * in parallel where: + * - `i` is in the range `[0, range_i)`, + * - `j` is in the range `[0, range_j)`, + * - `k` is in the range `[0, range_k)` and a multiple of the provided @a + * tile_k, + * - `l` is in the range `[0, range_l)` and a multiple of the provided @a + * tile_l, + * - `count_k` and `count_l` are integer multiples of @a tile_k and @a tile_l, + * unless `k + count_k == range_k` or `l + count_l == range_l`, respectivly. + * + * The `count`s are chosen such as to minimize the number of calls to @a + * function while keeping the computation load balanced across all threads. + * + * When the call returns, all items have been processed and the thread pool is + * ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, + * the calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling + * thread. + * @param function the function to call for each interval of the given range. + * @param context the first argument passed to the specified function. + * @param range_i the number of items on the first dimension of the 4D + * grid to process. + * @param range_j the number of items on the second dimension of the 4D + * grid to process. + * @param range_k the number of items on the third dimension of the 4D + * grid to process. + * @param range_l the number of items on the fourth dimension of the 4D + * grid to process. + * @param tile_k the preferred multiple number of items on the third + * dimension of the 4D grid to process in each function call. + * @param tile_l the preferred multiple number of items on the fourth + * dimension of the 4D grid to process in each function call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or + * PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_4d_tile_2d_dynamic( + pthreadpool_t threadpool, const T& functor, size_t range_i, size_t range_j, + size_t range_k, size_t range_l, size_t tile_k, size_t tile_l, + uint32_t flags = 0) { + pthreadpool_parallelize_3d_tile_2d_dynamic( + threadpool, + &libpthreadpool::detail::call_wrapper_4d_tile_2d_dynamic, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, tile_k, tile_l, flags); +} + +/** + * Process items on a 5D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m++) + * functor(i, j, k, l, m); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 5D grid. + * @param range_j the number of items to process along the second dimension + * of the 5D grid. + * @param range_k the number of items to process along the third dimension + * of the 5D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 5D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 5D grid. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_5d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + uint32_t flags = 0) { + pthreadpool_parallelize_5d( + threadpool, &libpthreadpool::detail::call_wrapper_5d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, range_m, flags); +} + +/** + * Process items on a 5D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m += tile_m) + * functor(i, j, k, l, m, min(range_m - m, tile_m)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 5D grid. + * @param range_j the number of items to process along the second dimension + * of the 5D grid. + * @param range_k the number of items to process along the third dimension + * of the 5D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 5D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 5D grid. + * @param tile_m the maximum number of items along the fifth dimension of + * the 5D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_5d_tile_1d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t tile_m, + uint32_t flags = 0) { + pthreadpool_parallelize_5d_tile_1d( + threadpool, &libpthreadpool::detail::call_wrapper_5d_tile_1d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, range_m, tile_m, flags); +} + +/** + * Process items on a 5D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l += tile_l) + * for (size_t m = 0; m < range_m; m += tile_m) + * functor(i, j, k, l, m, + * min(range_l - l, tile_l), min(range_m - m, tile_m)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 5D grid. + * @param range_j the number of items to process along the second dimension + * of the 5D grid. + * @param range_k the number of items to process along the third dimension + * of the 5D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 5D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 5D grid. + * @param tile_l the maximum number of items along the fourth dimension of + * the 5D grid to process in one functor call. + * @param tile_m the maximum number of items along the fifth dimension of + * the 5D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_5d_tile_2d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t tile_l, size_t tile_m, + uint32_t flags = 0) { + pthreadpool_parallelize_5d_tile_2d( + threadpool, &libpthreadpool::detail::call_wrapper_5d_tile_2d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, range_m, tile_l, tile_m, flags); +} + +/** + * Process items on a 6D grid. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m++) + * for (size_t n = 0; n < range_n; n++) + * functor(i, j, k, l, m, n); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 6D grid. + * @param range_j the number of items to process along the second dimension + * of the 6D grid. + * @param range_k the number of items to process along the third dimension + * of the 6D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 6D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 6D grid. + * @param range_n the number of items to process along the sixth dimension + * of the 6D grid. + * @param tile_n the maximum number of items along the sixth dimension of + * the 6D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_6d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t range_n, uint32_t flags = 0) { + pthreadpool_parallelize_6d( + threadpool, &libpthreadpool::detail::call_wrapper_6d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, range_m, range_n, flags); +} + +/** + * Process items on a 6D grid with the specified maximum tile size along the + * last grid dimension. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m++) + * for (size_t n = 0; n < range_n; n += tile_n) + * functor(i, j, k, l, m, n, min(range_n - n, tile_n)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 6D grid. + * @param range_j the number of items to process along the second dimension + * of the 6D grid. + * @param range_k the number of items to process along the third dimension + * of the 6D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 6D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 6D grid. + * @param range_n the number of items to process along the sixth dimension + * of the 6D grid. + * @param tile_n the maximum number of items along the sixth dimension of + * the 6D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_6d_tile_1d(pthreadpool_t threadpool, + const T& functor, size_t range_i, + size_t range_j, size_t range_k, + size_t range_l, size_t range_m, + size_t range_n, size_t tile_n, + uint32_t flags = 0) { + pthreadpool_parallelize_6d_tile_1d( + threadpool, &libpthreadpool::detail::call_wrapper_6d_tile_1d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, range_m, range_n, tile_n, flags); +} + +/** + * Process items on a 6D grid with the specified maximum tile size along the + * last two grid dimensions. + * + * The function implements a parallel version of the following snippet: + * + * for (size_t i = 0; i < range_i; i++) + * for (size_t j = 0; j < range_j; j++) + * for (size_t k = 0; k < range_k; k++) + * for (size_t l = 0; l < range_l; l++) + * for (size_t m = 0; m < range_m; m += tile_m) + * for (size_t n = 0; n < range_n; n += tile_n) + * functor(i, j, k, l, m, n, + * min(range_m - m, tile_m), min(range_n - n, tile_n)); + * + * When the function returns, all items have been processed and the thread pool + * is ready for a new task. + * + * @note If multiple threads call this function with the same thread pool, the + * calls are serialized. + * + * @param threadpool the thread pool to use for parallelisation. If threadpool + * is NULL, all items are processed serially on the calling thread. + * @param functor the functor to call for each tile. + * @param range_i the number of items to process along the first dimension + * of the 6D grid. + * @param range_j the number of items to process along the second dimension + * of the 6D grid. + * @param range_k the number of items to process along the third dimension + * of the 6D grid. + * @param range_l the number of items to process along the fourth dimension + * of the 6D grid. + * @param range_m the number of items to process along the fifth dimension + * of the 6D grid. + * @param range_n the number of items to process along the sixth dimension + * of the 6D grid. + * @param tile_m the maximum number of items along the fifth dimension of + * the 6D grid to process in one functor call. + * @param tile_n the maximum number of items along the sixth dimension of + * the 6D grid to process in one functor call. + * @param flags a bitwise combination of zero or more optional flags + * (PTHREADPOOL_FLAG_DISABLE_DENORMALS or PTHREADPOOL_FLAG_YIELD_WORKERS) + */ +template +inline void pthreadpool_parallelize_6d_tile_2d( + pthreadpool_t threadpool, const T& functor, size_t range_i, size_t range_j, + size_t range_k, size_t range_l, size_t range_m, size_t range_n, + size_t tile_m, size_t tile_n, uint32_t flags = 0) { + pthreadpool_parallelize_6d_tile_2d( + threadpool, &libpthreadpool::detail::call_wrapper_6d_tile_2d, + const_cast(static_cast(&functor)), range_i, range_j, + range_k, range_l, range_m, range_n, tile_m, tile_n, flags); +} + +#endif /* __cplusplus */ + +#endif /* __PTHREADPOOL_INCLUDE_PTHREADPOOL_H_ */ diff --git a/deps/exla/cache/xla_extension/include/include/xnnpack.h b/deps/exla/cache/xla_extension/include/include/xnnpack.h new file mode 100644 index 0000000000000000000000000000000000000000..6c33a142de5b5d76531483bfe11d233463d7a75e --- /dev/null +++ b/deps/exla/cache/xla_extension/include/include/xnnpack.h @@ -0,0 +1,4760 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// Copyright 2019 Google LLC +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +// clang-format off + +#pragma once + +#include +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/// The number of bytes XNNPACK may read beyond array bounds. +/// The caller must allocate at least this many extra bytes after the tensor data passed to XNNPACK. +/// +/// Note: XNNPACK reads, but never writes beyond array bounds. +#if XNN_ARCH_HEXAGON +#define XNN_EXTRA_BYTES 128 +#else +#define XNN_EXTRA_BYTES 16 +#endif // XNN_ARCH_HEXAGON + +/// Maximum number of dimensions in tensor shape. +#define XNN_MAX_TENSOR_DIMS 6 + +/// A value ID that cannot be valid. +#define XNN_INVALID_VALUE_ID UINT32_MAX + +/// Allow sparse inference in a Runtime. +/// +/// Note: this flag is a hint to XNNPACK that it should consider sparse inference, but does not guarantee it. +#define XNN_FLAG_HINT_SPARSE_INFERENCE 0x00000001 + +/// Allow IEEE FP16 inference in a Runtime. +/// +/// Note: this flag hints XNNPACK to consider IEEE FP16 inference, but does not guarantee it. +#define XNN_FLAG_HINT_FP16_INFERENCE 0x00000002 + +/// Force IEEE FP16 inference in a Runtime, and fail if FP16 inference is not possible. +/// +/// Note: this flag guarantees that XNNPACK will use IEEE FP16 inference, or fail to create the Runtime object. +/// Warning: on x86 systems FP16 computations will be emulated at a substantial performance cost. +#define XNN_FLAG_FORCE_FP16_INFERENCE 0x00000004 + +/// Enable timing of each operator's runtime. +#define XNN_FLAG_BASIC_PROFILING 0x00000008 + +/// Deprecated +#define XNN_FLAG_JIT 0x00000010 + +/// The convolution operator represents a depthwise convolution, and use HWGo layout for filters. +#define XNN_FLAG_DEPTHWISE_CONVOLUTION 0x00000001 + +/// Assume transposed weights in a fully connected operator. +#define XNN_FLAG_TRANSPOSE_WEIGHTS 0x00000001 + +/// The operator assumes NHWC layout for the input, regardless of the output layout. +#define XNN_FLAG_INPUT_NHWC 0x00000002 + +/// Match "SAME" padding in TensorFlow. Exact padding values are computed dynamically depending on input size. +#define XNN_FLAG_TENSORFLOW_SAME_PADDING 0x00000004 + +/// Assume transposed weights in a batch matrix multiply operator. +#define XNN_FLAG_TRANSPOSE_B XNN_FLAG_TRANSPOSE_WEIGHTS + +/// Assume transposed input in a batch matrix multiply operator. +#define XNN_FLAG_TRANSPOSE_A 0x00000002 + +/// Implicitly flatten and reshape input of a Fully Connected operator into a 2D tensor. +#define XNN_FLAG_TENSORFLOW_RESHAPE_2D 0x00000004 + +/// Match behaviour of TensorFlow 1.x. +#define XNN_FLAG_TENSORFLOW_LEGACY_MODE 0x00000004 + +/// Static weights of the FP16 operator are in FP32 format. +#define XNN_FLAG_FP32_STATIC_WEIGHTS 0x00000008 + +/// Static biases of the FP16 operator are in FP32 format. +#define XNN_FLAG_FP32_STATIC_BIASES 0x00000080 + +/// Align corners of input and output images in resize operations. +#define XNN_FLAG_ALIGN_CORNERS 0x00000008 + +/// Yield worker threads of the thread pool to the system scheduler after the inference. +#define XNN_FLAG_YIELD_WORKERS 0x00000010 + +/// Use transient indirection buffer to reduce memory footprint +#define XNN_FLAG_TRANSIENT_INDIRECTION_BUFFER 0x00000020 + +/// Retain reduced dimensions with length 1. +#define XNN_FLAG_KEEP_DIMS 0x00000040 + +/// Indicates that length 1 dimensions should not be implicitly broadcasted if needed. +/// Operations that expect to broadcast length 1 dimensions to match a dimension with length != 1 +/// may fail with an error. +#define XNN_FLAG_NO_BROADCAST 0x00001000 + +/// This flag indicates that XNNPACK should attempt to produce numerically consistent results from a specific +/// build of XNNPACK. This causes XNNPACK to avoid using faster codepaths that are numerically inconsistent +/// with any other codepath that could be used in the same compiled XNNPACK library. +#define XNN_FLAG_SLOW_CONSISTENT_ARITHMETIC 0x00002000 + +/// The number of entries in an array of xnn_quantization_params that XNNPACK may read beyond array bounds. +/// The caller must allocate at least this many extra xnn_quantization_params before passing the array to XNNPACK. +/// +/// Note: XNNPACK reads, but never writes beyond array bounds. +#define XNN_EXTRA_QUANTIZATION_PARAMS 15 + +/// The minimum blocksize for blockwise quantized operators. +#define XNN_MIN_BLOCKSIZE 32 + +#ifdef __GNUC__ +#define XNN_DEPRECATED __attribute__((deprecated)) +#else +#define XNN_DEPRECATED +#endif + +struct xnn_quantization_params { + int32_t zero_point; + float scale; +}; + +/// Status code for any XNNPACK function call. +enum xnn_status { + /// The call succeeded, and all output arguments now contain valid data. + xnn_status_success = 0, + xnn_status_uninitialized = 1, + xnn_status_invalid_parameter = 2, + xnn_status_invalid_state = 3, + xnn_status_unsupported_parameter = 4, + xnn_status_unsupported_hardware = 5, + xnn_status_out_of_memory = 6, + xnn_status_reallocation_required = 7, + xnn_status_deprecated = 8, +}; + +struct xnn_allocator { + /// User-specified pointer that will be passed as-is to all functions in this structure. + void* context; + /// Pointer to a function to be called for general memory allocation. + /// + /// @param context - The user-specified pointer from xnn_allocator structure. + /// @param size - The size of the memory block to allocate, in bytes. + /// + /// @returns Pointer to the allocated memory block of at least @ref size bytes. + /// If allocation fails, the function must return NULL. + void* (*allocate)(void* context, size_t size); + /// Pointer to a function to be called for general memory re-allocation, i.e. to increase or shrink a previously + /// allocated memory block. The content of the old memory block is copied to the new memory block. + /// + /// @param context - The user-specified pointer from xnn_allocator structure. + /// @param pointer - Pointer to a memory block allocated by @ref allocate or @ref reallocate functions. Can be NULL. + /// If the pointer is NULL, the @ref reallocate call is equivalent to an @ref allocate call. + /// @param size - The new size of the memory block to allocate, in bytes. + /// + /// @returns Pointer to the newly allocated memory block of at least @ref size bytes with the content of the previous + /// memory block. + /// If allocation fails, the function must return NULL, but must not release the previous memory block. + void* (*reallocate)(void* context, void* pointer, size_t size); + /// Pointer to a function to be called for general memory de-allocation. + /// + /// @param context - The user-specified pointer from xnn_allocator structure. + /// @param pointer - Pointer to a memory block allocated by @ref allocate or @ref reallocate functions. Can be NULL. + /// If the pointer is NULL, the @ref deallocate call is a no-op. + void (*deallocate)(void* context, void* pointer); + /// Pointer to a function to be called for aligned memory allocation. + /// + /// @param context - The user-specified pointer from xnn_allocator structure. + /// @param alignment - The alignment of the memory block to allocate, in bytes. Alignment is always a power-of-2. + /// @param size - The size of the memory block to allocate, in bytes. + /// + /// @returns Pointer to the allocated memory block of at least @ref size bytes. + /// If allocation fails, the function must return NULL. + void* (*aligned_allocate)(void* context, size_t alignment, size_t size); + /// Pointer to a function to be called for aligned memory deallocation. + /// + /// @param context - The user-specified pointer from xnn_allocator structure. + /// @param pointer - Pointer to a memory block allocated by @ref aligned_allocate function. Can be NULL. + /// If the pointer is NULL, the @ref aligned_deallocate call is a no-op. + void (*aligned_deallocate)(void* context, void* pointer); +}; + +/// Initialize XNNPACK library. +/// +/// XNNPACK must be successfully initialized before use. During initialization, XNNPACK populates internal structures +/// depending on the host processor. Initialization can be time-consuming. +/// +/// @param[in] allocator - structure with function pointers to be use for memory allocation and de-allocation. +/// If this argument is NULL, system-provided memory management functions (e.g. malloc/free) +/// will be used. +/// +/// @retval xnn_status_success - XNNPACK is successfully initialized and ready to use. +/// @retval xnn_status_out_of_memory - initialization failed due to out-of-memory condition. +/// @retval xnn_status_unsupported_hardware - initialization failed because the host processor does not satisfy the +/// minimum hardware requirements for XNNPACK. E.g. this may happen on x86 +/// processors without SSE2 extension, or on 32-bit ARM processors without +/// the NEON SIMD extension. +enum xnn_status xnn_initialize(const struct xnn_allocator* allocator); + +/// Deinitialize XNNPACK library. +/// +/// Currently, this does nothing. +/// +/// @retval xnn_status_success - deinitialization call succeeded. +enum xnn_status xnn_deinitialize(void); + +/// Get the microkernel implementation build identifier's data. +/// +/// That identifier will be unique for the current set of microkernels implementations. +/// +/// @returns A pointer to the current identifier's data. +const void* xnn_experimental_get_build_identifier_data(); + +/// Get the microkernel implementation build identifier's data size. +/// +/// @returns The size in bytes of the identifier's data. +size_t xnn_experimental_get_build_identifier_size(); + +/// Check whether the given data matches this version's identifier. +/// +/// @returns The size in bytes of the identifier's data. +bool xnn_experimental_check_build_identifier(const void* data, size_t size); + +/// Subgraph is an abstract representation of a neural network model. +/// Subgraph objects are used to define Values (tensors) and Nodes (operators) comprising the model. +typedef struct xnn_subgraph* xnn_subgraph_t; + +/// Create a empty Subgraph object. +/// +/// @param external_value_ids - number of Value IDs to reserve for communication with external graph representation. +/// The Subgraph object would avoid creating internal Value IDs in the +/// [0, reserved_value_ids-1] range. +/// @param flags - binary features of the subgraph. No supported flags are currently defined. +/// @param subgraph_out - pointer to the variable that will be initialized with a handle to the Subgraph object upon +/// successful return. +enum xnn_status xnn_create_subgraph( + uint32_t external_value_ids, + uint32_t flags, + xnn_subgraph_t* subgraph_out); + +/// Destroy a Subgraph object, as well as Values, and Nodes associated with the subgraph. +/// +/// @param subgraph - the Subgraph object to destroy. +enum xnn_status xnn_delete_subgraph( + xnn_subgraph_t subgraph); + +#define XNN_VALUE_FLAG_EXTERNAL_INPUT 0x00000001 +#define XNN_VALUE_FLAG_EXTERNAL_OUTPUT 0x00000002 +#define XNN_VALUE_FLAG_PERSISTENT 0x00000004 + +#define XNN_INVALID_VALUE_ID UINT32_MAX + +/// Type of elements in a Value object. +enum xnn_datatype { + /// Invalid data type. Valid Values never have this datatype. + xnn_datatype_invalid = 0, + /// IEEE754 single-precision floating-point. + xnn_datatype_fp32 = 1, + /// IEEE754 half-precision floating-point. + xnn_datatype_fp16 = 2, + /// Quantized 8-bit signed integer with shared per-Value quantization + /// parameters. + xnn_datatype_qint8 = 3, + /// Quantized 8-bit unsigned integer with shared per-Value quantization + /// parameters. + xnn_datatype_quint8 = 4, + /// Quantized 32-bit signed integer with shared per-Value quantization + /// parameters. + xnn_datatype_qint32 = 5, + /// Quantized 8-bit signed integer with shared per-channel quantization + /// parameters. + xnn_datatype_qcint8 = 6, + /// Quantized 32-bit signed integer with shared per-channel quantization + /// parameters. + xnn_datatype_qcint32 = 7, + /// Quantized 4-bit signed integer with shared per-channel quantization + /// parameters. + xnn_datatype_qcint4 = 8, + /// Dynamically quantized 8-bit signed integer with per-batch quantization + /// parameters. + xnn_datatype_qdint8 = 9, + /// Dynamically quantized 8-bit signed integers packed with their per-row + /// quantization parameters. + xnn_datatype_qpint8 = 10, + /// 32-bit signed integers. + xnn_datatype_int32 = 11, + /// Quantized 4-bit signed integer with shared per-channel-block quantization + /// parameters. + xnn_datatype_qbint4 = 12, + /// IEEE754 single-precision packed floating-point. + xnn_datatype_pfp32 = 13, + /// BFloat16, i.e. the upper 16 bits of a float32. + xnn_datatype_bf16 = 14, + /// Dynamically quantized 8-bit unsigned integer with per-batch quantization + /// parameters. + xnn_datatype_qduint8 = 15, + /// IEEE754 half-precision packed floating-point. + xnn_datatype_pfp16 = 16, + /// Packed quantized 8-bit unsigned integer with shared per-Value quantization + /// parameters. + xnn_datatype_pqint8 = 17, +}; + +/// Define a tensor-type Value and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Value. +/// @param datatype - type of the tensor elements. +/// @param num_dims - number of dimensions in the shape. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +/// @param data - pointer to static data used for tensor initialization. If the tensor is not statically initialized, +/// this pointer must be is NULL. If non-NULL, the life-time of the static data must exceed the life-time +/// of the Subgraph object, and of any Runtime objects created from the Subgraph. +/// @param external_id - external ID for the Value. The ID must be within the range of reversed Value IDs specified on +/// the Subgraph creation. If the external ID is XNN_INVALID_VALUE_ID, an internal ID will be +/// created for the Value. +/// @param flags - binary features of the Value. Supported values are any combination of XNN_VALUE_FLAG_EXTERNAL_INPUT +/// and XNN_VALUE_FLAG_EXTERNAL_OUTPUT. +/// @param id_out - pointer to the variable that will be initialized with the Value ID upon successful return. If a +/// valid @a external_id was provided, the variable will be initialized with the @a external_id value. +enum xnn_status xnn_define_tensor_value( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + size_t num_dims, + const size_t* dims, + const void* data, + uint32_t external_id, + uint32_t flags, + uint32_t* id_out); + +/// Define a quantized tensor-type Value and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Value. +/// @param datatype - type of the tensor elements. +/// @param zero_point - offset from zero to subtract from the quantized elements in the Value. +/// @param scale - multiplication factor to convert quantized elements to real representation. +/// @param num_dims - number of dimensions in the shape. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +/// @param data - pointer to static data used for tensor initialization. If the tensor is not statically initialized, +/// this pointer must be is NULL. If non-NULL, the life-time of the static data must exceed the life-time +/// of the Subgraph object, and of any Runtime objects created from the Subgraph. +/// @param external_id - external ID for the Value. The ID must be within the range of reversed Value IDs specified on +/// the Subgraph creation. If the external ID is XNN_INVALID_VALUE_ID, an internal ID will be +/// created for the Value. +/// @param flags - binary features of the Value. Supported values are any combination of XNN_VALUE_FLAG_EXTERNAL_INPUT +/// and XNN_VALUE_FLAG_EXTERNAL_OUTPUT. +/// @param id_out - pointer to the variable that will be initialized with the Value ID upon successful return. If a +/// valid @a external_id was provided, the variable will be initialized with the @a external_id value. +enum xnn_status xnn_define_quantized_tensor_value( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + int32_t zero_point, + float scale, + size_t num_dims, + const size_t* dims, + const void* data, + uint32_t external_id, + uint32_t flags, + uint32_t* id_out); + +enum xnn_status xnn_define_channelwise_quantized_tensor_value( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + const float* scale, + size_t num_dims, + size_t channel_dim, + const size_t* dims, + const void* data, + uint32_t external_id, + uint32_t flags, + uint32_t* id_out); + +/// Validate the dimensions, channel_dim, zero point, datatype, and scale of a quantized tensor-type. +/// +/// @param datatype - type of the tensor elements. +/// @param zero_point - offset from zero to subtract from the quantized elements in the Value. +/// @param scale - multiplication factor to convert quantized elements to real representation. +/// @param num_dims - number of dimensions in the shape. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +enum xnn_status xnn_validate_quantized_tensor( + enum xnn_datatype datatype, + int32_t zero_point, + float scale, + size_t num_dims, + const size_t* dims); + +/// Validate the dimensions, channel_dim, zero point, datatype, and scales of a channelwise quantized tensor-type. +/// +/// @param datatype - type of the tensor elements. +/// @param zero_point - offset from zero to subtract from the quantized elements in the Value. +/// @param scale - per-channel multiplication factors to convert quantized elements to real representation. +/// @param num_dims - number of dimensions in the shape. +/// @param channel_dim - index of the channel dimension in the tensor with per-channel quantization parameters. +/// Typically this is the first dimension (dimension #0) of the filter tensors in the Convolution, +/// Deconvolution, and Fully Connected operators and the last dimension of the filter tensors in +/// the Depthwise Convolution operators. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +enum xnn_status xnn_validate_channelwise_quantized_tensor( + enum xnn_datatype datatype, + int32_t zero_point, + const float* scale, + size_t num_dims, + size_t channel_dim, + const size_t* dims); + +/// Define a channelwise quantized tensor-type Value and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Value. +/// @param datatype - type of the tensor elements. +/// @param zero_point - offset from zero to subtract from the quantized elements in the Value. +/// @param scale - per-channel multiplication factors to convert quantized elements to real representation. +/// @param num_dims - number of dimensions in the shape. +/// @param channel_dim - index of the channel dimension in the tensor with per-channel quantization parameters. +/// Typically this is the first dimension (dimension #0) of the filter tensors in the Convolution, +/// Deconvolution, and Fully Connected operators and the last dimension of the filter tensors in +/// the Depthwise Convolution operators. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +/// @param data - pointer to static data used for tensor initialization. If the tensor is not statically initialized, +/// this pointer must be is NULL. If non-NULL, the life-time of the static data must exceed the life-time +/// of the Subgraph object, and of any Runtime objects created from the Subgraph. +/// @param external_id - external ID for the Value. The ID must be within the range of reversed Value IDs specified on +/// the Subgraph creation. If the external ID is XNN_INVALID_VALUE_ID, an internal ID will be +/// created for the Value. +/// @param flags - binary features of the Value. Supported values are any combination of XNN_VALUE_FLAG_EXTERNAL_INPUT +/// and XNN_VALUE_FLAG_EXTERNAL_OUTPUT. +/// @param id_out - pointer to the variable that will be initialized with the Value ID upon successful return. If a +/// valid @a external_id was provided, the variable will be initialized with the @a external_id value. +enum xnn_status xnn_define_channelwise_quantized_tensor_value_v2( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + int32_t zero_point, + const float* scale, + size_t num_dims, + size_t channel_dim, + const size_t* dims, + const void* data, + uint32_t external_id, + uint32_t flags, + uint32_t* id_out); + +/// Define a blockwise quantized tensor-type Value and add it to a Subgraph. +/// @param block_size - size of a block in the tensor with blockwise quantization parameters. Block is defined as +/// number of input channel element per output channel. +/// For Fully connected operators with 2d filters of size [output_channels, input_channels], +/// expecting number of scale values to be = output_channels * (input_channels / block_size). +/// @param scale_type - datatype of the scale. bf6 & fp16 are supported, +/// however, only 7 mantisaa bits are used for scale calculation. +enum xnn_status xnn_define_blockwise_quantized_tensor_value_v2( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + int32_t zero_point, + const void* scale, + size_t num_dims, + size_t channel_dim, + size_t block_size, + const size_t* dims, + const void* data, + uint32_t external_id, + uint32_t flags, + enum xnn_datatype scale_type, + uint32_t* id_out); + +enum xnn_status xnn_define_blockwise_quantized_tensor_value( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + int32_t zero_point, + const uint16_t* scale, + size_t num_dims, + size_t channel_dim, + size_t block_size, + const size_t* dims, + const void* data, + uint32_t external_id, + uint32_t flags, + uint32_t* id_out); + +/// Define a dynamically quantized tensor-type Value and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Value. +/// @param datatype - type of the tensor elements. +/// @param num_dims - number of dimensions in the shape. +/// @param num_non_batch_dims - number of non-batch dimensions in the shape. The leading (num_dims - num_non_batch_dims) +/// dimensions will be flattened and treated as batch size. A set of quantization parameters +/// will be calculated for each batch element. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +/// @param external_id - external ID for the Value. The ID must be within the range of reversed Value IDs specified on +/// the Subgraph creation. If the external ID is XNN_INVALID_VALUE_ID, an internal ID will be +/// created for the Value. +/// @param flags - binary features of the Value. No supported flags are currently defined. +/// @param id_out - pointer to the variable that will be initialized with the Value ID upon successful return. If a +/// valid @a external_id was provided, the variable will be initialized with the @a external_id value. +enum xnn_status xnn_define_dynamically_quantized_tensor_value( + xnn_subgraph_t subgraph, + enum xnn_datatype datatype, + size_t num_dims, + size_t num_nonbatch_dims, + const size_t* dims, + uint32_t external_id, + uint32_t flags, + uint32_t* id_out); + +/// Type of unary operation +enum xnn_unary_operator { + xnn_unary_invalid = -1, + xnn_unary_abs, + // This is a GELU approximation that mimics the approximation: + // + // 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3))) + // + // which differs sufficiently from the exact GELU (`xnn_unary_gelu` below) to + // cause problems in some models. Note that both the approximation and the + // exact GELU use the same order rational approximation polynomials and are + // therefore both equally fast. + xnn_unary_approxgelu, + xnn_unary_bankers_rounding, + xnn_unary_ceiling, + xnn_unary_clamp, + xnn_unary_convert, + xnn_unary_cosine, + xnn_unary_elu, + xnn_unary_exp, + xnn_unary_floor, + xnn_unary_gelu, + xnn_unary_hardswish, + xnn_unary_leaky_relu, + xnn_unary_log, + xnn_unary_negate, + xnn_unary_reciprocal_square_root, + xnn_unary_sigmoid, + xnn_unary_sine, + xnn_unary_square_root, + xnn_unary_square, + xnn_unary_tanh, + // The following operators are experimental and may be removed. + xnn_unary_bitwise_not, + xnn_unary_count_leading_zeros, + xnn_unary_cube_root, + xnn_unary_popcount, + xnn_unary_sign, +}; + +/// Parameters for xnn_define_unary +union xnn_unary_params { + struct { + /// lower bound for clipping output values. + float min; + /// upper bound for clipping output values. + float max; + } clamp; + struct { + /// scale factor for negative input elements. + float alpha; + } elu; + struct { + /// scale factor for negative input elements. + float negative_slope; + } leaky_relu; +}; + +/// Define a unary operator Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param operator - type of unary operator to define. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param params - parameters to be interpreted by the specific operator type. +/// @param flags - binary features of the Node. No supported flags are currently defined. +enum xnn_status xnn_define_unary( + xnn_subgraph_t subgraph, + enum xnn_unary_operator type, + const union xnn_unary_params* params, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Convert Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Convert Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_convert( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Convolution Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_padding_top - implicit zero-padding above 2D input data. Must be 0 if XNN_FLAG_TENSORFLOW_SAME_PADDING +/// flag is specified. +/// @param input_padding_right - implicit zero-padding to the right of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_bottom - implicit zero-padding below 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_left - implicit zero-padding to the left of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param kernel_height - kernel (filter) height. +/// @param kernel_width - kernel (filter) width. +/// @param subsampling_height - height of subsampling region for convolution output (convolution height stride). +/// @param subsampling_width - width of subsampling region for convolution output (convolution width stride). +/// @param dilation_height - dilation of kernel elements along the height dimension. +/// @param dilation_width - dilation of kernel elements along the width dimension. +/// @param groups - number of convolution groups. +/// @param group_input_channels - number of input channels per group. +/// @param group_output_channels - number of output channels per group. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, groups * group_input_channels] dimensions +/// @param filter_id - Value ID for the filter tensor. The filter tensor must ge a 4D tensor defined in the @a subgraph +/// with [groups * group_output_channels, kernel_height, kernel_width, group_input_channels] +/// dimensions. +/// @param bias_id - Value ID for the bias tensor, or XNN_INVALID_VALUE_ID for a 2D Convolution Node without a bias. If +/// present, the bias tensor must be a 1D tensor defined in the @a subgraph with [groups * +/// group_output_channels] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, OH, OW, groups * group_output_channels] dimensions. +/// @param flags - binary features of the 2D Convolution Node. The only currently supported values is +/// XNN_FLAG_TENSORFLOW_SAME_PADDING. +enum xnn_status xnn_define_convolution_2d( + xnn_subgraph_t subgraph, + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + float output_min, + float output_max, + uint32_t input_id, + uint32_t filter_id, + uint32_t bias_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Deconvolution (Transposed Convolution) Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param padding_top - implicit padding above 2D output data. +/// @param padding_right - implicit padding to the right of 2D output data. +/// @param padding_bottom - implicit padding below 2D output data. +/// @param padding_left - implicit padding to the left of 2D output data. +/// @param adjustment_height - additional elements in the bottom of the 2D output data. +/// @param adjustment_width - additional elements to the right of the 2D output data. +/// @param kernel_height - kernel (filter) height. +/// @param kernel_width - kernel (filter) width. +/// @param upsampling_height - height of upsampling region for deconvolution input (deconvolution height stride). +/// @param upsampling_width - width of upsampling region for deconvolution input (deconvolution width stride). +/// @param dilation_height - dilation of kernel elements along the height dimension. +/// @param dilation_width - dilation of kernel elements along the width dimension. +/// @param groups - number of convolution groups. +/// @param group_input_channels - number of input channels per group. +/// @param group_output_channels - number of output channels per group. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, groups * group_input_channels] dimensions +/// @param filter_id - Value ID for the filter tensor. The filter tensor must ge a 4D tensor defined in the @a subgraph +/// with [groups * group_output_channels, kernel_height, kernel_width, group_input_channels] +/// dimensions. +/// @param bias_id - Value ID for the bias tensor, or XNN_INVALID_VALUE_ID for a 2D Convolution Node without a bias. If +/// present, the bias tensor must be a 1D tensor defined in the @a subgraph with +/// [groups * group_output_channels] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, OH, OW, groups * group_output_channels] dimensions. +/// @param flags - binary features of the 2D Deconvolution Node. No supported flags are currently defined. +enum xnn_status xnn_define_deconvolution_2d( + xnn_subgraph_t subgraph, + uint32_t padding_top, + uint32_t padding_right, + uint32_t padding_bottom, + uint32_t padding_left, + uint32_t adjustment_height, + uint32_t adjustment_width, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t upsampling_height, + uint32_t upsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + float output_min, + float output_max, + uint32_t input_id, + uint32_t filter_id, + uint32_t bias_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Depthwise Convolution Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_padding_top - implicit zero-padding above 2D input data. Must be 0 if XNN_FLAG_TENSORFLOW_SAME_PADDING +/// flag is specified. +/// @param input_padding_right - implicit zero-padding to the right of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_bottom - implicit zero-padding below 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_left - implicit zero-padding to the left of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param kernel_height - kernel (filter) height. +/// @param kernel_width - kernel (filter) width. +/// @param subsampling_height - height of subsampling region for convolution output (convolution height stride). +/// @param subsampling_width - width of subsampling region for convolution output (convolution width stride). +/// @param dilation_height - dilation of kernel elements along the height dimension. +/// @param dilation_width - dilation of kernel elements along the width dimension. +/// @param depth_multiplier - ratio of output channels to input channels. +/// @param input_channels - number of input channels. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, input_channels] dimensions +/// @param filter_id - Value ID for the filter tensor. The filter tensor must ge a 4D tensor defined in the @a subgraph +/// with [1, kernel_height, kernel_width, input_channels * depth_multiplier] dimensions. +/// @param bias_id - Value ID for the bias tensor, or XNN_INVALID_VALUE_ID for a 2D Depthwise Convolution Node without +/// a bias. If present, the bias tensor must be a 1D tensor defined in the @a subgraph with +/// [input_channels * depth_multiplier] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, OH, OW, input_channels * depth_multiplier] dimensions. +/// @param flags - binary features of the 2D Depthwise Convolution Node. The only currently supported values is +/// XNN_FLAG_TENSORFLOW_SAME_PADDING. +enum xnn_status xnn_define_depthwise_convolution_2d( + xnn_subgraph_t subgraph, + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t depth_multiplier, + size_t input_channels, + float output_min, + float output_max, + uint32_t input_id, + uint32_t filter_id, + uint32_t bias_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Depth To Space Node 2D and add it to a Subgraph. +/// +/// The Depth To Space 2D Node rearranges data from depth into blocks of spatial data (a reverse transform to +/// Space To Depth). For a given input pixel, an output square of pixels with side @a block_size is formed from values +/// in the corresponding number of its channels. The output depth is therefore @a block_size x @a block_size times +/// smaller than that of the input. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param block_size - the size of the spatial block. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, OC * block_size * block_size] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH * block_size, IW * block_size, OC] dimensions. +/// @param flags - binary features of the input_channels Node. No supported flags are currently defined. +enum xnn_status xnn_define_depth_to_space_2d( + xnn_subgraph_t subgraph, + uint32_t block_size, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +enum xnn_status xnn_define_depth_to_space( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t block_size, + uint32_t flags); + +/// Define a 1D Global Average Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a dense tensor with 2 or more dimensions +/// defined in the @a subgraph. Averaging is performed across the second-innermost dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a dense tensor with 2 or more +/// dimensions defined in the @a subgraph. +/// @param flags - binary features of the 1D Global Average Pooling Node. The only currently supported value is +/// XNN_FLAG_KEEP_DIMS. +XNN_DEPRECATED enum xnn_status xnn_define_global_average_pooling_1d( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Global Average Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a dense tensor with 3 or more dimensions +/// defined in the @a subgraph. Averaging is performed across the second- and third-innermost +/// dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a dense tensor with 3 or more +/// dimensions defined in the @a subgraph. +/// @param flags - binary features of the 2D Global Average Pooling Node. The only currently supported value is +/// XNN_FLAG_KEEP_DIMS. +XNN_DEPRECATED enum xnn_status xnn_define_global_average_pooling_2d( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 1D Global Sum Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a dense tensor with 2 or more dimensions +/// defined in the @a subgraph. Averaging is performed across the second-innermost dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a dense tensor with 2 or more +/// dimensions defined in the @a subgraph. +/// @param flags - binary features of the 1D Global Sum Pooling Node. The only currently supported value is +/// XNN_FLAG_KEEP_DIMS. +XNN_DEPRECATED enum xnn_status xnn_define_global_sum_pooling_1d( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Global Sum Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a dense tensor with 3 or more dimensions +/// defined in the @a subgraph. Averaging is performed across the second- and third-innermost +/// dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a dense tensor with 3 or more +/// dimensions defined in the @a subgraph. +/// @param flags - binary features of the 2D Global Sum Pooling Node. The only currently supported value is +/// XNN_FLAG_KEEP_DIMS. +XNN_DEPRECATED enum xnn_status xnn_define_global_sum_pooling_2d( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Average Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_padding_top - implicit zero-padding above 2D input data. Must be 0 if XNN_FLAG_TENSORFLOW_SAME_PADDING +/// flag is specified. +/// @param input_padding_right - implicit zero-padding to the right of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_bottom - implicit zero-padding below 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_left - implicit zero-padding to the left of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param pooling_height - pooling (kernel) height. +/// @param pooling_width - pooling (kernel) width. +/// @param stride_height - displacing of the pooling window in the vertical dimension of the input pixels corresponding +/// to vertically adjacent output pixels. +/// @param stride_width - displacing of the pooling window in the horizontal dimension of the input pixels corresponding +/// to horizontally adjacent output pixels. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, channels] dimensions +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, OH, OW, channels] dimensions. +/// @param flags - binary features of the 2D Average Pooling Node. The only currently supported values is +/// XNN_FLAG_TENSORFLOW_SAME_PADDING. +enum xnn_status xnn_define_average_pooling_2d( + xnn_subgraph_t subgraph, + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Fully Connected Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in the +/// @a subgraph. If XNN_FLAG_TENSORFLOW_RESHAPE_2D is not specified, the input tensor must be at least +/// 1D and its last dimension must match the last dimension of the filter tensor. In particular, if +/// input is a 2D tensor, it must have [batch_size, input_channels] dimensions. +/// If XNN_FLAG_TENSORFLOW_RESHAPE_2D is specified, the number of elements in the input tensor must be +/// divisible by the input_channels. The tensor will be first flattened into a 1D tensor of +/// [num_input_elements] dimensions, then reshaped into a 2D tensor of +/// [num_input_elements / input_channels, input_channels] dimensions where num_input_elements is the +/// total number of elements in the input tensor. +/// @param filter_id - Value ID for the filter tensor. The filter tensor must a 2D tensor defined in the @a subgraph. +/// If the XNN_FLAG_TRANSPOSE_WEIGHTS flag is not specified, the filter tensor must have +/// [output_channels, input_channels] dimensions. If the XNN_FLAG_TRANSPOSE_WEIGHTS flag is +/// specified, the filter tensor must have [input_channels, output_channels] dimensions. +/// @param bias_id - Value ID for the bias tensor, or XNN_INVALID_VALUE_ID for a Fully Connected Node without a bias. +/// If present, the bias tensor must be a 1D tensor defined in the @a subgraph with [output_channels] +/// dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph. +/// If XNN_FLAG_TENSORFLOW_RESHAPE_2D is not specified, the output tensor must have the same +/// dimensionality as the input tensor, all its dimensions but the last one must match the +/// corresponding dimensions of the input tensor, and the last dimensions of the output tensor must +/// match the first dimension of the filter tensor. In particular, if input is a 2D tensor, output +/// must be a 2D tensor of [batch_size, output_channels] dimensions. +/// If XNN_FLAG_TENSORFLOW_RESHAPE_2D is specified, output must be a 2D tensor of +/// [num_input_elements / input_channels, output_channels] dimensions where num_input_elements is the +/// total number of elements in the input tensor. +/// @param flags - binary features of the Fully Connected Node. The only currently supported values are +/// XNN_FLAG_TENSORFLOW_RESHAPE_2D and XNN_FLAG_TRANSPOSE_WEIGHTS. +enum xnn_status xnn_define_fully_connected( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t filter_id, + uint32_t bias_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Sparse Fully Connected Node and add it to a Subgraph. +/// +/// This operator is experimental, and will be removed in the future. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in the +/// @a subgraph. If XNN_FLAG_TENSORFLOW_RESHAPE_2D is not specified, the input tensor must be at least +/// 1D and its last dimension must match the last dimension of the filter tensor. In particular, if +/// input is a 2D tensor, it must have [batch_size, input_channels] dimensions. +/// If XNN_FLAG_TENSORFLOW_RESHAPE_2D is specified, the number of elements in the input tensor must be +/// divisible by the input_channels. The tensor will be first flattened into a 1D tensor of +/// [num_input_elements] dimensions, then reshaped into a 2D tensor of +/// [num_input_elements / input_channels, input_channels] dimensions where num_input_elements is the +/// total number of elements in the input tensor. +/// @param filter_id - Value ID for the filter tensor. The filter tensor must a 2D tensor defined in the @a subgraph. +/// If the XNN_FLAG_TRANSPOSE_WEIGHTS flag is not specified, the filter tensor must have +/// [output_channels, input_channels] dimensions. If the XNN_FLAG_TRANSPOSE_WEIGHTS flag is +/// specified, the filter tensor must have [input_channels, output_channels] dimensions. +/// @param bias_id - Value ID for the bias tensor, or XNN_INVALID_VALUE_ID for a Fully Connected Node without a bias. +/// If present, the bias tensor must be a 1D tensor defined in the @a subgraph with [output_channels] +/// dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph. +/// If XNN_FLAG_TENSORFLOW_RESHAPE_2D is not specified, the output tensor must have the same +/// dimensionality as the input tensor, all its dimensions but the last one must match the +/// corresponding dimensions of the input tensor, and the last dimensions of the output tensor must +/// match the first dimension of the filter tensor. In particular, if input is a 2D tensor, output +/// must be a 2D tensor of [batch_size, output_channels] dimensions. +/// If XNN_FLAG_TENSORFLOW_RESHAPE_2D is specified, output must be a 2D tensor of +/// [num_input_elements / input_channels, output_channels] dimensions where num_input_elements is the +/// total number of elements in the input tensor. +/// @param flags - binary features of the Fully Connected Node. The only currently supported values are +/// XNN_FLAG_TENSORFLOW_RESHAPE_2D and XNN_FLAG_TRANSPOSE_WEIGHTS. +enum xnn_status xnn_define_fully_connected_sparse( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t filter_id, + uint32_t bias_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Max Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_padding_top - implicit zero-padding above 2D input data. Must be 0 if XNN_FLAG_TENSORFLOW_SAME_PADDING +/// flag is specified. +/// @param input_padding_right - implicit zero-padding to the right of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_bottom - implicit zero-padding below 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param input_padding_left - implicit zero-padding to the left of 2D input data. Must be 0 if +/// XNN_FLAG_TENSORFLOW_SAME_PADDING flag is specified. +/// @param pooling_height - pooling (kernel) height. +/// @param pooling_width - pooling (kernel) width. +/// @param stride_height - displacing of the pooling window in the vertical dimension of the input pixels corresponding +/// to vertically adjacent output pixels. +/// @param stride_width - displacing of the pooling window in the horizontal dimension of the input pixels corresponding +/// to horizontally adjacent output pixels. +/// @param dilation_height - dilation of pooling elements along the height dimension. +/// @param dilation_width - dilation of pooling elements along the width dimension. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, channels] dimensions +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, OH, OW, channels] dimensions. +/// @param flags - binary features of the 2D Max Pooling Node. The only currently supported values is +/// XNN_FLAG_TENSORFLOW_SAME_PADDING. +enum xnn_status xnn_define_max_pooling_2d( + xnn_subgraph_t subgraph, + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D ArgMax Pooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_padding_top - implicit zero-padding above 2D input data. +/// @param input_padding_right - implicit zero-padding to the right of 2D input data. +/// @param input_padding_bottom - implicit zero-padding below 2D input data. +/// @param input_padding_left - implicit zero-padding to the left of 2D input data. +/// @param pooling_height - pooling (kernel) height. Vertical stride between pooling regions match this value. +/// @param pooling_width - pooling (kernel) width. Horizontal stride between pooling regions match this value. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, channels] dimensions +/// @param output_value_id - Value ID for the output tensor with the maximum values in the pools. The output tensor must +/// be a 4D tensor defined in the @a subgraph with [N, OH, OW, channels] dimensions. +/// @param output_index_id - Value ID for the output tensor with the indexes of the maximum values in the pools. The +/// output tensor must be a 4D tensor defined in the @a subgraph with [N, OH, OW, channels] +/// dimensions. +/// @param flags - binary features of the 2D ArgMax Pooling Node. No supported flags are currently defined. +enum xnn_status xnn_define_argmax_pooling_2d( + xnn_subgraph_t subgraph, + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t input_id, + uint32_t output_value_id, + uint32_t output_index_id, + uint32_t flags); + +/// Define a 2D UnPooling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param padding_top - implicit padding above 2D output data. +/// @param padding_right - implicit padding to the right of 2D output data. +/// @param padding_bottom - implicit padding below 2D output data. +/// @param padding_left - implicit padding to the left of 2D output data. +/// @param pooling_height - height of the pooling window. +/// @param pooling_width - width of the pooling window. +/// @param input_value_id - Value ID for the input tensor with the max-pooling values to invert. The input value tensor +/// must be a 4D tensor defined in the @a subgraph with [N, IH, IW, channels] dimensions. +/// @param input_index_id - Value ID for the input tensor with the indices of the per-pool maximum values produced by +/// a 2D UnPooling Node. The input tensor must be a 4D tensor defined in the @a subgraph with +/// [N, IH, IW, channels] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, OH, OW, channels] dimensions. +/// @param flags - binary features of the 2D UnPooling Node. No supported flags are currently defined. +enum xnn_status xnn_define_unpooling_2d( + xnn_subgraph_t subgraph, + uint32_t padding_top, + uint32_t padding_right, + uint32_t padding_bottom, + uint32_t padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t input_value_id, + uint32_t input_index_id, + uint32_t output_id, + uint32_t flags); + +enum xnn_binary_operator { + xnn_binary_invalid = -1, + xnn_binary_add, + xnn_binary_subtract, + xnn_binary_multiply, + xnn_binary_divide, + xnn_binary_maximum, + xnn_binary_minimum, + xnn_binary_copysign, + xnn_binary_squared_difference, + xnn_binary_prelu, + // The following operators are experimental and may be removed. + xnn_binary_modulus, + xnn_binary_atan2, + xnn_binary_pow, + xnn_binary_bitwise_and, + xnn_binary_bitwise_or, + xnn_binary_bitwise_xor, + xnn_binary_shift_left, + xnn_binary_shift_right_logical, + xnn_binary_shift_right_arithmetic, +}; + +struct xnn_binary_params { + /// lower bound for clipping output values. + double output_min; + /// upper bound for clipping output values. + double output_max; +}; + +/// Define a 2-Input binary operator Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param type - Type of operator to apply to the two inputs. +/// @param params - Optional parameters for the operator. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Node. The only flag supported is XNN_FLAG_NO_BROADCAST, indicating that the +/// binary operator can assume that no broadcasting is required. +enum xnn_status xnn_define_binary( + xnn_subgraph_t subgraph, + enum xnn_binary_operator type, + const struct xnn_binary_params* params, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2-Input Add Node and add it to a Subgraph. +/// +/// The 2-Input Add Node computes elementwise addition of two tensor inputs with numpy broadcasting rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Add Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_add2( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2-Input Multiply Node and add it to a Subgraph. +/// +/// The 2-Input Multiply Node computes elementwise multiplication of two tensor inputs with numpy broadcasting rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Multiply Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_multiply2( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +// Cap operations applied to logits (Q * K) of attention operator. +enum xnn_attention_logits_cap_type { + // No capping. + xnn_attention_logits_cap_type_none = 0, + // Cap the absolute values of logits by tanh: tanh(logits / cap) * cap + xnn_attention_logits_cap_type_tanh +}; + +// Params when the cap type is xnn_attention_logits_cap_type_tanh. +struct xnn_attention_logits_cap_tanh_params { + float cap; +}; + +/// Define a Subtract Node and add it to a Subgraph. +/// +/// The Subtract Node computes elementwise subtraction of two tensor inputs with numpy broadcasting rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Subtract Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_subtract( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Divide Node and add it to a Subgraph. +/// +/// The Divide Node computes elementwise division of two tensor inputs with numpy broadcasting rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Divide Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_divide( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2-Input Maximum Node and add it to a Subgraph. +/// +/// The 2-Input Maximum Node computes elementwise maximum of two tensor inputs with numpy broadcasting rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Maximum Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_maximum2( + xnn_subgraph_t subgraph, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2-Input Minimum Node and add it to a Subgraph. +/// +/// The 2-Input Minimum Node computes elementwise minimum of two tensor inputs with numpy broadcasting rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Minimum Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_minimum2( + xnn_subgraph_t subgraph, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Squared Difference Node and add it to a Subgraph. +/// +/// The Squared Difference Node computes elementwise squared difference of two tensor inputs with numpy broadcasting +/// rules. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the second +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an M-dimensional tensor defined in +/// the @a subgraph with each dimension either equal to the corresponding dimension of the first +/// input, or equal to 1. In the latter case, the elements of the input tensor are broadcasted along +/// that dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be a max(N,M)-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the maximum between the corresponding dimension +/// of the two inputs. +/// @param flags - binary features of the Squared Difference Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_squared_difference( + xnn_subgraph_t subgraph, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Constant Pad Node with static padding specification and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param pre_paddings - number of padding elements to insert before input elements for every dimension. This array +/// must have as many elements as the number of dimensions in the input tensor. +/// @param post_paddings - number of padding elements to insert after input elements for every dimension. This array +/// must have as many elements as the number of dimensions in the input tensor. +/// @param padding_value - constant value used to initialize padding elements. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor with padding. +/// @param flags - binary features of the Constant Pad Node. No supported flags are currently defined. +enum xnn_status xnn_define_static_constant_pad( + xnn_subgraph_t subgraph, + const size_t* pre_paddings, + const size_t* post_paddings, + float padding_value, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Expand Dims Node with and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_new_axes - number of new axes of size 1 to be inserted. +/// @param new_axes - The axis positions of the new axes in the expanded +/// dimensions. +/// @param input_id - Value ID for the input tensor. The input tensor must be +/// defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be +/// defined in the @a subgraph, and its shape must match the +/// shape of the input tensor with padding. +/// @param flags - binary features of the Expand Dims Node. No supported flags +/// are currently defined. +enum xnn_status xnn_define_static_expand_dims( + xnn_subgraph_t subgraph, + size_t num_new_axes, + const size_t* new_axes, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Fuse Dims Node with and add it to a Subgraph. +/// +/// Given an input Tensor of shape `[a, b, c, d]` and @a axis = 1 and +/// @a axes_count = 2, this node reshapes the Tensor to the shape +/// `[a, b * c, d]`. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - The index of the first dimension to be contracted. +/// @param axes_count - The number of dimensions, starting from @a axis, +/// to contract. +/// @param input_id - Value ID for the input tensor. The input tensor must be +/// defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be +/// defined in the @a subgraph. +/// @param flags - binary features of the Fuse Dims Node. No supported flags +/// are currently defined. +enum xnn_status xnn_define_fuse_dims( // + xnn_subgraph_t subgraph, // + size_t axis, // + size_t axes_count, // + uint32_t input_id, // + uint32_t output_id, // + uint32_t flags); + +/// Define a Split Dims Node with and add it to a Subgraph. +/// +/// Given an input Tensor of shape `[a, b, c]` and @a axis = 1, +/// @a num_splits = 3, and @a splits = `[3, 0, 2]`, this node reshapes the +/// Tensor to the shape `[a, 3, b / (3 * 2), 2, c]`, i.e. the first zero in +/// @a splits is replaced with the original dimension divided by the product of +/// the non-zero entries of @a splits. Note that if the original dimension is +/// not an integer multiple of the product of non-zero entries of @a splits, an +/// error is returned. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - The index of the first dimension to split. +/// @param num_splits - The number of dimensions in which to split the given +/// @a axis. +/// @param splits - The size of the dimensions in which to split the given +/// @a axis. +/// @param input_id - Value ID for the input tensor. The input tensor must be +/// defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be +/// defined in the @a subgraph, and its +/// shape must match the shape of the input tensor with +/// padding. +/// @param flags - binary features of the Split Dims Node. No supported flags +/// are currently defined. +enum xnn_status xnn_define_split_dim( // + xnn_subgraph_t subgraph, // + size_t axis, // + size_t num_splits, // + const size_t* splits, // + uint32_t input_id, // + uint32_t output_id, // + uint32_t flags); + +/// Define a Mean Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_reduction_axes - number of axes along which mean is computed. +/// @param reduction_axes - axes along which mean is computed. +/// @param input_id - Value ID for the input tensor. The input tensor must be a dense tensor with at least +/// @a num_reduction_axes dimensions defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be a dense tensor defined in the +/// @a subgraph with @a num_reduction_axes fewer dimensions than the input tensor (if +/// XNN_FLAG_KEEP_DIMS is not specified), or has same dimension rank but the dimension at +/// @a reduction_axes reduced to 1 (if XNN_FLAG_KEEP_DIMS is specified). +/// @param flags - binary features of the Mean Node. The only currently supported value is XNN_FLAG_KEEP_DIMS +XNN_DEPRECATED enum xnn_status xnn_define_static_mean( + xnn_subgraph_t subgraph, + size_t num_reduction_axes, + const size_t* reduction_axes, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +enum xnn_reduce_operator { + xnn_reduce_invalid = -1, + xnn_reduce_sum, + xnn_reduce_mean, + xnn_reduce_max, + xnn_reduce_min, +}; + +/// Define a Reduce Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_reduction_axes - number of axes along which reduce is computed. +/// @param reduction_axes - axes along which reduce is computed. +/// @param input_id - Value ID for the input tensor. The input tensor must be a dense tensor with at least +/// @a num_reduction_axes dimensions defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be a dense tensor defined in the +/// @a subgraph with @a num_reduction_axes fewer dimensions than the input tensor (if +/// XNN_FLAG_KEEP_DIMS is not specified), or has same dimension rank but the dimension at +/// @a reduction_axes reduced to 1 (if XNN_FLAG_KEEP_DIMS is specified). +/// @param flags - binary features of the Reduce Node. The only currently supported value is XNN_FLAG_KEEP_DIMS +enum xnn_status xnn_define_static_reduce( + xnn_subgraph_t subgraph, + enum xnn_reduce_operator reduce_operator_type, + size_t num_reduction_axes, + const size_t* reduction_axes, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Reduce Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_reduction_axes - number of axes along which reduce is computed. +/// @param reduction_axes - axes along which reduce is computed. Negative values +/// are interpreted as offsets from @a +/// num_reduction_axes. +/// @param input_id - Value ID for the input tensor. The input tensor must be a +/// dense tensor with at least @a num_reduction_axes +/// dimensions defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be +/// a dense tensor defined in the @a subgraph with @a +/// num_reduction_axes fewer dimensions than the input tensor +/// (if XNN_FLAG_KEEP_DIMS is not specified), or has same +/// dimension rank but the dimension at +/// @a reduction_axes reduced to 1 (if XNN_FLAG_KEEP_DIMS is +/// specified). +/// @param flags - binary features of the Reduce Node. The only currently +/// supported value is XNN_FLAG_KEEP_DIMS +enum xnn_status xnn_define_static_reduce_v2( // + xnn_subgraph_t subgraph, // + enum xnn_reduce_operator reduce_operator_type, // + size_t num_reduction_axes, // + const int64_t* reduction_axes, // + uint32_t input_id, // + uint32_t output_id, // + uint32_t flags); + +/// Define a n-Input Concatenate Node and add it to a Subgraph. +/// +/// The n-Input Concatenate Node concatenates 'n' tensors along a specified axis. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - the axis to concatenate the two input tensors along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param num_inputs - The number of input tensors to concatenate. Must be greater than or equal to 2. +/// @param inputs - An array of Value IDs representing the input tensors. Each tensor must be an N-dimensional tensor defined in the @a subgraph. +/// All input tensors must have identical dimensions, except for the concatenation axis. +/// @param output_id - Value ID for the output tensor. The output tensor must be a N-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the dimension of both inputs, except the axis +/// dimension, where it is the sum of the corresponding dimensions of both inputs. +/// @param flags - binary features of the Concatenate Node. No supported flags are currently defined. +enum xnn_status xnn_define_concatenate( + xnn_subgraph_t subgraph, + int32_t axis, + size_t num_inputs, + const uint32_t* inputs, + uint32_t output_id, + uint32_t flags); + +/// Define a 2-Input Concatenate Node and add it to a Subgraph. +/// +/// The 2-Input Concatenate Node concatenates two tensors along a specified axis. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - the axis to concatenate the two input tensors along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// second input. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// first input. +/// @param output_id - Value ID for the output tensor. The output tensor must be a N-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the dimension of both inputs, except the axis +/// dimension, where it is the sum of the corresponding dimensions of both inputs. +/// @param flags - binary features of the Concatenate Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_concatenate2( + xnn_subgraph_t subgraph, + int32_t axis, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 3-Input Concatenate Node and add it to a Subgraph. +/// +/// The 3-Input Concatenate Node concatenates three tensors along a specified axis. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - the axis to concatenate the two input tensors along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input3_id - Value ID for the third input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param output_id - Value ID for the output tensor. The output tensor must be a N-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the dimension of all inputs, except the axis +/// dimension, where it is the sum of the corresponding dimensions of all inputs. +/// @param flags - binary features of the Concatenate Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_concatenate3( + xnn_subgraph_t subgraph, + int32_t axis, + uint32_t input1_id, + uint32_t input2_id, + uint32_t input3_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 4-Input Concatenate Node and add it to a Subgraph. +/// +/// The 4-Input Concatenate Node concatenates four tensors along a specified axis. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - the axis to concatenate the two input tensors along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input3_id - Value ID for the third input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input4_id - Value ID for the fourth input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param output_id - Value ID for the output tensor. The output tensor must be a N-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the dimension of all inputs, except the axis +/// dimension, where it is the sum of the corresponding dimensions of all inputs. +/// @param flags - binary features of the Concatenate Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_concatenate4( + xnn_subgraph_t subgraph, + int32_t axis, + uint32_t input1_id, + uint32_t input2_id, + uint32_t input3_id, + uint32_t input4_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 5-Input Concatenate Node and add it to a Subgraph. +/// +/// The 5-Input Concatenate Node concatenates four tensors along a specified axis. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param axis - the axis to concatenate the two input tensors along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input3_id - Value ID for the third input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input4_id - Value ID for the fourth input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param input5_id - Value ID for the fourth input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph with each dimension, except the axis, equal to the corresponding dimension of the +/// other inputs. +/// @param output_id - Value ID for the output tensor. The output tensor must be a N-dimensional tensor defined +/// in the @a subgraph with each dimension equal to the dimension of all inputs, except the axis +/// dimension, where it is the sum of the corresponding dimensions of all inputs. +XNN_DEPRECATED enum xnn_status xnn_define_concatenate5( + xnn_subgraph_t subgraph, + int32_t axis, + uint32_t input1_id, + uint32_t input2_id, + uint32_t input3_id, + uint32_t input4_id, + uint32_t input5_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Copy Sign Node and add it to a Subgraph. +/// +/// The Copy Sign Node copies the sign of the second input to the first input. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be defined in the @a subgraph. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. +/// @param flags - binary features of the Copy Sign Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_copysign( + xnn_subgraph_t subgraph, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Copy Node and add it to a Subgraph. +/// +/// The Copy Node copies an input tensor to an output tensor. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the first input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Copy Node. No supported flags are currently defined. +enum xnn_status xnn_define_copy( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a n-Output Split Node and add it to a Subgraph. +/// +/// The n-Output Split Node splits an input tensor into n output tensors along a specified axis evenly. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param split_dim - the dimension to split the input tensor along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in the @a +/// subgraph. +/// @param num_outputs - The number of output tensors to generate. The input tensor will be evenly split into +/// this number of output tensors along the `split_dim`. Each output tensor will have +/// the same dimensions as the input tensor, except for the `split_dim`, which will be +/// divided evenly between the outputs. +/// @param outputs - An array of Value IDs for the output tensors. Each output tensor must be an N-dimensional +/// tensor defined in the @a subgraph with the same shape as the input tensor, except along the +/// `split_dim` dimension, which will be split evenly among the output tensors. The number of +/// output tensors corresponds to the value of `num_outputs`. +enum xnn_status xnn_define_even_split( + xnn_subgraph_t subgraph, + int32_t split_dim, + uint32_t input_id, + size_t num_outputs, + const uint32_t* outputs, + uint32_t flags); + +/// Define a 2-Output Split Node and add it to a Subgraph. +/// +/// The 2-Output Split Node splits an input tensor into two output tensors along a specified axis evenly. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param split_dim - the dimension to split the input tensor along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in the @a +/// subgraph. +/// @param output1_id - Value ID for the first output tensor. The output tensor must be an N-dimensional tensor defined +/// in the @a subgraph with each dimension, except the axis, equal to the corresponding dimension +/// of the second output. The split_dim dimension is half of the input's split_dim. +/// @param output2_id - Value ID for the second output tensor. The output tensor must be an N-dimensional tensor +/// defined in the @a subgraph with each dimension, except the axis, equal to the corresponding +/// dimension of the first output. The split_dim dimension is half of the input's split_dim. +/// @param flags - binary features of the Split Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_even_split2( + xnn_subgraph_t subgraph, + int32_t split_dim, + uint32_t input_id, + uint32_t output1_id, + uint32_t output2_id, + uint32_t flags); + +/// Define a 3-Output Split Node and add it to a Subgraph. +/// +/// The 3-Output Split Node splits an input tensor into three output tensors along a specified axis evenly. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param split_dim - the dimension to split the input tensor along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in the @a +/// subgraph. +/// @param output1_id - Value ID for the first output tensor. The output tensor must be an N-dimensional tensor defined +/// in the @a subgraph with each dimension, except the axis, equal to the corresponding dimension +/// of the second and third output. The split_dim dimension is one third of the input's split_dim. +/// @param output2_id - Value ID for the second output tensor. The output tensor must be an N-dimensional tensor +/// defined in the @a subgraph with each dimension, except the axis, equal to the corresponding +/// dimension of the first and third output. The split_dim dimension is one third of the input's +/// split_dim. +/// @param output3_id - Value ID for the third output tensor. The output tensor must be an N-dimensional tensor +/// defined in the @a subgraph with each dimension, except the axis, equal to the corresponding +/// dimension of the second and third output. The split_dim dimension is one third of the input's +/// split_dim. +/// @param flags - binary features of the Split Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_even_split3( + xnn_subgraph_t subgraph, + int32_t split_dim, + uint32_t input_id, + uint32_t output1_id, + uint32_t output2_id, + uint32_t output3_id, + uint32_t flags); + +/// Define a 4-Output Split Node and add it to a Subgraph. +/// +/// The 4-Output Split Node splits an input tensor into four output tensors along a specified axis evenly. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param split_dim - the dimension to split the input tensor along. If this is less than zero, the number of +/// dimensions is added to it. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in the @a +/// subgraph. +/// @param output1_id - Value ID for the first output tensor. The output tensor must be an N-dimensional tensor defined +/// in the @a subgraph with each dimension, except the axis, equal to the corresponding dimension +/// of the other output tensors. The split_dim dimension is one fourth of the input's split_dim. +/// @param output2_id - Value ID for the second output tensor. The output tensor must be an N-dimensional tensor +/// defined in the @a subgraph with each dimension, except the axis, equal to the corresponding +/// dimension of the other output tensors. The split_dim dimension is one fourth of the input's +/// split_dim. +/// @param output3_id - Value ID for the third output tensor. The output tensor must be an N-dimensional tensor +/// defined in the @a subgraph with each dimension, except the axis, equal to the corresponding +/// dimension of the other output tensors. The split_dim dimension is one fourth of the input's +/// split_dim. +/// @param output4_id - Value ID for the fourth output tensor. The output tensor must be an N-dimensional tensor +/// defined in the @a subgraph with each dimension, except the axis, equal to the corresponding +/// dimension of the other output tensors. The split_dim dimension is one fourth of the input's +/// split_dim. +/// @param flags - binary features of the Split Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_even_split4( + xnn_subgraph_t subgraph, + int32_t split_dim, + uint32_t input_id, + uint32_t output1_id, + uint32_t output2_id, + uint32_t output3_id, + uint32_t output4_id, + uint32_t flags); + +/// Define a Reshape Node with static shape specification and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_dims - number of shape dimensions in the output tensor. +/// @param new_shape - shape dimensions of the output tensor. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor with padding. +/// @param flags - binary features of the Reshape Node. No supported flags are currently defined. +enum xnn_status xnn_define_static_reshape( + xnn_subgraph_t subgraph, + size_t num_dims, + const size_t* new_shape, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a 2D Resize Bilinear Node with static output height & width specification and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param new_height - height dimension of the output tensor. +/// @param new_width - width dimension of the output tensor. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, H, W, C] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, new_height, new_width, C] dimensions. +/// @param flags - binary features of the 2D Resize Bilinear Node. The only currently supported values are +/// XNN_FLAG_TENSORFLOW_LEGACY_MODE and XNN_FLAG_ALIGN_CORNERS, which are mutually exclusive. +enum xnn_status xnn_define_static_resize_bilinear_2d( + xnn_subgraph_t subgraph, + size_t new_height, + size_t new_width, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a PReLU (Parametric ReLU) Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, H, W, channels] dimensions. +/// @param slope_id - Value ID for the slope tensor. The slope tensor must be a 1D tensor defined in the @a subgraph with +/// either [1] or [channels] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, H, W, channels] dimensions. +/// @param flags - binary features of the PReLU Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_prelu( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t slope_id, + uint32_t output_id, + uint32_t flags); + +/// Define a RoPE (Rotary Positional Embeddings) Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param max_tokens - deprecated. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [batch, tokens, heads, channels] dimensions. +/// @param weights_id - Value ID for the weights tensor. The weights tensor must be a 2D tensor defined in the +/// @a subgraph with [max_tokens, channels] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [batch, tokens, heads, channels] dimensions. +/// @param flags - binary features of the RoPE Node. No supported flags are currently defined. +enum xnn_status xnn_define_rope( + xnn_subgraph_t subgraph, + size_t max_sequence_size, + uint32_t input_id, + uint32_t weights_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Abs Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Abs Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_abs( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Bankers' Rounding Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Bankers' Rounding Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_bankers_rounding( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Batch Matrix Multiply Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input1_id - Value ID for the first input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph. It must be at least 3D. The first N-2 dimensions must match the second input +/// tensor. The last 2 dimensions are [M, K]. If XNN_FLAG_TRANSPOSE_B is not specified, the last +/// dimension must match the second last dimension of the second input tensor. If +/// XNN_FLAG_TRANSPOSE_B is specified, the last dimension must match the last dimension of the +/// second input tensor. +/// @param input2_id - Value ID for the second input tensor. The input tensor must be an N-dimensional tensor defined +/// in the @a subgraph. It must be at least 3D. The first N-2 dimensions must match the first input +/// tensor. If XNN_FLAG_TRANSPOSE_B is not specified, the last 2 dimensions are [K, N], and the +/// second last dimension must match the last dimension of the first input tensor. If +/// XNN_FLAG_TRANSPOSE_B is specified, the last 2 dimensions are [N, K], and the last dimension must +/// match the last dimension of the first input tensor. +/// @param output_id - Value ID for the output tensor. The output tensor must be an N-dimensional tensor defined in the +/// @a subgraph. It must be at least 3D. The first N-2 dimensions must match the first and second +/// input tensors . The last 2 dimensions must be [M, N]. +/// @param flags - binary features of the Batch Matrix Multiply Node. The only currently supported values are +/// XNN_FLAG_TRANSPOSE_B and XNN_FLAG_NO_BROADCAST. +enum xnn_status xnn_define_batch_matrix_multiply( + xnn_subgraph_t subgraph, + uint32_t input1_id, + uint32_t input2_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Ceiling Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Ceiling Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_ceiling( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Clamp Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param output_min - lower bound for clipping output values. +/// @param output_max - upper bound for clipping output values. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Clamp Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_clamp( + xnn_subgraph_t subgraph, + float output_min, + float output_max, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define an ELU (Exponential Linear Unit) Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param alpha - scale factor for negative output elements. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the ELU Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_elu( + xnn_subgraph_t subgraph, + float alpha, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Exp Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Exp Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_exp( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Floor Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Floor Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_floor( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define an GELU (Gaussian Error Linear Unit) Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the GELU Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_gelu( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a HardSwish Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the HardSwish Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_hardswish( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Leaky ReLU Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param negative_slope - scale factor for negative input elements. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Leaky ReLU Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_leaky_relu( + xnn_subgraph_t subgraph, + float negative_slope, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Log Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Log Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_log( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Negate Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Negate Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_negate( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Sigmoid Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Sigmoid Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_sigmoid( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a SoftMax Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph, and have at +/// least one dimension. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the SoftMax Node. No supported flags are currently defined. +enum xnn_status xnn_define_softmax( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Space To Depth 2D Node and add it to a Subgraph. +/// +/// The Space To Depth 2D Node rearranges blocks of spatial data into blocks (a reverse transform to Depth To Space 2D). +/// For a given input pixel, an output square of pixels with side @a block_size is formed from values in the +/// corresponding number of its channels. The output depth is therefore @a block_size x @a block_size times greater +/// than that of the input. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param block_size - the size of the spatial block. +/// @param input_id - Value ID for the input tensor. The input tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH * block_size, IW * block_size, OC] dimensions. +/// @param output_id - Value ID for the output tensor. The output tensor must be a 4D tensor defined in the @a subgraph +/// with [N, IH, IW, OC * block_size * block_size] dimensions. +/// @param flags - binary features of the input_channels Node. No supported flags are currently defined. +enum xnn_status xnn_define_space_to_depth_2d( + xnn_subgraph_t subgraph, + uint32_t block_size, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Square Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Square Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_square( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Square Root Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Square Root Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_square_root( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Reciprocal Square Root Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be +/// defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be +/// defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Square Root Node. No supported flags +/// are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_reciprocal_square_root( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +enum xnn_status xnn_define_static_slice( + xnn_subgraph_t subgraph, + size_t num_dims, + const size_t* offsets, + const size_t* sizes, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); +/// Define a Static Slice Node add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_dims - number of shape dimensions in the input and output tensor. +/// @param offsets - offsets in each dimension of the input tensor. This array must have @a num_dims elements. Can be +/// negative meaning that the offset is relative to the end of the dimension. +/// @param sizes - size of each dimension in output tensor. This array must have @a num_dims elements. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// dimensions must match @a sizes. +/// @param flags - binary features of the Static Slice Node. No supported flags are currently defined. +enum xnn_status xnn_define_static_slice_v2( // + xnn_subgraph_t subgraph, // + size_t num_dims, // + const int64_t* offsets, // + const size_t* sizes, // + uint32_t input_id, // + uint32_t output_id, // + uint32_t flags); + +/// Define a Static Slice Node add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param num_dims - number of shape dimensions in the input and output tensor. +/// @param begins - offsets to the start in each dimension of the input tensor. This array must have @a num_dims elements. +/// Can be negative meaning that the offset is relative to the end of the dimension. +/// @param ends - offsets to the end in each dimension of the input tensor. This array must have @a num_dims elements. +/// Can be negative meaning that the offset is relative to the end of the dimension. +/// An end value of 0 means "infer the largest open interval". +/// @param strides - The stride to use for each dimension of the slice. Can be NULL, in which case +/// a value of 1 is assumed for all dimensions. +/// TODO: at present, only stride values of 1 are supported (other values will return errors); +/// this will be supported more fully in the future. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// dimensions must match @a sizes. +/// @param flags - binary features of the Static Slice Node. No supported flags are currently defined. +enum xnn_status xnn_define_static_slice_v3( // + xnn_subgraph_t subgraph, // + size_t num_dims, // + const int64_t* begins, // + const int64_t* ends, // + const int64_t* strides, // + uint32_t input_id, // + uint32_t output_id, // + uint32_t flags); + +/// Define a Static Transpose Node and add it to a Subgraph. +/// +/// The Static Transpose Node applies a generalized transpose to the input tensor using the permuation in perm. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be an N-dimensional tensor defined in +/// the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be an N-dimensional tensor defined +/// in the @a subgraph with each dimension equal to its corresponding permuted input dimension. +/// @param num_dims - the number of permutation dimensions. This must be equal to the number of input dimensions. +/// @param perm - The permutation of the axis of the input tensor. The perm array must must contain 0 to N-1 in the +/// permuted order. +/// @param flags - binary features of the Static Transpose Node. No supported flags are currently defined. +enum xnn_status xnn_define_static_transpose( + xnn_subgraph_t subgraph, + size_t num_dims, + const size_t* perm, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Define a Tanh Node and add it to a Subgraph. +/// +/// @param subgraph - a Subgraph object that will own the created Node. +/// @param input_id - Value ID for the input tensor. The input tensor must be defined in the @a subgraph. +/// @param output_id - Value ID for the output tensor. The output tensor must be defined in the @a subgraph, and its +/// shape must match the shape of the input tensor. +/// @param flags - binary features of the Tanh Node. No supported flags are currently defined. +XNN_DEPRECATED enum xnn_status xnn_define_tanh( + xnn_subgraph_t subgraph, + uint32_t input_id, + uint32_t output_id, + uint32_t flags); + +/// Weights cache can be finalized in these ways: +enum xnn_weights_cache_finalization_kind { + /// Weights cache is finalized, no insert operations into the weights cache is allowed, even if the "inserted" + /// weights already exist in thee cache. Weights cache memory will also be trimmed to page boundary and set to + /// read-only (to prevent writes). + xnn_weights_cache_finalization_kind_hard, + /// Weights cache will be finalized with some extra space at the end, this allows for "inserting" into the cache only + /// if the weights are already in the cache, and errors on inserting uncached weights. There is memory overhead. + xnn_weights_cache_finalization_kind_soft, +}; + +/// A combination of multiple factors to uniquely locate the weights cache. +struct xnn_weights_cache_look_up_key { + /// The unique seed for each ukernel. It is guaranteed that each ukernel provides + /// a consistent and identical seed. + uint32_t seed; + /// Pointer to the original kernel. + const void* kernel; + /// Pointer to the original bias, could be NULL. + const void* bias; +}; + +/// A group of function pointers to manage weights cache. All functions may be +/// called on multi threads. +struct xnn_weights_cache_provider { + /// User-specified pointer that will be passed as-is to all functions in this + /// structure. + void* context; + + /// Looks up the tuple of {cache_key, kernel, bias} in the cache. If it is found, + /// returns the offset to the found entry for reuse. Otherwise, returns SIZE_MAX. + /// @param context - The user-specified pointer from xnn_weights_cache_provider structure. + /// @param cache_key - The key used to locate the weights cache entry. + size_t (*look_up)(void* context, const struct xnn_weights_cache_look_up_key* cache_key); + + /// Ensures that cache has enough space for `n` bytes. Returns the address to + /// store weight cache. Returns NULL if fails to reserve space. + /// @param context - The user-specified pointer from xnn_weights_cache_provider structure. + /// @param n - size to be reserved. + void* (*reserve_space)(void* context, size_t n); + + /// Looks up packed weights at `ptr` in the cache. If it is found, reuse it. + /// Otherwise, it is added to the cache. Returns the offset to the cache. + /// @param context - The user-specified pointer from xnn_weights_cache_provider structure. + /// @param cache_key - The key used to locate the weights cache entry. + /// @param ptr - pointer pointing to the packed weight. + /// @param size - size of the packed weight. + size_t (*look_up_or_insert)(void* context, const struct xnn_weights_cache_look_up_key* cache_key, void* ptr, size_t size); + + /// Returns whether the cache is finalized. + /// @param context - The user-specified pointer from xnn_weights_cache_provider structure. + bool (*is_finalized)(void* context); + + /// Returns the absolute pointer corresponding to `offset`, where the offset is returned from + /// `look_up` or `get_or_insert`. This function must be called after finalize. + /// @param context - The user-specified pointer from xnn_weights_cache_provider structure. + /// @param offset - offset to the start of internal buffer + void* (*offset_to_addr)(void* context, size_t offset); + + /// Destroy a weights cache object, as well as memory used for the cache. + /// @param context - The user-specified pointer from xnn_weights_cache_provider structure. + enum xnn_status (*delete_cache)(void* context); +}; + +/// Weights cache is a cache for packed weights. It can be reused between runtimes. +typedef struct xnn_weights_cache_provider* xnn_weights_cache_t; + +/// Create a weights cache object specifying the initial size of weights cache (in bytes). +/// +/// @param[in] size - initial capacity of the weights cache (in bytes), i.e. it can hold size bytes without growing. +/// @param weights_cache_out - pointer to the variable that will be initialized to a handle to the weights cache provider +/// upon successful return. Once created, the weights cache provider can be shared between +/// different Runtime objects. +enum xnn_status xnn_create_weights_cache_with_size(size_t size, xnn_weights_cache_t* weights_cache_out); + +enum xnn_status xnn_create_weights_cache(xnn_weights_cache_t* weights_cache_out); + +/// Finalizes the weights cache. The kind of finalization is specified by `finalization_kind`. +/// @param weights_cache - the weights cache object to finalize. +/// @param finalization_kind - the kind of finalization. +enum xnn_status xnn_finalize_weights_cache( + xnn_weights_cache_t weights_cache, + enum xnn_weights_cache_finalization_kind finalization_kind); + +// Wrapper function of the function pointers in `xnn_weights_cache_t`. +bool xnn_weights_cache_is_finalized(xnn_weights_cache_t cache); + +/// Destroy a weights cache object, as well as memory used for the cache. +/// @param weights_cache - the weights cache object to destroy. +enum xnn_status xnn_delete_weights_cache(xnn_weights_cache_t weights_cache); + +typedef struct xnn_workspace* xnn_workspace_t; + +/// Create a workspace object. +/// @param workspace_out - pointer to the variable that will be initialized to a handle to the workspace object upon +/// successful return. Once created, the workspace can be shared between different Runtime +/// objects. +enum xnn_status xnn_create_workspace(xnn_workspace_t* workspace_out); +/// Destroy a workspace object, as well as memory used by the workspace. Object destruction can be deferred until all +/// Runtime objects created with this workspace are destroyed. +/// @param workspace - the workspace object to destroy. +enum xnn_status xnn_release_workspace(xnn_workspace_t workspace); + +/// Runtime is a combination of an execution plan for subgraph Nodes and a memory manager for subgraph Values. +typedef struct xnn_runtime* xnn_runtime_t; + +enum xnn_profile_info { + /// Returns a size_t containing the number of operators. + xnn_profile_info_num_operators, + /// Returns a char[] containing the null character separated names of all operators. + xnn_profile_info_operator_name, + /// Returns a uint64_t[] with the runtimes of all operators in the same order as xnn_profile_info_operator_name. + xnn_profile_info_operator_timing, +}; + +/// Return profile information for all operators. +/// +/// @param runtime - a Runtime object created with @ref xnn_create_runtime, @ref xnn_create_runtime_v2 or +/// @ref xnn_create_runtime_v3. +/// @param param_name - type of profile information required. +/// @param param_value_size - the size in bytes of memory pointed to by param_value. If this is not sufficient then +/// param_value_size_ret will be set to the required size and xnn_status_out_of_memory will be +/// returned. +/// @param param_value - a pointer to memory location where appropriate values for a given param_value will be written. +/// @param param_value_size_ret - returns number of bytes required to write the result if param_value_size is not +/// sufficient. +enum xnn_status xnn_get_runtime_profiling_info(xnn_runtime_t runtime, + enum xnn_profile_info param_name, + size_t param_value_size, + void* param_value, + size_t* param_value_size_ret); + +/// Create a Runtime object from a subgraph. +/// +/// @param subgraph - a Subgraph object with all Values and Nodes that would be handled by the runtime. No Values or +/// Nodes can be added to the runtime once it is constructed. +/// @param weights_cache - a cache for packed weights. The runtime will look up and reuse packed weights in this cache, +/// this will reduce memory allocated for packed weights. +/// @param workspace - a workspace to hold internal tensors. The runtime will allocate space used for internal tensors +/// and track them using workspace. Workspace can be shared and reused across different runtimes. If +/// workspace is NULL, there will be no sharing: each runtime has its own workspace. +/// @param threadpool - the thread pool to be used for parallelisation of computations in the runtime. If the thread +/// pool is NULL, the computation would run on the caller thread without parallelization. +/// @param flags - binary features of the runtime. The only currently supported values are +/// XNN_FLAG_HINT_SPARSE_INFERENCE, XNN_FLAG_HINT_FP16_INFERENCE, XNN_FLAG_FORCE_FP16_INFERENCE, +/// XNN_FLAG_YIELD_WORKERS, and XNN_FLAG_TRANSIENT_INDIRECTION_BUFFER. If XNN_FLAG_YIELD_WORKERS is +/// specified, worker threads would be yielded to the system scheduler after processing the last operator +/// in the Runtime. If XNN_FLAG_TRANSIENT_INDIRECTION_BUFFER is specified, convolution operators will +/// initialize indirection buffers on each inference run using temporary memory in the workspace, instead +/// of initializing persistent indirection buffers once. +/// @param runtime_out - pointer to the variable that will be initialized with a handle to the Runtime object upon +/// successful return. Once constructed, the Runtime object is independent of the Subgraph object +/// used to create it. +enum xnn_status xnn_create_runtime_v4( + xnn_subgraph_t subgraph, + xnn_weights_cache_t weights_cache, + xnn_workspace_t workspace, + pthreadpool_t threadpool, + uint32_t flags, + xnn_runtime_t* runtime_out); + +enum xnn_status xnn_create_runtime_v3( + xnn_subgraph_t subgraph, + xnn_weights_cache_t weights_cache, + pthreadpool_t threadpool, + uint32_t flags, + xnn_runtime_t* runtime_out); + +enum xnn_status xnn_create_runtime_v2( + xnn_subgraph_t subgraph, + pthreadpool_t threadpool, + uint32_t flags, + xnn_runtime_t* runtime_out); + +enum xnn_status xnn_create_runtime( + xnn_subgraph_t subgraph, + xnn_runtime_t* runtime_out); + +struct xnn_external_value { + uint32_t id; + void* data; +}; + +/// Reshape an external value. +/// +/// @param external_id - external ID for the Value. The ID must be within the range of reversed Value IDs specified on +/// the Subgraph creation. If the external ID is XNN_INVALID_VALUE_ID, an internal ID will be +/// created for the Value. +/// @param num_dims - number of dimensions in the shape. +/// @param dims - pointer to an array of @a num_dims shape dimensions. If num_dims is 0, this pointer can be NULL. +/// XNNPACK does not keep any pointers to this array after the function returns. +enum xnn_status xnn_reshape_external_value( + xnn_runtime_t runtime, + uint32_t external_id, + size_t num_dims, + const size_t* dims); + +/// Get the external value shape. +/// +/// @param external_id - external ID for the Value. The ID must be within the range of reversed Value IDs specified on +/// the Subgraph creation. The external ID can not be XNN_INVALID_VALUE_ID. +/// @param num_dims - A valid pointer into which the number of dimensions in the shape will be written. It can not be larger than XNN_MAX_TENSOR_DIMS. +/// @param dims - pointer to an array of @a num_dims shape dimensions. This pointer can't be NULL. It must be large enough to hold +/// at least @a num_dims elements. XNNPACK does not keep any pointers to this array after the function returns. +enum xnn_status xnn_get_external_value_shape( + xnn_runtime_t runtime, + uint32_t external_id, + size_t* num_dims, + size_t* dims); + +/// Reshape the XNNPACK runtime. +/// +/// Propagates the shapes of input tensors through the graph to determine the shapes of intermediate and output tensors. +/// Memory is allocated if required. Output tensor shapes are returned by xnn_get_external_value_shape. +/// +/// @param runtime - a Runtime object created with @ref xnn_create_runtime or @ref xnn_create_runtime_v2. +enum xnn_status xnn_reshape_runtime( + xnn_runtime_t runtime); + +/// Deprecated. Use xnn_reshape_runtime and xnn_setup_runtime_v2. +/// +/// Setup data pointers for external inputs and outputs in a Runtime object and +/// allocate memory. +/// +/// @param runtime - a Runtime object created with @ref xnn_create_runtime or @ref xnn_create_runtime_v2. +/// @param num_external_values - the number of external inputs and outputs specified in this call. This number must +/// match the number of external inputs and outputs in the runtime, i.e. all external +/// inputs and outputs in the runtime must be specified in one call. +/// @param external_values - array with location information for all external inputs and outputs in the runtime. +enum xnn_status xnn_setup_runtime( + xnn_runtime_t runtime, + size_t num_external_values, + const struct xnn_external_value* external_values); + +/// Setup data pointers for external inputs and outputs in a Runtime object. +/// Should be called after xnn_reshape_runtime. +/// +/// @param runtime - a Runtime object created with @ref xnn_create_runtime or @ref xnn_create_runtime_v2. +/// @param num_external_values - the number of external inputs and outputs specified in this call. This number must +/// match the number of external inputs and outputs in the runtime, i.e. all external +/// inputs and outputs in the runtime must be specified in one call. +/// @param external_values - array with location information for all external inputs and outputs in the runtime. +enum xnn_status xnn_setup_runtime_v2( + xnn_runtime_t runtime, + size_t num_external_values, + const struct xnn_external_value* external_values); + +/// Execute forward pass for all operators in the runtime. +/// +/// @param runtime - the Runtime object with the execution plan to invoke. +enum xnn_status xnn_invoke_runtime( + xnn_runtime_t runtime); + +/// Destroy a Runtime object, as well as operators and memory associated with it. +/// +/// @param runtime - the Runtime object to destroy. +enum xnn_status xnn_delete_runtime( + xnn_runtime_t runtime); + +typedef struct xnn_operator* xnn_operator_t; + +enum xnn_status xnn_run_operator( + xnn_operator_t op, + pthreadpool_t threadpool); + +enum xnn_status xnn_delete_operator( + xnn_operator_t op); + +/// Operator API: +/// - create operator will create and populate a xnn_operator_t +/// - reshape operator will update fields in xnn_operator_t with shape/dimensions and parallelization information +/// - setup operator will update pointers to input and outputs +/// Each supported operator must have a create, reshape, and setup function. (Optionally a run function.) +/// Operators listed below are in alphabetical order by operator name; within each operator, we sort alphabetically by +/// data layout and type. We also group create, reshape, setup (and optionally run) functions of each operator together. + +enum xnn_status xnn_create_binary_elementwise_nd( + enum xnn_binary_operator type, + enum xnn_datatype datatype, + const struct xnn_quantization_params* input1_quantization, + const struct xnn_quantization_params* input2_quantization, + const struct xnn_quantization_params* output_quantization, + uint32_t flags, + xnn_operator_t* binary_op_out); + +enum xnn_status xnn_reshape_binary_elementwise_nd( + xnn_operator_t binary_op, + size_t num_input1_dims, + const size_t* input1_shape, + size_t num_input2_dims, + const size_t* input2_shape, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_binary_elementwise_nd( + xnn_operator_t binary_op, + const void* input1, + const void* input2, + void* output); + +enum xnn_status xnn_run_binary_elementwise_nd( + enum xnn_binary_operator type, + enum xnn_datatype datatype, + const struct xnn_quantization_params* input1_quantization, + const struct xnn_quantization_params* input2_quantization, + const struct xnn_quantization_params* output_quantization, + uint32_t flags, + size_t num_input1_dims, + const size_t* input1_shape, + size_t num_input2_dims, + const size_t* input2_shape, + const void* input1, + const void* input2, + void* output, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_unary_elementwise_nc( + enum xnn_unary_operator op_type, + enum xnn_datatype input_datatype, + enum xnn_datatype output_datatype, + const union xnn_unary_params* params, + const void* lut, + const struct xnn_quantization_params* input_quantization, + const struct xnn_quantization_params* output_quantization, + uint32_t flags, + xnn_operator_t* op_out); + +enum xnn_status xnn_reshape_unary_elementwise_nc( + xnn_operator_t op, + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_unary_elementwise_nc( + xnn_operator_t op, + const void* input, + void* output); + +enum xnn_status xnn_run_unary_elementwise_nc( + // create parameters + enum xnn_unary_operator op_type, + enum xnn_datatype input_datatype, + enum xnn_datatype output_datatype, + const union xnn_unary_params* params, + const struct xnn_quantization_params* input_quantization, + const struct xnn_quantization_params* output_quantization, + uint32_t flags, + // reshape parameters + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool, + // setup parameters + const void* input, + void* output); + +enum xnn_status xnn_create_argmax_pooling2d_nhwc_f32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t flags, + xnn_operator_t* argmax_pooling_op_out); + +enum xnn_status xnn_reshape_argmax_pooling2d_nhwc_f32( + xnn_operator_t argmax_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_argmax_pooling2d_nhwc_f32( + xnn_operator_t argmax_pooling_op, + const float* input, + float* output, + uint32_t* index); + +enum xnn_status xnn_create_average_pooling2d_nhwc_f16( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + float output_min, + float output_max, + uint32_t flags, + xnn_operator_t* average_pooling_op_out); + +enum xnn_status xnn_reshape_average_pooling2d_nhwc_f16( + xnn_operator_t average_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_average_pooling2d_nhwc_f16( + xnn_operator_t average_pooling_op, + const void* input, + void* output); + +enum xnn_status xnn_create_average_pooling2d_nhwc_f32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + float output_min, + float output_max, + uint32_t flags, + xnn_operator_t* average_pooling_op_out); + +enum xnn_status xnn_reshape_average_pooling2d_nhwc_f32( + xnn_operator_t average_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_average_pooling2d_nhwc_f32( + xnn_operator_t average_pooling_op, + const float* input, + float* output); + +enum xnn_status xnn_create_batch_matrix_multiply_nc_f16( + uint32_t flags, + xnn_operator_t* batch_matrix_multiply_op); + +enum xnn_status xnn_create_batch_matrix_multiply_nc_bf16_f32( + uint32_t flags, xnn_operator_t* batch_matrix_multiply_op); + +enum xnn_status xnn_create_batch_matrix_multiply_nc_f16_const_weights( + size_t batch_size_b, size_t k, size_t n, const void* data_b, uint32_t flags, + xnn_operator_t* batch_matrix_multiply_op); + +enum xnn_status xnn_reshape_batch_matrix_multiply_nc_f16( + xnn_operator_t batch_matrix_multiply_op, size_t num_batch_dims, + const size_t* batch_dims_a, const size_t* batch_dims_b, size_t m, size_t k, + size_t n, size_t* workspace_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_batch_matrix_multiply_nc_f16( + xnn_operator_t batch_matrix_multiply_op, void* workspace, + const void* input_a, const void* input_b, void* output); + +enum xnn_status xnn_reshape_batch_matrix_multiply_nc_bf16_f32( + xnn_operator_t batch_matrix_multiply_op, size_t num_batch_dims, + const size_t* batch_dims_a, const size_t* batch_dims_b, size_t m, size_t k, + size_t n, size_t* workspace_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_batch_matrix_multiply_nc_bf16_f32( + xnn_operator_t batch_matrix_multiply_op, void* workspace, + const void* input_a, const void* input_b, void* output); + +enum xnn_status xnn_create_batch_matrix_multiply_nc_f32( + uint32_t flags, xnn_operator_t* batch_matrix_multiply_op); + +enum xnn_status xnn_create_batch_matrix_multiply_nc_f32_const_weights( + size_t batch_size_b, size_t k, size_t n, const float* data_b, + uint32_t flags, xnn_operator_t* batch_matrix_multiply_op); + +enum xnn_status xnn_reshape_batch_matrix_multiply_nc_f32( + xnn_operator_t batch_matrix_multiply_op, size_t num_batch_dims, + const size_t* batch_dims_a, const size_t* batch_dims_b, size_t m, size_t k, + size_t n, size_t* workspace_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_batch_matrix_multiply_nc_f32( + xnn_operator_t batch_matrix_multiply_op, void* workspace, + const float* input_a, const float* input_b, float* output); + +enum xnn_status xnn_create_batch_matrix_multiply_nc_qd8_f32_qc8w( + size_t batch_size_b, size_t k, size_t n, const int8_t* data_b, + const float* scale_b, uint32_t flags, + xnn_operator_t* batch_matrix_multiply_op); + +enum xnn_status xnn_reshape_batch_matrix_multiply_nc_qd8_f32_qc8w( + xnn_operator_t batch_matrix_multiply_op, size_t num_batch_dims, + const size_t* batch_dims_a, const size_t* batch_dims_b, size_t m, size_t k, + size_t n, pthreadpool_t threadpool); + +enum xnn_status xnn_setup_batch_matrix_multiply_nc_qd8_f32_qc8w( + xnn_operator_t batch_matrix_multiply_op, const int8_t* input_a, + const struct xnn_quantization_params* quantization_params, + float* output); + +enum xnn_status xnn_create_constant_pad_nd_x8( + const void* padding_value, + uint32_t flags, + xnn_operator_t* constant_pad_op_out); + +enum xnn_status xnn_reshape_constant_pad_nd_x8( + xnn_operator_t constant_pad_op, + size_t num_dims, + const size_t* input_shape, + const size_t* pre_padding, + const size_t* post_padding, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_constant_pad_nd_x8( + xnn_operator_t constant_pad_op, + const void* input, + void* output); + +enum xnn_status xnn_run_constant_pad_nd_x8( + uint32_t flags, + size_t num_dims, + const size_t* input_shape, + const size_t* pre_paddings, + const size_t* post_paddings, + const void* input, + void* output, + const void* padding_value, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_constant_pad_nd_x16( + const void* padding_value, + uint32_t flags, + xnn_operator_t* constant_pad_op_out); + +enum xnn_status xnn_reshape_constant_pad_nd_x16( + xnn_operator_t constant_pad_op, + size_t num_dims, + const size_t* input_shape, + const size_t* pre_padding, + const size_t* post_padding, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_constant_pad_nd_x16( + xnn_operator_t constant_pad_op, + const void* input, + void* output); + +enum xnn_status xnn_run_constant_pad_nd_x16( + uint32_t flags, + size_t num_dims, + const size_t* input_shape, + const size_t* pre_paddings, + const size_t* post_paddings, + const void* input, + void* output, + const void* padding_value, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_constant_pad_nd_x32( + const void* padding_value, + uint32_t flags, + xnn_operator_t* constant_pad_op_out); + +enum xnn_status xnn_reshape_constant_pad_nd_x32( + xnn_operator_t constant_pad_op, + size_t num_dims, + const size_t* input_shape, + const size_t* pre_padding, + const size_t* post_padding, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_constant_pad_nd_x32( + xnn_operator_t constant_pad_op, + const void* input, + void* output); + +enum xnn_status xnn_run_constant_pad_nd_x32( + uint32_t flags, + size_t num_dims, + const size_t* input_shape, + const size_t* pre_paddings, + const size_t* post_paddings, + const void* input, + void* output, + const void* padding_value, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_convert_nc_f16_qd8( + uint32_t flags, + xnn_operator_t* convert_op_out); + +enum xnn_status xnn_reshape_convert_nc_f16_qd8( + xnn_operator_t convert_op, + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool); + +// quantization_params must be padded with at least XNN_EXTRA_QUANTIZATION_PARAMS entries. +enum xnn_status xnn_setup_convert_nc_f16_qd8( + xnn_operator_t convert_op, + const void* input, + int8_t* output, + struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_create_convert_nc_f32_qd8( + uint32_t flags, + xnn_operator_t* convert_op_out); + +enum xnn_status xnn_reshape_convert_nc_f32_qd8( + xnn_operator_t convert_op, + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool); + +// quantization_params must be padded with at least XNN_EXTRA_QUANTIZATION_PARAMS entries. +enum xnn_status xnn_setup_convert_nc_f32_qd8( + xnn_operator_t convert_op, + const float* input, + int8_t* output, + struct xnn_quantization_params* quantization_params); + +XNN_DEPRECATED enum xnn_status xnn_run_convert_nc_f32_f16( + size_t channels, + size_t input_stride, + size_t output_stride, + size_t batch_size, + const float* input, + void* output, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_convolution2d_nchw_f16( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nchw_f16( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nchw_f16( + xnn_operator_t convolution_op, + const void* input, + void* output); + +enum xnn_status xnn_create_convolution2d_nchw_f32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + const float* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nchw_f32( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nchw_f32( + xnn_operator_t convolution_op, + const float* input, + float* output); + +enum xnn_status xnn_create_convolution2d_nhwc_f16( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nhwc_f16( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* workspace_size, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nhwc_f16( + xnn_operator_t convolution_op, + void* workspace, + const void* input, + void* output); + +enum xnn_status xnn_create_convolution2d_nhwc_f32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + const float* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_create_convolution2d_nhwc_f32_f16( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +// Forward declare. +struct xnn_post_operation; + +/// Deprecated +enum xnn_status xnn_create_fused_convolution2d_nhwc_f32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + const float* kernel, + const float* bias, + size_t num_post_operations, + struct xnn_post_operation* post_operations, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nhwc_f32( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* workspace_size, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nhwc_f32( + xnn_operator_t convolution_op, + void* workspace, + const float* input, + float* output); + +enum xnn_status xnn_create_convolution2d_nhwc_qd8_f16_qc8w( + uint32_t input_padding_top, uint32_t input_padding_right, + uint32_t input_padding_bottom, uint32_t input_padding_left, + uint32_t kernel_height, uint32_t kernel_width, uint32_t subsampling_height, + uint32_t subsampling_width, uint32_t dilation_height, + uint32_t dilation_width, uint32_t groups, size_t group_input_channels, + size_t group_output_channels, size_t input_channel_stride, + size_t output_channel_stride, const float* kernel_scale, + const int8_t* kernel, const float* bias, float output_min, float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_create_convolution2d_nhwc_qd8_f32_qc8w( + uint32_t input_padding_top, uint32_t input_padding_right, + uint32_t input_padding_bottom, uint32_t input_padding_left, + uint32_t kernel_height, uint32_t kernel_width, uint32_t subsampling_height, + uint32_t subsampling_width, uint32_t dilation_height, + uint32_t dilation_width, uint32_t groups, size_t group_input_channels, + size_t group_output_channels, size_t input_channel_stride, + size_t output_channel_stride, const float* kernel_scale, + const int8_t* kernel, const float* bias, float output_min, float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_create_convolution2d_nhwc_qs8( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + int8_t input_zero_point, + float input_scale, + float kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nhwc_qd8_f16_qc8w( + xnn_operator_t convolution_op, size_t batch_size, size_t input_height, + size_t input_width, size_t* workspace_size, + size_t* output_height_out, size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_reshape_convolution2d_nhwc_qd8_f32_qc8w( + xnn_operator_t convolution_op, size_t batch_size, size_t input_height, + size_t input_width, size_t* workspace_size, + size_t* output_height_out, size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_reshape_convolution2d_nhwc_qs8( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* workspace_size, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nhwc_qd8_f16_qc8w( + xnn_operator_t convolution_op, void* workspace, const int8_t* input, + void* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_setup_convolution2d_nhwc_qd8_f32_qc8w( + xnn_operator_t convolution_op, void* workspace, const int8_t* input, + float* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_setup_convolution2d_nhwc_qs8( + xnn_operator_t convolution_op, + void* workspace, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_convolution2d_nhwc_qs8_qc8w( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + int8_t input_zero_point, + float input_scale, + const float* kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nhwc_qs8_qc8w( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* workspace_size, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nhwc_qs8_qc8w( + xnn_operator_t convolution_op, + void* workspace, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_convolution2d_nhwc_qu8( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t subsampling_height, + uint32_t subsampling_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_channel_stride, + size_t output_channel_stride, + uint8_t input_zero_point, + float input_scale, + uint8_t kernel_zero_point, + float kernel_scale, + const uint8_t* kernel, + const int32_t* bias, + uint8_t output_zero_point, + float output_scale, + uint8_t output_min, + uint8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* convolution_op_out); + +enum xnn_status xnn_reshape_convolution2d_nhwc_qu8( + xnn_operator_t convolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t* workspace_size, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_convolution2d_nhwc_qu8( + xnn_operator_t convolution_op, + void* workspace, + const uint8_t* input, + uint8_t* output); + +enum xnn_status xnn_create_copy_nc_x8( + uint32_t flags, + xnn_operator_t* copy_op_out); + +enum xnn_status xnn_reshape_copy_nc_x8( + xnn_operator_t copy_op, + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_copy_nc_x8( + xnn_operator_t copy_op, + const void* input, + void* output); + +enum xnn_status xnn_create_copy_nc_x16( + uint32_t flags, + xnn_operator_t* copy_op_out); + +enum xnn_status xnn_reshape_copy_nc_x16( + xnn_operator_t copy_op, + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_copy_nc_x16( + xnn_operator_t copy_op, + const void* input, + void* output); + +enum xnn_status xnn_create_copy_nc_x32( + uint32_t flags, + xnn_operator_t* copy_op_out); + +enum xnn_status xnn_reshape_copy_nc_x32( + xnn_operator_t copy_op, + size_t batch_size, + size_t channels, + size_t input_stride, + size_t output_stride, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_copy_nc_x32( + xnn_operator_t copy_op, + const void* input, + void* output); + +enum xnn_status xnn_run_copy_nc_x32( + size_t channels, + size_t input_stride, + size_t output_stride, + size_t batch_size, + const uint32_t* input, + uint32_t* output, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_deconvolution2d_nhwc_f16( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_reshape_deconvolution2d_nhwc_f16( + xnn_operator_t deconvolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + uint32_t adjustment_height, + uint32_t adjustment_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_deconvolution2d_nhwc_f16( + xnn_operator_t deconvolution_op, + const void* input, + void* output); + +enum xnn_status xnn_create_deconvolution2d_nhwc_f32( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + const float* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_create_deconvolution2d_nhwc_f32_f16( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_reshape_deconvolution2d_nhwc_f32( + xnn_operator_t deconvolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + uint32_t adjustment_height, + uint32_t adjustment_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_deconvolution2d_nhwc_f32( + xnn_operator_t deconvolution_op, + const float* input, + float* output); + +enum xnn_status xnn_create_deconvolution2d_nhwc_qd8_f32_qc8w( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + const float* kernel_scale, + const int8_t* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_reshape_deconvolution2d_nhwc_qd8_f32_qc8w( + xnn_operator_t deconvolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + uint32_t adjustment_height, + uint32_t adjustment_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_deconvolution2d_nhwc_qd8_f32_qc8w( + xnn_operator_t deconvolution_op, + const int8_t* input, + float* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_create_deconvolution2d_nhwc_qs8( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + int8_t input_zero_point, + float input_scale, + float kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_reshape_deconvolution2d_nhwc_qs8( + xnn_operator_t deconvolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + uint32_t adjustment_height, + uint32_t adjustment_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_deconvolution2d_nhwc_qs8( + xnn_operator_t deconvolution_op, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_deconvolution2d_nhwc_qs8_qc8w( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + int8_t input_zero_point, + float input_scale, + const float* kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_reshape_deconvolution2d_nhwc_qs8_qc8w( + xnn_operator_t deconvolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + uint32_t adjustment_height, + uint32_t adjustment_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_deconvolution2d_nhwc_qs8_qc8w( + xnn_operator_t deconvolution_op, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_deconvolution2d_nhwc_qu8( + uint32_t output_padding_top, + uint32_t output_padding_right, + uint32_t output_padding_bottom, + uint32_t output_padding_left, + uint32_t kernel_height, + uint32_t kernel_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint32_t groups, + size_t group_input_channels, + size_t group_output_channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + uint8_t input_zero_point, + float input_scale, + uint8_t kernel_zero_point, + float kernel_scale, + const uint8_t* kernel, + const int32_t* bias, + uint8_t output_zero_point, + float output_scale, + uint8_t output_min, + uint8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* deconvolution_op_out); + +enum xnn_status xnn_reshape_deconvolution2d_nhwc_qu8( + xnn_operator_t deconvolution_op, + size_t batch_size, + size_t input_height, + size_t input_width, + uint32_t adjustment_height, + uint32_t adjustment_width, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_deconvolution2d_nhwc_qu8( + xnn_operator_t deconvolution_op, + const uint8_t* input, + uint8_t* output); + +enum xnn_status xnn_create_depth_to_space_nchw2nhwc_x16( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* depth_to_space_op_out); + +enum xnn_status xnn_reshape_depth_to_space_nchw2nhwc_x16( + xnn_operator_t depth_to_space_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_depth_to_space_nchw2nhwc_x16( + xnn_operator_t depth_to_space_op, + const void* input, + void* output); + +enum xnn_status xnn_create_depth_to_space_nchw2nhwc_x32( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* depth_to_space_op_out); + +enum xnn_status xnn_reshape_depth_to_space_nchw2nhwc_x32( + xnn_operator_t depth_to_space_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_depth_to_space_nchw2nhwc_x32( + xnn_operator_t depth_to_space_op, + const void* input, + void* output); + +enum xnn_status xnn_create_depth_to_space_nhwc_x8( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* depth_to_space_op_out); + +enum xnn_status xnn_reshape_depth_to_space_nhwc_x8( + xnn_operator_t depth_to_space_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_depth_to_space_nhwc_x8( + xnn_operator_t depth_to_space_op, + const void* input, + void* output); + +enum xnn_status xnn_create_depth_to_space_nhwc_x16( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* depth_to_space_op_out); + +enum xnn_status xnn_reshape_depth_to_space_nhwc_x16( + xnn_operator_t depth_to_space_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_depth_to_space_nhwc_x16( + xnn_operator_t depth_to_space_op, + const void* input, + void* output); + +enum xnn_status xnn_create_depth_to_space_nhwc_x32( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* depth_to_space_op_out); + +enum xnn_status xnn_reshape_depth_to_space_nhwc_x32( + xnn_operator_t depth_to_space_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_depth_to_space_nhwc_x32( + xnn_operator_t depth_to_space_op, + const void* input, + void* output); + +enum xnn_status xnn_create_dynamic_fully_connected_nc_f16( + float output_min, + float output_max, + uint32_t flags, + xnn_operator_t* dynamic_fully_connected_op_out); + +enum xnn_status xnn_reshape_dynamic_fully_connected_nc_f16( + xnn_operator_t dynamic_fully_connected_op, + size_t batch_size, + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + size_t* workspace_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_dynamic_fully_connected_nc_f16( + xnn_operator_t dynamic_fully_connected_op, + void* workspace, + const void* input, + const void* kernel, + const void* bias, + void* output); + +enum xnn_status xnn_create_dynamic_fully_connected_nc_f32( + float output_min, + float output_max, + uint32_t flags, + xnn_operator_t* dynamic_fully_connected_op_out); + +enum xnn_status xnn_reshape_dynamic_fully_connected_nc_f32( + xnn_operator_t dynamic_fully_connected_op, + size_t batch_size, + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + size_t* workspace_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_dynamic_fully_connected_nc_f32( + xnn_operator_t dynamic_fully_connected_op, + void* workspace, + const float* input, + const float* kernel, + const float* bias, + float* output); + +enum xnn_status xnn_create_fully_connected_nc_f16( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_f16( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_f16( + xnn_operator_t fully_connected_op, + const void* input, + void* output); + +enum xnn_status xnn_create_fully_connected_nc_f32_f16( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const void* kernel, + const void* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_create_fully_connected_nc_bf16_f32( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const void* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_create_fully_connected_nc_f32( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const float* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_f32_f16( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_reshape_fully_connected_nc_bf16_f32( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_reshape_fully_connected_nc_f32( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_f32_f16( + xnn_operator_t fully_connected_op, + const float* input, + float* output); + +enum xnn_status xnn_setup_fully_connected_nc_bf16_f32( + xnn_operator_t fully_connected_op, + const void* input, + float* output); + +enum xnn_status xnn_setup_fully_connected_nc_f32( + xnn_operator_t fully_connected_op, + const float* input, + float* output); + +enum xnn_status xnn_create_fully_connected_nc_f32_qc4w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + uint8_t kernel_zero_point, + const float* kernel_scale, + const uint8_t* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_f32_qc4w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_f32_qc4w( + xnn_operator_t fully_connected_op, + const float* input, + float* output); + +enum xnn_status xnn_create_fully_connected_nc_f32_qc8w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const float* kernel_scale, + const int8_t* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_f32_qc8w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_f32_qc8w( + xnn_operator_t fully_connected_op, + const float* input, + float* output); + +enum xnn_status xnn_create_fully_connected_nc_qd8_f16_qc4w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + uint8_t kernel_zero_point, + const float* kernel_scale, + const void* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_setup_fully_connected_nc_qd8_f16_qc4w( + xnn_operator_t fully_connected_op, + const int8_t* input, + void* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_reshape_fully_connected_nc_qd8_f16_qc4w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_fully_connected_nc_qd8_f16_qb4w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + size_t block_size, + uint8_t kernel_zero_point, + const uint16_t* kernel_scale, + const void* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_qd8_f16_qb4w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_qd8_f16_qb4w( + xnn_operator_t fully_connected_op, + const int8_t* input, + void* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_create_fully_connected_nc_qd8_f32_qc4w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + uint8_t kernel_zero_point, + const float* kernel_scale, + const void* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_setup_fully_connected_nc_qd8_f32_qc4w( + xnn_operator_t fully_connected_op, + const int8_t* input, + float* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_reshape_fully_connected_nc_qd8_f32_qc4w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_fully_connected_nc_qd8_f32_qb4w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + size_t block_size, + uint8_t kernel_zero_point, + const uint16_t* kernel_scale, + const void* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_qd8_f32_qb4w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_qd8_f32_qb4w( + xnn_operator_t fully_connected_op, + const int8_t* input, + float* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_create_fully_connected_nc_qd8_f16_qc8w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const float* kernel_scale, + const int8_t* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_setup_fully_connected_nc_qd8_f16_qc8w( + xnn_operator_t fully_connected_op, + const int8_t* input, + void* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_reshape_fully_connected_nc_qd8_f16_qc8w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_fully_connected_nc_qd8_f32_qc8w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + const float* kernel_scale, + const int8_t* kernel, + const float* bias, + float output_min, + float output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_setup_fully_connected_nc_qd8_f32_qc8w( + xnn_operator_t fully_connected_op, + const int8_t* input, + float* output, + const struct xnn_quantization_params* quantization_params); + +enum xnn_status xnn_reshape_fully_connected_nc_qd8_f32_qc8w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_fully_connected_nc_qs8( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + int8_t input_zero_point, + float input_scale, + float kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_qs8( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_qs8( + xnn_operator_t fully_connected_op, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_fully_connected_nc_qs8_qc4w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + int8_t input_zero_point, + float input_scale, + uint8_t kernel_zero_point, + const float* kernel_scale, + const void* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_qs8_qc4w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_qs8_qc4w( + xnn_operator_t fully_connected_op, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_fully_connected_nc_qs8_qc8w( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + int8_t input_zero_point, + float input_scale, + const float* kernel_scale, + const int8_t* kernel, + const int32_t* bias, + int8_t output_zero_point, + float output_scale, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_qs8_qc8w( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_qs8_qc8w( + xnn_operator_t fully_connected_op, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_fully_connected_nc_qu8( + size_t input_channels, + size_t output_channels, + size_t input_stride, + size_t output_stride, + uint8_t input_zero_point, + float input_scale, + uint8_t kernel_zero_point, + float kernel_scale, + const uint8_t* kernel, + const int32_t* bias, + uint8_t output_zero_point, + float output_scale, + uint8_t output_min, + uint8_t output_max, + uint32_t flags, + xnn_weights_cache_t weights_cache, + xnn_operator_t* fully_connected_op_out); + +enum xnn_status xnn_reshape_fully_connected_nc_qu8( + xnn_operator_t fully_connected_op, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_fully_connected_nc_qu8( + xnn_operator_t fully_connected_op, + const uint8_t* input, + uint8_t* output); + + +enum xnn_status xnn_create_max_pooling2d_nhwc_f16( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + float output_min, + float output_max, + uint32_t flags, + xnn_operator_t* max_pooling_op_out); + +enum xnn_status xnn_reshape_max_pooling2d_nhwc_f16( + xnn_operator_t max_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_max_pooling2d_nhwc_f16( + xnn_operator_t max_pooling_op, + const void* input, + void* output); + +enum xnn_status xnn_create_max_pooling2d_nhwc_f32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + float output_min, + float output_max, + uint32_t flags, + xnn_operator_t* max_pooling_op_out); + +enum xnn_status xnn_reshape_max_pooling2d_nhwc_f32( + xnn_operator_t max_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_max_pooling2d_nhwc_f32( + xnn_operator_t max_pooling_op, + const float* input, + float* output); + +enum xnn_status xnn_create_max_pooling2d_nhwc_s8( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + int8_t output_min, + int8_t output_max, + uint32_t flags, + xnn_operator_t* max_pooling_op_out); + +enum xnn_status xnn_reshape_max_pooling2d_nhwc_s8( + xnn_operator_t max_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_max_pooling2d_nhwc_s8( + xnn_operator_t max_pooling_op, + const int8_t* input, + int8_t* output); + +enum xnn_status xnn_create_max_pooling2d_nhwc_u8( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t stride_height, + uint32_t stride_width, + uint32_t dilation_height, + uint32_t dilation_width, + uint8_t output_min, + uint8_t output_max, + uint32_t flags, + xnn_operator_t* max_pooling_op_out); + +enum xnn_status xnn_reshape_max_pooling2d_nhwc_u8( + xnn_operator_t max_pooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_max_pooling2d_nhwc_u8( + xnn_operator_t max_pooling_op, + const uint8_t* input, + uint8_t* output); + +enum xnn_status xnn_create_reduce_nd( + enum xnn_reduce_operator reduce_operator_type, + enum xnn_datatype datatype, + const struct xnn_quantization_params* input_quantization, + const struct xnn_quantization_params* output_quantization, + uint32_t flags, + xnn_operator_t* reduce_op_out); + +enum xnn_status xnn_reshape_reduce_nd( // + xnn_operator_t reduce_op, // + size_t num_reduction_axes, // + const int64_t* reduction_axes, // + size_t num_input_dims, // + const size_t* input_shape, // + size_t* workspace_size, // + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_reduce_nd( + xnn_operator_t reduce_op, + void* workspace, + const void* input, + void* output); + +enum xnn_status xnn_create_resize_bilinear2d_nchw( + enum xnn_datatype datatype, + size_t output_height, + size_t output_width, + uint32_t flags, + xnn_operator_t* resize_op_out); + +enum xnn_status xnn_reshape_resize_bilinear2d_nchw( + xnn_operator_t resize_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_resize_bilinear2d_nchw( + xnn_operator_t resize_op, + const void* input, + void* output); + +enum xnn_status xnn_create_resize_bilinear2d_nhwc( + enum xnn_datatype datatype, + size_t output_height, + size_t output_width, + uint32_t flags, + xnn_operator_t* resize_op_out); + +enum xnn_status xnn_reshape_resize_bilinear2d_nhwc( + xnn_operator_t resize_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* workspace_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_resize_bilinear2d_nhwc( + xnn_operator_t resize_op, + void* workspace, + const void* input, + void* output); + +enum xnn_status xnn_create_rope_nthc_f16( + uint32_t flags, + xnn_operator_t* rope_op_out); + +enum xnn_status xnn_reshape_rope_nthc_f16( + xnn_operator_t rope_op, + size_t batch_size, + size_t tokens, + size_t heads, + size_t channels, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_rope_nthc_f16( + xnn_operator_t rope_op, + const void* input, + const void* weights, + void* output); + +enum xnn_status xnn_create_rope_nthc_f32( + uint32_t flags, + xnn_operator_t* rope_op_out); + +enum xnn_status xnn_reshape_rope_nthc_f32( + xnn_operator_t rope_op, + size_t batch_size, + size_t tokens, + size_t heads, + size_t channels, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_rope_nthc_f32( + xnn_operator_t rope_op, + const float* input, + const float* weights, + float* output); + +enum xnn_status xnn_create_slice_nd_x16( + uint32_t flags, + xnn_operator_t* slice_op_out); + +enum xnn_status xnn_reshape_slice_nd_x16( + xnn_operator_t slice_op, + size_t num_dims, + const size_t* input_shape, + const size_t* offsets, + const size_t* sizes, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_slice_nd_x16( + xnn_operator_t slice_op, + const void* input, + void* output); + +enum xnn_status xnn_create_slice_nd_x32( + uint32_t flags, + xnn_operator_t* slice_op_out); + +enum xnn_status xnn_reshape_slice_nd_x32( + xnn_operator_t slice_op, + size_t num_dims, + const size_t* input_shape, + const size_t* offsets, + const size_t* sizes, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_slice_nd_x32( + xnn_operator_t slice_op, + const void* input, + void* output); + +enum xnn_status xnn_run_slice_nd_x32( + size_t num_dims, + const size_t* input_shape, + const size_t* offsets, + const size_t* sizes, + const void* input, + void* output, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_softmax_nc_f16( + uint32_t flags, + xnn_operator_t* softmax_op_out); + +enum xnn_status xnn_reshape_softmax_nc_f16( + xnn_operator_t softmax_op, + size_t channels, + size_t input_stride, + size_t output_stride, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_softmax_nc_f16( + xnn_operator_t softmax_op, + const void* input, + void* output); + +enum xnn_status xnn_create_softmax_nc_f32( + uint32_t flags, + xnn_operator_t* softmax_op_out); + +enum xnn_status xnn_reshape_softmax_nc_f32( + xnn_operator_t softmax_op, + size_t channels, + size_t input_stride, + size_t output_stride, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_softmax_nc_f32( + xnn_operator_t softmax_op, + const float* input, + float* output); + +enum xnn_status xnn_create_softmax_nc_qu8( + float input_scale, + uint8_t output_zero_point, + float output_scale, + uint32_t flags, + xnn_operator_t* softmax_op_out); + +enum xnn_status xnn_reshape_softmax_nc_qu8( + xnn_operator_t softmax_op, + size_t channels, + size_t input_stride, + size_t output_stride, + size_t batch_size, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_softmax_nc_qu8( + xnn_operator_t softmax_op, + const uint8_t* input, + uint8_t* output); + +enum xnn_status xnn_create_space_to_depth_nhwc_x16( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* space_to_depth_op_out); + +enum xnn_status xnn_reshape_space_to_depth_nhwc_x16( + xnn_operator_t space_to_depth_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_space_to_depth_nhwc_x16( + xnn_operator_t space_to_depth_op, + const void* input, + void* output); + +enum xnn_status xnn_create_space_to_depth_nhwc_x32( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* space_to_depth_op_out); + +enum xnn_status xnn_reshape_space_to_depth_nhwc_x32( + xnn_operator_t space_to_depth_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_space_to_depth_nhwc_x32( + xnn_operator_t space_to_depth_op, + const void* input, + void* output); + +enum xnn_status xnn_create_transpose_nd_x8( + uint32_t flags, + xnn_operator_t* transpose_op_out); + +enum xnn_status xnn_reshape_transpose_nd_x8( + xnn_operator_t transpose_op, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_transpose_nd_x8( + xnn_operator_t transpose_op, + const void* input, + void* output); + +enum xnn_status xnn_run_transpose_nd_x8( + const void* input, + void* output, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_transpose_nd_x16( + uint32_t flags, + xnn_operator_t* transpose_op_out); + +enum xnn_status xnn_reshape_transpose_nd_x16( + xnn_operator_t transpose_op, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_transpose_nd_x16( + xnn_operator_t transpose_op, + const void* input, + void* output); + +enum xnn_status xnn_run_transpose_nd_x16( + const void* input, + void* output, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_transpose_nd_x32( + uint32_t flags, + xnn_operator_t* transpose_op_out); + +enum xnn_status xnn_reshape_transpose_nd_x32( + xnn_operator_t transpose_op, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_transpose_nd_x32( + xnn_operator_t transpose_op, + const void* input, + void* output); + +enum xnn_status xnn_run_transpose_nd_x32( + const void* input, + void* output, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_transpose_nd_x64( + uint32_t flags, + xnn_operator_t* transpose_op_out); + +enum xnn_status xnn_reshape_transpose_nd_x64( + xnn_operator_t transpose_op, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_transpose_nd_x64( + xnn_operator_t transpose_op, + const void* input, + void* output); + +enum xnn_status xnn_run_transpose_nd_x64( + const void* input, + void* output, + size_t num_dims, + const size_t* input_shape, + const size_t* output_perm, + uint32_t flags, + pthreadpool_t threadpool); + +enum xnn_status xnn_create_unpooling2d_nhwc_x32( + uint32_t input_padding_top, + uint32_t input_padding_right, + uint32_t input_padding_bottom, + uint32_t input_padding_left, + uint32_t pooling_height, + uint32_t pooling_width, + uint32_t flags, + xnn_operator_t* unpooling_op_out); + +enum xnn_status xnn_reshape_unpooling2d_nhwc_x32( + xnn_operator_t unpooling_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t channels, + size_t input_pixel_stride, + size_t output_pixel_stride, + size_t* output_height_out, + size_t* output_width_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_unpooling2d_nhwc_x32( + xnn_operator_t unpooling_op, + const void* input, + const uint32_t* index, + void* output); + +enum xnn_status xnn_create_slice_nd_x8( + uint32_t flags, + xnn_operator_t* slice_op_out); + +enum xnn_status xnn_reshape_slice_nd_x8( + xnn_operator_t slice_op, + size_t num_dims, + const size_t* input_shape, + const size_t* offsets, + const size_t* sizes, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_slice_nd_x8( + xnn_operator_t slice_op, + const void* input, + void* output); + +enum xnn_status xnn_create_space_to_depth_nhwc_x8( + uint32_t block_size, + uint32_t flags, + xnn_operator_t* space_to_depth_op_out); + +enum xnn_status xnn_reshape_space_to_depth_nhwc_x8( + xnn_operator_t space_to_depth_op, + size_t batch_size, + size_t input_height, + size_t input_width, + size_t input_channels, + size_t* output_height_out, + size_t* output_width_out, + size_t* output_channels_out, + pthreadpool_t threadpool); + +enum xnn_status xnn_setup_space_to_depth_nhwc_x8( + xnn_operator_t space_to_depth_op, + const void* input, + void* output); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/AliasAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/AliasAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..5beae79ad1a03a9cd06ff866e5ff307f2b8e3926 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/AliasAnalysis.h @@ -0,0 +1,284 @@ +//===- AliasAnalysis.h - Alias Analysis in MLIR -----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header file defines utilities and analyses for performing alias queries +// and related memory queries in MLIR. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_ALIASANALYSIS_H_ +#define MLIR_ANALYSIS_ALIASANALYSIS_H_ + +#include "mlir/IR/Operation.h" + +namespace mlir { + +//===----------------------------------------------------------------------===// +// AliasResult +//===----------------------------------------------------------------------===// + +/// The possible results of an alias query. +class AliasResult { +public: + enum Kind { + /// The two locations do not alias at all. + /// + /// This value is arranged to convert to false, while all other values + /// convert to true. This allows a boolean context to convert the result to + /// a binary flag indicating whether there is the possibility of aliasing. + NoAlias = 0, + /// The two locations may or may not alias. This is the least precise + /// result. + MayAlias, + /// The two locations alias, but only due to a partial overlap. + PartialAlias, + /// The two locations precisely alias each other. + MustAlias, + }; + + AliasResult(Kind kind) : kind(kind) {} + bool operator==(const AliasResult &other) const { return kind == other.kind; } + bool operator!=(const AliasResult &other) const { return !(*this == other); } + + /// Allow conversion to bool to signal if there is an aliasing or not. + explicit operator bool() const { return kind != NoAlias; } + + /// Merge this alias result with `other` and return a new result that + /// represents the conservative merge of both results. If the results + /// represent a known alias, the stronger alias is chosen (i.e. + /// Partial+Must=Must). If the two results are conflicting, MayAlias is + /// returned. + AliasResult merge(AliasResult other) const; + + /// Returns if this result indicates no possibility of aliasing. + bool isNo() const { return kind == NoAlias; } + + /// Returns if this result is a may alias. + bool isMay() const { return kind == MayAlias; } + + /// Returns if this result is a must alias. + bool isMust() const { return kind == MustAlias; } + + /// Returns if this result is a partial alias. + bool isPartial() const { return kind == PartialAlias; } + + /// Print this alias result to the provided output stream. + void print(raw_ostream &os) const; + +private: + /// The internal kind of the result. + Kind kind; +}; + +inline raw_ostream &operator<<(raw_ostream &os, const AliasResult &result) { + result.print(os); + return os; +} + +//===----------------------------------------------------------------------===// +// ModRefResult +//===----------------------------------------------------------------------===// + +/// The possible results of whether a memory access modifies or references +/// a memory location. The possible results are: no access at all, a +/// modification, a reference, or both a modification and a reference. +class [[nodiscard]] ModRefResult { + /// Note: This is a simplified version of the ModRefResult in + /// `llvm/Analysis/AliasAnalysis.h`, and namely removes the `Must` concept. If + /// this becomes useful/necessary we should add it here. + enum class Kind { + /// The access neither references nor modifies the value stored in memory. + NoModRef = 0, + /// The access may reference the value stored in memory. + Ref = 1, + /// The access may modify the value stored in memory. + Mod = 2, + /// The access may reference and may modify the value stored in memory. + ModRef = Ref | Mod, + }; + +public: + bool operator==(const ModRefResult &rhs) const { return kind == rhs.kind; } + bool operator!=(const ModRefResult &rhs) const { return !(*this == rhs); } + + /// Return a new result that indicates that the memory access neither + /// references nor modifies the value stored in memory. + static ModRefResult getNoModRef() { return Kind::NoModRef; } + + /// Return a new result that indicates that the memory access may reference + /// the value stored in memory. + static ModRefResult getRef() { return Kind::Ref; } + + /// Return a new result that indicates that the memory access may modify the + /// value stored in memory. + static ModRefResult getMod() { return Kind::Mod; } + + /// Return a new result that indicates that the memory access may reference + /// and may modify the value stored in memory. + static ModRefResult getModAndRef() { return Kind::ModRef; } + + /// Returns if this result does not modify or reference memory. + [[nodiscard]] bool isNoModRef() const { return kind == Kind::NoModRef; } + + /// Returns if this result modifies memory. + [[nodiscard]] bool isMod() const { + return static_cast(kind) & static_cast(Kind::Mod); + } + + /// Returns if this result references memory. + [[nodiscard]] bool isRef() const { + return static_cast(kind) & static_cast(Kind::Ref); + } + + /// Returns if this result modifies *or* references memory. + [[nodiscard]] bool isModOrRef() const { return kind != Kind::NoModRef; } + + /// Returns if this result modifies *and* references memory. + [[nodiscard]] bool isModAndRef() const { return kind == Kind::ModRef; } + + /// Merge this ModRef result with `other` and return the result. + ModRefResult merge(const ModRefResult &other) { + return ModRefResult(static_cast(static_cast(kind) | + static_cast(other.kind))); + } + /// Intersect this ModRef result with `other` and return the result. + ModRefResult intersect(const ModRefResult &other) { + return ModRefResult(static_cast(static_cast(kind) & + static_cast(other.kind))); + } + + /// Print this ModRef result to the provided output stream. + void print(raw_ostream &os) const; + +private: + ModRefResult(Kind kind) : kind(kind) {} + + /// The internal kind of the result. + Kind kind; +}; + +inline raw_ostream &operator<<(raw_ostream &os, const ModRefResult &result) { + result.print(os); + return os; +} + +//===----------------------------------------------------------------------===// +// AliasAnalysisTraits +//===----------------------------------------------------------------------===// + +namespace detail { +/// This class contains various internal trait classes used by the main +/// AliasAnalysis class below. +struct AliasAnalysisTraits { + /// This class represents the `Concept` of an alias analysis implementation. + /// It is the abstract base class used by the AliasAnalysis class for + /// querying into derived analysis implementations. + class Concept { + public: + virtual ~Concept() = default; + + /// Given two values, return their aliasing behavior. + virtual AliasResult alias(Value lhs, Value rhs) = 0; + + /// Return the modify-reference behavior of `op` on `location`. + virtual ModRefResult getModRef(Operation *op, Value location) = 0; + }; + + /// This class represents the `Model` of an alias analysis implementation + /// `ImplT`. A model is instantiated for each alias analysis implementation + /// to implement the `Concept` without the need for the derived + /// implementation to inherit from the `Concept` class. + template + class Model final : public Concept { + public: + explicit Model(ImplT &&impl) : impl(std::forward(impl)) {} + ~Model() override = default; + + /// Given two values, return their aliasing behavior. + AliasResult alias(Value lhs, Value rhs) final { + return impl.alias(lhs, rhs); + } + + /// Return the modify-reference behavior of `op` on `location`. + ModRefResult getModRef(Operation *op, Value location) final { + return impl.getModRef(op, location); + } + + private: + ImplT impl; + }; +}; +} // namespace detail + +//===----------------------------------------------------------------------===// +// AliasAnalysis +//===----------------------------------------------------------------------===// + +/// This class represents the main alias analysis interface in MLIR. It +/// functions as an aggregate of various different alias analysis +/// implementations. This aggregation allows for utilizing the strengths of +/// different alias analysis implementations that either target or have access +/// to different aliasing information. This is especially important for MLIR +/// given the scope of different types of memory models and aliasing behaviors. +/// For users of this analysis that want to perform aliasing queries, see the +/// `Alias Queries` section below for the available methods. For users of this +/// analysis that want to add a new alias analysis implementation to the +/// aggregate, see the `Alias Implementations` section below. +class AliasAnalysis { + using Concept = detail::AliasAnalysisTraits::Concept; + template + using Model = detail::AliasAnalysisTraits::Model; + +public: + AliasAnalysis(Operation *op); + + //===--------------------------------------------------------------------===// + // Alias Implementations + //===--------------------------------------------------------------------===// + + /// Add a new alias analysis implementation `AnalysisT` to this analysis + /// aggregate. This allows for users to access this implementation when + /// performing alias queries. Implementations added here must provide the + /// following: + /// * AnalysisT(AnalysisT &&) + /// * AliasResult alias(Value lhs, Value rhs) + /// - This method returns an `AliasResult` that corresponds to the + /// aliasing behavior between `lhs` and `rhs`. The conservative "I don't + /// know" result of this method should be MayAlias. + /// * ModRefResult getModRef(Operation *op, Value location) + /// - This method returns a `ModRefResult` that corresponds to the + /// modify-reference behavior of `op` on the given `location`. The + /// conservative "I don't know" result of this method should be ModRef. + template + void addAnalysisImplementation(AnalysisT &&analysis) { + aliasImpls.push_back( + std::make_unique>(std::forward(analysis))); + } + + //===--------------------------------------------------------------------===// + // Alias Queries + //===--------------------------------------------------------------------===// + + /// Given two values, return their aliasing behavior. + AliasResult alias(Value lhs, Value rhs); + + //===--------------------------------------------------------------------===// + // ModRef Queries + //===--------------------------------------------------------------------===// + + /// Return the modify-reference behavior of `op` on `location`. + ModRefResult getModRef(Operation *op, Value location); + +private: + /// A set of internal alias analysis implementations. + SmallVector, 4> aliasImpls; +}; + +} // namespace mlir + +#endif // MLIR_ANALYSIS_ALIASANALYSIS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/AliasAnalysis/LocalAliasAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/AliasAnalysis/LocalAliasAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..a9b4d5b2b66e52990dcab7f5b16faf2cf592db92 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/AliasAnalysis/LocalAliasAnalysis.h @@ -0,0 +1,40 @@ +//===- LocalAliasAnalysis.h - Local Stateless Alias Analysis ----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains the implementation of a local stateless alias analysis. +// This analysis walks from the values being compared to determine their +// potential for aliasing. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_ALIASANALYSIS_LOCALALIASANALYSIS_H_ +#define MLIR_ANALYSIS_ALIASANALYSIS_LOCALALIASANALYSIS_H_ + +#include "mlir/Analysis/AliasAnalysis.h" + +namespace mlir { +/// This class implements a local form of alias analysis that tries to identify +/// the underlying values addressed by each value and performs a few basic +/// checks to see if they alias. +class LocalAliasAnalysis { +public: + virtual ~LocalAliasAnalysis() = default; + + /// Given two values, return their aliasing behavior. + AliasResult alias(Value lhs, Value rhs); + + /// Return the modify-reference behavior of `op` on `location`. + ModRefResult getModRef(Operation *op, Value location); + +protected: + /// Given the two values, return their aliasing behavior. + virtual AliasResult aliasImpl(Value lhs, Value rhs); +}; +} // namespace mlir + +#endif // MLIR_ANALYSIS_ALIASANALYSIS_LOCALALIASANALYSIS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/CFGLoopInfo.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/CFGLoopInfo.h new file mode 100644 index 0000000000000000000000000000000000000000..15ac0d71cb94db06e1dee15db865d9c520681fd8 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/CFGLoopInfo.h @@ -0,0 +1,54 @@ +//===- CFGLoopInfo.h - LoopInfo analysis for region bodies ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the CFGLoopInfo analysis for MLIR. The CFGLoopInfo is used +// to identify natural loops and determine the loop depth of various nodes of a +// CFG. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_LOOPINFO_H +#define MLIR_ANALYSIS_LOOPINFO_H + +#include "mlir/IR/Dominance.h" +#include "mlir/IR/RegionGraphTraits.h" +#include "llvm/Support/GenericLoopInfo.h" + +namespace mlir { +class CFGLoop; +class CFGLoopInfo; +} // namespace mlir + +namespace llvm { +// Implementation in LLVM's LoopInfoImpl.h +extern template class LoopBase; +extern template class LoopInfoBase; +} // namespace llvm + +namespace mlir { + +/// Representation of a single loop formed by blocks. The inherited LoopBase +/// class provides accessors to the loop analysis. +class CFGLoop : public llvm::LoopBase { +private: + explicit CFGLoop(mlir::Block *block); + + friend class llvm::LoopBase; + friend class llvm::LoopInfoBase; +}; + +/// An LLVM LoopInfo instantiation for MLIR that provides access to CFG loops +/// found in the dominator tree. +class CFGLoopInfo : public llvm::LoopInfoBase { +public: + CFGLoopInfo(const llvm::DominatorTreeBase &domTree); +}; + +} // namespace mlir + +#endif // MLIR_ANALYSIS_LOOPINFO_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/CallGraph.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/CallGraph.h new file mode 100644 index 0000000000000000000000000000000000000000..631cdd1ad229092e5205135d00f4e59d18b717e3 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/CallGraph.h @@ -0,0 +1,267 @@ +//===- CallGraph.h - CallGraph analysis for MLIR ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains an analysis for computing the multi-level callgraph from a +// given top-level operation. This nodes within this callgraph are defined by +// the `CallOpInterface` and `CallableOpInterface` operation interfaces defined +// in CallInterface.td. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_CALLGRAPH_H +#define MLIR_ANALYSIS_CALLGRAPH_H + +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/GraphTraits.h" +#include "llvm/ADT/MapVector.h" +#include "llvm/ADT/PointerIntPair.h" +#include "llvm/ADT/SetVector.h" + +namespace mlir { +class CallOpInterface; +struct CallInterfaceCallable; +class Operation; +class Region; +class SymbolTableCollection; + +//===----------------------------------------------------------------------===// +// CallGraphNode +//===----------------------------------------------------------------------===// + +/// This class represents a single callable in the callgraph. Aside from the +/// external node, each node represents a callable node in the graph and +/// contains a valid corresponding Region. The external node is a virtual node +/// used to represent external edges into, and out of, the callgraph. +class CallGraphNode { +public: + /// This class represents a directed edge between two nodes in the callgraph. + class Edge { + enum class Kind { + // An 'Abstract' edge represents an opaque, non-operation, reference + // between this node and the target. Edges of this type are only valid + // from the external node, as there is no valid connection to an operation + // in the module. + Abstract, + + // A 'Call' edge represents a direct reference to the target node via a + // call-like operation within the callable region of this node. + Call, + + // A 'Child' edge is used when the region of target node is defined inside + // of the callable region of this node. This means that the region of this + // node is an ancestor of the region for the target node. As such, this + // edge cannot be used on the 'external' node. + Child, + }; + + public: + /// Returns true if this edge represents an `Abstract` edge. + bool isAbstract() const { return targetAndKind.getInt() == Kind::Abstract; } + + /// Returns true if this edge represents a `Call` edge. + bool isCall() const { return targetAndKind.getInt() == Kind::Call; } + + /// Returns true if this edge represents a `Child` edge. + bool isChild() const { return targetAndKind.getInt() == Kind::Child; } + + /// Returns the target node for this edge. + CallGraphNode *getTarget() const { return targetAndKind.getPointer(); } + + bool operator==(const Edge &edge) const { + return targetAndKind == edge.targetAndKind; + } + + private: + Edge(CallGraphNode *node, Kind kind) : targetAndKind(node, kind) {} + explicit Edge(llvm::PointerIntPair targetAndKind) + : targetAndKind(targetAndKind) {} + + /// The target node of this edge, as well as the edge kind. + llvm::PointerIntPair targetAndKind; + + // Provide access to the constructor and Kind. + friend class CallGraphNode; + }; + + /// Returns true if this node is an external node. + bool isExternal() const; + + /// Returns the callable region this node represents. This can only be called + /// on non-external nodes. + Region *getCallableRegion() const; + + /// Adds an abstract reference edge to the given node. An abstract edge does + /// not come from any observable operations, so this is only valid on the + /// external node. + void addAbstractEdge(CallGraphNode *node); + + /// Add an outgoing call edge from this node. + void addCallEdge(CallGraphNode *node); + + /// Adds a reference edge to the given child node. + void addChildEdge(CallGraphNode *child); + + /// Iterator over the outgoing edges of this node. + using iterator = SmallVectorImpl::const_iterator; + iterator begin() const { return edges.begin(); } + iterator end() const { return edges.end(); } + + /// Returns true if this node has any child edges. + bool hasChildren() const; + +private: + /// DenseMap info for callgraph edges. + struct EdgeKeyInfo { + using BaseInfo = + DenseMapInfo>; + + static Edge getEmptyKey() { return Edge(BaseInfo::getEmptyKey()); } + static Edge getTombstoneKey() { return Edge(BaseInfo::getTombstoneKey()); } + static unsigned getHashValue(const Edge &edge) { + return BaseInfo::getHashValue(edge.targetAndKind); + } + static bool isEqual(const Edge &lhs, const Edge &rhs) { return lhs == rhs; } + }; + + CallGraphNode(Region *callableRegion) : callableRegion(callableRegion) {} + + /// Add an edge to 'node' with the given kind. + void addEdge(CallGraphNode *node, Edge::Kind kind); + + /// The callable region defines the boundary of the call graph node. This is + /// the region referenced by 'call' operations. This is at a per-region + /// boundary as operations may define multiple callable regions. + Region *callableRegion; + + /// A set of out-going edges from this node to other nodes in the graph. + SetVector, + llvm::SmallDenseSet> + edges; + + // Provide access to private methods. + friend class CallGraph; +}; + +//===----------------------------------------------------------------------===// +// CallGraph +//===----------------------------------------------------------------------===// + +class CallGraph { + using NodeMapT = llvm::MapVector>; + + /// This class represents an iterator over the internal call graph nodes. This + /// class unwraps the map iterator to access the raw node. + class NodeIterator final + : public llvm::mapped_iterator< + NodeMapT::const_iterator, + CallGraphNode *(*)(const NodeMapT::value_type &)> { + static CallGraphNode *unwrap(const NodeMapT::value_type &value) { + return value.second.get(); + } + + public: + /// Initializes the result type iterator to the specified result iterator. + NodeIterator(NodeMapT::const_iterator it) + : llvm::mapped_iterator< + NodeMapT::const_iterator, + CallGraphNode *(*)(const NodeMapT::value_type &)>(it, &unwrap) {} + }; + +public: + CallGraph(Operation *op); + + /// Get or add a call graph node for the given region. `parentNode` + /// corresponds to the direct node in the callgraph that contains the parent + /// operation of `region`, or nullptr if there is no parent node. + CallGraphNode *getOrAddNode(Region *region, CallGraphNode *parentNode); + + /// Lookup a call graph node for the given region, or nullptr if none is + /// registered. + CallGraphNode *lookupNode(Region *region) const; + + /// Return the callgraph node representing an external caller. + CallGraphNode *getExternalCallerNode() const { + return const_cast(&externalCallerNode); + } + + /// Return the callgraph node representing an indirect callee. + CallGraphNode *getUnknownCalleeNode() const { + return const_cast(&unknownCalleeNode); + } + + /// Resolve the callable for given callee to a node in the callgraph, or the + /// external node if a valid node was not resolved. The provided symbol table + /// is used when resolving calls that reference callables via a symbol + /// reference. + CallGraphNode *resolveCallable(CallOpInterface call, + SymbolTableCollection &symbolTable) const; + + /// Erase the given node from the callgraph. + void eraseNode(CallGraphNode *node); + + /// An iterator over the nodes of the graph. + using iterator = NodeIterator; + iterator begin() const { return nodes.begin(); } + iterator end() const { return nodes.end(); } + + /// Dump the graph in a human readable format. + void dump() const; + void print(raw_ostream &os) const; + +private: + /// The set of nodes within the callgraph. + NodeMapT nodes; + + /// A special node used to indicate an external caller. + CallGraphNode externalCallerNode; + + /// A special node used to indicate an unknown callee. + CallGraphNode unknownCalleeNode; +}; + +} // namespace mlir + +namespace llvm { +// Provide graph traits for traversing call graphs using standard graph +// traversals. +template <> +struct GraphTraits { + using NodeRef = mlir::CallGraphNode *; + static NodeRef getEntryNode(NodeRef node) { return node; } + + static NodeRef unwrap(const mlir::CallGraphNode::Edge &edge) { + return edge.getTarget(); + } + + // ChildIteratorType/begin/end - Allow iteration over all nodes in the graph. + using ChildIteratorType = + mapped_iterator; + static ChildIteratorType child_begin(NodeRef node) { + return {node->begin(), &unwrap}; + } + static ChildIteratorType child_end(NodeRef node) { + return {node->end(), &unwrap}; + } +}; + +template <> +struct GraphTraits + : public GraphTraits { + /// The entry node into the graph is the external node. + static NodeRef getEntryNode(const mlir::CallGraph *cg) { + return cg->getExternalCallerNode(); + } + + // nodes_iterator/begin/end - Allow iteration over all nodes in the graph + using nodes_iterator = mlir::CallGraph::iterator; + static nodes_iterator nodes_begin(mlir::CallGraph *cg) { return cg->begin(); } + static nodes_iterator nodes_end(mlir::CallGraph *cg) { return cg->end(); } +}; +} // namespace llvm + +#endif // MLIR_ANALYSIS_CALLGRAPH_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/ConstantPropagationAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/ConstantPropagationAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..d2d4ff9960ea36761a5c6ea590259bed987c1520 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/ConstantPropagationAnalysis.h @@ -0,0 +1,115 @@ +//===- ConstantPropagationAnalysis.h - Constant propagation analysis ------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements constant propagation analysis. In this file are defined +// the lattice value class that represents constant values in the program and +// a sparse constant propagation analysis that uses operation folders to +// speculate about constant values in the program. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATAFLOW_CONSTANTPROPAGATIONANALYSIS_H +#define MLIR_ANALYSIS_DATAFLOW_CONSTANTPROPAGATIONANALYSIS_H + +#include "mlir/Analysis/DataFlow/SparseAnalysis.h" +#include + +namespace mlir { +namespace dataflow { + +//===----------------------------------------------------------------------===// +// ConstantValue +//===----------------------------------------------------------------------===// + +/// This lattice value represents a known constant value of a lattice. +class ConstantValue { +public: + /// Construct a constant value as uninitialized. + explicit ConstantValue() = default; + + /// Construct a constant value with a known constant. + explicit ConstantValue(Attribute constant, Dialect *dialect) + : constant(constant), dialect(dialect) {} + + /// Get the constant value. Returns null if no value was determined. + Attribute getConstantValue() const { + assert(!isUninitialized()); + return *constant; + } + + /// Get the dialect instance that can be used to materialize the constant. + Dialect *getConstantDialect() const { + assert(!isUninitialized()); + return dialect; + } + + /// Compare the constant values. + bool operator==(const ConstantValue &rhs) const { + return constant == rhs.constant; + } + + /// Print the constant value. + void print(raw_ostream &os) const; + + /// The state where the constant value is uninitialized. This happens when the + /// state hasn't been set during the analysis. + static ConstantValue getUninitialized() { return ConstantValue{}; } + + /// Whether the state is uninitialized. + bool isUninitialized() const { return !constant.has_value(); } + + /// The state where the constant value is unknown. + static ConstantValue getUnknownConstant() { + return ConstantValue{/*constant=*/nullptr, /*dialect=*/nullptr}; + } + + /// The union with another constant value is null if they are different, and + /// the same if they are the same. + static ConstantValue join(const ConstantValue &lhs, + const ConstantValue &rhs) { + if (lhs.isUninitialized()) + return rhs; + if (rhs.isUninitialized()) + return lhs; + if (lhs == rhs) + return lhs; + return getUnknownConstant(); + } + +private: + /// The constant value. + std::optional constant; + /// A dialect instance that can be used to materialize the constant. + Dialect *dialect = nullptr; +}; + +//===----------------------------------------------------------------------===// +// SparseConstantPropagation +//===----------------------------------------------------------------------===// + +/// This analysis implements sparse constant propagation, which attempts to +/// determine constant-valued results for operations using constant-valued +/// operands, by speculatively folding operations. When combined with dead-code +/// analysis, this becomes sparse conditional constant propagation (SCCP). +class SparseConstantPropagation + : public SparseForwardDataFlowAnalysis> { +public: + using SparseForwardDataFlowAnalysis::SparseForwardDataFlowAnalysis; + + LogicalResult + visitOperation(Operation *op, + ArrayRef *> operands, + ArrayRef *> results) override; + + void setToEntryState(Lattice *lattice) override; +}; + +} // end namespace dataflow +} // end namespace mlir + +#endif // MLIR_ANALYSIS_DATAFLOW_CONSTANTPROPAGATIONANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/DeadCodeAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/DeadCodeAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..2250db823b551982fba878e28aa5a5baf6ebc45b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/DeadCodeAnalysis.h @@ -0,0 +1,239 @@ +//===- DeadCodeAnalysis.h - Dead code analysis ----------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements dead code analysis using the data-flow analysis +// framework. This analysis uses the results of constant propagation to +// determine live blocks, control-flow edges, and control-flow predecessors. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATAFLOW_DEADCODEANALYSIS_H +#define MLIR_ANALYSIS_DATAFLOW_DEADCODEANALYSIS_H + +#include "mlir/Analysis/DataFlowFramework.h" +#include "mlir/IR/SymbolTable.h" +#include "llvm/ADT/SmallPtrSet.h" +#include + +namespace mlir { + +class CallOpInterface; +class CallableOpInterface; +class BranchOpInterface; +class RegionBranchOpInterface; +class RegionBranchTerminatorOpInterface; + +namespace dataflow { + +//===----------------------------------------------------------------------===// +// Executable +//===----------------------------------------------------------------------===// + +/// This is a simple analysis state that represents whether the associated +/// lattice anchor (either a block or a control-flow edge) is live. +class Executable : public AnalysisState { +public: + using AnalysisState::AnalysisState; + + /// Set the state of the lattice anchor to live. + ChangeResult setToLive(); + + /// Get whether the lattice anchor is live. + bool isLive() const { return live; } + + /// Print the liveness. + void print(raw_ostream &os) const override; + + /// When the state of the lattice anchor is changed to live, re-invoke + /// subscribed analyses on the operations in the block and on the block + /// itself. + void onUpdate(DataFlowSolver *solver) const override; + + /// Subscribe an analysis to changes to the liveness. + void blockContentSubscribe(DataFlowAnalysis *analysis) { + subscribers.insert(analysis); + } + +private: + /// Whether the lattice anchor is live. Optimistically assume that the lattice + /// anchor is dead. + bool live = false; + + /// A set of analyses that should be updated when this state changes. + SetVector, + SmallPtrSet> + subscribers; +}; + +//===----------------------------------------------------------------------===// +// PredecessorState +//===----------------------------------------------------------------------===// + +/// This analysis state represents a set of live control-flow "predecessors" of +/// a program point (either an operation or a block), which are the last +/// operations along all execution paths that pass through this point. +/// +/// For example, in dead-code analysis, an operation with region control-flow +/// can be the predecessor of a region's entry block or itself, the exiting +/// terminator of a region can be the predecessor of the parent operation or +/// another region's entry block, the callsite of a callable operation can be +/// the predecessor to its entry block, and the exiting terminator or a callable +/// operation can be the predecessor of the call operation. +/// +/// The state can optionally contain information about which values are +/// propagated from each predecessor to the successor point. +/// +/// The state can indicate that it is underdefined, meaning that not all live +/// control-flow predecessors can be known. +class PredecessorState : public AnalysisState { +public: + using AnalysisState::AnalysisState; + + /// Print the known predecessors. + void print(raw_ostream &os) const override; + + /// Returns true if all predecessors are known. + bool allPredecessorsKnown() const { return allKnown; } + + /// Indicate that there are potentially unknown predecessors. + ChangeResult setHasUnknownPredecessors() { + return std::exchange(allKnown, false) ? ChangeResult::Change + : ChangeResult::NoChange; + } + + /// Get the known predecessors. + ArrayRef getKnownPredecessors() const { + return knownPredecessors.getArrayRef(); + } + + /// Get the successor inputs from a predecessor. + ValueRange getSuccessorInputs(Operation *predecessor) const { + return successorInputs.lookup(predecessor); + } + + /// Add a known predecessor. + ChangeResult join(Operation *predecessor); + + /// Add a known predecessor with successor inputs. + ChangeResult join(Operation *predecessor, ValueRange inputs); + +private: + /// Whether all predecessors are known. Optimistically assume that we know + /// all predecessors. + bool allKnown = true; + + /// The known control-flow predecessors of this program point. + SetVector, + SmallPtrSet> + knownPredecessors; + + /// The successor inputs when branching from a given predecessor. + DenseMap successorInputs; +}; + +//===----------------------------------------------------------------------===// +// CFGEdge +//===----------------------------------------------------------------------===// + +/// This lattice anchor represents a control-flow edge between a block and one +/// of its successors. +class CFGEdge + : public GenericLatticeAnchorBase> { +public: + using Base::Base; + + /// Get the block from which the edge originates. + Block *getFrom() const { return getValue().first; } + /// Get the target block. + Block *getTo() const { return getValue().second; } + + /// Print the blocks between the control-flow edge. + void print(raw_ostream &os) const override; + /// Get a fused location of both blocks. + Location getLoc() const override; +}; + +//===----------------------------------------------------------------------===// +// DeadCodeAnalysis +//===----------------------------------------------------------------------===// + +/// Dead code analysis analyzes control-flow, as understood by +/// `RegionBranchOpInterface` and `BranchOpInterface`, and the callgraph, as +/// understood by `CallableOpInterface` and `CallOpInterface`. +/// +/// This analysis uses known constant values of operands to determine the +/// liveness of each block and each edge between a block and its predecessors. +/// For region control-flow, this analysis determines the predecessor operations +/// for region entry blocks and region control-flow operations. For the +/// callgraph, this analysis determines the callsites and live returns of every +/// function. +class DeadCodeAnalysis : public DataFlowAnalysis { +public: + explicit DeadCodeAnalysis(DataFlowSolver &solver); + + /// Initialize the analysis by visiting every operation with potential + /// control-flow semantics. + LogicalResult initialize(Operation *top) override; + + /// Visit an operation with control-flow semantics and deduce which of its + /// successors are live. + LogicalResult visit(ProgramPoint *point) override; + +private: + /// Find and mark symbol callables with potentially unknown callsites as + /// having overdefined predecessors. `top` is the top-level operation that the + /// analysis is operating on. + void initializeSymbolCallables(Operation *top); + + /// Recursively Initialize the analysis on nested regions. + LogicalResult initializeRecursively(Operation *op); + + /// Visit the given call operation and compute any necessary lattice state. + void visitCallOperation(CallOpInterface call); + + /// Visit the given branch operation with successors and try to determine + /// which are live from the current block. + void visitBranchOperation(BranchOpInterface branch); + + /// Visit the given region branch operation, which defines regions, and + /// compute any necessary lattice state. This also resolves the lattice state + /// of both the operation results and any nested regions. + void visitRegionBranchOperation(RegionBranchOpInterface branch); + + /// Visit the given terminator operation that exits a region under an + /// operation with control-flow semantics. These are terminators with no CFG + /// successors. + void visitRegionTerminator(Operation *op, RegionBranchOpInterface branch); + + /// Visit the given terminator operation that exits a callable region. These + /// are terminators with no CFG successors. + void visitCallableTerminator(Operation *op, CallableOpInterface callable); + + /// Mark the edge between `from` and `to` as executable. + void markEdgeLive(Block *from, Block *to); + + /// Mark the entry blocks of the operation as executable. + void markEntryBlocksLive(Operation *op); + + /// Get the constant values of the operands of the operation. Returns + /// std::nullopt if any of the operand lattices are uninitialized. + std::optional> getOperandValues(Operation *op); + + /// The top-level operation the analysis is running on. This is used to detect + /// if a callable is outside the scope of the analysis and thus must be + /// considered an external callable. + Operation *analysisScope; + + /// A symbol table used for O(1) symbol lookups during simplification. + SymbolTableCollection symbolTable; +}; + +} // end namespace dataflow +} // end namespace mlir + +#endif // MLIR_ANALYSIS_DATAFLOW_DEADCODEANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/DenseAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/DenseAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..8bcfe51ad7cd1c90e9b481c0df92c34c3c9ad5cf --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/DenseAnalysis.h @@ -0,0 +1,585 @@ +//===- DenseAnalysis.h - Dense data-flow analysis -------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements dense data-flow analysis using the data-flow analysis +// framework. The analysis is forward and conditional and uses the results of +// dead code analysis to prune dead code during the analysis. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DENSEDATAFLOWANALYSIS_H +#define MLIR_ANALYSIS_DENSEDATAFLOWANALYSIS_H + +#include "mlir/Analysis/DataFlowFramework.h" +#include "mlir/IR/SymbolTable.h" +#include "mlir/Interfaces/CallInterfaces.h" +#include "mlir/Interfaces/ControlFlowInterfaces.h" + +namespace mlir { +namespace dataflow { + +//===----------------------------------------------------------------------===// +// CallControlFlowAction +//===----------------------------------------------------------------------===// + +/// Indicates whether the control enters, exits, or skips over the callee (in +/// the case of external functions). +enum class CallControlFlowAction { EnterCallee, ExitCallee, ExternalCallee }; + +//===----------------------------------------------------------------------===// +// AbstractDenseLattice +//===----------------------------------------------------------------------===// + +/// This class represents a dense lattice. A dense lattice is attached to +/// program point to represent the program state at the program point. +/// lattice is propagated through the IR by dense data-flow analysis. +class AbstractDenseLattice : public AnalysisState { +public: + /// A dense lattice can only be created for operations and blocks. + using AnalysisState::AnalysisState; + + /// Join the lattice across control-flow or callgraph edges. + virtual ChangeResult join(const AbstractDenseLattice &rhs) { + return ChangeResult::NoChange; + } + + virtual ChangeResult meet(const AbstractDenseLattice &rhs) { + return ChangeResult::NoChange; + } +}; + +//===----------------------------------------------------------------------===// +// AbstractDenseForwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// Base class for dense forward data-flow analyses. Dense data-flow analysis +/// attaches a lattice to program points and implements a transfer function from +/// the lattice before each operation to the lattice after. The lattice contains +/// information about the state of the program at that program point. +/// +/// Visit a program point in forward dense data-flow analysis will invoke the +/// transfer function of the operation preceding the program point iterator. +/// Visit a program point at the begining of block will visit the block itself. +class AbstractDenseForwardDataFlowAnalysis : public DataFlowAnalysis { +public: + using DataFlowAnalysis::DataFlowAnalysis; + + /// Initialize the analysis by visiting every program point whose execution + /// may modify the program state; that is, every operation and block. + LogicalResult initialize(Operation *top) override; + + /// Initialize lattice anchor equivalence class from the provided top-level + /// operation. + /// + /// This function will union lattice anchor to same equivalent class if the + /// analysis can determine the lattice content of lattice anchor is + /// necessarily identical under the corrensponding lattice type. + virtual void initializeEquivalentLatticeAnchor(Operation *top) override; + + /// Visit a program point that modifies the state of the program. If the + /// program point is at the beginning of a block, then the state is propagated + /// from control-flow predecessors or callsites. If the operation before + /// program point iterator is a call operation or region control-flow + /// operation, then the state after the execution of the operation is set by + /// control-flow or the callgraph. Otherwise, this function invokes the + /// operation transfer function before the program point iterator. + LogicalResult visit(ProgramPoint *point) override; + +protected: + /// Propagate the dense lattice before the execution of an operation to the + /// lattice after its execution. + virtual LogicalResult visitOperationImpl(Operation *op, + const AbstractDenseLattice &before, + AbstractDenseLattice *after) = 0; + + /// Get the dense lattice on the given lattice anchor. + virtual AbstractDenseLattice *getLattice(LatticeAnchor anchor) = 0; + + /// Get the dense lattice on the given lattice anchor and add dependent as its + /// dependency. That is, every time the lattice after anchor is updated, the + /// dependent program point must be visited, and the newly triggered visit + /// might update the lattice on dependent. + virtual const AbstractDenseLattice *getLatticeFor(ProgramPoint *dependent, + LatticeAnchor anchor) = 0; + + /// Set the dense lattice at control flow entry point and propagate an update + /// if it changed. + virtual void setToEntryState(AbstractDenseLattice *lattice) = 0; + + /// Join a lattice with another and propagate an update if it changed. + void join(AbstractDenseLattice *lhs, const AbstractDenseLattice &rhs) { + propagateIfChanged(lhs, lhs->join(rhs)); + } + + /// Visit an operation. If this is a call operation or region control-flow + /// operation, then the state after the execution of the operation is set by + /// control-flow or the callgraph. Otherwise, this function invokes the + /// operation transfer function. + virtual LogicalResult processOperation(Operation *op); + + /// Visit an operation. If this analysis can confirm that lattice content + /// of lattice anchors around operation are necessarily identical, join + /// them into the same equivalent class. + virtual void buildOperationEquivalentLatticeAnchor(Operation *op) {} + + /// Propagate the dense lattice forward along the control flow edge from + /// `regionFrom` to `regionTo` regions of the `branch` operation. `nullopt` + /// values correspond to control flow branches originating at or targeting the + /// `branch` operation itself. Default implementation just joins the states, + /// meaning that operations implementing `RegionBranchOpInterface` don't have + /// any effect on the lattice that isn't already expressed by the interface + /// itself. + virtual void visitRegionBranchControlFlowTransfer( + RegionBranchOpInterface branch, std::optional regionFrom, + std::optional regionTo, const AbstractDenseLattice &before, + AbstractDenseLattice *after) { + join(after, before); + } + + /// Propagate the dense lattice forward along the call control flow edge, + /// which can be either entering or exiting the callee. Default implementation + /// for enter and exit callee actions just meets the states, meaning that + /// operations implementing `CallOpInterface` don't have any effect on the + /// lattice that isn't already expressed by the interface itself. Default + /// implementation for the external callee action additionally sets the + /// "after" lattice to the entry state. + virtual void visitCallControlFlowTransfer(CallOpInterface call, + CallControlFlowAction action, + const AbstractDenseLattice &before, + AbstractDenseLattice *after) { + join(after, before); + // Note that `setToEntryState` may be a "partial fixpoint" for some + // lattices, e.g., lattices that are lists of maps of other lattices will + // only set fixpoint for "known" lattices. + if (action == CallControlFlowAction::ExternalCallee) + setToEntryState(after); + } + + /// Visit a program point within a region branch operation with predecessors + /// in it. This can either be an entry block of one of the regions of the + /// parent operation itself. + void visitRegionBranchOperation(ProgramPoint *point, + RegionBranchOpInterface branch, + AbstractDenseLattice *after); + +private: + /// Visit a block. The state at the start of the block is propagated from + /// control-flow predecessors or callsites. + void visitBlock(Block *block); + + /// Visit an operation for which the data flow is described by the + /// `CallOpInterface`. + void visitCallOperation(CallOpInterface call, + const AbstractDenseLattice &before, + AbstractDenseLattice *after); +}; + +//===----------------------------------------------------------------------===// +// DenseForwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// A dense forward data-flow analysis for propagating lattices before and +/// after the execution of every operation across the IR by implementing +/// transfer functions for operations. +/// +/// `LatticeT` is expected to be a subclass of `AbstractDenseLattice`. +template +class DenseForwardDataFlowAnalysis + : public AbstractDenseForwardDataFlowAnalysis { + static_assert( + std::is_base_of::value, + "analysis state class expected to subclass AbstractDenseLattice"); + +public: + using AbstractDenseForwardDataFlowAnalysis:: + AbstractDenseForwardDataFlowAnalysis; + + /// Visit an operation with the dense lattice before its execution. This + /// function is expected to set the dense lattice after its execution and + /// trigger change propagation in case of change. + virtual LogicalResult visitOperation(Operation *op, const LatticeT &before, + LatticeT *after) = 0; + + /// Hook for customizing the behavior of lattice propagation along the call + /// control flow edges. Two types of (forward) propagation are possible here: + /// - `action == CallControlFlowAction::Enter` indicates that: + /// - `before` is the state before the call operation; + /// - `after` is the state at the beginning of the callee entry block; + /// - `action == CallControlFlowAction::Exit` indicates that: + /// - `before` is the state at the end of a callee exit block; + /// - `after` is the state after the call operation. + /// By default, the `after` state is simply joined with the `before` state. + /// Concrete analyses can override this behavior or delegate to the parent + /// call for the default behavior. Specifically, if the `call` op may affect + /// the lattice prior to entering the callee, the custom behavior can be added + /// for `action == CallControlFlowAction::Enter`. If the `call` op may affect + /// the lattice post exiting the callee, the custom behavior can be added for + /// `action == CallControlFlowAction::Exit`. + virtual void visitCallControlFlowTransfer(CallOpInterface call, + CallControlFlowAction action, + const LatticeT &before, + LatticeT *after) { + AbstractDenseForwardDataFlowAnalysis::visitCallControlFlowTransfer( + call, action, before, after); + } + + /// Hook for customizing the behavior of lattice propagation along the control + /// flow edges between regions and their parent op. The control flows from + /// `regionFrom` to `regionTo`, both of which may be `nullopt` to indicate the + /// parent op. The lattice is propagated forward along this edge. The lattices + /// are as follows: + /// - `before:` + /// - if `regionFrom` is a region, this is the lattice at the end of the + /// block that exits the region; note that for multi-exit regions, the + /// lattices are equal at the end of all exiting blocks, but they are + /// associated with different program points. + /// - otherwise, this is the lattice before the parent op. + /// - `after`: + /// - if `regionTo` is a region, this is the lattice at the beginning of + /// the entry block of that region; + /// - otherwise, this is the lattice after the parent op. + /// By default, the `after` state is simply joined with the `before` state. + /// Concrete analyses can override this behavior or delegate to the parent + /// call for the default behavior. Specifically, if the `branch` op may affect + /// the lattice before entering any region, the custom behavior can be added + /// for `regionFrom == nullopt`. If the `branch` op may affect the lattice + /// after all terminated, the custom behavior can be added for `regionTo == + /// nullptr`. The behavior can be further refined for specific pairs of "from" + /// and "to" regions. + virtual void visitRegionBranchControlFlowTransfer( + RegionBranchOpInterface branch, std::optional regionFrom, + std::optional regionTo, const LatticeT &before, + LatticeT *after) { + AbstractDenseForwardDataFlowAnalysis::visitRegionBranchControlFlowTransfer( + branch, regionFrom, regionTo, before, after); + } + +protected: + /// Get the dense lattice on this lattice anchor. + LatticeT *getLattice(LatticeAnchor anchor) override { + return getOrCreate(anchor); + } + + /// Get the dense lattice on the given lattice anchor and add dependent as its + /// dependency. That is, every time the lattice after anchor is updated, the + /// dependent program point must be visited, and the newly triggered visit + /// might update the lattice on dependent. + const AbstractDenseLattice *getLatticeFor(ProgramPoint *dependent, + LatticeAnchor anchor) override { + return getOrCreateFor(dependent, anchor); + } + + /// Set the dense lattice at control flow entry point and propagate an update + /// if it changed. + virtual void setToEntryState(LatticeT *lattice) = 0; + void setToEntryState(AbstractDenseLattice *lattice) override { + setToEntryState(static_cast(lattice)); + } + + /// Type-erased wrappers that convert the abstract dense lattice to a derived + /// lattice and invoke the virtual hooks operating on the derived lattice. + LogicalResult visitOperationImpl(Operation *op, + const AbstractDenseLattice &before, + AbstractDenseLattice *after) final { + return visitOperation(op, static_cast(before), + static_cast(after)); + } + void visitCallControlFlowTransfer(CallOpInterface call, + CallControlFlowAction action, + const AbstractDenseLattice &before, + AbstractDenseLattice *after) final { + visitCallControlFlowTransfer(call, action, + static_cast(before), + static_cast(after)); + } + void visitRegionBranchControlFlowTransfer(RegionBranchOpInterface branch, + std::optional regionFrom, + std::optional regionTo, + const AbstractDenseLattice &before, + AbstractDenseLattice *after) final { + visitRegionBranchControlFlowTransfer(branch, regionFrom, regionTo, + static_cast(before), + static_cast(after)); + } +}; + +//===----------------------------------------------------------------------===// +// AbstractDenseBackwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// Base class for dense backward dataflow analyses. Such analyses attach a +/// lattice to program point and implement a transfer function from the lattice +/// after the operation to the lattice before it, thus propagating backward. +/// +/// Visit a program point in dense backward data-flow analysis will invoke the +/// transfer function of the operation following the program point iterator. +/// Visit a program point at the end of block will visit the block itself. +class AbstractDenseBackwardDataFlowAnalysis : public DataFlowAnalysis { +public: + /// Construct the analysis in the given solver. Takes a symbol table + /// collection that is used to cache symbol resolution in interprocedural part + /// of the analysis. The symbol table need not be prefilled. + AbstractDenseBackwardDataFlowAnalysis(DataFlowSolver &solver, + SymbolTableCollection &symbolTable) + : DataFlowAnalysis(solver), symbolTable(symbolTable) {} + + /// Initialize the analysis by visiting every program point whose execution + /// may modify the program state; that is, every operation and block. + LogicalResult initialize(Operation *top) override; + + /// Initialize lattice anchor equivalence class from the provided top-level + /// operation. + /// + /// This function will union lattice anchor to same equivalent class if the + /// analysis can determine the lattice content of lattice anchor is + /// necessarily identical under the corrensponding lattice type. + virtual void initializeEquivalentLatticeAnchor(Operation *top) override; + + /// Visit a program point that modifies the state of the program. The state is + /// propagated along control flow directions for branch-, region- and + /// call-based control flow using the respective interfaces. For other + /// operations, the state is propagated using the transfer function + /// (visitOperation). + /// + /// Note: the transfer function is currently *not* invoked before operations + /// with region or call interface, but *is* invoked before block terminators. + LogicalResult visit(ProgramPoint *point) override; + +protected: + /// Propagate the dense lattice after the execution of an operation to the + /// lattice before its execution. + virtual LogicalResult visitOperationImpl(Operation *op, + const AbstractDenseLattice &after, + AbstractDenseLattice *before) = 0; + + /// Get the dense lattice before the execution of the lattice anchor. That is, + /// before the execution of the given operation or after the execution of the + /// block. + virtual AbstractDenseLattice *getLattice(LatticeAnchor anchor) = 0; + + /// Get the dense lattice on the given lattice anchor and add dependent as its + /// dependency. That is, every time the lattice after anchor is updated, the + /// dependent program point must be visited, and the newly triggered visit + /// might update the lattice before dependent. + virtual const AbstractDenseLattice *getLatticeFor(ProgramPoint *dependent, + LatticeAnchor anchor) = 0; + + /// Set the dense lattice before at the control flow exit point and propagate + /// the update if it changed. + virtual void setToExitState(AbstractDenseLattice *lattice) = 0; + + /// Meet a lattice with another lattice and propagate an update if it changed. + void meet(AbstractDenseLattice *lhs, const AbstractDenseLattice &rhs) { + propagateIfChanged(lhs, lhs->meet(rhs)); + } + + /// Visit an operation. Dispatches to specialized methods for call or region + /// control-flow operations. Otherwise, this function invokes the operation + /// transfer function. + virtual LogicalResult processOperation(Operation *op); + + /// Visit an operation. If this analysis can confirm that lattice content + /// of lattice anchors around operation are necessarily identical, join + /// them into the same equivalent class. + virtual void buildOperationEquivalentLatticeAnchor(Operation *op) {} + + /// Propagate the dense lattice backwards along the control flow edge from + /// `regionFrom` to `regionTo` regions of the `branch` operation. `nullopt` + /// values correspond to control flow branches originating at or targeting the + /// `branch` operation itself. Default implementation just meets the states, + /// meaning that operations implementing `RegionBranchOpInterface` don't have + /// any effect on the lattice that isn't already expressed by the interface + /// itself. + virtual void visitRegionBranchControlFlowTransfer( + RegionBranchOpInterface branch, RegionBranchPoint regionFrom, + RegionBranchPoint regionTo, const AbstractDenseLattice &after, + AbstractDenseLattice *before) { + meet(before, after); + } + + /// Propagate the dense lattice backwards along the call control flow edge, + /// which can be either entering or exiting the callee. Default implementation + /// for enter and exit callee action just meets the states, meaning that + /// operations implementing `CallOpInterface` don't have any effect on the + /// lattice that isn't already expressed by the interface itself. Default + /// implementation for external callee action additional sets the result to + /// the exit (fixpoint) state. + virtual void visitCallControlFlowTransfer(CallOpInterface call, + CallControlFlowAction action, + const AbstractDenseLattice &after, + AbstractDenseLattice *before) { + meet(before, after); + + // Note that `setToExitState` may be a "partial fixpoint" for some lattices, + // e.g., lattices that are lists of maps of other lattices will only + // set fixpoint for "known" lattices. + if (action == CallControlFlowAction::ExternalCallee) + setToExitState(before); + } + +private: + /// Visit a block. The state and the end of the block is propagated from + /// control-flow successors of the block or callsites. + void visitBlock(Block *block); + + /// Visit a program point within a region branch operation with successors + /// (from which the state is propagated) in or after it. `regionNo` indicates + /// the region that contains the successor, `nullopt` indicating the successor + /// of the branch operation itself. + void visitRegionBranchOperation(ProgramPoint *point, + RegionBranchOpInterface branch, + RegionBranchPoint branchPoint, + AbstractDenseLattice *before); + + /// Visit an operation for which the data flow is described by the + /// `CallOpInterface`. Performs inter-procedural data flow as follows: + /// + /// - find the callable (resolve via the symbol table), + /// - get the entry block of the callable region, + /// - take the state before the first operation if present or at block end + /// otherwise, + /// - meet that state with the state before the call-like op, or use the + /// custom logic if overridden by concrete analyses. + void visitCallOperation(CallOpInterface call, + const AbstractDenseLattice &after, + AbstractDenseLattice *before); + + /// Symbol table for call-level control flow. + SymbolTableCollection &symbolTable; +}; + +//===----------------------------------------------------------------------===// +// DenseBackwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// A dense backward dataflow analysis propagating lattices after and before the +/// execution of every operation across the IR by implementing transfer +/// functions for opreations. +/// +/// `LatticeT` is expected to be a subclass of `AbstractDenseLattice`. +template +class DenseBackwardDataFlowAnalysis + : public AbstractDenseBackwardDataFlowAnalysis { + static_assert(std::is_base_of_v, + "analysis state expected to subclass AbstractDenseLattice"); + +public: + using AbstractDenseBackwardDataFlowAnalysis:: + AbstractDenseBackwardDataFlowAnalysis; + + /// Transfer function. Visits an operation with the dense lattice after its + /// execution. This function is expected to set the dense lattice before its + /// execution and trigger propagation in case of change. + virtual LogicalResult visitOperation(Operation *op, const LatticeT &after, + LatticeT *before) = 0; + + /// Hook for customizing the behavior of lattice propagation along the call + /// control flow edges. Two types of (back) propagation are possible here: + /// - `action == CallControlFlowAction::Enter` indicates that: + /// - `after` is the state at the top of the callee entry block; + /// - `before` is the state before the call operation; + /// - `action == CallControlFlowAction::Exit` indicates that: + /// - `after` is the state after the call operation; + /// - `before` is the state of exit blocks of the callee. + /// By default, the `before` state is simply met with the `after` state. + /// Concrete analyses can override this behavior or delegate to the parent + /// call for the default behavior. Specifically, if the `call` op may affect + /// the lattice prior to entering the callee, the custom behavior can be added + /// for `action == CallControlFlowAction::Enter`. If the `call` op may affect + /// the lattice post exiting the callee, the custom behavior can be added for + /// `action == CallControlFlowAction::Exit`. + virtual void visitCallControlFlowTransfer(CallOpInterface call, + CallControlFlowAction action, + const LatticeT &after, + LatticeT *before) { + AbstractDenseBackwardDataFlowAnalysis::visitCallControlFlowTransfer( + call, action, after, before); + } + + /// Hook for customizing the behavior of lattice propagation along the control + /// flow edges between regions and their parent op. The control flows from + /// `regionFrom` to `regionTo`, both of which may be `nullopt` to indicate the + /// parent op. The lattice is propagated back along this edge. The lattices + /// are as follows: + /// - `after`: + /// - if `regionTo` is a region, this is the lattice at the beginning of + /// the entry block of that region; + /// - otherwise, this is the lattice after the parent op. + /// - `before:` + /// - if `regionFrom` is a region, this is the lattice at the end of the + /// block that exits the region; note that for multi-exit regions, the + /// lattices are equal at the end of all exiting blocks, but they are + /// associated with different program points. + /// - otherwise, this is the lattice before the parent op. + /// By default, the `before` state is simply met with the `after` state. + /// Concrete analyses can override this behavior or delegate to the parent + /// call for the default behavior. Specifically, if the `branch` op may affect + /// the lattice before entering any region, the custom behavior can be added + /// for `regionFrom == nullopt`. If the `branch` op may affect the lattice + /// after all terminated, the custom behavior can be added for `regionTo == + /// nullptr`. The behavior can be further refined for specific pairs of "from" + /// and "to" regions. + virtual void visitRegionBranchControlFlowTransfer( + RegionBranchOpInterface branch, RegionBranchPoint regionFrom, + RegionBranchPoint regionTo, const LatticeT &after, LatticeT *before) { + AbstractDenseBackwardDataFlowAnalysis::visitRegionBranchControlFlowTransfer( + branch, regionFrom, regionTo, after, before); + } + +protected: + /// Get the dense lattice at the given lattice anchor. + LatticeT *getLattice(LatticeAnchor anchor) override { + return getOrCreate(anchor); + } + + /// Get the dense lattice on the given lattice anchor and add dependent as its + /// dependency. That is, every time the lattice after anchor is updated, the + /// dependent program point must be visited, and the newly triggered visit + /// might update the lattice before dependent. + virtual const AbstractDenseLattice * + getLatticeFor(ProgramPoint *dependent, LatticeAnchor anchor) override { + return getOrCreateFor(dependent, anchor); + } + + /// Set the dense lattice at control flow exit point (after the terminator) + /// and propagate an update if it changed. + virtual void setToExitState(LatticeT *lattice) = 0; + void setToExitState(AbstractDenseLattice *lattice) final { + setToExitState(static_cast(lattice)); + } + + /// Type-erased wrappers that convert the abstract dense lattice to a derived + /// lattice and invoke the virtual hooks operating on the derived lattice. + LogicalResult visitOperationImpl(Operation *op, + const AbstractDenseLattice &after, + AbstractDenseLattice *before) final { + return visitOperation(op, static_cast(after), + static_cast(before)); + } + void visitCallControlFlowTransfer(CallOpInterface call, + CallControlFlowAction action, + const AbstractDenseLattice &after, + AbstractDenseLattice *before) final { + visitCallControlFlowTransfer(call, action, + static_cast(after), + static_cast(before)); + } + void visitRegionBranchControlFlowTransfer( + RegionBranchOpInterface branch, RegionBranchPoint regionForm, + RegionBranchPoint regionTo, const AbstractDenseLattice &after, + AbstractDenseLattice *before) final { + visitRegionBranchControlFlowTransfer(branch, regionForm, regionTo, + static_cast(after), + static_cast(before)); + } +}; + +} // end namespace dataflow +} // end namespace mlir + +#endif // MLIR_ANALYSIS_DENSEDATAFLOWANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/IntegerRangeAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/IntegerRangeAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..72ec6061cbb62fc345290fc056d141b07f7db6d4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/IntegerRangeAnalysis.h @@ -0,0 +1,93 @@ +//===-IntegerRangeAnalysis.h - Integer range analysis -----------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file declares the dataflow analysis class for integer range inference +// so that it can be used in transformations over the `arith` dialect such as +// branch elimination or signed->unsigned rewriting. +// +// One can also implement InferIntRangeInterface on ops in custom dialects, +// and then use this analysis to propagate ranges with custom semantics. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATAFLOW_INTEGERANGEANALYSIS_H +#define MLIR_ANALYSIS_DATAFLOW_INTEGERANGEANALYSIS_H + +#include "mlir/Analysis/DataFlow/SparseAnalysis.h" +#include "mlir/Interfaces/InferIntRangeInterface.h" + +namespace mlir { +class RewriterBase; +namespace dataflow { + +/// This lattice element represents the integer value range of an SSA value. +/// When this lattice is updated, it automatically updates the constant value +/// of the SSA value (if the range can be narrowed to one). +class IntegerValueRangeLattice : public Lattice { +public: + using Lattice::Lattice; + + /// If the range can be narrowed to an integer constant, update the constant + /// value of the SSA value. + void onUpdate(DataFlowSolver *solver) const override; +}; + +/// Integer range analysis determines the integer value range of SSA values +/// using operations that define `InferIntRangeInterface` and also sets the +/// range of iteration indices of loops with known bounds. +/// +/// This analysis depends on DeadCodeAnalysis, and will be a silent no-op +/// if DeadCodeAnalysis is not loaded in the same solver context. +class IntegerRangeAnalysis + : public SparseForwardDataFlowAnalysis { +public: + using SparseForwardDataFlowAnalysis::SparseForwardDataFlowAnalysis; + + /// At an entry point, we cannot reason about interger value ranges. + void setToEntryState(IntegerValueRangeLattice *lattice) override { + propagateIfChanged(lattice, lattice->join(IntegerValueRange::getMaxRange( + lattice->getAnchor()))); + } + + /// Visit an operation. Invoke the transfer function on each operation that + /// implements `InferIntRangeInterface`. + LogicalResult + visitOperation(Operation *op, + ArrayRef operands, + ArrayRef results) override; + + /// Visit block arguments or operation results of an operation with region + /// control-flow for which values are not defined by region control-flow. This + /// function calls `InferIntRangeInterface` to provide values for block + /// arguments or tries to reduce the range on loop induction variables with + /// known bounds. + void + visitNonControlFlowArguments(Operation *op, const RegionSuccessor &successor, + ArrayRef argLattices, + unsigned firstIndex) override; +}; + +/// Succeeds if an op can be converted to its unsigned equivalent without +/// changing its semantics. This is the case when none of its openands or +/// results can be below 0 when analyzed from a signed perspective. +LogicalResult staticallyNonNegative(DataFlowSolver &solver, Operation *op); + +/// Succeeds when a value is statically non-negative in that it has a lower +/// bound on its value (if it is treated as signed) and that bound is +/// non-negative. +/// Note, the results of this query may not be accurate for `index` if you plan +/// to use a non-64-bit index. +LogicalResult staticallyNonNegative(DataFlowSolver &solver, Value v); + +LogicalResult maybeReplaceWithConstant(DataFlowSolver &solver, + RewriterBase &rewriter, Value value); + +} // end namespace dataflow +} // end namespace mlir + +#endif // MLIR_ANALYSIS_DATAFLOW_INTEGERANGEANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/LivenessAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/LivenessAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..cf1fd6e2d48caa5b241a84d1c74c46aebc9114be --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/LivenessAnalysis.h @@ -0,0 +1,112 @@ +//===- LivenessAnalysis.h - Liveness analysis -------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements liveness analysis using the sparse backward data-flow +// analysis framework. Theoretically, liveness analysis assigns liveness to each +// (value, program point) pair in the program and it is thus a dense analysis. +// However, since values are immutable in MLIR, a sparse analysis, which will +// assign liveness to each value in the program, suffices here. +// +// Liveness analysis has many applications. It can be used to avoid the +// computation of extraneous operations that have no effect on the memory or the +// final output of a program. It can also be used to optimize register +// allocation. Both of these applications help achieve one very important goal: +// reducing runtime. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATAFLOW_LIVENESSANALYSIS_H +#define MLIR_ANALYSIS_DATAFLOW_LIVENESSANALYSIS_H + +#include +#include + +namespace mlir::dataflow { + +//===----------------------------------------------------------------------===// +// Liveness +//===----------------------------------------------------------------------===// + +/// This lattice represents, for a given value, whether or not it is "live". +/// +/// A value is considered "live" iff it: +/// (1) has memory effects OR +/// (2) is returned by a public function OR +/// (3) is used to compute a value of type (1) or (2). +/// It is also to be noted that a value could be of multiple types (1/2/3) at +/// the same time. +/// +/// A value "has memory effects" iff it: +/// (1.a) is an operand of an op with memory effects OR +/// (1.b) is a non-forwarded branch operand and its branch op could take the +/// control to a block that has an op with memory effects OR +/// (1.c) is a non-forwarded call operand. +/// +/// A value `A` is said to be "used to compute" value `B` iff `B` cannot be +/// computed in the absence of `A`. Thus, in this implementation, we say that +/// value `A` is used to compute value `B` iff: +/// (3.a) `B` is a result of an op with operand `A` OR +/// (3.b) `A` is used to compute some value `C` and `C` is used to compute +/// `B`. +struct Liveness : public AbstractSparseLattice { + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(Liveness) + using AbstractSparseLattice::AbstractSparseLattice; + + void print(raw_ostream &os) const override; + + ChangeResult markLive(); + + ChangeResult meet(const AbstractSparseLattice &other) override; + + // At the beginning of the analysis, everything is marked "not live" and as + // the analysis progresses, values are marked "live" if they are found to be + // live. + bool isLive = false; +}; + +//===----------------------------------------------------------------------===// +// LivenessAnalysis +//===----------------------------------------------------------------------===// + +/// An analysis that, by going backwards along the dataflow graph, annotates +/// each value with a boolean storing true iff it is "live". +class LivenessAnalysis : public SparseBackwardDataFlowAnalysis { +public: + using SparseBackwardDataFlowAnalysis::SparseBackwardDataFlowAnalysis; + + LogicalResult visitOperation(Operation *op, ArrayRef operands, + ArrayRef results) override; + + void visitBranchOperand(OpOperand &operand) override; + + void visitCallOperand(OpOperand &operand) override; + + void setToExitState(Liveness *lattice) override; +}; + +//===----------------------------------------------------------------------===// +// RunLivenessAnalysis +//===----------------------------------------------------------------------===// + +/// Runs liveness analysis on the IR defined by `op`. +struct RunLivenessAnalysis { +public: + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(RunLivenessAnalysis) + + RunLivenessAnalysis(Operation *op); + + const Liveness *getLiveness(Value val); + +private: + /// Stores the result of the liveness analysis that was run. + DataFlowSolver solver; +}; + +} // end namespace mlir::dataflow + +#endif // MLIR_ANALYSIS_DATAFLOW_LIVENESSANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/SparseAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/SparseAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..3f8874d02afadc43688057f71ae8769c7c238c3f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlow/SparseAnalysis.h @@ -0,0 +1,591 @@ +//===- SparseAnalysis.h - Sparse data-flow analysis -----------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements sparse data-flow analysis using the data-flow analysis +// framework. The analysis is forward and conditional and uses the results of +// dead code analysis to prune dead code during the analysis. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATAFLOW_SPARSEANALYSIS_H +#define MLIR_ANALYSIS_DATAFLOW_SPARSEANALYSIS_H + +#include "mlir/Analysis/DataFlowFramework.h" +#include "mlir/IR/SymbolTable.h" +#include "mlir/Interfaces/CallInterfaces.h" +#include "mlir/Interfaces/ControlFlowInterfaces.h" +#include "llvm/ADT/SmallPtrSet.h" + +namespace mlir { +namespace dataflow { + +//===----------------------------------------------------------------------===// +// AbstractSparseLattice +//===----------------------------------------------------------------------===// + +/// This class represents an abstract lattice. A lattice contains information +/// about an SSA value and is what's propagated across the IR by sparse +/// data-flow analysis. +class AbstractSparseLattice : public AnalysisState { +public: + /// Lattices can only be created for values. + AbstractSparseLattice(Value value) : AnalysisState(value) {} + + /// Return the value this lattice is located at. + Value getAnchor() const { return cast(AnalysisState::getAnchor()); } + + /// Join the information contained in 'rhs' into this lattice. Returns + /// if the value of the lattice changed. + virtual ChangeResult join(const AbstractSparseLattice &rhs) { + return ChangeResult::NoChange; + } + + /// Meet (intersect) the information in this lattice with 'rhs'. Returns + /// if the value of the lattice changed. + virtual ChangeResult meet(const AbstractSparseLattice &rhs) { + return ChangeResult::NoChange; + } + + /// When the lattice gets updated, propagate an update to users of the value + /// using its use-def chain to subscribed analyses. + void onUpdate(DataFlowSolver *solver) const override; + + /// Subscribe an analysis to updates of the lattice. When the lattice changes, + /// subscribed analyses are re-invoked on all users of the value. This is + /// more efficient than relying on the dependency map. + void useDefSubscribe(DataFlowAnalysis *analysis) { + useDefSubscribers.insert(analysis); + } + +private: + /// A set of analyses that should be updated when this lattice changes. + SetVector, + SmallPtrSet> + useDefSubscribers; +}; + +//===----------------------------------------------------------------------===// +// Lattice +//===----------------------------------------------------------------------===// + +/// This class represents a lattice holding a specific value of type `ValueT`. +/// Lattice values (`ValueT`) are required to adhere to the following: +/// +/// * static ValueT join(const ValueT &lhs, const ValueT &rhs); +/// - This method conservatively joins the information held by `lhs` +/// and `rhs` into a new value. This method is required to be monotonic. +/// * bool operator==(const ValueT &rhs) const; +/// +template +class Lattice : public AbstractSparseLattice { +public: + using AbstractSparseLattice::AbstractSparseLattice; + + /// Return the value this lattice is located at. + Value getAnchor() const { return cast(anchor); } + + /// Return the value held by this lattice. This requires that the value is + /// initialized. + ValueT &getValue() { return value; } + const ValueT &getValue() const { + return const_cast *>(this)->getValue(); + } + + using LatticeT = Lattice; + + /// Join the information contained in the 'rhs' lattice into this + /// lattice. Returns if the state of the current lattice changed. + ChangeResult join(const AbstractSparseLattice &rhs) override { + return join(static_cast(rhs).getValue()); + } + + /// Meet (intersect) the information contained in the 'rhs' lattice with + /// this lattice. Returns if the state of the current lattice changed. + ChangeResult meet(const AbstractSparseLattice &rhs) override { + return meet(static_cast(rhs).getValue()); + } + + /// Join the information contained in the 'rhs' value into this + /// lattice. Returns if the state of the current lattice changed. + ChangeResult join(const ValueT &rhs) { + // Otherwise, join rhs with the current optimistic value. + ValueT newValue = ValueT::join(value, rhs); + assert(ValueT::join(newValue, value) == newValue && + "expected `join` to be monotonic"); + assert(ValueT::join(newValue, rhs) == newValue && + "expected `join` to be monotonic"); + + // Update the current optimistic value if something changed. + if (newValue == value) + return ChangeResult::NoChange; + + value = newValue; + return ChangeResult::Change; + } + + /// Trait to check if `T` provides a `meet` method. Needed since for forward + /// analysis, lattices will only have a `join`, no `meet`, but we want to use + /// the same `Lattice` class for both directions. + template + using has_meet = decltype(&T::meet); + template + using lattice_has_meet = llvm::is_detected; + + /// Meet (intersect) the information contained in the 'rhs' value with this + /// lattice. Returns if the state of the current lattice changed. If the + /// lattice elements don't have a `meet` method, this is a no-op (see below.) + template ::value> * = nullptr> + ChangeResult meet(const VT &rhs) { + ValueT newValue = ValueT::meet(value, rhs); + assert(ValueT::meet(newValue, value) == newValue && + "expected `meet` to be monotonic"); + assert(ValueT::meet(newValue, rhs) == newValue && + "expected `meet` to be monotonic"); + + // Update the current optimistic value if something changed. + if (newValue == value) + return ChangeResult::NoChange; + + value = newValue; + return ChangeResult::Change; + } + + template ::value> * = nullptr> + ChangeResult meet(const VT &rhs) { + return ChangeResult::NoChange; + } + + /// Print the lattice element. + void print(raw_ostream &os) const override { value.print(os); } + +private: + /// The currently computed value that is optimistically assumed to be true. + ValueT value; +}; + +//===----------------------------------------------------------------------===// +// AbstractSparseForwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// Base class for sparse forward data-flow analyses. A sparse analysis +/// implements a transfer function on operations from the lattices of the +/// operands to the lattices of the results. This analysis will propagate +/// lattices across control-flow edges and the callgraph using liveness +/// information. +/// +/// Visit a program point in sparse forward data-flow analysis will invoke the +/// transfer function of the operation preceding the program point iterator. +/// Visit a program point at the begining of block will visit the block itself. +class AbstractSparseForwardDataFlowAnalysis : public DataFlowAnalysis { +public: + /// Initialize the analysis by visiting every owner of an SSA value: all + /// operations and blocks. + LogicalResult initialize(Operation *top) override; + + /// Visit a program point. If this is at beginning of block and all + /// control-flow predecessors or callsites are known, then the arguments + /// lattices are propagated from them. If this is after call operation or an + /// operation with region control-flow, then its result lattices are set + /// accordingly. Otherwise, the operation transfer function is invoked. + LogicalResult visit(ProgramPoint *point) override; + +protected: + explicit AbstractSparseForwardDataFlowAnalysis(DataFlowSolver &solver); + + /// The operation transfer function. Given the operand lattices, this + /// function is expected to set the result lattices. + virtual LogicalResult + visitOperationImpl(Operation *op, + ArrayRef operandLattices, + ArrayRef resultLattices) = 0; + + /// The transfer function for calls to external functions. + virtual void visitExternalCallImpl( + CallOpInterface call, + ArrayRef argumentLattices, + ArrayRef resultLattices) = 0; + + /// Given an operation with region control-flow, the lattices of the operands, + /// and a region successor, compute the lattice values for block arguments + /// that are not accounted for by the branching control flow (ex. the bounds + /// of loops). + virtual void visitNonControlFlowArgumentsImpl( + Operation *op, const RegionSuccessor &successor, + ArrayRef argLattices, unsigned firstIndex) = 0; + + /// Get the lattice element of a value. + virtual AbstractSparseLattice *getLatticeElement(Value value) = 0; + + /// Get a read-only lattice element for a value and add it as a dependency to + /// a program point. + const AbstractSparseLattice *getLatticeElementFor(ProgramPoint *point, + Value value); + + /// Set the given lattice element(s) at control flow entry point(s). + virtual void setToEntryState(AbstractSparseLattice *lattice) = 0; + void setAllToEntryStates(ArrayRef lattices); + + /// Join the lattice element and propagate and update if it changed. + void join(AbstractSparseLattice *lhs, const AbstractSparseLattice &rhs); + + /// Visits a call operation. Given the operand lattices, sets the result + /// lattices. Performs interprocedural data flow as follows: if the call + /// operation targets an external function, or if the solver is not + /// interprocedural, attempts to infer the results from the call arguments + /// using the user-provided `visitExternalCallImpl`. Otherwise, computes the + /// result lattices from the return sites if all return sites are known; + /// otherwise, conservatively marks the result lattices as having reached + /// their pessimistic fixpoints. + /// This method can be overridden to, for example, be less conservative and + /// propagate the information even if some return sites are unknown. + virtual LogicalResult + visitCallOperation(CallOpInterface call, + ArrayRef operandLattices, + ArrayRef resultLattices); + + /// Visits a callable operation. Computes the argument lattices from call + /// sites if all call sites are known; otherwise, conservatively marks them + /// as having reached their pessimistic fixpoints. + /// This method can be overridden to, for example, be less conservative and + /// propagate the information even if some call sites are unknown. + virtual void + visitCallableOperation(CallableOpInterface callable, + ArrayRef argLattices); + +private: + /// Recursively initialize the analysis on nested operations and blocks. + LogicalResult initializeRecursively(Operation *op); + + /// Visit an operation. If this is a call operation or an operation with + /// region control-flow, then its result lattices are set accordingly. + /// Otherwise, the operation transfer function is invoked. + LogicalResult visitOperation(Operation *op); + + /// Visit a block to compute the lattice values of its arguments. If this is + /// an entry block, then the argument values are determined from the block's + /// "predecessors" as set by `PredecessorState`. The predecessors can be + /// region terminators or callable callsites. Otherwise, the values are + /// determined from block predecessors. + void visitBlock(Block *block); + + /// Visit a program point `point` with predecessors within a region branch + /// operation `branch`, which can either be the entry block of one of the + /// regions or the parent operation itself, and set either the argument or + /// parent result lattices. + /// This method can be overridden to control precisely how the region + /// successors of `branch` are visited. For example in order to precisely + /// control the order in which predecessor operand lattices are propagated + /// from. An override is responsible for visiting all the known predecessors + /// and propagating therefrom. + virtual void + visitRegionSuccessors(ProgramPoint *point, RegionBranchOpInterface branch, + RegionBranchPoint successor, + ArrayRef lattices); +}; + +//===----------------------------------------------------------------------===// +// SparseForwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// A sparse forward data-flow analysis for propagating SSA value lattices +/// across the IR by implementing transfer functions for operations. +/// +/// `StateT` is expected to be a subclass of `AbstractSparseLattice`. +template +class SparseForwardDataFlowAnalysis + : public AbstractSparseForwardDataFlowAnalysis { + static_assert( + std::is_base_of::value, + "analysis state class expected to subclass AbstractSparseLattice"); + +public: + explicit SparseForwardDataFlowAnalysis(DataFlowSolver &solver) + : AbstractSparseForwardDataFlowAnalysis(solver) {} + + /// Visit an operation with the lattices of its operands. This function is + /// expected to set the lattices of the operation's results. + virtual LogicalResult visitOperation(Operation *op, + ArrayRef operands, + ArrayRef results) = 0; + + /// Visit a call operation to an externally defined function given the + /// lattices of its arguments. + virtual void visitExternalCall(CallOpInterface call, + ArrayRef argumentLattices, + ArrayRef resultLattices) { + setAllToEntryStates(resultLattices); + } + + /// Given an operation with possible region control-flow, the lattices of the + /// operands, and a region successor, compute the lattice values for block + /// arguments that are not accounted for by the branching control flow (ex. + /// the bounds of loops). By default, this method marks all such lattice + /// elements as having reached a pessimistic fixpoint. `firstIndex` is the + /// index of the first element of `argLattices` that is set by control-flow. + virtual void visitNonControlFlowArguments(Operation *op, + const RegionSuccessor &successor, + ArrayRef argLattices, + unsigned firstIndex) { + setAllToEntryStates(argLattices.take_front(firstIndex)); + setAllToEntryStates(argLattices.drop_front( + firstIndex + successor.getSuccessorInputs().size())); + } + +protected: + /// Get the lattice element for a value. + StateT *getLatticeElement(Value value) override { + return getOrCreate(value); + } + + /// Get the lattice element for a value and create a dependency on the + /// provided program point. + const StateT *getLatticeElementFor(ProgramPoint *point, Value value) { + return static_cast( + AbstractSparseForwardDataFlowAnalysis::getLatticeElementFor(point, + value)); + } + + /// Set the given lattice element(s) at control flow entry point(s). + virtual void setToEntryState(StateT *lattice) = 0; + void setAllToEntryStates(ArrayRef lattices) { + AbstractSparseForwardDataFlowAnalysis::setAllToEntryStates( + {reinterpret_cast(lattices.begin()), + lattices.size()}); + } + +private: + /// Type-erased wrappers that convert the abstract lattice operands to derived + /// lattices and invoke the virtual hooks operating on the derived lattices. + LogicalResult visitOperationImpl( + Operation *op, ArrayRef operandLattices, + ArrayRef resultLattices) override { + return visitOperation( + op, + {reinterpret_cast(operandLattices.begin()), + operandLattices.size()}, + {reinterpret_cast(resultLattices.begin()), + resultLattices.size()}); + } + void visitExternalCallImpl( + CallOpInterface call, + ArrayRef argumentLattices, + ArrayRef resultLattices) override { + visitExternalCall( + call, + {reinterpret_cast(argumentLattices.begin()), + argumentLattices.size()}, + {reinterpret_cast(resultLattices.begin()), + resultLattices.size()}); + } + void visitNonControlFlowArgumentsImpl( + Operation *op, const RegionSuccessor &successor, + ArrayRef argLattices, + unsigned firstIndex) override { + visitNonControlFlowArguments( + op, successor, + {reinterpret_cast(argLattices.begin()), + argLattices.size()}, + firstIndex); + } + void setToEntryState(AbstractSparseLattice *lattice) override { + return setToEntryState(reinterpret_cast(lattice)); + } +}; + +//===----------------------------------------------------------------------===// +// AbstractSparseBackwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// Base class for sparse backward data-flow analyses. Similar to +/// AbstractSparseForwardDataFlowAnalysis, but walks bottom to top. +class AbstractSparseBackwardDataFlowAnalysis : public DataFlowAnalysis { +public: + /// Initialize the analysis by visiting the operation and everything nested + /// under it. + LogicalResult initialize(Operation *top) override; + + /// Visit a program point. If it is after call operation or an operation with + /// block or region control-flow, then operand lattices are set accordingly. + /// Otherwise, invokes the operation transfer function (`visitOperationImpl`). + LogicalResult visit(ProgramPoint *point) override; + +protected: + explicit AbstractSparseBackwardDataFlowAnalysis( + DataFlowSolver &solver, SymbolTableCollection &symbolTable); + + /// The operation transfer function. Given the result lattices, this + /// function is expected to set the operand lattices. + virtual LogicalResult visitOperationImpl( + Operation *op, ArrayRef operandLattices, + ArrayRef resultLattices) = 0; + + /// The transfer function for calls to external functions. + virtual void visitExternalCallImpl( + CallOpInterface call, ArrayRef operandLattices, + ArrayRef resultLattices) = 0; + + // Visit operands on branch instructions that are not forwarded. + virtual void visitBranchOperand(OpOperand &operand) = 0; + + // Visit operands on call instructions that are not forwarded. + virtual void visitCallOperand(OpOperand &operand) = 0; + + /// Set the given lattice element(s) at control flow exit point(s) and + /// propagate the update if it chaned. + virtual void setToExitState(AbstractSparseLattice *lattice) = 0; + + /// Set the given lattice element(s) at control flow exit point(s) and + /// propagate the update if it chaned. + void setAllToExitStates(ArrayRef lattices); + + /// Get the lattice element for a value. + virtual AbstractSparseLattice *getLatticeElement(Value value) = 0; + + /// Get the lattice elements for a range of values. + SmallVector getLatticeElements(ValueRange values); + + /// Join the lattice element and propagate and update if it changed. + void meet(AbstractSparseLattice *lhs, const AbstractSparseLattice &rhs); + + /// Visits a callable operation. If all the call sites are known computes the + /// operand lattices of `op` from the result lattices of all the call sites; + /// otherwise, conservatively marks them as having reached their pessimistic + /// fixpoints. + /// This method can be overridden to, for example, be less conservative and + /// propagate the information even if some call sites are unknown. + virtual LogicalResult + visitCallableOperation(Operation *op, CallableOpInterface callable, + ArrayRef operandLattices); + +private: + /// Recursively initialize the analysis on nested operations and blocks. + LogicalResult initializeRecursively(Operation *op); + + /// Visit an operation. If this is a call operation or an operation with + /// region control-flow, then its operand lattices are set accordingly. + /// Otherwise, the operation transfer function is invoked. + LogicalResult visitOperation(Operation *op); + + /// Visit a block. + void visitBlock(Block *block); + + /// Visit an op with regions (like e.g. `scf.while`) + void visitRegionSuccessors(RegionBranchOpInterface branch, + ArrayRef operands); + + /// Visit a `RegionBranchTerminatorOpInterface` to compute the lattice values + /// of its operands, given its parent op `branch`. The lattice value of an + /// operand is determined based on the corresponding arguments in + /// `terminator`'s region successor(s). + void visitRegionSuccessorsFromTerminator( + RegionBranchTerminatorOpInterface terminator, + RegionBranchOpInterface branch); + + /// Get the lattice element for a value, and also set up + /// dependencies so that the analysis on the given ProgramPoint is re-invoked + /// if the value changes. + const AbstractSparseLattice *getLatticeElementFor(ProgramPoint *point, + Value value); + + /// Get the lattice elements for a range of values, and also set up + /// dependencies so that the analysis on the given ProgramPoint is re-invoked + /// if any of the values change. + SmallVector + getLatticeElementsFor(ProgramPoint *point, ValueRange values); + + SymbolTableCollection &symbolTable; +}; + +//===----------------------------------------------------------------------===// +// SparseBackwardDataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// A sparse (backward) data-flow analysis for propagating SSA value lattices +/// backwards across the IR by implementing transfer functions for operations. +/// +/// `StateT` is expected to be a subclass of `AbstractSparseLattice`. +/// +/// Visit a program point in sparse backward data-flow analysis will invoke the +/// transfer function of the operation preceding the program point iterator. +/// Visit a program point at the begining of block will visit the block itself. +template +class SparseBackwardDataFlowAnalysis + : public AbstractSparseBackwardDataFlowAnalysis { +public: + explicit SparseBackwardDataFlowAnalysis(DataFlowSolver &solver, + SymbolTableCollection &symbolTable) + : AbstractSparseBackwardDataFlowAnalysis(solver, symbolTable) {} + + /// Visit an operation with the lattices of its results. This function is + /// expected to set the lattices of the operation's operands. + virtual LogicalResult visitOperation(Operation *op, + ArrayRef operands, + ArrayRef results) = 0; + + /// Visit a call to an external function. This function is expected to set + /// lattice values of the call operands. By default, calls `visitCallOperand` + /// for all operands. + virtual void visitExternalCall(CallOpInterface call, + ArrayRef argumentLattices, + ArrayRef resultLattices) { + (void)argumentLattices; + (void)resultLattices; + for (OpOperand &operand : call->getOpOperands()) { + visitCallOperand(operand); + } + }; + +protected: + /// Get the lattice element for a value. + StateT *getLatticeElement(Value value) override { + return getOrCreate(value); + } + + /// Set the given lattice element(s) at control flow exit point(s). + virtual void setToExitState(StateT *lattice) = 0; + void setToExitState(AbstractSparseLattice *lattice) override { + return setToExitState(reinterpret_cast(lattice)); + } + void setAllToExitStates(ArrayRef lattices) { + AbstractSparseBackwardDataFlowAnalysis::setAllToExitStates( + {reinterpret_cast(lattices.begin()), + lattices.size()}); + } + +private: + /// Type-erased wrappers that convert the abstract lattice operands to derived + /// lattices and invoke the virtual hooks operating on the derived lattices. + LogicalResult visitOperationImpl( + Operation *op, ArrayRef operandLattices, + ArrayRef resultLattices) override { + return visitOperation( + op, + {reinterpret_cast(operandLattices.begin()), + operandLattices.size()}, + {reinterpret_cast(resultLattices.begin()), + resultLattices.size()}); + } + + void visitExternalCallImpl( + CallOpInterface call, ArrayRef operandLattices, + ArrayRef resultLattices) override { + visitExternalCall( + call, + {reinterpret_cast(operandLattices.begin()), + operandLattices.size()}, + {reinterpret_cast(resultLattices.begin()), + resultLattices.size()}); + } +}; + +} // end namespace dataflow +} // end namespace mlir + +#endif // MLIR_ANALYSIS_DATAFLOW_SPARSEANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlowFramework.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlowFramework.h new file mode 100644 index 0000000000000000000000000000000000000000..49862927caff275012d6cf79cd51e67ea433f332 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataFlowFramework.h @@ -0,0 +1,813 @@ +//===- DataFlowFramework.h - A generic framework for data-flow analysis ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines a generic framework for writing data-flow analysis in MLIR. +// The framework consists of a solver, which runs the fixed-point iteration and +// manages analysis dependencies, and a data-flow analysis class used to +// implement specific analyses. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATAFLOWFRAMEWORK_H +#define MLIR_ANALYSIS_DATAFLOWFRAMEWORK_H + +#include "mlir/IR/Operation.h" +#include "mlir/Support/StorageUniquer.h" +#include "llvm/ADT/EquivalenceClasses.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/TypeName.h" +#include +#include + +namespace mlir { + +//===----------------------------------------------------------------------===// +// ChangeResult +//===----------------------------------------------------------------------===// + +/// A result type used to indicate if a change happened. Boolean operations on +/// ChangeResult behave as though `Change` is truth. +enum class [[nodiscard]] ChangeResult { + NoChange, + Change, +}; +inline ChangeResult operator|(ChangeResult lhs, ChangeResult rhs) { + return lhs == ChangeResult::Change ? lhs : rhs; +} +inline ChangeResult &operator|=(ChangeResult &lhs, ChangeResult rhs) { + lhs = lhs | rhs; + return lhs; +} +inline ChangeResult operator&(ChangeResult lhs, ChangeResult rhs) { + return lhs == ChangeResult::NoChange ? lhs : rhs; +} + +/// Forward declare the analysis state class. +class AnalysisState; + +/// Program point represents a specific location in the execution of a program. +/// A sequence of program points can be combined into a control flow graph. +struct ProgramPoint : public StorageUniquer::BaseStorage { + /// Creates a new program point at the given location. + ProgramPoint(Block *parentBlock, Block::iterator pp) + : block(parentBlock), point(pp) {} + + /// Creates a new program point at the given operation. + ProgramPoint(Operation *op) : op(op) {} + + /// The concrete key type used by the storage uniquer. This class is uniqued + /// by its contents. + using KeyTy = std::tuple; + + /// Create a empty program point. + ProgramPoint() {} + + /// Create a new program point from the given program point. + ProgramPoint(const ProgramPoint &point) { + this->block = point.getBlock(); + this->point = point.getPoint(); + this->op = point.getOperation(); + } + + static ProgramPoint *construct(StorageUniquer::StorageAllocator &alloc, + KeyTy &&key) { + if (std::get<0>(key)) { + return new (alloc.allocate()) + ProgramPoint(std::get<0>(key), std::get<1>(key)); + } + return new (alloc.allocate()) ProgramPoint(std::get<2>(key)); + } + + /// Returns true if this program point is set. + bool isNull() const { return block == nullptr && op == nullptr; } + + /// Two program points are equal if their block and iterator are equal. + bool operator==(const KeyTy &key) const { + return block == std::get<0>(key) && point == std::get<1>(key) && + op == std::get<2>(key); + } + + bool operator==(const ProgramPoint &pp) const { + return block == pp.block && point == pp.point && op == pp.op; + } + + /// Get the block contains this program point. + Block *getBlock() const { return block; } + + /// Get the the iterator this program point refers to. + Block::iterator getPoint() const { return point; } + + /// Get the the iterator this program point refers to. + Operation *getOperation() const { return op; } + + /// Get the next operation of this program point. + Operation *getNextOp() const { + assert(!isBlockEnd()); + // If the current program point has no parent block, both the next op and + // the previous op point to the op corresponding to the current program + // point. + if (block == nullptr) { + return op; + } + return &*point; + } + + /// Get the previous operation of this program point. + Operation *getPrevOp() const { + assert(!isBlockStart()); + // If the current program point has no parent block, both the next op and + // the previous op point to the op corresponding to the current program + // point. + if (block == nullptr) { + return op; + } + return &*(--Block::iterator(point)); + } + + bool isBlockStart() const { return block && block->begin() == point; } + + bool isBlockEnd() const { return block && block->end() == point; } + + /// Print the program point. + void print(raw_ostream &os) const; + +private: + Block *block = nullptr; + Block::iterator point; + + /// For operations without a parent block, we record the operation itself as + /// its program point. + Operation *op = nullptr; +}; + +inline raw_ostream &operator<<(raw_ostream &os, const ProgramPoint &point) { + point.print(os); + return os; +} + +//===----------------------------------------------------------------------===// +// GenericLatticeAnchor +//===----------------------------------------------------------------------===// + +/// Abstract class for generic lattice anchor. In classical data-flow analysis, +/// lattice anchor represent positions in a program to which lattice elements +/// are attached. In sparse data-flow analysis, these can be SSA values, and in +/// dense data-flow analysis, these are the program points before and after +/// every operation. +/// +/// Lattice anchor are implemented using MLIR's storage uniquer framework and +/// type ID system to provide RTTI. +class GenericLatticeAnchor : public StorageUniquer::BaseStorage { +public: + virtual ~GenericLatticeAnchor(); + + /// Get the abstract lattice anchor's type identifier. + TypeID getTypeID() const { return typeID; } + + /// Get a derived source location for the lattice anchor. + virtual Location getLoc() const = 0; + + /// Print the lattice anchor. + virtual void print(raw_ostream &os) const = 0; + +protected: + /// Create an abstract lattice anchor with type identifier. + explicit GenericLatticeAnchor(TypeID typeID) : typeID(typeID) {} + +private: + /// The type identifier of the lattice anchor. + TypeID typeID; +}; + +//===----------------------------------------------------------------------===// +// GenericLatticeAnchorBase +//===----------------------------------------------------------------------===// + +/// Base class for generic lattice anchor based on a concrete lattice anchor +/// type and a content key. This class defines the common methods required for +/// operability with the storage uniquer framework. +/// +/// The provided key type uniquely identifies the concrete lattice anchor +/// instance and are the data members of the class. +template +class GenericLatticeAnchorBase : public GenericLatticeAnchor { +public: + /// The concrete key type used by the storage uniquer. This class is uniqued + /// by its contents. + using KeyTy = Value; + /// Alias for the base class. + using Base = GenericLatticeAnchorBase; + + /// Construct an instance of the lattice anchor using the provided value and + /// the type ID of the concrete type. + template + explicit GenericLatticeAnchorBase(ValueT &&value) + : GenericLatticeAnchor(TypeID::get()), + value(std::forward(value)) {} + + /// Get a uniqued instance of this lattice anchor class with the given + /// arguments. + template + static ConcreteT *get(StorageUniquer &uniquer, Args &&...args) { + return uniquer.get(/*initFn=*/{}, std::forward(args)...); + } + + /// Allocate space for a lattice anchor and construct it in-place. + template + static ConcreteT *construct(StorageUniquer::StorageAllocator &alloc, + ValueT &&value) { + return new (alloc.allocate()) + ConcreteT(std::forward(value)); + } + + /// Two lattice anchors are equal if their values are equal. + bool operator==(const Value &value) const { return this->value == value; } + + /// Provide LLVM-style RTTI using type IDs. + static bool classof(const GenericLatticeAnchor *point) { + return point->getTypeID() == TypeID::get(); + } + + /// Get the contents of the lattice anchor. + const Value &getValue() const { return value; } + +private: + /// The lattice anchor value. + Value value; +}; + +//===----------------------------------------------------------------------===// +// LatticeAnchor +//===----------------------------------------------------------------------===// + +/// Fundamental IR components are supported as first-class lattice anchor. +struct LatticeAnchor + : public PointerUnion { + using ParentTy = PointerUnion; + /// Inherit constructors. + using ParentTy::PointerUnion; + /// Allow implicit conversion from the parent type. + LatticeAnchor(ParentTy point = nullptr) : ParentTy(point) {} + + /// Print the lattice anchor. + void print(raw_ostream &os) const; + + /// Get the source location of the lattice anchor. + Location getLoc() const; +}; + +/// Forward declaration of the data-flow analysis class. +class DataFlowAnalysis; + +} // namespace mlir + +template <> +struct llvm::DenseMapInfo + : public llvm::DenseMapInfo {}; + +namespace mlir { + +//===----------------------------------------------------------------------===// +// DataFlowConfig +//===----------------------------------------------------------------------===// + +/// Configuration class for data flow solver and child analyses. Follows the +/// fluent API pattern. +class DataFlowConfig { +public: + DataFlowConfig() = default; + + /// Set whether the solver should operate interpocedurally, i.e. enter the + /// callee body when available. Interprocedural analyses may be more precise, + /// but also more expensive as more states need to be computed and the + /// fixpoint convergence takes longer. + DataFlowConfig &setInterprocedural(bool enable) { + interprocedural = enable; + return *this; + } + + /// Return `true` if the solver operates interprocedurally, `false` otherwise. + bool isInterprocedural() const { return interprocedural; } + +private: + bool interprocedural = true; +}; + +//===----------------------------------------------------------------------===// +// DataFlowSolver +//===----------------------------------------------------------------------===// + +/// The general data-flow analysis solver. This class is responsible for +/// orchestrating child data-flow analyses, running the fixed-point iteration +/// algorithm, managing analysis state and lattice anchor memory, and tracking +/// dependencies between analyses, lattice anchor, and analysis states. +/// +/// Steps to run a data-flow analysis: +/// +/// 1. Load and initialize children analyses. Children analyses are instantiated +/// in the solver and initialized, building their dependency relations. +/// 2. Configure and run the analysis. The solver invokes the children analyses +/// according to their dependency relations until a fixed point is reached. +/// 3. Query analysis state results from the solver. +/// +/// Steps to re-run a data-flow analysis when IR changes: +/// 1. Erase all analysis states as they are no longer valid. +/// 2. Re-run the analysis using `initializeAndRun`. +/// +/// TODO: Optimize the internal implementation of the solver. +class DataFlowSolver { +public: + explicit DataFlowSolver(const DataFlowConfig &config = DataFlowConfig()) + : config(config) { + uniquer.registerParametricStorageType(); + } + + /// Load an analysis into the solver. Return the analysis instance. + template + AnalysisT *load(Args &&...args); + + /// Initialize the children analyses starting from the provided top-level + /// operation and run the analysis until fixpoint. + LogicalResult initializeAndRun(Operation *top); + + /// Lookup an analysis state for the given lattice anchor. Returns null if one + /// does not exist. + template + const StateT *lookupState(AnchorT anchor) const { + LatticeAnchor latticeAnchor = + getLeaderAnchorOrSelf(LatticeAnchor(anchor)); + const auto &mapIt = analysisStates.find(latticeAnchor); + if (mapIt == analysisStates.end()) + return nullptr; + auto it = mapIt->second.find(TypeID::get()); + if (it == mapIt->second.end()) + return nullptr; + return static_cast(it->second.get()); + } + + /// Erase any analysis state associated with the given lattice anchor. + template + void eraseState(AnchorT anchor) { + LatticeAnchor latticeAnchor(anchor); + + // Update equivalentAnchorMap. + for (auto &&[TypeId, eqClass] : equivalentAnchorMap) { + if (!eqClass.contains(latticeAnchor)) { + continue; + } + llvm::EquivalenceClasses::member_iterator leaderIt = + eqClass.findLeader(latticeAnchor); + + // Update analysis states with new leader if needed. + if (*leaderIt == latticeAnchor && ++leaderIt != eqClass.member_end()) { + analysisStates[*leaderIt][TypeId] = + std::move(analysisStates[latticeAnchor][TypeId]); + } + + eqClass.erase(latticeAnchor); + } + + // Update analysis states. + analysisStates.erase(latticeAnchor); + } + + /// Erase all analysis states. + void eraseAllStates() { + analysisStates.clear(); + equivalentAnchorMap.clear(); + } + + /// Get a uniqued lattice anchor instance. If one is not present, it is + /// created with the provided arguments. + template + AnchorT *getLatticeAnchor(Args &&...args) { + return AnchorT::get(uniquer, std::forward(args)...); + } + + /// Get a uniqued program point instance. + ProgramPoint *getProgramPointBefore(Operation *op) { + if (op->getBlock()) + return uniquer.get(/*initFn*/ {}, op->getBlock(), + Block::iterator(op), nullptr); + else + return uniquer.get(/*initFn*/ {}, nullptr, + Block::iterator(), op); + } + + ProgramPoint *getProgramPointBefore(Block *block) { + return uniquer.get(/*initFn*/ {}, block, block->begin(), + nullptr); + } + + ProgramPoint *getProgramPointAfter(Operation *op) { + if (op->getBlock()) + return uniquer.get(/*initFn*/ {}, op->getBlock(), + ++Block::iterator(op), nullptr); + else + return uniquer.get(/*initFn*/ {}, nullptr, + Block::iterator(), op); + } + + ProgramPoint *getProgramPointAfter(Block *block) { + return uniquer.get(/*initFn*/ {}, block, block->end(), + nullptr); + } + + /// A work item on the solver queue is a program point, child analysis pair. + /// Each item is processed by invoking the child analysis at the program + /// point. + using WorkItem = std::pair; + /// Push a work item onto the worklist. + void enqueue(WorkItem item) { worklist.push(std::move(item)); } + + /// Get the state associated with the given lattice anchor. If it does not + /// exist, create an uninitialized state. + template + StateT *getOrCreateState(AnchorT anchor); + + /// Get leader lattice anchor in equivalence lattice anchor group, return + /// input lattice anchor if input not found in equivalece lattice anchor + /// group. + template + LatticeAnchor getLeaderAnchorOrSelf(LatticeAnchor latticeAnchor) const; + + /// Union input anchors under the given state. + template + void unionLatticeAnchors(AnchorT anchor, AnchorT other); + + /// Return given lattice is equivalent on given state. + template + bool isEquivalent(LatticeAnchor lhs, LatticeAnchor rhs) const; + + /// Propagate an update to an analysis state if it changed by pushing + /// dependent work items to the back of the queue. + /// This should only be used when DataFlowSolver is running. + /// Otherwise, the solver won't process the work items. + void propagateIfChanged(AnalysisState *state, ChangeResult changed); + + /// Get the configuration of the solver. + const DataFlowConfig &getConfig() const { return config; } + +private: + /// Configuration of the dataflow solver. + DataFlowConfig config; + + /// The solver is working on the worklist. + bool isRunning = false; + + /// The solver's work queue. Work items can be inserted to the front of the + /// queue to be processed greedily, speeding up computations that otherwise + /// quickly degenerate to quadratic due to propagation of state updates. + std::queue worklist; + + /// Type-erased instances of the children analyses. + SmallVector> childAnalyses; + + /// The storage uniquer instance that owns the memory of the allocated lattice + /// anchors + StorageUniquer uniquer; + + /// A type-erased map of lattice anchors to associated analysis states for + /// first-class lattice anchors. + DenseMap>> + analysisStates; + + /// A map of Ananlysis state type to the equivalent lattice anchors. + /// Lattice anchors are considered equivalent under a certain analysis state + /// type if and only if, the analysis states pointed to by these lattice + /// anchors necessarily contain identical value. + DenseMap> equivalentAnchorMap; + + /// Allow the base child analysis class to access the internals of the solver. + friend class DataFlowAnalysis; +}; + +//===----------------------------------------------------------------------===// +// AnalysisState +//===----------------------------------------------------------------------===// + +/// Base class for generic analysis states. Analysis states contain data-flow +/// information that are attached to lattice anchors and which evolve as the +/// analysis iterates. +/// +/// This class places no restrictions on the semantics of analysis states beyond +/// these requirements. +/// +/// 1. Querying the state of a lattice anchor prior to visiting that anchor +/// results in uninitialized state. Analyses must be aware of unintialized +/// states. +/// 2. Analysis states can reach fixpoints, where subsequent updates will never +/// trigger a change in the state. +/// 3. Analysis states that are uninitialized can be forcefully initialized to a +/// default value. +class AnalysisState { +public: + virtual ~AnalysisState(); + + /// Create the analysis state on the given lattice anchor. + AnalysisState(LatticeAnchor anchor) : anchor(anchor) {} + + /// Returns the lattice anchor this state is located at. + LatticeAnchor getAnchor() const { return anchor; } + + /// Print the contents of the analysis state. + virtual void print(raw_ostream &os) const = 0; + LLVM_DUMP_METHOD void dump() const; + + /// Add a dependency to this analysis state on a lattice anchor and an + /// analysis. If this state is updated, the analysis will be invoked on the + /// given lattice anchor again (in onUpdate()). + void addDependency(ProgramPoint *point, DataFlowAnalysis *analysis); + +protected: + /// This function is called by the solver when the analysis state is updated + /// to enqueue more work items. For example, if a state tracks dependents + /// through the IR (e.g. use-def chains), this function can be implemented to + /// push those dependents on the worklist. + virtual void onUpdate(DataFlowSolver *solver) const { + for (const DataFlowSolver::WorkItem &item : dependents) + solver->enqueue(item); + } + + /// The lattice anchor to which the state belongs. + LatticeAnchor anchor; + +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + /// When compiling with debugging, keep a name for the analysis state. + StringRef debugName; +#endif // LLVM_ENABLE_ABI_BREAKING_CHECKS + +private: + /// The dependency relations originating from this analysis state. An entry + /// `state -> (analysis, anchor)` is created when `analysis` queries `state` + /// when updating `anchor`. + /// + /// When this state is updated, all dependent child analysis invocations are + /// pushed to the back of the queue. Use a `SetVector` to keep the analysis + /// deterministic. + /// + /// Store the dependents on the analysis state for efficiency. + SetVector dependents; + + /// Allow the framework to access the dependents. + friend class DataFlowSolver; +}; + +//===----------------------------------------------------------------------===// +// DataFlowAnalysis +//===----------------------------------------------------------------------===// + +/// Base class for all data-flow analyses. A child analysis is expected to build +/// an initial dependency graph (and optionally provide an initial state) when +/// initialized and define transfer functions when visiting program points. +/// +/// In classical data-flow analysis, the dependency graph is fixed and analyses +/// define explicit transfer functions between input states and output states. +/// In this framework, however, the dependency graph can change during the +/// analysis, and transfer functions are opaque such that the solver doesn't +/// know what states calling `visit` on an analysis will be updated. This allows +/// multiple analyses to plug in and provide values for the same state. +/// +/// Generally, when an analysis queries an uninitialized state, it is expected +/// to "bail out", i.e., not provide any updates. When the value is initialized, +/// the solver will re-invoke the analysis. If the solver exhausts its worklist, +/// however, and there are still uninitialized states, the solver "nudges" the +/// analyses by default-initializing those states. +class DataFlowAnalysis { +public: + virtual ~DataFlowAnalysis(); + + /// Create an analysis with a reference to the parent solver. + explicit DataFlowAnalysis(DataFlowSolver &solver); + + /// Initialize the analysis from the provided top-level operation by building + /// an initial dependency graph between all lattice anchors of interest. This + /// can be implemented by calling `visit` on all program points of interest + /// below the top-level operation. + /// + /// An analysis can optionally provide initial values to certain analysis + /// states to influence the evolution of the analysis. + virtual LogicalResult initialize(Operation *top) = 0; + + /// Visit the given program point. This function is invoked by the solver on + /// this analysis with a given program point when a dependent analysis state + /// is updated. The function is similar to a transfer function; it queries + /// certain analysis states and sets other states. + /// + /// The function is expected to create dependencies on queried states and + /// propagate updates on changed states. A dependency can be created by + /// calling `addDependency` between the input state and a program point, + /// indicating that, if the state is updated, the solver should invoke `solve` + /// on the program point. The dependent point does not have to be the same as + /// the provided point. An update to a state is propagated by calling + /// `propagateIfChange` on the state. If the state has changed, then all its + /// dependents are placed on the worklist. + /// + /// The dependency graph does not need to be static. Each invocation of + /// `visit` can add new dependencies, but these dependencies will not be + /// dynamically added to the worklist because the solver doesn't know what + /// will provide a value for then. + virtual LogicalResult visit(ProgramPoint *point) = 0; + + /// Initialize lattice anchor equivalence class from the provided top-level + /// operation. + /// + /// This function will union lattice anchor to same equivalent class if the + /// analysis can determine the lattice content of lattice anchor is + /// necessarily identical under the corrensponding lattice type. + virtual void initializeEquivalentLatticeAnchor(Operation *top) {} + +protected: + /// Create a dependency between the given analysis state and lattice anchor + /// on this analysis. + void addDependency(AnalysisState *state, ProgramPoint *point); + + /// Propagate an update to a state if it changed. + void propagateIfChanged(AnalysisState *state, ChangeResult changed); + + /// Register a custom lattice anchor class. + template + void registerAnchorKind() { + solver.uniquer.registerParametricStorageType(); + } + + /// Get or create a custom lattice anchor. + template + AnchorT *getLatticeAnchor(Args &&...args) { + return solver.getLatticeAnchor(std::forward(args)...); + } + + /// Union input anchors under the given state. + template + void unionLatticeAnchors(AnchorT anchor, AnchorT other) { + return solver.unionLatticeAnchors(anchor, other); + } + + /// Get the analysis state associated with the lattice anchor. The returned + /// state is expected to be "write-only", and any updates need to be + /// propagated by `propagateIfChanged`. + template + StateT *getOrCreate(AnchorT anchor) { + return solver.getOrCreateState(anchor); + } + + /// Get a read-only analysis state for the given point and create a dependency + /// on `dependent`. If the return state is updated elsewhere, this analysis is + /// re-invoked on the dependent. + template + const StateT *getOrCreateFor(ProgramPoint *dependent, AnchorT anchor) { + StateT *state = getOrCreate(anchor); + if (!solver.isEquivalent(LatticeAnchor(anchor), + LatticeAnchor(dependent))) + addDependency(state, dependent); + return state; + } + + /// Get a uniqued program point instance. + ProgramPoint *getProgramPointBefore(Operation *op) { + return solver.getProgramPointBefore(op); + } + + ProgramPoint *getProgramPointBefore(Block *block) { + return solver.getProgramPointBefore(block); + } + + ProgramPoint *getProgramPointAfter(Operation *op) { + return solver.getProgramPointAfter(op); + } + + ProgramPoint *getProgramPointAfter(Block *block) { + return solver.getProgramPointAfter(block); + } + + /// Return the configuration of the solver used for this analysis. + const DataFlowConfig &getSolverConfig() const { return solver.getConfig(); } + +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + /// When compiling with debugging, keep a name for the analyis. + StringRef debugName; +#endif // LLVM_ENABLE_ABI_BREAKING_CHECKS + +private: + /// The parent data-flow solver. + DataFlowSolver &solver; + + /// Allow the data-flow solver to access the internals of this class. + friend class DataFlowSolver; +}; + +template +AnalysisT *DataFlowSolver::load(Args &&...args) { + childAnalyses.emplace_back(new AnalysisT(*this, std::forward(args)...)); +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + childAnalyses.back()->debugName = llvm::getTypeName(); +#endif // LLVM_ENABLE_ABI_BREAKING_CHECKS + return static_cast(childAnalyses.back().get()); +} + +template +LatticeAnchor +DataFlowSolver::getLeaderAnchorOrSelf(LatticeAnchor latticeAnchor) const { + if (!equivalentAnchorMap.contains(TypeID::get())) { + return latticeAnchor; + } + const llvm::EquivalenceClasses &eqClass = + equivalentAnchorMap.at(TypeID::get()); + llvm::EquivalenceClasses::member_iterator leaderIt = + eqClass.findLeader(latticeAnchor); + if (leaderIt != eqClass.member_end()) { + return *leaderIt; + } + return latticeAnchor; +} + +template +StateT *DataFlowSolver::getOrCreateState(AnchorT anchor) { + // Replace to leader anchor if found. + LatticeAnchor latticeAnchor(anchor); + latticeAnchor = getLeaderAnchorOrSelf(latticeAnchor); + std::unique_ptr &state = + analysisStates[latticeAnchor][TypeID::get()]; + if (!state) { + state = std::unique_ptr(new StateT(anchor)); +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + state->debugName = llvm::getTypeName(); +#endif // LLVM_ENABLE_ABI_BREAKING_CHECKS + } + return static_cast(state.get()); +} + +template +bool DataFlowSolver::isEquivalent(LatticeAnchor lhs, LatticeAnchor rhs) const { + if (!equivalentAnchorMap.contains(TypeID::get())) { + return false; + } + const llvm::EquivalenceClasses &eqClass = + equivalentAnchorMap.at(TypeID::get()); + if (!eqClass.contains(lhs) || !eqClass.contains(rhs)) + return false; + return eqClass.isEquivalent(lhs, rhs); +} + +template +void DataFlowSolver::unionLatticeAnchors(AnchorT anchor, AnchorT other) { + llvm::EquivalenceClasses &eqClass = + equivalentAnchorMap[TypeID::get()]; + eqClass.unionSets(LatticeAnchor(anchor), LatticeAnchor(other)); +} + +inline raw_ostream &operator<<(raw_ostream &os, const AnalysisState &state) { + state.print(os); + return os; +} + +inline raw_ostream &operator<<(raw_ostream &os, const LatticeAnchor &anchor) { + anchor.print(os); + return os; +} + +} // end namespace mlir + +namespace llvm { +/// Allow hashing of lattice anchors and program points. +template <> +struct DenseMapInfo { + static mlir::ProgramPoint getEmptyKey() { + void *pointer = llvm::DenseMapInfo::getEmptyKey(); + return mlir::ProgramPoint( + (mlir::Block *)pointer, + mlir::Block::iterator((mlir::Operation *)pointer)); + } + static mlir::ProgramPoint getTombstoneKey() { + void *pointer = llvm::DenseMapInfo::getTombstoneKey(); + return mlir::ProgramPoint( + (mlir::Block *)pointer, + mlir::Block::iterator((mlir::Operation *)pointer)); + } + static unsigned getHashValue(mlir::ProgramPoint pp) { + return hash_combine(pp.getBlock(), pp.getPoint().getNodePtr()); + } + static bool isEqual(mlir::ProgramPoint lhs, mlir::ProgramPoint rhs) { + return lhs == rhs; + } +}; + +// Allow llvm::cast style functions. +template +struct CastInfo + : public CastInfo {}; + +template +struct CastInfo + : public CastInfo {}; + +} // end namespace llvm + +#endif // MLIR_ANALYSIS_DATAFLOWFRAMEWORK_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/DataLayoutAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataLayoutAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..cba7ee1b0169268d262959cb7fd6b2e587192ef7 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/DataLayoutAnalysis.h @@ -0,0 +1,48 @@ +//===- DataLayoutAnalysis.h - API for Querying Nested Data Layout -*- C++ -*-=// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_DATALAYOUTANALYSIS_H +#define MLIR_ANALYSIS_DATALAYOUTANALYSIS_H + +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/DenseMap.h" + +#include + +namespace mlir { + +class Operation; +class DataLayout; + +/// Stores data layout objects for each operation that specifies the data layout +/// above and below the given operation. +class DataLayoutAnalysis { +public: + /// Constructs the data layouts. + explicit DataLayoutAnalysis(Operation *root); + + /// Returns the data layout active at the given operation, that is the + /// data layout specified by the closest ancestor that can specify one, or the + /// default layout if there is no such ancestor. + const DataLayout &getAbove(Operation *operation) const; + + /// Returns the data layout specified by the given operation or its closest + /// ancestor that can specify one. + const DataLayout &getAtOrAbove(Operation *operation) const; + +private: + /// Storage for individual data layouts. + DenseMap> layouts; + + /// Default data layout in case no operations specify one. + std::unique_ptr defaultLayout; +}; + +} // namespace mlir + +#endif // MLIR_ANALYSIS_DATALAYOUTANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/FlatLinearValueConstraints.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/FlatLinearValueConstraints.h new file mode 100644 index 0000000000000000000000000000000000000000..e481ef85562b3fa81d7bcf48aee2254f8535f364 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/FlatLinearValueConstraints.h @@ -0,0 +1,586 @@ +//===- FlatLinearValueConstraints.h - Linear Constraints --------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_FLATLINEARVALUECONSTRAINTS_H +#define MLIR_ANALYSIS_FLATLINEARVALUECONSTRAINTS_H + +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include "mlir/Analysis/Presburger/Matrix.h" +#include "mlir/IR/AffineExpr.h" +#include "mlir/IR/OpDefinition.h" +#include + +namespace mlir { + +class AffineMap; +class IntegerSet; +class MLIRContext; +class Value; +class MemRefType; +struct MutableAffineMap; + +namespace presburger { +class MultiAffineFunction; +} // namespace presburger + +/// FlatLinearConstraints is an extension of IntegerPolyhedron. It provides an +/// AffineExpr-based API. +class FlatLinearConstraints : public presburger::IntegerPolyhedron { +public: + /// Constructs a constraint system reserving memory for the specified number + /// of constraints and variables. `valArgs` are the optional SSA values + /// associated with each dimension/symbol. These must either be empty or match + /// the number of dimensions and symbols. + FlatLinearConstraints(unsigned numReservedInequalities, + unsigned numReservedEqualities, + unsigned numReservedCols, unsigned numDims, + unsigned numSymbols, unsigned numLocals) + : IntegerPolyhedron(numReservedInequalities, numReservedEqualities, + numReservedCols, + presburger::PresburgerSpace::getSetSpace( + numDims, numSymbols, numLocals)) { + assert(numReservedCols >= getNumVars() + 1); + } + + /// Constructs a constraint system with the specified number of dimensions + /// and symbols. `valArgs` are the optional SSA values associated with each + /// dimension/symbol. These must either be empty or match the number of + /// dimensions and symbols. + FlatLinearConstraints(unsigned numDims = 0, unsigned numSymbols = 0, + unsigned numLocals = 0) + : FlatLinearConstraints(/*numReservedInequalities=*/0, + /*numReservedEqualities=*/0, + /*numReservedCols=*/numDims + numSymbols + + numLocals + 1, + numDims, numSymbols, numLocals) {} + + FlatLinearConstraints(const IntegerPolyhedron &fac) + : IntegerPolyhedron(fac) {} + + /// Return the kind of this object. + Kind getKind() const override { return Kind::FlatLinearConstraints; } + + /// Flag to control if conservative semi-affine bounds should be added in + /// `addBound()`. + enum class AddConservativeSemiAffineBounds { No = 0, Yes }; + + /// Adds a bound for the variable at the specified position with constraints + /// being drawn from the specified bound map. In case of an EQ bound, the + /// bound map is expected to have exactly one result. In case of a LB/UB, the + /// bound map may have more than one result, for each of which an inequality + /// is added. + /// + /// The bound can be added as open or closed by specifying isClosedBound. In + /// case of a LB/UB, isClosedBound = false means the bound is added internally + /// as a closed bound by +1/-1 respectively. In case of an EQ bound, it can + /// only be added as a closed bound. + /// + /// Conservative bounds for semi-affine expressions will be added if + /// `AddConservativeSemiAffineBounds` is set to `Yes`. This currently only + /// covers semi-affine `mod` expressions, so `addBound()` will still fail if + /// it encounters a semi-affine `floordiv`, `ceildiv`, or `mul`. Note: If + /// enabled it is possible for the resulting constraint set to become empty if + /// a precondition of a conservative bound is found not to hold. + /// + /// Note: The dimensions/symbols of this FlatLinearConstraints must match the + /// dimensions/symbols of the affine map. + LogicalResult addBound( + presburger::BoundType type, unsigned pos, AffineMap boundMap, + bool isClosedBound, + AddConservativeSemiAffineBounds = AddConservativeSemiAffineBounds::No); + + /// Adds a bound for the variable at the specified position with constraints + /// being drawn from the specified bound map. In case of an EQ bound, the + /// bound map is expected to have exactly one result. In case of a LB/UB, the + /// bound map may have more than one result, for each of which an inequality + /// is added. + /// + /// Conservative bounds for semi-affine expressions will be added if + /// `AddConservativeSemiAffineBounds` is set to `Yes`. This currently only + /// covers semi-affine `mod` expressions, so `addBound()` will still fail if + /// it encounters a semi-affine `floordiv`, `ceildiv`, or `mul`. Note: If + /// enabled it is possible for the resulting constraint set to become empty if + /// a precondition of a conservative bound is found not to hold. + /// + /// Note: The dimensions/symbols of this FlatLinearConstraints must match the + /// dimensions/symbols of the affine map. By default the lower bound is closed + /// and the upper bound is open. + LogicalResult addBound( + presburger::BoundType type, unsigned pos, AffineMap boundMap, + AddConservativeSemiAffineBounds = AddConservativeSemiAffineBounds::No); + + /// The `addBound` overload above hides the inherited overloads by default, so + /// we explicitly introduce them here. + using IntegerPolyhedron::addBound; + + /// Returns a non-negative constant bound on the extent (upper bound - lower + /// bound) of the specified variable if it is found to be a constant; returns + /// std::nullopt if it's not a constant. This method treats symbolic + /// variables specially, i.e., it looks for constant differences between + /// affine expressions involving only the symbolic variables. 'lb', if + /// provided, is set to the lower bound map associated with the constant + /// difference, and similarly, `ub` to the upper bound. Note that 'lb', 'ub' + /// are purely symbolic and will correspond to the symbolic variables of the + /// constaint set. + // Egs: 0 <= i <= 15, return 16. + // s0 + 2 <= i <= s0 + 17, returns 16. (s0 has to be a symbol) + // s0 + s1 + 16 <= d0 <= s0 + s1 + 31, returns 16. + // s0 - 7 <= 8*j <= s0 returns 1 with lb = s0, lbDivisor = 8 (since lb = + // ceil(s0 - 7 / 8) = floor(s0 / 8)). + /// The difference between this method and + /// IntegerRelation::getConstantBoundOnDimSize is that unlike the latter, this + /// makes use of affine expressions and maps in its inference and provides + /// output with affine maps; it thus handles local variables by detecting them + /// as affine functions of the symbols when possible. + std::optional + getConstantBoundOnDimSize(MLIRContext *context, unsigned pos, + AffineMap *lb = nullptr, AffineMap *ub = nullptr, + unsigned *minLbPos = nullptr, + unsigned *minUbPos = nullptr) const; + + /// Returns the constraint system as an integer set. Returns a null integer + /// set if the system has no constraints, or if an integer set couldn't be + /// constructed as a result of a local variable's explicit representation not + /// being known and such a local variable appearing in any of the constraints. + IntegerSet getAsIntegerSet(MLIRContext *context) const; + + /// Computes the lower and upper bounds of the first `num` dimensional + /// variables (starting at `offset`) as an affine map of the remaining + /// variables (dimensional and symbolic). This method is able to detect + /// variables as floordiv's and mod's of affine expressions of other + /// variables with respect to (positive) constants. Sets bound map to a + /// null AffineMap if such a bound can't be found (or yet unimplemented). + /// + /// By default the returned lower bounds are closed and upper bounds are open. + /// If `closedUb` is true, the upper bound is closed. + void getSliceBounds(unsigned offset, unsigned num, MLIRContext *context, + SmallVectorImpl *lbMaps, + SmallVectorImpl *ubMaps, + bool closedUB = false); + + /// Composes an affine map whose dimensions and symbols match one to one with + /// the dimensions and symbols of this FlatLinearConstraints. The results of + /// the map `other` are added as the leading dimensions of this constraint + /// system. Returns failure if `other` is a semi-affine map. + LogicalResult composeMatchingMap(AffineMap other); + + /// Gets the lower and upper bound of the `offset` + `pos`th variable + /// treating [0, offset) U [offset + num, symStartPos) as dimensions and + /// [symStartPos, getNumDimAndSymbolVars) as symbols, and `pos` lies in + /// [0, num). The multi-dimensional maps in the returned pair represent the + /// max and min of potentially multiple affine expressions. `localExprs` holds + /// pre-computed AffineExpr's for all local variables in the system. + /// + /// By default the returned lower bounds are closed and upper bounds are open. + /// If `closedUb` is true, the upper bound is closed. + std::pair + getLowerAndUpperBound(unsigned pos, unsigned offset, unsigned num, + unsigned symStartPos, ArrayRef localExprs, + MLIRContext *context, bool closedUB = false) const; + + /// Insert variables of the specified kind at position `pos`. Positions are + /// relative to the kind of variable. The coefficient columns corresponding + /// to the added variables are initialized to zero. `vals` are the Values + /// corresponding to the variables. Values should not be used with + /// VarKind::Local since values can only be attached to non-local variables. + /// Return the absolute column position (i.e., not relative to the kind of + /// variable) of the first added variable. + /// + /// Note: Empty Values are allowed in `vals`. + unsigned insertDimVar(unsigned pos, unsigned num = 1) { + return insertVar(VarKind::SetDim, pos, num); + } + unsigned insertSymbolVar(unsigned pos, unsigned num = 1) { + return insertVar(VarKind::Symbol, pos, num); + } + unsigned insertLocalVar(unsigned pos, unsigned num = 1) { + return insertVar(VarKind::Local, pos, num); + } + + /// Append variables of the specified kind after the last variable of that + /// kind. The coefficient columns corresponding to the added variables are + /// initialized to zero. `vals` are the Values corresponding to the + /// variables. Return the absolute column position (i.e., not relative to the + /// kind of variable) of the first appended variable. + /// + /// Note: Empty Values are allowed in `vals`. + unsigned appendDimVar(unsigned num = 1) { + return appendVar(VarKind::SetDim, num); + } + unsigned appendSymbolVar(unsigned num = 1) { + return appendVar(VarKind::Symbol, num); + } + unsigned appendLocalVar(unsigned num = 1) { + return appendVar(VarKind::Local, num); + } + + /// A more human-readable version of dump(). + void dumpPretty() const; + /// An easier to read dump of a `row` of the same width as the number of + /// columns. `fixedColWidth` ensure that even with a zero coefficient, we + /// print spaces so that variables are aligned. + void dumpRow(ArrayRef row, bool fixedColWidth = true) const; + +protected: + using VarKind = presburger::VarKind; + + /// Compute an explicit representation for local vars. For all systems coming + /// from MLIR integer sets, maps, or expressions where local vars were + /// introduced to model floordivs and mods, this always succeeds. + LogicalResult computeLocalVars(SmallVectorImpl &memo, + MLIRContext *context) const; + + /// Given an affine map that is aligned with this constraint system: + /// * Flatten the map. + /// * Add newly introduced local columns at the beginning of this constraint + /// system (local column pos 0). + /// * Add equalities that define the new local columns to this constraint + /// system. + /// * Return the flattened expressions via `flattenedExprs`. + /// + /// Note: This is a shared helper function of `addLowerOrUpperBound` and + /// `composeMatchingMap`. + LogicalResult flattenAlignedMapAndMergeLocals( + AffineMap map, std::vector> *flattenedExprs, + bool addConservativeSemiAffineBounds = false); + + /// Prints the number of constraints, dimensions, symbols and locals in the + /// FlatLinearConstraints. Also, prints for each variable whether there is + /// an SSA Value attached to it. + void printSpace(raw_ostream &os) const override; +}; + +/// FlatLinearValueConstraints represents an extension of FlatLinearConstraints +/// where each non-local variable can have an SSA Value attached to it. +class FlatLinearValueConstraints : public FlatLinearConstraints { +public: + /// The SSA Values attached to each non-local variable are stored as + /// identifiers in the constraint system's space. + using Identifier = presburger::Identifier; + + /// Constructs a constraint system reserving memory for the specified number + /// of constraints and variables. `valArgs` are the optional SSA values + /// associated with each dimension/symbol. These must either be empty or match + /// the number of dimensions and symbols. + FlatLinearValueConstraints(unsigned numReservedInequalities, + unsigned numReservedEqualities, + unsigned numReservedCols, unsigned numDims, + unsigned numSymbols, unsigned numLocals, + ArrayRef> valArgs) + : FlatLinearConstraints(numReservedInequalities, numReservedEqualities, + numReservedCols, numDims, numSymbols, numLocals) { + assert(valArgs.empty() || valArgs.size() == getNumDimAndSymbolVars()); + for (unsigned i = 0, e = valArgs.size(); i < e; ++i) + if (valArgs[i]) + setValue(i, *valArgs[i]); + } + + /// Constructs a constraint system reserving memory for the specified number + /// of constraints and variables. `valArgs` are the optional SSA values + /// associated with each dimension/symbol. These must either be empty or match + /// the number of dimensions and symbols. + FlatLinearValueConstraints(unsigned numReservedInequalities, + unsigned numReservedEqualities, + unsigned numReservedCols, unsigned numDims, + unsigned numSymbols, unsigned numLocals, + ArrayRef valArgs) + : FlatLinearConstraints(numReservedInequalities, numReservedEqualities, + numReservedCols, numDims, numSymbols, numLocals) { + assert(valArgs.empty() || valArgs.size() == getNumDimAndSymbolVars()); + for (unsigned i = 0, e = valArgs.size(); i < e; ++i) + if (valArgs[i]) + setValue(i, valArgs[i]); + } + + /// Constructs a constraint system with the specified number of dimensions + /// and symbols. `valArgs` are the optional SSA values associated with each + /// dimension/symbol. These must either be empty or match the number of + /// dimensions and symbols. + FlatLinearValueConstraints(unsigned numDims, unsigned numSymbols, + unsigned numLocals, + ArrayRef> valArgs) + : FlatLinearValueConstraints(/*numReservedInequalities=*/0, + /*numReservedEqualities=*/0, + /*numReservedCols=*/numDims + numSymbols + + numLocals + 1, + numDims, numSymbols, numLocals, valArgs) {} + + /// Constructs a constraint system with the specified number of dimensions + /// and symbols. `valArgs` are the optional SSA values associated with each + /// dimension/symbol. These must either be empty or match the number of + /// dimensions and symbols. + FlatLinearValueConstraints(unsigned numDims = 0, unsigned numSymbols = 0, + unsigned numLocals = 0, + ArrayRef valArgs = {}) + : FlatLinearValueConstraints(/*numReservedInequalities=*/0, + /*numReservedEqualities=*/0, + /*numReservedCols=*/numDims + numSymbols + + numLocals + 1, + numDims, numSymbols, numLocals, valArgs) {} + + FlatLinearValueConstraints(const IntegerPolyhedron &fac, + ArrayRef> valArgs = {}) + : FlatLinearConstraints(fac) { + if (valArgs.empty()) + return; + assert(valArgs.size() == getNumDimAndSymbolVars()); + for (unsigned i = 0, e = valArgs.size(); i < e; ++i) + if (valArgs[i]) + setValue(i, *valArgs[i]); + } + + /// Creates an affine constraint system from an IntegerSet. + explicit FlatLinearValueConstraints(IntegerSet set, ValueRange operands = {}); + + /// Return the kind of this object. + Kind getKind() const override { return Kind::FlatLinearValueConstraints; } + + static bool classof(const IntegerRelation *cst) { + return cst->getKind() >= Kind::FlatLinearValueConstraints && + cst->getKind() <= Kind::FlatAffineRelation; + } + + /// Adds a constant bound for the variable associated with the given Value. + void addBound(presburger::BoundType type, Value val, int64_t value); + using FlatLinearConstraints::addBound; + + /// Returns the Value associated with the pos^th variable. Asserts if + /// no Value variable was associated. + inline Value getValue(unsigned pos) const { + assert(pos < getNumDimAndSymbolVars() && "Invalid position"); + assert(hasValue(pos) && "variable's Value not set"); + VarKind kind = getVarKindAt(pos); + unsigned relativePos = pos - getVarKindOffset(kind); + return space.getId(kind, relativePos).getValue(); + } + + /// Returns the Values associated with variables in range [start, end). + /// Asserts if no Value was associated with one of these variables. + inline void getValues(unsigned start, unsigned end, + SmallVectorImpl *values) const { + assert(end <= getNumDimAndSymbolVars() && "invalid end position"); + assert(start <= end && "invalid start position"); + values->clear(); + values->reserve(end - start); + for (unsigned i = start; i < end; ++i) + values->push_back(getValue(i)); + } + + inline SmallVector> getMaybeValues() const { + SmallVector> maybeValues; + maybeValues.reserve(getNumDimAndSymbolVars()); + for (unsigned i = 0, e = getNumDimAndSymbolVars(); i < e; ++i) + if (hasValue(i)) { + maybeValues.push_back(getValue(i)); + } else { + maybeValues.push_back(std::nullopt); + } + return maybeValues; + } + + inline SmallVector> + getMaybeValues(presburger::VarKind kind) const { + assert(kind != VarKind::Local && + "Local variables do not have any value attached to them."); + SmallVector> maybeValues; + maybeValues.reserve(getNumVarKind(kind)); + const unsigned offset = space.getVarKindOffset(kind); + for (unsigned i = 0, e = getNumVarKind(kind); i < e; ++i) { + if (hasValue(offset + i)) + maybeValues.push_back(getValue(offset + i)); + else + maybeValues.push_back(std::nullopt); + } + return maybeValues; + } + + /// Returns true if the pos^th variable has an associated Value. + inline bool hasValue(unsigned pos) const { + assert(pos < getNumDimAndSymbolVars() && "Invalid position"); + VarKind kind = getVarKindAt(pos); + unsigned relativePos = pos - getVarKindOffset(kind); + return space.getId(kind, relativePos).hasValue(); + } + + unsigned appendDimVar(ValueRange vals); + using FlatLinearConstraints::appendDimVar; + + unsigned appendSymbolVar(ValueRange vals); + using FlatLinearConstraints::appendSymbolVar; + + unsigned insertDimVar(unsigned pos, ValueRange vals); + using FlatLinearConstraints::insertDimVar; + + unsigned insertSymbolVar(unsigned pos, ValueRange vals); + using FlatLinearConstraints::insertSymbolVar; + + unsigned insertVar(presburger::VarKind kind, unsigned pos, + unsigned num = 1) override; + unsigned insertVar(presburger::VarKind kind, unsigned pos, ValueRange vals); + + /// Removes variables in the column range [varStart, varLimit), and copies any + /// remaining valid data into place, updates member variables, and resizes + /// arrays as needed. + void removeVarRange(presburger::VarKind kind, unsigned varStart, + unsigned varLimit) override; + using IntegerPolyhedron::removeVarRange; + + /// Sets the Value associated with the pos^th variable. + /// Stores the Value in the space's identifiers. + inline void setValue(unsigned pos, Value val) { + assert(pos < getNumDimAndSymbolVars() && "invalid var position"); + VarKind kind = getVarKindAt(pos); + unsigned relativePos = pos - getVarKindOffset(kind); + space.setId(kind, relativePos, presburger::Identifier(val)); + } + + /// Sets the Values associated with the variables in the range [start, end). + /// The range must contain only dim and symbol variables. + void setValues(unsigned start, unsigned end, ArrayRef values) { + assert(end <= getNumVars() && "invalid end position"); + assert(start <= end && "invalid start position"); + assert(values.size() == end - start && + "value should be provided for each variable in the range."); + for (unsigned i = start; i < end; ++i) + setValue(i, values[i - start]); + } + + /// Looks up the position of the variable with the specified Value starting + /// with variables at offset `offset`. Returns true if found (false + /// otherwise). `pos` is set to the (column) position of the variable. + bool findVar(Value val, unsigned *pos, unsigned offset = 0) const; + + /// Returns true if a variable with the specified Value exists, false + /// otherwise. + bool containsVar(Value val) const; + + /// Projects out the variable that is associate with Value. + void projectOut(Value val); + using IntegerPolyhedron::projectOut; + + /// Prints the number of constraints, dimensions, symbols and locals in the + /// FlatAffineValueConstraints. Also, prints for each variable whether there + /// is an SSA Value attached to it. + void printSpace(raw_ostream &os) const override; + + /// Align `map` with this constraint system based on `operands`. Each operand + /// must already have a corresponding dim/symbol in this constraint system. + AffineMap computeAlignedMap(AffineMap map, ValueRange operands) const; + + /// Merge and align the variables of `this` and `other` starting at + /// `offset`, so that both constraint systems get the union of the contained + /// variables that is dimension-wise and symbol-wise unique; both + /// constraint systems are updated so that they have the union of all + /// variables, with `this`'s original variables appearing first followed + /// by any of `other`'s variables that didn't appear in `this`. Local + /// variables in `other` that have the same division representation as local + /// variables in `this` are merged into one. + // E.g.: Input: `this` has (%i, %j) [%M, %N] + // `other` has (%k, %j) [%P, %N, %M] + // Output: both `this`, `other` have (%i, %j, %k) [%M, %N, %P] + // + void mergeAndAlignVarsWithOther(unsigned offset, + FlatLinearValueConstraints *other); + + /// Merge and align symbols of `this` and `other` such that both get union of + /// of symbols that are unique. Symbols in `this` and `other` should be + /// unique. Symbols with Value as `None` are considered to be inequal to all + /// other symbols. + void mergeSymbolVars(FlatLinearValueConstraints &other); + + /// Returns true if this constraint system and `other` are in the same + /// space, i.e., if they are associated with the same set of variables, + /// appearing in the same order. Returns false otherwise. + bool areVarsAlignedWithOther(const FlatLinearConstraints &other); + + /// Updates the constraints to be the smallest bounding (enclosing) box that + /// contains the points of `this` set and that of `other`, with the symbols + /// being treated specially. For each of the dimensions, the min of the lower + /// bounds (symbolic) and the max of the upper bounds (symbolic) is computed + /// to determine such a bounding box. `other` is expected to have the same + /// dimensional variables as this constraint system (in the same order). + /// + /// E.g.: + /// 1) this = {0 <= d0 <= 127}, + /// other = {16 <= d0 <= 192}, + /// output = {0 <= d0 <= 192} + /// 2) this = {s0 + 5 <= d0 <= s0 + 20}, + /// other = {s0 + 1 <= d0 <= s0 + 9}, + /// output = {s0 + 1 <= d0 <= s0 + 20} + /// 3) this = {0 <= d0 <= 5, 1 <= d1 <= 9} + /// other = {2 <= d0 <= 6, 5 <= d1 <= 15}, + /// output = {0 <= d0 <= 6, 1 <= d1 <= 15} + LogicalResult unionBoundingBox(const FlatLinearValueConstraints &other); + using IntegerPolyhedron::unionBoundingBox; +}; + +/// Flattens 'expr' into 'flattenedExpr', which contains the coefficients of the +/// dimensions, symbols, and additional variables that represent floor divisions +/// of dimensions, symbols, and in turn other floor divisions. Returns failure +/// if 'expr' could not be flattened (i.e., an unhandled semi-affine was found). +/// 'cst' contains constraints that connect newly introduced local variables +/// to existing dimensional and symbolic variables. See documentation for +/// AffineExprFlattener on how mod's and div's are flattened. +LogicalResult +getFlattenedAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols, + SmallVectorImpl *flattenedExpr, + FlatLinearConstraints *cst = nullptr, + bool addConservativeSemiAffineBounds = false); + +/// Flattens the result expressions of the map to their corresponding flattened +/// forms and set in 'flattenedExprs'. Returns failure if any expression in the +/// map could not be flattened (i.e., an unhandled semi-affine was found). 'cst' +/// contains constraints that connect newly introduced local variables to +/// existing dimensional and / symbolic variables. See documentation for +/// AffineExprFlattener on how mod's and div's are flattened. For all affine +/// expressions that share the same operands (like those of an affine map), this +/// method should be used instead of repeatedly calling getFlattenedAffineExpr +/// since local variables added to deal with div's and mod's will be reused +/// across expressions. +LogicalResult +getFlattenedAffineExprs(AffineMap map, + std::vector> *flattenedExprs, + FlatLinearConstraints *cst = nullptr, + bool addConservativeSemiAffineBounds = false); +LogicalResult +getFlattenedAffineExprs(IntegerSet set, + std::vector> *flattenedExprs, + FlatLinearConstraints *cst = nullptr); + +LogicalResult +getMultiAffineFunctionFromMap(AffineMap map, + presburger::MultiAffineFunction &multiAff); + +/// Re-indexes the dimensions and symbols of an affine map with given `operands` +/// values to align with `dims` and `syms` values. +/// +/// Each dimension/symbol of the map, bound to an operand `o`, is replaced with +/// dimension `i`, where `i` is the position of `o` within `dims`. If `o` is not +/// in `dims`, replace it with symbol `i`, where `i` is the position of `o` +/// within `syms`. If `o` is not in `syms` either, replace it with a new symbol. +/// +/// Note: If a value appears multiple times as a dimension/symbol (or both), all +/// corresponding dim/sym expressions are replaced with the first dimension +/// bound to that value (or first symbol if no such dimension exists). +/// +/// The resulting affine map has `dims.size()` many dimensions and at least +/// `syms.size()` many symbols. +/// +/// The SSA values of the symbols of the resulting map are optionally returned +/// via `newSyms`. This is a concatenation of `syms` with the SSA values of the +/// newly added symbols. +/// +/// Note: As part of this re-indexing, dimensions may turn into symbols, or vice +/// versa. +AffineMap alignAffineMapWithValues(AffineMap map, ValueRange operands, + ValueRange dims, ValueRange syms, + SmallVector *newSyms = nullptr); + +} // namespace mlir + +#endif // MLIR_ANALYSIS_FLATLINEARVALUECONSTRAINTS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Liveness.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Liveness.h new file mode 100644 index 0000000000000000000000000000000000000000..ca4d8dfab3c919a837b09675c4b6f453ae3b2e86 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Liveness.h @@ -0,0 +1,158 @@ +//===- Liveness.h - Liveness analysis for MLIR ------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains an analysis for computing liveness information from a +// given top-level operation. The current version of the analysis uses a +// traditional algorithm to resolve detailed live-range information about all +// values within the specified regions. It is also possible to query liveness +// information on block level. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_LIVENESS_H +#define MLIR_ANALYSIS_LIVENESS_H + +#include + +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/SmallPtrSet.h" + +namespace mlir { + +class Block; +class LivenessBlockInfo; +class Operation; +class Region; +class Value; + +/// Represents an analysis for computing liveness information from a +/// given top-level operation. The analysis iterates over all associated +/// regions that are attached to the given top-level operation. It +/// computes liveness information for every value and block that are +/// included in the mentioned regions. It relies on a fixpoint iteration +/// to compute all live-in and live-out values of all included blocks. +/// Sample usage: +/// Liveness liveness(topLevelOp); +/// auto &allInValues = liveness.getLiveIn(block); +/// auto &allOutValues = liveness.getLiveOut(block); +/// auto allOperationsInWhichValueIsLive = liveness.resolveLiveness(value); +/// bool isDeafAfter = liveness.isDeadAfter(value, operation); +class Liveness { +public: + using OperationListT = std::vector; + using BlockMapT = DenseMap; + using ValueSetT = SmallPtrSet; + +public: + /// Creates a new Liveness analysis that computes liveness + /// information for all associated regions. + Liveness(Operation *op); + + /// Returns the operation this analysis was constructed from. + Operation *getOperation() const { return operation; } + + /// Gets liveness info (if any) for the given value. + /// This includes all operations in which the given value is live. + /// Note that the operations in this list are not ordered and the current + /// implementation is computationally expensive (as it iterates over all + /// blocks in which the given value is live). + OperationListT resolveLiveness(Value value) const; + + /// Gets liveness info (if any) for the block. + const LivenessBlockInfo *getLiveness(Block *block) const; + + /// Returns a reference to a set containing live-in values (unordered). + const ValueSetT &getLiveIn(Block *block) const; + + /// Returns a reference to a set containing live-out values (unordered). + const ValueSetT &getLiveOut(Block *block) const; + + /// Returns true if `value` is not live after `operation`. + bool isDeadAfter(Value value, Operation *operation) const; + + /// Dumps the liveness information in a human readable format. + void dump() const; + + /// Dumps the liveness information to the given stream. + void print(raw_ostream &os) const; + +private: + /// Initializes the internal mappings. + void build(); + +private: + /// The operation this analysis was constructed from. + Operation *operation; + + /// Maps blocks to internal liveness information. + BlockMapT blockMapping; +}; + +/// This class represents liveness information on block level. +class LivenessBlockInfo { +public: + /// A typedef declaration of a value set. + using ValueSetT = Liveness::ValueSetT; + +public: + /// Returns the underlying block. + Block *getBlock() const { return block; } + + /// Returns all values that are live at the beginning + /// of the block (unordered). + const ValueSetT &in() const { return inValues; } + + /// Returns all values that are live at the end + /// of the block (unordered). + const ValueSetT &out() const { return outValues; } + + /// Returns true if the given value is in the live-in set. + bool isLiveIn(Value value) const; + + /// Returns true if the given value is in the live-out set. + bool isLiveOut(Value value) const; + + /// Gets the start operation for the given value. This is the first operation + /// the given value is considered to be live. This could either be the start + /// operation of the current block (in case the value is live-in) or the + /// operation that defines the given value (must be referenced in this block). + Operation *getStartOperation(Value value) const; + + /// Gets the end operation for the given value using the start operation + /// provided (must be referenced in this block). + Operation *getEndOperation(Value value, Operation *startOperation) const; + + /// Get the set of values that are currently live (if any) for the current op. + /// This analysis takes an expansive view of "live" in that if a value is + /// defined by or within the operation or is fully consumed (as in last user) + /// by or within the operation the value is considered "live". The values in + /// the list are not ordered. + /// + /// This check is quite expensive as it does not cache the results of the + /// computation, so the currently live values have to be recomputed for each + /// op. + ValueSetT currentlyLiveValues(Operation *op) const; + +private: + /// The underlying block. + Block *block = nullptr; + + /// The set of all live in values. + ValueSetT inValues; + + /// The set of all live out values. + ValueSetT outValues; + + friend class Liveness; +}; + +} // namespace mlir + +#endif // MLIR_ANALYSIS_LIVENESS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Barvinok.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Barvinok.h new file mode 100644 index 0000000000000000000000000000000000000000..b09617f0fe88e5a588bf0d1ce5006b3f4daf2378 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Barvinok.h @@ -0,0 +1,149 @@ +//===- Barvinok.h - Barvinok's Algorithm ------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Implementation of Barvinok's algorithm and related utility functions. +// Currently a work in progress. +// These include functions to manipulate cones (define a cone object, get its +// dual, and find its index). +// +// The implementation is based on: +// 1. Barvinok, Alexander, and James E. Pommersheim. "An algorithmic theory of +// lattice points in polyhedra." New perspectives in algebraic combinatorics +// 38 (1999): 91-147. +// 2. Verdoolaege, Sven, et al. "Counting integer points in parametric +// polytopes using Barvinok's rational functions." Algorithmica 48 (2007): +// 37-66. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_BARVINOK_H +#define MLIR_ANALYSIS_PRESBURGER_BARVINOK_H + +#include "mlir/Analysis/Presburger/GeneratingFunction.h" +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include "mlir/Analysis/Presburger/Matrix.h" +#include "mlir/Analysis/Presburger/PresburgerRelation.h" +#include "mlir/Analysis/Presburger/QuasiPolynomial.h" +#include + +namespace mlir { +namespace presburger { +namespace detail { + +/// A polyhedron in H-representation is a set of inequalities +/// in d variables with integer coefficients. +using PolyhedronH = IntegerRelation; + +/// A polyhedron in V-representation is a set of rays and points, i.e., +/// vectors, stored as rows of a matrix. +using PolyhedronV = IntMatrix; + +/// A cone in either representation is a special case of +/// a polyhedron in that representation. +using ConeH = PolyhedronH; +using ConeV = PolyhedronV; + +inline PolyhedronH defineHRep(int numVars, int numSymbols = 0) { + // We don't distinguish between domain and range variables, so + // we set the number of domain variables as 0 and the number of + // range variables as the number of actual variables. + // + // numSymbols is the number of parameters. + // + // There are no local (existentially quantified) variables. + // + // The number of symbols is the number of parameters. By default, we consider + // nonparametric polyhedra. + // + // Once the cone is defined, we use `addInequality()` to set inequalities. + return PolyhedronH(PresburgerSpace::getSetSpace(/*numDims=*/numVars, + /*numSymbols=*/numSymbols, + /*numLocals=*/0)); +} + +/// Get the index of a cone, i.e., the volume of the parallelepiped +/// spanned by its generators, which is equal to the number of integer +/// points in its fundamental parallelepiped. +/// If the index is 1, the cone is unimodular. +/// Barvinok, A., and J. E. Pommersheim. "An algorithmic theory of lattice +/// points in polyhedra." p. 107 If it has more rays than the dimension, return +/// 0. +DynamicAPInt getIndex(const ConeV &cone); + +/// Given a cone in H-representation, return its dual. The dual cone is in +/// V-representation. +/// This assumes that the input is pointed at the origin; it assert-fails +/// otherwise. +ConeV getDual(ConeH cone); + +/// Given a cone in V-representation, return its dual. The dual cone is in +/// H-representation. +/// The returned cone is pointed at the origin. +ConeH getDual(ConeV cone); + +/// Compute the generating function for a unimodular cone. +/// The input cone must be unimodular; it assert-fails otherwise. +GeneratingFunction computeUnimodularConeGeneratingFunction(ParamPoint vertex, + int sign, + const ConeH &cone); + +/// Find the solution of a set of equations that express affine constraints +/// between a set of variables and a set of parameters. The solution expresses +/// each variable as an affine function of the parameters. +/// +/// If there is no solution, return null. +std::optional solveParametricEquations(FracMatrix equations); + +/// Given a list of possibly intersecting regions (PresburgerSet) and the +/// generating functions active in each region, produce a pairwise disjoint +/// list of regions (chambers) and identify the generating function of the +/// polytope in each chamber. +/// +/// "Disjoint" here means that the intersection of two chambers is no full- +/// dimensional. +/// +/// The returned list partitions the universe into parts depending on which +/// subset of GFs is active there, and gives the sum of active GFs for each +/// part. +std::vector> +computeChamberDecomposition( + unsigned numSymbols, ArrayRef> + regionsAndGeneratingFunctions); + +/// Compute the generating function corresponding to a polytope. +/// +/// All tangent cones of the polytope must be unimodular. +std::vector> +computePolytopeGeneratingFunction(const PolyhedronH &poly); + +/// Find a vector that is not orthogonal to any of the given vectors, +/// i.e., has nonzero dot product with those of the given vectors +/// that are not null. +/// If any of the vectors is null, it is ignored. +Point getNonOrthogonalVector(ArrayRef vectors); + +/// Find the coefficient of a given power of s in a rational function +/// given by P(s)/Q(s), where +/// P is a polynomial, in which the coefficients are QuasiPolynomials +/// over d parameters (distinct from s), and +/// and Q is a polynomial with Fraction coefficients. +QuasiPolynomial getCoefficientInRationalFunction(unsigned power, + ArrayRef num, + ArrayRef den); + +/// Find the number of terms in a generating function, as +/// a quasipolynomial in the parameter space of the input function. +/// The generating function must be such that for all values of the +/// parameters, the number of terms is finite. +QuasiPolynomial computeNumTerms(const GeneratingFunction &gf); + +} // namespace detail +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_BARVINOK_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Fraction.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Fraction.h new file mode 100644 index 0000000000000000000000000000000000000000..585a6d48506d245e610d7942ff869ee54f31fe16 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Fraction.h @@ -0,0 +1,169 @@ +//===- Fraction.h - MLIR Fraction Class -------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This is a simple class to represent fractions. It supports arithmetic, +// comparison, floor, and ceiling operations. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_FRACTION_H +#define MLIR_ANALYSIS_PRESBURGER_FRACTION_H + +#include "llvm/ADT/DynamicAPInt.h" +#include "llvm/Support/raw_ostream.h" + +namespace mlir { +namespace presburger { +using llvm::DynamicAPInt; + +/// A class to represent fractions. The sign of the fraction is represented +/// in the sign of the numerator; the denominator is always positive. +/// +/// Note that overflows may occur if the numerator or denominator are not +/// representable by 64-bit integers. +struct Fraction { + /// Default constructor initializes the represented rational number to zero. + Fraction() = default; + + /// Construct a Fraction from a numerator and denominator. + Fraction(const DynamicAPInt &oNum, const DynamicAPInt &oDen = DynamicAPInt(1)) + : num(oNum), den(oDen) { + if (den < 0) { + num = -num; + den = -den; + } + } + /// Overloads for passing literals. + Fraction(const DynamicAPInt &num, int64_t den) + : Fraction(num, DynamicAPInt(den)) {} + Fraction(int64_t num, const DynamicAPInt &den = DynamicAPInt(1)) + : Fraction(DynamicAPInt(num), den) {} + Fraction(int64_t num, int64_t den) + : Fraction(DynamicAPInt(num), DynamicAPInt(den)) {} + + // Return the value of the fraction as an integer. This should only be called + // when the fraction's value is really an integer. + DynamicAPInt getAsInteger() const { + assert(num % den == 0 && "Get as integer called on non-integral fraction!"); + return num / den; + } + + llvm::raw_ostream &print(llvm::raw_ostream &os) const { + return os << "(" << num << "/" << den << ")"; + } + + /// The numerator and denominator, respectively. The denominator is always + /// positive. + DynamicAPInt num{0}, den{1}; +}; + +/// Three-way comparison between two fractions. +/// Returns +1, 0, and -1 if the first fraction is greater than, equal to, or +/// less than the second fraction, respectively. +inline int compare(const Fraction &x, const Fraction &y) { + DynamicAPInt diff = x.num * y.den - y.num * x.den; + if (diff > 0) + return +1; + if (diff < 0) + return -1; + return 0; +} + +inline DynamicAPInt floor(const Fraction &f) { return floorDiv(f.num, f.den); } + +inline DynamicAPInt ceil(const Fraction &f) { return ceilDiv(f.num, f.den); } + +inline Fraction operator-(const Fraction &x) { return Fraction(-x.num, x.den); } + +inline bool operator<(const Fraction &x, const Fraction &y) { + return compare(x, y) < 0; +} + +inline bool operator<=(const Fraction &x, const Fraction &y) { + return compare(x, y) <= 0; +} + +inline bool operator==(const Fraction &x, const Fraction &y) { + return compare(x, y) == 0; +} + +inline bool operator!=(const Fraction &x, const Fraction &y) { + return compare(x, y) != 0; +} + +inline bool operator>(const Fraction &x, const Fraction &y) { + return compare(x, y) > 0; +} + +inline bool operator>=(const Fraction &x, const Fraction &y) { + return compare(x, y) >= 0; +} + +inline Fraction abs(const Fraction &f) { + assert(f.den > 0 && "denominator of fraction must be positive!"); + return Fraction(abs(f.num), f.den); +} + +inline Fraction reduce(const Fraction &f) { + if (f == Fraction(0)) + return Fraction(0, 1); + DynamicAPInt g = gcd(abs(f.num), abs(f.den)); + return Fraction(f.num / g, f.den / g); +} + +inline Fraction operator*(const Fraction &x, const Fraction &y) { + return reduce(Fraction(x.num * y.num, x.den * y.den)); +} + +inline Fraction operator/(const Fraction &x, const Fraction &y) { + return reduce(Fraction(x.num * y.den, x.den * y.num)); +} + +inline Fraction operator+(const Fraction &x, const Fraction &y) { + return reduce(Fraction(x.num * y.den + x.den * y.num, x.den * y.den)); +} + +inline Fraction operator-(const Fraction &x, const Fraction &y) { + return reduce(Fraction(x.num * y.den - x.den * y.num, x.den * y.den)); +} + +// Find the integer nearest to a given fraction. +inline DynamicAPInt round(const Fraction &f) { + DynamicAPInt rem = f.num % f.den; + return (f.num / f.den) + (rem > f.den / 2); +} + +inline Fraction &operator+=(Fraction &x, const Fraction &y) { + x = x + y; + return x; +} + +inline Fraction &operator-=(Fraction &x, const Fraction &y) { + x = x - y; + return x; +} + +inline Fraction &operator/=(Fraction &x, const Fraction &y) { + x = x / y; + return x; +} + +inline Fraction &operator*=(Fraction &x, const Fraction &y) { + x = x * y; + return x; +} + +inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Fraction &x) { + x.print(os); + return os; +} + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_FRACTION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/GeneratingFunction.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/GeneratingFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..b81042b4e6f9d6efce5a130f646f50ab57df7e63 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/GeneratingFunction.h @@ -0,0 +1,137 @@ +//===- GeneratingFunction.h - Generating Functions over Q^d -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Definition of the GeneratingFunction class for Barvinok's algorithm, +// which represents a function over Q^n, parameterized by d parameters. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_GENERATINGFUNCTION_H +#define MLIR_ANALYSIS_PRESBURGER_GENERATINGFUNCTION_H + +#include "mlir/Analysis/Presburger/Fraction.h" +#include "mlir/Analysis/Presburger/Matrix.h" + +namespace mlir { +namespace presburger { +namespace detail { + +// A parametric point is a vector, each of whose elements +// is an affine function of n parameters. Each column +// in the matrix represents the affine function and +// has n+1 elements. +using ParamPoint = FracMatrix; + +// A point is simply a vector. +using Point = SmallVector; + +// A class to describe the type of generating function +// used to enumerate the integer points in a polytope. +// Consists of a set of terms, where the ith term has +// * a sign, ±1, stored in `signs[i]` +// * a numerator, of the form x^{n}, +// where n, stored in `numerators[i]`, +// is a parametric point. +// * a denominator, of the form (1 - x^{d1})...(1 - x^{dn}), +// where each dj, stored in `denominators[i][j]`, +// is a vector. +// +// Represents functions f_p : Q^n -> Q of the form +// +// f_p(x) = \sum_i s_i * (x^n_i(p)) / (\prod_j (1 - x^d_{ij}) +// +// where s_i is ±1, +// n_i \in Q^d -> Q^n is an n-vector of affine functions on d parameters, and +// g_{ij} \in Q^n are vectors. +class GeneratingFunction { +public: + GeneratingFunction(unsigned numParam, SmallVector signs, + std::vector nums, + std::vector> dens) + : numParam(numParam), signs(signs), numerators(nums), denominators(dens) { +#ifndef NDEBUG + for (const ParamPoint &term : numerators) + assert(term.getNumRows() == numParam + 1 && + "dimensionality of numerator exponents does not match number of " + "parameters!"); +#endif // NDEBUG + } + + unsigned getNumParams() const { return numParam; } + + SmallVector getSigns() const { return signs; } + + std::vector getNumerators() const { return numerators; } + + std::vector> getDenominators() const { + return denominators; + } + + GeneratingFunction operator+(const GeneratingFunction &gf) const { + assert(numParam == gf.getNumParams() && + "two generating functions with different numbers of parameters " + "cannot be added!"); + SmallVector sumSigns = signs; + sumSigns.append(gf.signs); + + std::vector sumNumerators = numerators; + llvm::append_range(sumNumerators, gf.numerators); + + std::vector> sumDenominators = denominators; + llvm::append_range(sumDenominators, gf.denominators); + return GeneratingFunction(numParam, sumSigns, sumNumerators, + sumDenominators); + } + + llvm::raw_ostream &print(llvm::raw_ostream &os) const { + for (unsigned i = 0, e = signs.size(); i < e; i++) { + if (i == 0) { + if (signs[i] == -1) + os << "- "; + } else { + if (signs[i] == 1) + os << " + "; + else + os << " - "; + } + + os << "x^["; + unsigned r = numerators[i].getNumRows(); + for (unsigned j = 0; j < r - 1; j++) { + os << "["; + for (unsigned k = 0, c = numerators[i].getNumColumns(); k < c - 1; k++) + os << numerators[i].at(j, k) << ","; + os << numerators[i].getRow(j).back() << "],"; + } + os << "["; + for (unsigned k = 0, c = numerators[i].getNumColumns(); k < c - 1; k++) + os << numerators[i].at(r - 1, k) << ","; + os << numerators[i].getRow(r - 1).back() << "]]/"; + + for (const Point &den : denominators[i]) { + os << "(x^["; + for (unsigned j = 0, e = den.size(); j < e - 1; j++) + os << den[j] << ","; + os << den.back() << "])"; + } + } + return os; + } + +private: + unsigned numParam; + SmallVector signs; + std::vector numerators; + std::vector> denominators; +}; + +} // namespace detail +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_GENERATINGFUNCTION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/IntegerRelation.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/IntegerRelation.h new file mode 100644 index 0000000000000000000000000000000000000000..b68262f09f485807d767002ecf7d888e39ef8b79 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/IntegerRelation.h @@ -0,0 +1,994 @@ +//===- IntegerRelation.h - MLIR IntegerRelation Class ---------*- C++ -*---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A class to represent a relation over integer tuples. A relation is +// represented as a constraint system over a space of tuples of integer valued +// variables supporting symbolic variables and existential quantification. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_INTEGERRELATION_H +#define MLIR_ANALYSIS_PRESBURGER_INTEGERRELATION_H + +#include "mlir/Analysis/Presburger/Fraction.h" +#include "mlir/Analysis/Presburger/Matrix.h" +#include "mlir/Analysis/Presburger/PresburgerSpace.h" +#include "mlir/Analysis/Presburger/Utils.h" +#include "llvm/ADT/DynamicAPInt.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/LogicalResult.h" +#include + +namespace mlir { +namespace presburger { +using llvm::DynamicAPInt; +using llvm::failure; +using llvm::int64fromDynamicAPInt; +using llvm::LogicalResult; +using llvm::SmallVectorImpl; +using llvm::success; + +class IntegerRelation; +class IntegerPolyhedron; +class PresburgerSet; +class PresburgerRelation; +struct SymbolicLexOpt; + +/// The type of bound: equal, lower bound or upper bound. +enum class BoundType { EQ, LB, UB }; + +/// An IntegerRelation represents the set of points from a PresburgerSpace that +/// satisfy a list of affine constraints. Affine constraints can be inequalities +/// or equalities in the form: +/// +/// Inequality: c_0*x_0 + c_1*x_1 + .... + c_{n-1}*x_{n-1} + c_n >= 0 +/// Equality : c_0*x_0 + c_1*x_1 + .... + c_{n-1}*x_{n-1} + c_n == 0 +/// +/// where c_0, c_1, ..., c_n are integers and n is the total number of +/// variables in the space. +/// +/// Such a relation corresponds to the set of integer points lying in a convex +/// polyhedron. For example, consider the relation: +/// (x) -> (y) : (1 <= x <= 7, x = 2y) +/// These can be thought of as points in the polyhedron: +/// (x, y) : (1 <= x <= 7, x = 2y) +/// This relation contains the pairs (2, 1), (4, 2), and (6, 3). +/// +/// Since IntegerRelation makes a distinction between dimensions, VarKind::Range +/// and VarKind::Domain should be used to refer to dimension variables. +class IntegerRelation { +public: + /// All derived classes of IntegerRelation. + enum class Kind { + IntegerRelation, + IntegerPolyhedron, + FlatLinearConstraints, + FlatLinearValueConstraints, + FlatAffineValueConstraints, + FlatAffineRelation + }; + + /// Constructs a relation reserving memory for the specified number + /// of constraints and variables. + IntegerRelation(unsigned numReservedInequalities, + unsigned numReservedEqualities, unsigned numReservedCols, + const PresburgerSpace &space) + : space(space), equalities(0, space.getNumVars() + 1, + numReservedEqualities, numReservedCols), + inequalities(0, space.getNumVars() + 1, numReservedInequalities, + numReservedCols) { + assert(numReservedCols >= space.getNumVars() + 1); + } + + /// Constructs a relation with the specified number of dimensions and symbols. + explicit IntegerRelation(const PresburgerSpace &space) + : IntegerRelation(/*numReservedInequalities=*/0, + /*numReservedEqualities=*/0, + /*numReservedCols=*/space.getNumVars() + 1, space) {} + + virtual ~IntegerRelation() = default; + + /// Return a system with no constraints, i.e., one which is satisfied by all + /// points. + static IntegerRelation getUniverse(const PresburgerSpace &space) { + return IntegerRelation(space); + } + + /// Return an empty system containing an invalid equation 0 = 1. + static IntegerRelation getEmpty(const PresburgerSpace &space) { + IntegerRelation result(0, 1, space.getNumVars() + 1, space); + SmallVector invalidEq(space.getNumVars() + 1, 0); + invalidEq.back() = 1; + result.addEquality(invalidEq); + return result; + } + + /// Return the kind of this IntegerRelation. + virtual Kind getKind() const { return Kind::IntegerRelation; } + + static bool classof(const IntegerRelation *cst) { return true; } + + // Clones this object. + std::unique_ptr clone() const; + + /// Returns a reference to the underlying space. + const PresburgerSpace &getSpace() const { return space; } + + /// Set the space to `oSpace`, which should have the same number of ids as + /// the current space. + void setSpace(const PresburgerSpace &oSpace); + + /// Set the space to `oSpace`, which should not have any local ids. + /// `oSpace` can have fewer ids than the current space; in that case, the + /// the extra ids in `this` that are not accounted for by `oSpace` will be + /// considered as local ids. `oSpace` should not have more ids than the + /// current space; this will result in an assert failure. + void setSpaceExceptLocals(const PresburgerSpace &oSpace); + + /// Set the identifier for the ith variable of the specified kind of the + /// IntegerRelation's PresburgerSpace. The index is relative to the kind of + /// the variable. + void setId(VarKind kind, unsigned i, Identifier id); + + void resetIds() { space.resetIds(); } + + /// Get the identifiers for the variables of specified varKind. Calls resetIds + /// on the relations space if identifiers are not enabled. + ArrayRef getIds(VarKind kind); + + /// Returns a copy of the space without locals. + PresburgerSpace getSpaceWithoutLocals() const { + return PresburgerSpace::getRelationSpace(space.getNumDomainVars(), + space.getNumRangeVars(), + space.getNumSymbolVars()); + } + + /// Appends constraints from `other` into `this`. This is equivalent to an + /// intersection with no simplification of any sort attempted. + void append(const IntegerRelation &other); + + /// Finds an equality that equates the specified variable to a constant. + /// Returns the position of the equality row. If 'symbolic' is set to true, + /// symbols are also treated like a constant, i.e., an affine function of the + /// symbols is also treated like a constant. Returns -1 if such an equality + /// could not be found. + int findEqualityToConstant(unsigned pos, bool symbolic = false) const; + + /// Return the intersection of the two relations. + /// If there are locals, they will be merged. + IntegerRelation intersect(IntegerRelation other) const; + + /// Return whether `this` and `other` are equal. This is integer-exact + /// and somewhat expensive, since it uses the integer emptiness check + /// (see IntegerRelation::findIntegerSample()). + bool isEqual(const IntegerRelation &other) const; + + /// Perform a quick equality check on `this` and `other`. The relations are + /// equal if the check return true, but may or may not be equal if the check + /// returns false. The equality check is performed in a plain manner, by + /// comparing if all the equalities and inequalities in `this` and `other` + /// are the same. + bool isObviouslyEqual(const IntegerRelation &other) const; + + /// Return whether this is a subset of the given IntegerRelation. This is + /// integer-exact and somewhat expensive, since it uses the integer emptiness + /// check (see IntegerRelation::findIntegerSample()). + bool isSubsetOf(const IntegerRelation &other) const; + + /// Returns the value at the specified equality row and column. + inline DynamicAPInt atEq(unsigned i, unsigned j) const { + return equalities(i, j); + } + /// The same, but casts to int64_t. This is unsafe and will assert-fail if the + /// value does not fit in an int64_t. + inline int64_t atEq64(unsigned i, unsigned j) const { + return int64_t(equalities(i, j)); + } + inline DynamicAPInt &atEq(unsigned i, unsigned j) { return equalities(i, j); } + + /// Returns the value at the specified inequality row and column. + inline DynamicAPInt atIneq(unsigned i, unsigned j) const { + return inequalities(i, j); + } + /// The same, but casts to int64_t. This is unsafe and will assert-fail if the + /// value does not fit in an int64_t. + inline int64_t atIneq64(unsigned i, unsigned j) const { + return int64_t(inequalities(i, j)); + } + inline DynamicAPInt &atIneq(unsigned i, unsigned j) { + return inequalities(i, j); + } + + unsigned getNumConstraints() const { + return getNumInequalities() + getNumEqualities(); + } + + unsigned getNumDomainVars() const { return space.getNumDomainVars(); } + unsigned getNumRangeVars() const { return space.getNumRangeVars(); } + unsigned getNumSymbolVars() const { return space.getNumSymbolVars(); } + unsigned getNumLocalVars() const { return space.getNumLocalVars(); } + + unsigned getNumDimVars() const { return space.getNumDimVars(); } + unsigned getNumDimAndSymbolVars() const { + return space.getNumDimAndSymbolVars(); + } + unsigned getNumVars() const { return space.getNumVars(); } + + /// Returns the number of columns in the constraint system. + inline unsigned getNumCols() const { return space.getNumVars() + 1; } + + inline unsigned getNumEqualities() const { return equalities.getNumRows(); } + + inline unsigned getNumInequalities() const { + return inequalities.getNumRows(); + } + + inline unsigned getNumReservedEqualities() const { + return equalities.getNumReservedRows(); + } + + inline unsigned getNumReservedInequalities() const { + return inequalities.getNumReservedRows(); + } + + inline ArrayRef getEquality(unsigned idx) const { + return equalities.getRow(idx); + } + inline ArrayRef getInequality(unsigned idx) const { + return inequalities.getRow(idx); + } + /// The same, but casts to int64_t. This is unsafe and will assert-fail if the + /// value does not fit in an int64_t. + inline SmallVector getEquality64(unsigned idx) const { + return getInt64Vec(equalities.getRow(idx)); + } + inline SmallVector getInequality64(unsigned idx) const { + return getInt64Vec(inequalities.getRow(idx)); + } + + inline IntMatrix getInequalities() const { return inequalities; } + + /// Get the number of vars of the specified kind. + unsigned getNumVarKind(VarKind kind) const { + return space.getNumVarKind(kind); + } + + /// Return the index at which the specified kind of vars starts. + unsigned getVarKindOffset(VarKind kind) const { + return space.getVarKindOffset(kind); + } + + /// Return the index at Which the specified kind of vars ends. + unsigned getVarKindEnd(VarKind kind) const { + return space.getVarKindEnd(kind); + } + + /// Get the number of elements of the specified kind in the range + /// [varStart, varLimit). + unsigned getVarKindOverlap(VarKind kind, unsigned varStart, + unsigned varLimit) const { + return space.getVarKindOverlap(kind, varStart, varLimit); + } + + /// Return the VarKind of the var at the specified position. + VarKind getVarKindAt(unsigned pos) const { return space.getVarKindAt(pos); } + + /// The struct CountsSnapshot stores the count of each VarKind, and also of + /// each constraint type. getCounts() returns a CountsSnapshot object + /// describing the current state of the IntegerRelation. truncate() truncates + /// all vars of each VarKind and all constraints of both kinds beyond the + /// counts in the specified CountsSnapshot object. This can be used to achieve + /// rudimentary rollback support. As long as none of the existing constraints + /// or vars are disturbed, and only additional vars or constraints are added, + /// this addition can be rolled back using truncate. + struct CountsSnapshot { + public: + CountsSnapshot(const PresburgerSpace &space, unsigned numIneqs, + unsigned numEqs) + : space(space), numIneqs(numIneqs), numEqs(numEqs) {} + const PresburgerSpace &getSpace() const { return space; }; + unsigned getNumIneqs() const { return numIneqs; } + unsigned getNumEqs() const { return numEqs; } + + private: + PresburgerSpace space; + unsigned numIneqs, numEqs; + }; + CountsSnapshot getCounts() const; + void truncate(const CountsSnapshot &counts); + + /// Insert `num` variables of the specified kind at position `pos`. + /// Positions are relative to the kind of variable. The coefficient columns + /// corresponding to the added variables are initialized to zero. Return the + /// absolute column position (i.e., not relative to the kind of variable) + /// of the first added variable. + virtual unsigned insertVar(VarKind kind, unsigned pos, unsigned num = 1); + + /// Append `num` variables of the specified kind after the last variable + /// of that kind. The coefficient columns corresponding to the added variables + /// are initialized to zero. Return the absolute column position (i.e., not + /// relative to the kind of variable) of the first appended variable. + unsigned appendVar(VarKind kind, unsigned num = 1); + + /// Adds an inequality (>= 0) from the coefficients specified in `inEq`. + void addInequality(ArrayRef inEq); + void addInequality(ArrayRef inEq) { + addInequality(getDynamicAPIntVec(inEq)); + } + /// Adds an equality from the coefficients specified in `eq`. + void addEquality(ArrayRef eq); + void addEquality(ArrayRef eq) { + addEquality(getDynamicAPIntVec(eq)); + } + + /// Eliminate the `posB^th` local variable, replacing every instance of it + /// with the `posA^th` local variable. This should be used when the two + /// local variables are known to always take the same values. + virtual void eliminateRedundantLocalVar(unsigned posA, unsigned posB); + + /// Removes variables of the specified kind with the specified pos (or + /// within the specified range) from the system. The specified location is + /// relative to the first variable of the specified kind. + void removeVar(VarKind kind, unsigned pos); + virtual void removeVarRange(VarKind kind, unsigned varStart, + unsigned varLimit); + + /// Removes the specified variable from the system. + void removeVar(unsigned pos); + + void removeEquality(unsigned pos); + void removeInequality(unsigned pos); + + /// Remove the (in)equalities at positions [start, end). + void removeEqualityRange(unsigned start, unsigned end); + void removeInequalityRange(unsigned start, unsigned end); + + /// Get the lexicographically minimum rational point satisfying the + /// constraints. Returns an empty optional if the relation is empty or if + /// the lexmin is unbounded. Symbols are not supported and will result in + /// assert-failure. Note that Domain is minimized first, then range. + MaybeOptimum> findRationalLexMin() const; + + /// Same as above, but returns lexicographically minimal integer point. + /// Note: this should be used only when the lexmin is really required. + /// For a generic integer sampling operation, findIntegerSample is more + /// robust and should be preferred. Note that Domain is minimized first, then + /// range. + MaybeOptimum> findIntegerLexMin() const; + + /// Swap the posA^th variable with the posB^th variable. + virtual void swapVar(unsigned posA, unsigned posB); + + /// Removes all equalities and inequalities. + void clearConstraints(); + + /// Sets the `values.size()` variables starting at `po`s to the specified + /// values and removes them. + void setAndEliminate(unsigned pos, ArrayRef values); + void setAndEliminate(unsigned pos, ArrayRef values) { + setAndEliminate(pos, getDynamicAPIntVec(values)); + } + + /// Replaces the contents of this IntegerRelation with `other`. + virtual void clearAndCopyFrom(const IntegerRelation &other); + + /// Gather positions of all lower and upper bounds of the variable at `pos`, + /// and optionally any equalities on it. In addition, the bounds are to be + /// independent of variables in position range [`offset`, `offset` + `num`). + void + getLowerAndUpperBoundIndices(unsigned pos, + SmallVectorImpl *lbIndices, + SmallVectorImpl *ubIndices, + SmallVectorImpl *eqIndices = nullptr, + unsigned offset = 0, unsigned num = 0) const; + + /// Checks for emptiness by performing variable elimination on all + /// variables, running the GCD test on each equality constraint, and + /// checking for invalid constraints. Returns true if the GCD test fails for + /// any equality, or if any invalid constraints are discovered on any row. + /// Returns false otherwise. + bool isEmpty() const; + + /// Performs GCD checks and invalid constraint checks. + bool isObviouslyEmpty() const; + + /// Runs the GCD test on all equality constraints. Returns true if this test + /// fails on any equality. Returns false otherwise. + /// This test can be used to disprove the existence of a solution. If it + /// returns true, no integer solution to the equality constraints can exist. + bool isEmptyByGCDTest() const; + + /// Returns true if the set of constraints is found to have no solution, + /// false if a solution exists. Uses the same algorithm as + /// `findIntegerSample`. + bool isIntegerEmpty() const; + + /// Returns a matrix where each row is a vector along which the polytope is + /// bounded. The span of the returned vectors is guaranteed to contain all + /// such vectors. The returned vectors are NOT guaranteed to be linearly + /// independent. This function should not be called on empty sets. + IntMatrix getBoundedDirections() const; + + /// Find an integer sample point satisfying the constraints using a + /// branch and bound algorithm with generalized basis reduction, with some + /// additional processing using Simplex for unbounded sets. + /// + /// Returns an integer sample point if one exists, or an empty Optional + /// otherwise. The returned value also includes values of local ids. + std::optional> findIntegerSample() const; + + /// Compute an overapproximation of the number of integer points in the + /// relation. Symbol vars currently not supported. If the computed + /// overapproximation is infinite, an empty optional is returned. + std::optional computeVolume() const; + + /// Returns true if the given point satisfies the constraints, or false + /// otherwise. Takes the values of all vars including locals. + bool containsPoint(ArrayRef point) const; + bool containsPoint(ArrayRef point) const { + return containsPoint(getDynamicAPIntVec(point)); + } + /// Given the values of non-local vars, return a satisfying assignment to the + /// local if one exists, or an empty optional otherwise. + std::optional> + containsPointNoLocal(ArrayRef point) const; + std::optional> + containsPointNoLocal(ArrayRef point) const { + return containsPointNoLocal(getDynamicAPIntVec(point)); + } + + /// Returns a `DivisonRepr` representing the division representation of local + /// variables in the constraint system. + /// + /// If `repr` is not `nullptr`, the equality and pairs of inequality + /// constraints identified by their position indices using which an explicit + /// representation for each local variable can be computed are set in `repr` + /// in the form of a `MaybeLocalRepr` struct. If no such inequality + /// pair/equality can be found, the kind attribute in `MaybeLocalRepr` is set + /// to None. + DivisionRepr getLocalReprs(std::vector *repr = nullptr) const; + + /// Adds a constant bound for the specified variable. + void addBound(BoundType type, unsigned pos, const DynamicAPInt &value); + void addBound(BoundType type, unsigned pos, int64_t value) { + addBound(type, pos, DynamicAPInt(value)); + } + + /// Adds a constant bound for the specified expression. + void addBound(BoundType type, ArrayRef expr, + const DynamicAPInt &value); + void addBound(BoundType type, ArrayRef expr, int64_t value) { + addBound(type, getDynamicAPIntVec(expr), DynamicAPInt(value)); + } + + /// Adds a new local variable as the floordiv of an affine function of other + /// variables, the coefficients of which are provided in `dividend` and with + /// respect to a positive constant `divisor`. Two constraints are added to the + /// system to capture equivalence with the floordiv: + /// q = dividend floordiv c <=> c*q <= dividend <= c*q + c - 1. + void addLocalFloorDiv(ArrayRef dividend, + const DynamicAPInt &divisor); + void addLocalFloorDiv(ArrayRef dividend, int64_t divisor) { + addLocalFloorDiv(getDynamicAPIntVec(dividend), DynamicAPInt(divisor)); + } + + /// Projects out (aka eliminates) `num` variables starting at position + /// `pos`. The resulting constraint system is the shadow along the dimensions + /// that still exist. This method may not always be integer exact. + // TODO: deal with integer exactness when necessary - can return a value to + // mark exactness for example. + void projectOut(unsigned pos, unsigned num); + inline void projectOut(unsigned pos) { return projectOut(pos, 1); } + + /// Tries to fold the specified variable to a constant using a trivial + /// equality detection; if successful, the constant is substituted for the + /// variable everywhere in the constraint system and then removed from the + /// system. + LogicalResult constantFoldVar(unsigned pos); + + /// This method calls `constantFoldVar` for the specified range of variables, + /// `num` variables starting at position `pos`. + void constantFoldVarRange(unsigned pos, unsigned num); + + /// Updates the constraints to be the smallest bounding (enclosing) box that + /// contains the points of `this` set and that of `other`, with the symbols + /// being treated specially. For each of the dimensions, the min of the lower + /// bounds (symbolic) and the max of the upper bounds (symbolic) is computed + /// to determine such a bounding box. `other` is expected to have the same + /// dimensional variables as this constraint system (in the same order). + /// + /// E.g.: + /// 1) this = {0 <= d0 <= 127}, + /// other = {16 <= d0 <= 192}, + /// output = {0 <= d0 <= 192} + /// 2) this = {s0 + 5 <= d0 <= s0 + 20}, + /// other = {s0 + 1 <= d0 <= s0 + 9}, + /// output = {s0 + 1 <= d0 <= s0 + 20} + /// 3) this = {0 <= d0 <= 5, 1 <= d1 <= 9} + /// other = {2 <= d0 <= 6, 5 <= d1 <= 15}, + /// output = {0 <= d0 <= 6, 1 <= d1 <= 15} + LogicalResult unionBoundingBox(const IntegerRelation &other); + + /// Returns the smallest known constant bound for the extent of the specified + /// variable (pos^th), i.e., the smallest known constant that is greater + /// than or equal to 'exclusive upper bound' - 'lower bound' of the + /// variable. This constant bound is guaranteed to be non-negative. Returns + /// std::nullopt if it's not a constant. This method employs trivial (low + /// complexity / cost) checks and detection. Symbolic variables are treated + /// specially, i.e., it looks for constant differences between affine + /// expressions involving only the symbolic variables. `lb` and `ub` (along + /// with the `boundFloorDivisor`) are set to represent the lower and upper + /// bound associated with the constant difference: `lb`, `ub` have the + /// coefficients, and `boundFloorDivisor`, their divisor. `minLbPos` and + /// `minUbPos` if non-null are set to the position of the constant lower bound + /// and upper bound respectively (to the same if they are from an + /// equality). Ex: if the lower bound is [(s0 + s2 - 1) floordiv 32] for a + /// system with three symbolic variables, *lb = [1, 0, 1], lbDivisor = 32. See + /// comments at function definition for examples. + std::optional getConstantBoundOnDimSize( + unsigned pos, SmallVectorImpl *lb = nullptr, + DynamicAPInt *boundFloorDivisor = nullptr, + SmallVectorImpl *ub = nullptr, unsigned *minLbPos = nullptr, + unsigned *minUbPos = nullptr) const; + /// The same, but casts to int64_t. This is unsafe and will assert-fail if the + /// value does not fit in an int64_t. + std::optional getConstantBoundOnDimSize64( + unsigned pos, SmallVectorImpl *lb = nullptr, + int64_t *boundFloorDivisor = nullptr, + SmallVectorImpl *ub = nullptr, unsigned *minLbPos = nullptr, + unsigned *minUbPos = nullptr) const { + SmallVector ubDynamicAPInt, lbDynamicAPInt; + DynamicAPInt boundFloorDivisorDynamicAPInt; + std::optional result = getConstantBoundOnDimSize( + pos, &lbDynamicAPInt, &boundFloorDivisorDynamicAPInt, &ubDynamicAPInt, + minLbPos, minUbPos); + if (lb) + *lb = getInt64Vec(lbDynamicAPInt); + if (ub) + *ub = getInt64Vec(ubDynamicAPInt); + if (boundFloorDivisor) + *boundFloorDivisor = static_cast(boundFloorDivisorDynamicAPInt); + return llvm::transformOptional(result, int64fromDynamicAPInt); + } + + /// Returns the constant bound for the pos^th variable if there is one; + /// std::nullopt otherwise. + std::optional getConstantBound(BoundType type, + unsigned pos) const; + /// The same, but casts to int64_t. This is unsafe and will assert-fail if the + /// value does not fit in an int64_t. + std::optional getConstantBound64(BoundType type, + unsigned pos) const { + return llvm::transformOptional(getConstantBound(type, pos), + int64fromDynamicAPInt); + } + + /// Removes constraints that are independent of (i.e., do not have a + /// coefficient) variables in the range [pos, pos + num). + void removeIndependentConstraints(unsigned pos, unsigned num); + + /// Returns true if the set can be trivially detected as being + /// hyper-rectangular on the specified contiguous set of variables. + bool isHyperRectangular(unsigned pos, unsigned num) const; + + /// Removes duplicate constraints, trivially true constraints, and constraints + /// that can be detected as redundant as a result of differing only in their + /// constant term part. A constraint of the form >= 0 + /// is considered trivially true. This method is a linear time method on the + /// constraints, does a single scan, and updates in place. It also normalizes + /// constraints by their GCD and performs GCD tightening on inequalities. + void removeTrivialRedundancy(); + + /// A more expensive check than `removeTrivialRedundancy` to detect redundant + /// inequalities. + void removeRedundantInequalities(); + + /// Removes redundant constraints using Simplex. Although the algorithm can + /// theoretically take exponential time in the worst case (rare), it is known + /// to perform much better in the average case. If V is the number of vertices + /// in the polytope and C is the number of constraints, the algorithm takes + /// O(VC) time. + void removeRedundantConstraints(); + + void removeDuplicateDivs(); + + /// Simplify the constraint system by removing canonicalizing constraints and + /// removing redundant constraints. + void simplify(); + + /// Converts variables of kind srcKind in the range [varStart, varLimit) to + /// variables of kind dstKind. If `pos` is given, the variables are placed at + /// position `pos` of dstKind, otherwise they are placed after all the other + /// variables of kind dstKind. The internal ordering among the moved variables + /// is preserved. + void convertVarKind(VarKind srcKind, unsigned varStart, unsigned varLimit, + VarKind dstKind, unsigned pos); + void convertVarKind(VarKind srcKind, unsigned varStart, unsigned varLimit, + VarKind dstKind) { + convertVarKind(srcKind, varStart, varLimit, dstKind, + getNumVarKind(dstKind)); + } + void convertToLocal(VarKind kind, unsigned varStart, unsigned varLimit) { + convertVarKind(kind, varStart, varLimit, VarKind::Local); + } + + /// Merge and align symbol variables of `this` and `other` with respect to + /// identifiers. After this operation the symbol variables of both relations + /// have the same identifiers in the same order. + void mergeAndAlignSymbols(IntegerRelation &other); + + /// Adds additional local vars to the sets such that they both have the union + /// of the local vars in each set, without changing the set of points that + /// lie in `this` and `other`. + /// + /// While taking union, if a local var in `other` has a division + /// representation which is a duplicate of division representation, of another + /// local var, it is not added to the final union of local vars and is instead + /// merged. The new ordering of local vars is: + /// + /// [Local vars of `this`] [Non-merged local vars of `other`] + /// + /// The relative ordering of local vars is same as before. + /// + /// After merging, if the `i^th` local variable in one set has a known + /// division representation, then the `i^th` local variable in the other set + /// either has the same division representation or no known division + /// representation. + /// + /// The spaces of both relations should be compatible. + /// + /// Returns the number of non-merged local vars of `other`, i.e. the number of + /// locals that have been added to `this`. + unsigned mergeLocalVars(IntegerRelation &other); + + /// Check whether all local ids have a division representation. + bool hasOnlyDivLocals() const; + + /// Changes the partition between dimensions and symbols. Depending on the new + /// symbol count, either a chunk of dimensional variables immediately before + /// the split become symbols, or some of the symbols immediately after the + /// split become dimensions. + void setDimSymbolSeparation(unsigned newSymbolCount) { + space.setVarSymbolSeparation(newSymbolCount); + } + + /// Return a set corresponding to all points in the domain of the relation. + IntegerPolyhedron getDomainSet() const; + + /// Return a set corresponding to all points in the range of the relation. + IntegerPolyhedron getRangeSet() const; + + /// Intersect the given `poly` with the domain in-place. + /// + /// Formally, let the relation `this` be R: A -> B and poly is C, then this + /// operation modifies R to be (A intersection C) -> B. + void intersectDomain(const IntegerPolyhedron &poly); + + /// Intersect the given `poly` with the range in-place. + /// + /// Formally, let the relation `this` be R: A -> B and poly is C, then this + /// operation modifies R to be A -> (B intersection C). + void intersectRange(const IntegerPolyhedron &poly); + + /// Invert the relation i.e., swap its domain and range. + /// + /// Formally, let the relation `this` be R: A -> B, then this operation + /// modifies R to be B -> A. + void inverse(); + + /// Let the relation `this` be R1, and the relation `rel` be R2. Modifies R1 + /// to be the composition of R1 and R2: R1;R2. + /// + /// Formally, if R1: A -> B, and R2: B -> C, then this function returns a + /// relation R3: A -> C such that a point (a, c) belongs to R3 iff there + /// exists b such that (a, b) is in R1 and, (b, c) is in R2. + void compose(const IntegerRelation &rel); + + /// Given a relation `rel`, apply the relation to the domain of this relation. + /// + /// R1: i -> j : (0 <= i < 2, j = i) + /// R2: i -> k : (k = i floordiv 2) + /// R3: k -> j : (0 <= k < 1, 2k <= j <= 2k + 1) + /// + /// R1 = {(0, 0), (1, 1)}. R2 maps both 0 and 1 to 0. + /// So R3 = {(0, 0), (0, 1)}. + /// + /// Formally, R1.applyDomain(R2) = R2.inverse().compose(R1). + void applyDomain(const IntegerRelation &rel); + + /// Given a relation `rel`, apply the relation to the range of this relation. + /// + /// Formally, R1.applyRange(R2) is the same as R1.compose(R2) but we provide + /// this for uniformity with `applyDomain`. + void applyRange(const IntegerRelation &rel); + + /// Given a relation `other: (A -> B)`, this operation merges the symbol and + /// local variables and then takes the composition of `other` on `this: (B -> + /// C)`. The resulting relation represents tuples of the form: `A -> C`. + void mergeAndCompose(const IntegerRelation &other); + + /// Compute an equivalent representation of the same set, such that all local + /// vars in all disjuncts have division representations. This representation + /// may involve local vars that correspond to divisions, and may also be a + /// union of convex disjuncts. + PresburgerRelation computeReprWithOnlyDivLocals() const; + + /// Compute the symbolic integer lexmin of the relation. + /// + /// This finds, for every assignment to the symbols and domain, + /// the lexicographically minimum value attained by the range. + /// + /// For example, the symbolic lexmin of the set + /// + /// (x, y)[a, b, c] : (a <= x, b <= x, x <= c) + /// + /// can be written as + /// + /// x = a if b <= a, a <= c + /// x = b if a < b, b <= c + /// + /// This function is stored in the `lexopt` function in the result. + /// Some assignments to the symbols might make the set empty. + /// Such points are not part of the function's domain. + /// In the above example, this happens when max(a, b) > c. + /// + /// For some values of the symbols, the lexmin may be unbounded. + /// `SymbolicLexOpt` stores these parts of the symbolic domain in a separate + /// `PresburgerSet`, `unboundedDomain`. + SymbolicLexOpt findSymbolicIntegerLexMin() const; + + /// Same as findSymbolicIntegerLexMin but produces lexmax instead of lexmin + SymbolicLexOpt findSymbolicIntegerLexMax() const; + + /// Finds a constraint with a non-zero coefficient at `colIdx` in equality + /// (isEq=true) or inequality (isEq=false) constraints. Returns the position + /// of the row if it was found or none otherwise. + std::optional findConstraintWithNonZeroAt(unsigned colIdx, + bool isEq) const; + + /// Return the set difference of this set and the given set, i.e., + /// return `this \ set`. + PresburgerRelation subtract(const PresburgerRelation &set) const; + + // Remove equalities which have only zero coefficients. + void removeTrivialEqualities(); + + // Verify whether the relation is full-dimensional, i.e., + // no equality holds for the relation. + // + // If there are no variables, it always returns true. + // If there is at least one variable and the relation is empty, it returns + // false. + bool isFullDim(); + + void print(raw_ostream &os) const; + void dump() const; + +protected: + /// Checks all rows of equality/inequality constraints for trivial + /// contradictions (for example: 1 == 0, 0 >= 1), which may have surfaced + /// after elimination. Returns true if an invalid constraint is found; + /// false otherwise. + bool hasInvalidConstraint() const; + + /// Returns the constant lower bound if isLower is true, and the upper + /// bound if isLower is false. + template + std::optional computeConstantLowerOrUpperBound(unsigned pos); + /// The same, but casts to int64_t. This is unsafe and will assert-fail if the + /// value does not fit in an int64_t. + template + std::optional computeConstantLowerOrUpperBound64(unsigned pos) { + return computeConstantLowerOrUpperBound(pos).map( + int64fromDynamicAPInt); + } + + /// Eliminates a single variable at `position` from equality and inequality + /// constraints. Returns `success` if the variable was eliminated, and + /// `failure` otherwise. + inline LogicalResult gaussianEliminateVar(unsigned position) { + return success(gaussianEliminateVars(position, position + 1) == 1); + } + + /// Removes local variables using equalities. Each equality is checked if it + /// can be reduced to the form: `e = affine-expr`, where `e` is a local + /// variable and `affine-expr` is an affine expression not containing `e`. + /// If an equality satisfies this form, the local variable is replaced in + /// each constraint and then removed. The equality used to replace this local + /// variable is also removed. + void removeRedundantLocalVars(); + + /// Eliminates variables from equality and inequality constraints + /// in column range [posStart, posLimit). + /// Returns the number of variables eliminated. + unsigned gaussianEliminateVars(unsigned posStart, unsigned posLimit); + + /// Perform a Gaussian elimination operation to reduce all equations to + /// standard form. Returns whether the constraint system was modified. + bool gaussianEliminate(); + + /// Eliminates the variable at the specified position using Fourier-Motzkin + /// variable elimination, but uses Gaussian elimination if there is an + /// equality involving that variable. If the result of the elimination is + /// integer exact, `*isResultIntegerExact` is set to true. If `darkShadow` is + /// set to true, a potential under approximation (subset) of the rational + /// shadow / exact integer shadow is computed. + // See implementation comments for more details. + virtual void fourierMotzkinEliminate(unsigned pos, bool darkShadow = false, + bool *isResultIntegerExact = nullptr); + + /// Tightens inequalities given that we are dealing with integer spaces. This + /// is similar to the GCD test but applied to inequalities. The constant term + /// can be reduced to the preceding multiple of the GCD of the coefficients, + /// i.e., + /// 64*i - 100 >= 0 => 64*i - 128 >= 0 (since 'i' is an integer). This is a + /// fast method (linear in the number of coefficients). + void gcdTightenInequalities(); + + /// Normalized each constraints by the GCD of its coefficients. + void normalizeConstraintsByGCD(); + + /// Returns true if the pos^th column is all zero for both inequalities and + /// equalities. + bool isColZero(unsigned pos) const; + + /// Checks for identical inequalities and eliminates redundant inequalities. + /// Returns whether the constraint system was modified. + bool removeDuplicateConstraints(); + + /// Returns false if the fields corresponding to various variable counts, or + /// equality/inequality buffer sizes aren't consistent; true otherwise. This + /// is meant to be used within an assert internally. + virtual bool hasConsistentState() const; + + /// Prints the number of constraints, dimensions, symbols and locals in the + /// IntegerRelation. + virtual void printSpace(raw_ostream &os) const; + + /// Removes variables in the column range [varStart, varLimit), and copies any + /// remaining valid data into place, updates member variables, and resizes + /// arrays as needed. + void removeVarRange(unsigned varStart, unsigned varLimit); + + /// Truncate the vars of the specified kind to the specified number by + /// dropping some vars at the end. `num` must be less than the current number. + void truncateVarKind(VarKind kind, unsigned num); + + /// Truncate the vars to the number in the space of the specified + /// CountsSnapshot. + void truncateVarKind(VarKind kind, const CountsSnapshot &counts); + + /// A parameter that controls detection of an unrealistic number of + /// constraints. If the number of constraints is this many times the number of + /// variables, we consider such a system out of line with the intended use + /// case of IntegerRelation. + // The rationale for 32 is that in the typical simplest of cases, an + // variable is expected to have one lower bound and one upper bound + // constraint. With a level of tiling or a connection to another variable + // through a div or mod, an extra pair of bounds gets added. As a limit, we + // don't expect a variable to have more than 32 lower/upper/equality + // constraints. This is conservatively set low and can be raised if needed. + constexpr static unsigned kExplosionFactor = 32; + + PresburgerSpace space; + + /// Coefficients of affine equalities (in == 0 form). + IntMatrix equalities; + + /// Coefficients of affine inequalities (in >= 0 form). + IntMatrix inequalities; +}; + +/// An IntegerPolyhedron represents the set of points from a PresburgerSpace +/// that satisfy a list of affine constraints. Affine constraints can be +/// inequalities or equalities in the form: +/// +/// Inequality: c_0*x_0 + c_1*x_1 + .... + c_{n-1}*x_{n-1} + c_n >= 0 +/// Equality : c_0*x_0 + c_1*x_1 + .... + c_{n-1}*x_{n-1} + c_n == 0 +/// +/// where c_0, c_1, ..., c_n are integers and n is the total number of +/// variables in the space. +/// +/// An IntegerPolyhedron is similar to an IntegerRelation but it does not make a +/// distinction between Domain and Range variables. Internally, +/// IntegerPolyhedron is implemented as a IntegerRelation with zero domain vars. +/// +/// Since IntegerPolyhedron does not make a distinction between kinds of +/// dimensions, VarKind::SetDim should be used to refer to dimension +/// variables. +class IntegerPolyhedron : public IntegerRelation { +public: + /// Constructs a set reserving memory for the specified number + /// of constraints and variables. + IntegerPolyhedron(unsigned numReservedInequalities, + unsigned numReservedEqualities, unsigned numReservedCols, + const PresburgerSpace &space) + : IntegerRelation(numReservedInequalities, numReservedEqualities, + numReservedCols, space) { + assert(space.getNumDomainVars() == 0 && + "Number of domain vars should be zero in Set kind space."); + } + + /// Constructs a relation with the specified number of dimensions and + /// symbols. + explicit IntegerPolyhedron(const PresburgerSpace &space) + : IntegerPolyhedron(/*numReservedInequalities=*/0, + /*numReservedEqualities=*/0, + /*numReservedCols=*/space.getNumVars() + 1, space) {} + + /// Constructs a relation with the specified number of dimensions and symbols + /// and adds the given inequalities. + explicit IntegerPolyhedron(const PresburgerSpace &space, + const IntMatrix &inequalities) + : IntegerPolyhedron(space) { + for (unsigned i = 0, e = inequalities.getNumRows(); i < e; i++) + addInequality(inequalities.getRow(i)); + } + + /// Constructs a relation with the specified number of dimensions and symbols + /// and adds the given inequalities, after normalizing row-wise to integer + /// values. + explicit IntegerPolyhedron(const PresburgerSpace &space, + const FracMatrix &inequalities) + : IntegerPolyhedron(space) { + IntMatrix ineqsNormalized = inequalities.normalizeRows(); + for (unsigned i = 0, e = inequalities.getNumRows(); i < e; i++) + addInequality(ineqsNormalized.getRow(i)); + } + + /// Construct a set from an IntegerRelation. The relation should have + /// no domain vars. + explicit IntegerPolyhedron(const IntegerRelation &rel) + : IntegerRelation(rel) { + assert(space.getNumDomainVars() == 0 && + "Number of domain vars should be zero in Set kind space."); + } + + /// Construct a set from an IntegerRelation, but instead of creating a copy, + /// use move constructor. The relation should have no domain vars. + explicit IntegerPolyhedron(IntegerRelation &&rel) : IntegerRelation(rel) { + assert(space.getNumDomainVars() == 0 && + "Number of domain vars should be zero in Set kind space."); + } + + /// Return a system with no constraints, i.e., one which is satisfied by all + /// points. + static IntegerPolyhedron getUniverse(const PresburgerSpace &space) { + return IntegerPolyhedron(space); + } + + /// Return the kind of this IntegerRelation. + Kind getKind() const override { return Kind::IntegerPolyhedron; } + + static bool classof(const IntegerRelation *cst) { + return cst->getKind() >= Kind::IntegerPolyhedron && + cst->getKind() <= Kind::FlatAffineRelation; + } + + // Clones this object. + std::unique_ptr clone() const; + + /// Insert `num` variables of the specified kind at position `pos`. + /// Positions are relative to the kind of variable. Return the absolute + /// column position (i.e., not relative to the kind of variable) of the + /// first added variable. + unsigned insertVar(VarKind kind, unsigned pos, unsigned num = 1) override; + + /// Return the intersection of the two relations. + /// If there are locals, they will be merged. + IntegerPolyhedron intersect(const IntegerPolyhedron &other) const; + + /// Return the set difference of this set and the given set, i.e., + /// return `this \ set`. + PresburgerSet subtract(const PresburgerSet &other) const; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_INTEGERRELATION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/LinearTransform.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/LinearTransform.h new file mode 100644 index 0000000000000000000000000000000000000000..eeac9f1dc39385517b6a79b9b26366c1a320d4e3 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/LinearTransform.h @@ -0,0 +1,62 @@ +//===- LinearTransform.h - MLIR LinearTransform Class -----------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Support for linear transforms and applying them to an IntegerRelation. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_LINEARTRANSFORM_H +#define MLIR_ANALYSIS_PRESBURGER_LINEARTRANSFORM_H + +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include "mlir/Analysis/Presburger/Matrix.h" +#include "llvm/ADT/SmallVector.h" + +namespace mlir { +namespace presburger { + +class LinearTransform { +public: + explicit LinearTransform(IntMatrix &&oMatrix); + explicit LinearTransform(const IntMatrix &oMatrix); + + // Returns a linear transform T such that MT is M in column echelon form. + // Also returns the number of non-zero columns in MT. + // + // Specifically, T is such that in every column the first non-zero row is + // strictly below that of the previous column, and all columns which have only + // zeros are at the end. + static std::pair + makeTransformToColumnEchelon(const IntMatrix &m); + + // Returns an IntegerRelation having a constraint vector vT for every + // constraint vector v in rel, where T is this transform. + IntegerRelation applyTo(const IntegerRelation &rel) const; + + // The given vector is interpreted as a row vector v. Post-multiply v with + // this transform, say T, and return vT. + SmallVector + preMultiplyWithRow(ArrayRef rowVec) const { + return matrix.preMultiplyWithRow(rowVec); + } + + // The given vector is interpreted as a column vector v. Pre-multiply v with + // this transform, say T, and return Tv. + SmallVector + postMultiplyWithColumn(ArrayRef colVec) const { + return matrix.postMultiplyWithColumn(colVec); + } + +private: + IntMatrix matrix; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_LINEARTRANSFORM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Matrix.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Matrix.h new file mode 100644 index 0000000000000000000000000000000000000000..054eb7b26d06ee8cd65dc285f35be5aefb1838f4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Matrix.h @@ -0,0 +1,335 @@ +//===- Matrix.h - MLIR Matrix Class -----------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This is a simple 2D matrix class that supports reading, writing, resizing, +// swapping rows, and swapping columns. It can hold integers (DynamicAPInt) or +// rational numbers (Fraction). +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_MATRIX_H +#define MLIR_ANALYSIS_PRESBURGER_MATRIX_H + +#include "mlir/Analysis/Presburger/Fraction.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/Support/raw_ostream.h" +#include + +namespace mlir { +namespace presburger { +using llvm::ArrayRef; +using llvm::MutableArrayRef; +using llvm::raw_ostream; +using llvm::SmallVector; + +/// This is a class to represent a resizable matrix. +/// +/// More columns and rows can be reserved than are currently used. The data is +/// stored as a single 1D array, viewed as a 2D matrix with nRows rows and +/// nReservedColumns columns, stored in row major form. Thus the element at +/// (i, j) is stored at data[i*nReservedColumns + j]. The reserved but unused +/// columns always have all zero values. The reserved rows are just reserved +/// space in the underlying SmallVector's capacity. +/// This class only works for the types DynamicAPInt and Fraction, since the +/// method implementations are in the Matrix.cpp file. Only these two types have +/// been explicitly instantiated there. +template +class Matrix { + static_assert(std::is_same_v || std::is_same_v, + "T must be DynamicAPInt or Fraction."); + +public: + Matrix() = delete; + + /// Construct a matrix with the specified number of rows and columns. + /// The number of reserved rows and columns will be at least the number + /// specified, and will always be sufficient to accomodate the number of rows + /// and columns specified. + /// + /// Initially, the entries are initialized to ero. + Matrix(unsigned rows, unsigned columns, unsigned reservedRows = 0, + unsigned reservedColumns = 0); + + /// Return the identity matrix of the specified dimension. + static Matrix identity(unsigned dimension); + + /// Access the element at the specified row and column. + T &at(unsigned row, unsigned column) { + assert(row < nRows && "Row outside of range"); + assert(column < nColumns && "Column outside of range"); + return data[row * nReservedColumns + column]; + } + + T at(unsigned row, unsigned column) const { + assert(row < nRows && "Row outside of range"); + assert(column < nColumns && "Column outside of range"); + return data[row * nReservedColumns + column]; + } + + T &operator()(unsigned row, unsigned column) { return at(row, column); } + + T operator()(unsigned row, unsigned column) const { return at(row, column); } + + bool operator==(const Matrix &m) const; + + /// Swap the given columns. + void swapColumns(unsigned column, unsigned otherColumn); + + /// Swap the given rows. + void swapRows(unsigned row, unsigned otherRow); + + unsigned getNumRows() const { return nRows; } + + unsigned getNumColumns() const { return nColumns; } + + /// Return the maximum number of rows/columns that can be added without + /// incurring a reallocation. + unsigned getNumReservedRows() const; + unsigned getNumReservedColumns() const { return nReservedColumns; } + + /// Reserve enough space to resize to the specified number of rows without + /// reallocations. + void reserveRows(unsigned rows); + + /// Get a [Mutable]ArrayRef corresponding to the specified row. + MutableArrayRef getRow(unsigned row); + ArrayRef getRow(unsigned row) const; + + /// Set the specified row to `elems`. + void setRow(unsigned row, ArrayRef elems); + + /// Insert columns having positions pos, pos + 1, ... pos + count - 1. + /// Columns that were at positions 0 to pos - 1 will stay where they are; + /// columns that were at positions pos to nColumns - 1 will be pushed to the + /// right. pos should be at most nColumns. + void insertColumns(unsigned pos, unsigned count); + void insertColumn(unsigned pos); + + /// Insert rows having positions pos, pos + 1, ... pos + count - 1. + /// Rows that were at positions 0 to pos - 1 will stay where they are; + /// rows that were at positions pos to nColumns - 1 will be pushed to the + /// right. pos should be at most nRows. + void insertRows(unsigned pos, unsigned count); + void insertRow(unsigned pos); + + /// Remove the columns having positions pos, pos + 1, ... pos + count - 1. + /// Rows that were at positions 0 to pos - 1 will stay where they are; + /// columns that were at positions pos + count - 1 or later will be pushed to + /// the right. The columns to be deleted must be valid rows: pos + count - 1 + /// must be at most nColumns - 1. + void removeColumns(unsigned pos, unsigned count); + void removeColumn(unsigned pos); + + /// Remove the rows having positions pos, pos + 1, ... pos + count - 1. + /// Rows that were at positions 0 to pos - 1 will stay where they are; + /// rows that were at positions pos + count - 1 or later will be pushed to the + /// right. The rows to be deleted must be valid rows: pos + count - 1 must be + /// at most nRows - 1. + void removeRows(unsigned pos, unsigned count); + void removeRow(unsigned pos); + + void copyRow(unsigned sourceRow, unsigned targetRow); + + void fillRow(unsigned row, const T &value); + void fillRow(unsigned row, int64_t value) { fillRow(row, T(value)); } + + /// Add `scale` multiples of the source row to the target row. + void addToRow(unsigned sourceRow, unsigned targetRow, const T &scale); + void addToRow(unsigned sourceRow, unsigned targetRow, int64_t scale) { + addToRow(sourceRow, targetRow, T(scale)); + } + /// Add `scale` multiples of the rowVec row to the specified row. + void addToRow(unsigned row, ArrayRef rowVec, const T &scale); + + /// Multiply the specified row by a factor of `scale`. + void scaleRow(unsigned row, const T &scale); + + /// Add `scale` multiples of the source column to the target column. + void addToColumn(unsigned sourceColumn, unsigned targetColumn, + const T &scale); + void addToColumn(unsigned sourceColumn, unsigned targetColumn, + int64_t scale) { + addToColumn(sourceColumn, targetColumn, T(scale)); + } + + /// Negate the specified column. + void negateColumn(unsigned column); + + /// Negate the specified row. + void negateRow(unsigned row); + + /// Negate the entire matrix. + void negateMatrix(); + + /// The given vector is interpreted as a row vector v. Post-multiply v with + /// this matrix, say M, and return vM. + SmallVector preMultiplyWithRow(ArrayRef rowVec) const; + + /// The given vector is interpreted as a column vector v. Pre-multiply v with + /// this matrix, say M, and return Mv. + SmallVector postMultiplyWithColumn(ArrayRef colVec) const; + + /// Resize the matrix to the specified dimensions. If a dimension is smaller, + /// the values are truncated; if it is bigger, the new values are initialized + /// to zero. + /// + /// Due to the representation of the matrix, resizing vertically (adding rows) + /// is less expensive than increasing the number of columns beyond + /// nReservedColumns. + void resize(unsigned newNRows, unsigned newNColumns); + void resizeHorizontally(unsigned newNColumns); + void resizeVertically(unsigned newNRows); + + /// Add an extra row at the bottom of the matrix and return its position. + unsigned appendExtraRow(); + /// Same as above, but copy the given elements into the row. The length of + /// `elems` must be equal to the number of columns. + unsigned appendExtraRow(ArrayRef elems); + + // Transpose the matrix without modifying it. + Matrix transpose() const; + + // Copy the cells in the intersection of + // the rows between `fromRows` and `toRows` and + // the columns between `fromColumns` and `toColumns`, both inclusive. + Matrix getSubMatrix(unsigned fromRow, unsigned toRow, unsigned fromColumn, + unsigned toColumn) const; + + /// Split the rows of a matrix into two matrices according to which bits are + /// 1 and which are 0 in a given bitset. + /// + /// The first matrix returned has the rows corresponding to 1 and the second + /// corresponding to 2. + std::pair, Matrix> splitByBitset(ArrayRef indicator); + + /// Print the matrix. + void print(raw_ostream &os) const; + void dump() const; + + /// Return whether the Matrix is in a consistent state with all its + /// invariants satisfied. + bool hasConsistentState() const; + + /// Move the columns in the source range [srcPos, srcPos + num) to the + /// specified destination [dstPos, dstPos + num), while moving the columns + /// adjacent to the source range to the left/right of the shifted columns. + /// + /// When moving the source columns right (i.e. dstPos > srcPos), columns that + /// were at positions [0, srcPos) and [dstPos + num, nCols) will stay where + /// they are; columns that were at positions [srcPos, srcPos + num) will be + /// moved to [dstPos, dstPos + num); and columns that were at positions + /// [srcPos + num, dstPos + num) will be moved to [srcPos, dstPos). + /// Equivalently, the columns [srcPos + num, dstPos + num) are interchanged + /// with [srcPos, srcPos + num). + /// For example, if m = |0 1 2 3 4 5| then: + /// m.moveColumns(1, 3, 2) will result in m = |0 4 1 2 3 5|; or + /// m.moveColumns(1, 2, 4) will result in m = |0 3 4 5 1 2|. + /// + /// The left shift operation (i.e. dstPos < srcPos) works in a similar way. + void moveColumns(unsigned srcPos, unsigned num, unsigned dstPos); + +protected: + /// The current number of rows, columns, and reserved columns. The underlying + /// data vector is viewed as an nRows x nReservedColumns matrix, of which the + /// first nColumns columns are currently in use, and the remaining are + /// reserved columns filled with zeros. + unsigned nRows, nColumns, nReservedColumns; + + /// Stores the data. data.size() is equal to nRows * nReservedColumns. + /// data.capacity() / nReservedColumns is the number of reserved rows. + SmallVector data; +}; + +extern template class Matrix; +extern template class Matrix; + +// An inherited class for integer matrices, with no new data attributes. +// This is only used for the matrix-related methods which apply only +// to integers (hermite normal form computation and row normalisation). +class IntMatrix : public Matrix { +public: + IntMatrix(unsigned rows, unsigned columns, unsigned reservedRows = 0, + unsigned reservedColumns = 0) + : Matrix(rows, columns, reservedRows, reservedColumns) {} + + IntMatrix(Matrix m) : Matrix(std::move(m)) {} + + /// Return the identity matrix of the specified dimension. + static IntMatrix identity(unsigned dimension); + + /// Given the current matrix M, returns the matrices H, U such that H is the + /// column hermite normal form of M, i.e. H = M * U, where U is unimodular and + /// the matrix H has the following restrictions: + /// - H is lower triangular. + /// - The leading coefficient (the first non-zero entry from the top, called + /// the pivot) of a non-zero column is always strictly below of the leading + /// coefficient of the column before it; moreover, it is positive. + /// - The elements to the right of the pivots are zero and the elements to + /// the left of the pivots are nonnegative and strictly smaller than the + /// pivot. + std::pair computeHermiteNormalForm() const; + + /// Divide the first `nCols` of the specified row by their GCD. + /// Returns the GCD of the first `nCols` of the specified row. + DynamicAPInt normalizeRow(unsigned row, unsigned nCols); + /// Divide the columns of the specified row by their GCD. + /// Returns the GCD of the columns of the specified row. + DynamicAPInt normalizeRow(unsigned row); + + // Compute the determinant of the matrix (cubic time). + // Stores the integer inverse of the matrix in the pointer + // passed (if any). The pointer is unchanged if the inverse + // does not exist, which happens iff det = 0. + // For a matrix M, the integer inverse is the matrix M' such that + // M x M' = M'  M = det(M) x I. + // Assert-fails if the matrix is not square. + DynamicAPInt determinant(IntMatrix *inverse = nullptr) const; +}; + +// An inherited class for rational matrices, with no new data attributes. +// This class is for functionality that only applies to matrices of fractions. +class FracMatrix : public Matrix { +public: + FracMatrix(unsigned rows, unsigned columns, unsigned reservedRows = 0, + unsigned reservedColumns = 0) + : Matrix(rows, columns, reservedRows, reservedColumns){}; + + FracMatrix(Matrix m) : Matrix(std::move(m)){}; + + explicit FracMatrix(IntMatrix m); + + /// Return the identity matrix of the specified dimension. + static FracMatrix identity(unsigned dimension); + + // Compute the determinant of the matrix (cubic time). + // Stores the inverse of the matrix in the pointer + // passed (if any). The pointer is unchanged if the inverse + // does not exist, which happens iff det = 0. + // Assert-fails if the matrix is not square. + Fraction determinant(FracMatrix *inverse = nullptr) const; + + // Computes the Gram-Schmidt orthogonalisation + // of the rows of matrix (cubic time). + // The rows of the matrix must be linearly independent. + FracMatrix gramSchmidt() const; + + // Run LLL basis reduction on the matrix, modifying it in-place. + // The parameter is what [the original + // paper](https://www.cs.cmu.edu/~avrim/451f11/lectures/lect1129_LLL.pdf) + // calls `y`, usually 3/4. + void LLL(Fraction delta); + + // Multiply each row of the matrix by the LCM of the denominators, thereby + // converting it to an integer matrix. + IntMatrix normalizeRows() const; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_MATRIX_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PWMAFunction.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PWMAFunction.h new file mode 100644 index 0000000000000000000000000000000000000000..fcc39bf0e0537d810fedca24f0025dda3a903739 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PWMAFunction.h @@ -0,0 +1,256 @@ +//===- PWMAFunction.h - MLIR PWMAFunction Class------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Support for piece-wise multi-affine functions. These are functions that are +// defined on a domain that is a union of IntegerPolyhedrons, and on each domain +// the value of the function is a tuple of integers, with each value in the +// tuple being an affine expression in the vars of the IntegerPolyhedron. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_PWMAFUNCTION_H +#define MLIR_ANALYSIS_PRESBURGER_PWMAFUNCTION_H + +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include "mlir/Analysis/Presburger/PresburgerRelation.h" +#include + +namespace mlir { +namespace presburger { + +/// Enum representing a binary comparison operator: equal, not equal, less than, +/// less than or equal, greater than, greater than or equal. +enum class OrderingKind { EQ, NE, LT, LE, GT, GE }; + +/// This class represents a multi-affine function with the domain as Z^d, where +/// `d` is the number of domain variables of the function. For example: +/// +/// (x, y) -> (x + 2, 2*x - 3y + 5, 2*x + y). +/// +/// The output expressions are represented as a matrix with one row for every +/// output, one column for each var including division variables, and an extra +/// column at the end for the constant term. +/// +/// Checking equality of two such functions is supported, as well as finding the +/// value of the function at a specified point. +class MultiAffineFunction { +public: + MultiAffineFunction(const PresburgerSpace &space, const IntMatrix &output) + : space(space), output(output), + divs(space.getNumVars() - space.getNumRangeVars()) { + assertIsConsistent(); + } + + MultiAffineFunction(const PresburgerSpace &space, const IntMatrix &output, + const DivisionRepr &divs) + : space(space), output(output), divs(divs) { + assertIsConsistent(); + } + + unsigned getNumDomainVars() const { return space.getNumDomainVars(); } + unsigned getNumSymbolVars() const { return space.getNumSymbolVars(); } + unsigned getNumOutputs() const { return space.getNumRangeVars(); } + unsigned getNumDivs() const { return space.getNumLocalVars(); } + + /// Get the space of this function. + const PresburgerSpace &getSpace() const { return space; } + /// Get the domain/output space of the function. The returned space is a set + /// space. + PresburgerSpace getDomainSpace() const { return space.getDomainSpace(); } + PresburgerSpace getOutputSpace() const { return space.getRangeSpace(); } + + /// Get a matrix with each row representing row^th output expression. + const IntMatrix &getOutputMatrix() const { return output; } + /// Get the `i^th` output expression. + ArrayRef getOutputExpr(unsigned i) const { + return output.getRow(i); + } + + /// Get the divisions used in this function. + const DivisionRepr &getDivs() const { return divs; } + + /// Remove the specified range of outputs. + void removeOutputs(unsigned start, unsigned end); + + /// Given a MAF `other`, merges division variables such that both functions + /// have the union of the division vars that exist in the functions. + void mergeDivs(MultiAffineFunction &other); + + //// Return the output of the function at the given point. + SmallVector valueAt(ArrayRef point) const; + SmallVector valueAt(ArrayRef point) const { + return valueAt(getDynamicAPIntVec(point)); + } + + /// Return whether the `this` and `other` are equal when the domain is + /// restricted to `domain`. This is the case if they lie in the same space, + /// and their outputs are equal for every point in `domain`. + bool isEqual(const MultiAffineFunction &other) const; + bool isEqual(const MultiAffineFunction &other, + const IntegerPolyhedron &domain) const; + bool isEqual(const MultiAffineFunction &other, + const PresburgerSet &domain) const; + + void subtract(const MultiAffineFunction &other); + + /// Return the set of domain points where the output of `this` and `other` + /// are ordered lexicographically according to the given ordering. + /// For example, if the given comparison is `LT`, then the returned set + /// contains all points where the first output of `this` is lexicographically + /// less than `other`. + PresburgerSet getLexSet(OrderingKind comp, + const MultiAffineFunction &other) const; + + /// Get this function as a relation. + IntegerRelation getAsRelation() const; + + void print(raw_ostream &os) const; + void dump() const; + +private: + /// Assert that the MAF is consistent. + void assertIsConsistent() const; + + /// The space of this function. The domain variables are considered as the + /// input variables of the function. The range variables are considered as + /// the outputs. The symbols parametrize the function and locals are used to + /// represent divisions. Each local variable has a corressponding division + /// representation stored in `divs`. + PresburgerSpace space; + + /// The function's output is a tuple of integers, with the ith element of the + /// tuple defined by the affine expression given by the ith row of this output + /// matrix. + IntMatrix output; + + /// Storage for division representation for each local variable in space. + DivisionRepr divs; +}; + +/// This class represents a piece-wise MultiAffineFunction. This can be thought +/// of as a list of MultiAffineFunction with disjoint domains, with each having +/// their own affine expressions for their output tuples. For example, we could +/// have a function with two input variables (x, y), defined as +/// +/// f(x, y) = (2*x + y, y - 4) if x >= 0, y >= 0 +/// = (-2*x + y, y + 4) if x < 0, y < 0 +/// = (4, 1) if x < 0, y >= 0 +/// +/// Note that the domains all have to be *disjoint*. Otherwise, the behaviour of +/// this class is undefined. The domains need not cover all possible points; +/// this represents a partial function and so could be undefined at some points. +/// +/// As in PresburgerSets, the input vars are partitioned into dimension vars and +/// symbolic vars. +/// +/// Support is provided to compare equality of two such functions as well as +/// finding the value of the function at a point. +class PWMAFunction { +public: + struct Piece { + PresburgerSet domain; + MultiAffineFunction output; + + bool isConsistent() const { + return domain.getSpace().isCompatible(output.getDomainSpace()); + } + }; + + PWMAFunction(const PresburgerSpace &space) : space(space) { + assert(space.getNumLocalVars() == 0 && + "PWMAFunction cannot have local vars."); + } + + // Get the space of this function. + const PresburgerSpace &getSpace() const { return space; } + + // Add a piece ([domain, output] pair) to this function. + void addPiece(const Piece &piece); + + unsigned getNumPieces() const { return pieces.size(); } + unsigned getNumVarKind(VarKind kind) const { + return space.getNumVarKind(kind); + } + unsigned getNumDomainVars() const { return space.getNumDomainVars(); } + unsigned getNumOutputs() const { return space.getNumRangeVars(); } + unsigned getNumSymbolVars() const { return space.getNumSymbolVars(); } + + /// Remove the specified range of outputs. + void removeOutputs(unsigned start, unsigned end); + + /// Get the domain/output space of the function. The returned space is a set + /// space. + PresburgerSpace getDomainSpace() const { return space.getDomainSpace(); } + PresburgerSpace getOutputSpace() const { return space.getDomainSpace(); } + + /// Return the domain of this piece-wise MultiAffineFunction. This is the + /// union of the domains of all the pieces. + PresburgerSet getDomain() const; + + /// Return the output of the function at the given point. + std::optional> + valueAt(ArrayRef point) const; + std::optional> + valueAt(ArrayRef point) const { + return valueAt(getDynamicAPIntVec(point)); + } + + /// Return all the pieces of this piece-wise function. + ArrayRef getAllPieces() const { return pieces; } + + /// Return whether `this` and `other` are equal as PWMAFunctions, i.e. whether + /// they have the same dimensions, the same domain and they take the same + /// value at every point in the domain. + bool isEqual(const PWMAFunction &other) const; + + /// Return a function defined on the union of the domains of this and func, + /// such that when only one of the functions is defined, it outputs the same + /// as that function, and if both are defined, it outputs the lexmax/lexmin of + /// the two outputs. On points where neither function is defined, the returned + /// function is not defined either. + /// + /// Currently this does not support PWMAFunctions which have pieces containing + /// divisions. + /// TODO: Support division in pieces. + PWMAFunction unionLexMin(const PWMAFunction &func); + PWMAFunction unionLexMax(const PWMAFunction &func); + + void print(raw_ostream &os) const; + void dump() const; + +private: + /// Return a function defined on the union of the domains of `this` and + /// `func`, such that when only one of the functions is defined, it outputs + /// the same as that function, and if neither is defined, the returned + /// function is not defined either. + /// + /// The provided `tiebreak` function determines which of the two functions' + /// output should be used on inputs where both the functions are defined. More + /// precisely, given two `MultiAffineFunction`s `mafA` and `mafB`, `tiebreak` + /// returns the subset of the intersection of the two functions' domains where + /// the output of `mafA` should be used. + /// + /// The PresburgerSet returned by `tiebreak` should be disjoint. + /// TODO: Remove this constraint of returning disjoint set. + PWMAFunction unionFunction( + const PWMAFunction &func, + llvm::function_ref tiebreak) const; + + /// The space of this function. The domain variables are considered as the + /// input variables of the function. The range variables are considered as + /// the outputs. The symbols paramterize the function. + PresburgerSpace space; + + // The pieces of the PWMAFunction. + SmallVector pieces; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_PWMAFUNCTION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PresburgerRelation.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PresburgerRelation.h new file mode 100644 index 0000000000000000000000000000000000000000..f7e06a6b22a95d8686926fd53729ea8ea0920aad --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PresburgerRelation.h @@ -0,0 +1,280 @@ +//===- PresburgerRelation.h - MLIR PresburgerRelation Class -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A class to represent unions of IntegerRelations. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_PRESBURGERRELATION_H +#define MLIR_ANALYSIS_PRESBURGER_PRESBURGERRELATION_H + +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include + +namespace mlir { +namespace presburger { + +/// The SetCoalescer class contains all functionality concerning the coalesce +/// heuristic. It is built from a `PresburgerRelation` and has the `coalesce()` +/// function as its main API. +class SetCoalescer; + +/// A PresburgerRelation represents a union of IntegerRelations that live in +/// the same PresburgerSpace with support for union, intersection, subtraction, +/// and complement operations, as well as sampling. +/// +/// The IntegerRelations (disjuncts) are stored in a vector, and the set +/// represents the union of these relations. An empty list corresponds to +/// the empty set. +/// +/// Note that there are no invariants guaranteed on the list of disjuncts +/// other than that they are all in the same PresburgerSpace. For example, the +/// relations may overlap with each other. +class PresburgerRelation { +public: + /// Return a universe set of the specified type that contains all points. + static PresburgerRelation getUniverse(const PresburgerSpace &space); + + /// Return an empty set of the specified type that contains no points. + static PresburgerRelation getEmpty(const PresburgerSpace &space); + + explicit PresburgerRelation(const IntegerRelation &disjunct); + + unsigned getNumDomainVars() const { return space.getNumDomainVars(); } + unsigned getNumRangeVars() const { return space.getNumRangeVars(); } + unsigned getNumSymbolVars() const { return space.getNumSymbolVars(); } + unsigned getNumLocalVars() const { return space.getNumLocalVars(); } + unsigned getNumVars() const { return space.getNumVars(); } + + /// Return the number of disjuncts in the union. + unsigned getNumDisjuncts() const; + + const PresburgerSpace &getSpace() const { return space; } + + /// Set the space to `oSpace`. `oSpace` should not contain any local ids. + /// `oSpace` need not have the same number of ids as the current space; + /// it could have more or less. If it has less, the extra ids become + /// locals of the disjuncts. It can also have more, in which case the + /// disjuncts will have fewer locals. If its total number of ids + /// exceeds that of some disjunct, an assert failure will occur. + void setSpace(const PresburgerSpace &oSpace); + + void insertVarInPlace(VarKind kind, unsigned pos, unsigned num = 1); + + /// Converts variables of the specified kind in the column range [srcPos, + /// srcPos + num) to variables of the specified kind at position dstPos. The + /// ranges are relative to the kind of variable. + /// + /// srcKind and dstKind must be different. + void convertVarKind(VarKind srcKind, unsigned srcPos, unsigned num, + VarKind dstKind, unsigned dstPos); + + /// Return a reference to the list of disjuncts. + ArrayRef getAllDisjuncts() const; + + /// Return the disjunct at the specified index. + const IntegerRelation &getDisjunct(unsigned index) const; + + /// Mutate this set, turning it into the union of this set and the given + /// disjunct. + void unionInPlace(const IntegerRelation &disjunct); + + /// Mutate this set, turning it into the union of this set and the given set. + void unionInPlace(const PresburgerRelation &set); + + /// Return the union of this set and the given set. + PresburgerRelation unionSet(const PresburgerRelation &set) const; + + /// Return the intersection of this set and the given set. + PresburgerRelation intersect(const PresburgerRelation &set) const; + + /// Return the range intersection of the given `set` with `this` relation. + /// + /// Formally, let the relation `this` be R: A -> B and `set` is C, then this + /// operation returns A -> (B intersection C). + PresburgerRelation intersectRange(const PresburgerSet &set) const; + + /// Return the domain intersection of the given `set` with `this` relation. + /// + /// Formally, let the relation `this` be R: A -> B and `set` is C, then this + /// operation returns (A intersection C) -> B. + PresburgerRelation intersectDomain(const PresburgerSet &set) const; + + /// Return a set corresponding to the domain of the relation. + PresburgerSet getDomainSet() const; + /// Return a set corresponding to the range of the relation. + PresburgerSet getRangeSet() const; + + /// Invert the relation, i.e. swap its domain and range. + /// + /// Formally, if `this`: A -> B then `inverse` updates `this` in-place to + /// `this`: B -> A. + void inverse(); + + /// Compose `this` relation with the given relation `rel` in-place. + /// + /// Formally, if `this`: A -> B, and `rel`: B -> C, then this function updates + /// `this` to `result`: A -> C where a point (a, c) belongs to `result` + /// iff there exists b such that (a, b) is in `this` and, (b, c) is in rel. + void compose(const PresburgerRelation &rel); + + /// Apply the domain of given relation `rel` to `this` relation. + /// + /// Formally, R1.applyDomain(R2) = R2.inverse().compose(R1). + void applyDomain(const PresburgerRelation &rel); + + /// Same as compose, provided for uniformity with applyDomain. + void applyRange(const PresburgerRelation &rel); + + /// Compute the symbolic integer lexmin of the relation, i.e. for every + /// assignment of the symbols and domain the lexicographically minimum value + /// attained by the range. + SymbolicLexOpt findSymbolicIntegerLexMin() const; + + /// Compute the symbolic integer lexmax of the relation, i.e. for every + /// assignment of the symbols and domain the lexicographically maximum value + /// attained by the range. + SymbolicLexOpt findSymbolicIntegerLexMax() const; + + /// Return true if the set contains the given point, and false otherwise. + bool containsPoint(ArrayRef point) const; + bool containsPoint(ArrayRef point) const { + return containsPoint(getDynamicAPIntVec(point)); + } + + /// Return the complement of this set. All local variables in the set must + /// correspond to floor divisions. + PresburgerRelation complement() const; + + /// Return the set difference of this set and the given set, i.e., + /// return `this \ set`. All local variables in `set` must correspond + /// to floor divisions, but local variables in `this` need not correspond to + /// divisions. + PresburgerRelation subtract(const PresburgerRelation &set) const; + + /// Return true if this set is a subset of the given set, and false otherwise. + bool isSubsetOf(const PresburgerRelation &set) const; + + /// Return true if this set is equal to the given set, and false otherwise. + /// All local variables in both sets must correspond to floor divisions. + bool isEqual(const PresburgerRelation &set) const; + + /// Return true if all the sets in the union are known to be integer empty + /// false otherwise. + bool isIntegerEmpty() const; + + /// Return true if there is no disjunct, false otherwise. + bool isObviouslyEmpty() const; + + /// Return true if the set is known to have one unconstrained disjunct, false + /// otherwise. + bool isObviouslyUniverse() const; + + /// Perform a quick equality check on `this` and `other`. The relations are + /// equal if the check return true, but may or may not be equal if the check + /// returns false. This is doing by directly comparing whether each internal + /// disjunct is the same. + bool isObviouslyEqual(const PresburgerRelation &set) const; + + /// Return true if the set is consist of a single disjunct, without any local + /// variables, false otherwise. + bool isConvexNoLocals() const; + + /// Find an integer sample from the given set. This should not be called if + /// any of the disjuncts in the union are unbounded. + bool findIntegerSample(SmallVectorImpl &sample); + + /// Compute an overapproximation of the number of integer points in the + /// disjunct. Symbol vars are currently not supported. If the computed + /// overapproximation is infinite, an empty optional is returned. + /// + /// This currently just sums up the overapproximations of the volumes of the + /// disjuncts, so the approximation might be far from the true volume in the + /// case when there is a lot of overlap between disjuncts. + std::optional computeVolume() const; + + /// Simplifies the representation of a PresburgerRelation. + /// + /// In particular, removes all disjuncts which are subsets of other + /// disjuncts in the union. + PresburgerRelation coalesce() const; + + /// Check whether all local ids in all disjuncts have a div representation. + bool hasOnlyDivLocals() const; + + /// Compute an equivalent representation of the same relation, such that all + /// local ids in all disjuncts have division representations. This + /// representation may involve local ids that correspond to divisions, and may + /// also be a union of convex disjuncts. + PresburgerRelation computeReprWithOnlyDivLocals() const; + + /// Simplify each disjunct, canonicalizing each disjunct and removing + /// redundencies. + PresburgerRelation simplify() const; + + /// Return whether the given PresburgerRelation is full-dimensional. By full- + /// dimensional we mean that it is not flat along any dimension. + bool isFullDim() const; + + /// Print the set's internal state. + void print(raw_ostream &os) const; + void dump() const; + +protected: + /// Construct an empty PresburgerRelation with the specified number of + /// dimension and symbols. + explicit PresburgerRelation(const PresburgerSpace &space) : space(space) { + assert(space.getNumLocalVars() == 0 && + "PresburgerRelation cannot have local vars."); + } + + PresburgerSpace space; + + /// The list of disjuncts that this set is the union of. + SmallVector disjuncts; + + friend class SetCoalescer; +}; + +class PresburgerSet : public PresburgerRelation { +public: + /// Return a universe set of the specified type that contains all points. + static PresburgerSet getUniverse(const PresburgerSpace &space); + + /// Return an empty set of the specified type that contains no points. + static PresburgerSet getEmpty(const PresburgerSpace &space); + + /// Create a set from a relation. + explicit PresburgerSet(const IntegerPolyhedron &disjunct); + explicit PresburgerSet(const PresburgerRelation &set); + + /// These operations are the same as the ones in PresburgeRelation, they just + /// forward the arguement and return the result as a set instead of a + /// relation. + PresburgerSet unionSet(const PresburgerRelation &set) const; + PresburgerSet intersect(const PresburgerRelation &set) const; + PresburgerSet complement() const; + PresburgerSet subtract(const PresburgerRelation &set) const; + PresburgerSet coalesce() const; + +protected: + /// Construct an empty PresburgerRelation with the specified number of + /// dimension and symbols. + explicit PresburgerSet(const PresburgerSpace &space) + : PresburgerRelation(space) { + assert(space.getNumDomainVars() == 0 && + "Set type cannot have domain vars."); + assert(space.getNumLocalVars() == 0 && + "PresburgerRelation cannot have local vars."); + } +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_PRESBURGERRELATION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PresburgerSpace.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PresburgerSpace.h new file mode 100644 index 0000000000000000000000000000000000000000..97573b6e4530135825ed6b160402d5e2febd3f0d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/PresburgerSpace.h @@ -0,0 +1,347 @@ +//===- PresburgerSpace.h - MLIR PresburgerSpace Class -----------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Classes representing space information like number of variables and kind of +// variables. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_PRESBURGERSPACE_H +#define MLIR_ANALYSIS_PRESBURGER_PRESBURGERSPACE_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/PointerLikeTypeTraits.h" +#include "llvm/Support/TypeName.h" +#include "llvm/Support/raw_ostream.h" + +namespace mlir { +namespace presburger { +using llvm::ArrayRef; +using llvm::SmallVector; + +/// Kind of variable. Implementation wise SetDims are treated as Range +/// vars, and spaces with no distinction between dimension vars are treated +/// as relations with zero domain vars. +enum class VarKind { Symbol, Local, Domain, Range, SetDim = Range }; + +/// An Identifier stores a pointer to an object, such as a Value or an +/// Operation. Identifiers are intended to be attached to a variable in a +/// PresburgerSpace and can be used to check if two variables correspond to the +/// same object. +/// +/// Take for example the following code: +/// +/// for i = 0 to 100 +/// for j = 0 to 100 +/// S0: A[j] = 0 +/// for k = 0 to 100 +/// S1: A[k] = 1 +/// +/// If we represent the space of iteration variables surrounding S0, S1 we have: +/// space(S0): {d0, d1} +/// space(S1): {d0, d1} +/// +/// Since the variables are in different spaces, without an identifier, there +/// is no way to distinguish if the variables in the two spaces correspond to +/// different SSA values in the program. So, we attach an Identifier +/// corresponding to the loop iteration variable to them. Now, +/// +/// space(S0) = {d0(id = i), d1(id = j)} +/// space(S1) = {d0(id = i), d1(id = k)}. +/// +/// Using the identifier, we can check that the first iteration variable in +/// both the spaces correspond to the same variable in the program, while they +/// are different for second iteration variable. +/// +/// The equality of Identifiers is checked by comparing the stored pointers. +/// Checking equality asserts that the type of the equal identifiers is same. +/// Identifiers storing null pointers are treated as having no attachment and +/// are considered unequal to any other identifier, including other identifiers +/// with no attachments. +/// +/// The type of the pointer stored must have an `llvm::PointerLikeTypeTraits` +/// specialization. +class Identifier { +public: + Identifier() = default; + + // Create an identifier from a pointer. + template + explicit Identifier(T value) + : value(llvm::PointerLikeTypeTraits::getAsVoidPointer(value)) { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + idType = llvm::getTypeName(); +#endif + } + + /// Get the value of the identifier casted to type `T`. `T` here should match + /// the type of the identifier used to create it. + template + T getValue() const { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + assert(llvm::getTypeName() == idType && + "Identifier was initialized with a different type than the one used " + "to retrieve it."); +#endif + return llvm::PointerLikeTypeTraits::getFromVoidPointer(value); + } + + bool hasValue() const { return value != nullptr; } + + /// Check if the two identifiers are equal. Null identifiers are considered + /// not equal. Asserts if two identifiers are equal but their types are not. + bool isEqual(const Identifier &other) const; + + bool operator==(const Identifier &other) const { return isEqual(other); } + bool operator!=(const Identifier &other) const { return !isEqual(other); } + + void print(llvm::raw_ostream &os) const; + void dump() const; + +private: + /// The value of the identifier. + void *value = nullptr; + +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + /// TypeID of the identifiers in space. This should be used in asserts only. + llvm::StringRef idType; +#endif +}; + +/// PresburgerSpace is the space of all possible values of a tuple of integer +/// valued variables/variables. Each variable has one of the three types: +/// +/// Dimension: Ordinary variables over which the space is represented. +/// +/// Symbol: Symbol variables correspond to fixed but unknown values. +/// Mathematically, a space with symbolic variables is like a +/// family of spaces indexed by the symbolic variables. +/// +/// Local: Local variables correspond to existentially quantified variables. +/// For example, consider the space: `(x, exists q)` where x is a dimension +/// variable and q is a local variable. Let us put the constraints: +/// `1 <= x <= 7, x = 2q` +/// on this space to get the set: +/// `(x) : (exists q : q <= x <= 7, x = 2q)`. +/// An assignment to symbolic and dimension variables is valid if there +/// exists some assignment to the local variable `q` satisfying these +/// constraints. For this example, the set is equivalent to {2, 4, 6}. +/// Mathematically, existential quantification can be thought of as the result +/// of projection. In this example, `q` is existentially quantified. This can be +/// thought of as the result of projecting out `q` from the previous example, +/// i.e. we obtained {2, 4, 6} by projecting out the second dimension from +/// {(2, 1), (4, 2), (6, 2)}. +/// +/// Dimension variables are further divided into Domain and Range variables +/// to support building relations. +/// +/// Variables are stored in the following order: +/// [Domain, Range, Symbols, Locals] +/// +/// A space with no distinction between types of dimension variables can +/// be implemented as a space with zero domain. VarKind::SetDim should be used +/// to refer to dimensions in such spaces. +/// +/// Compatibility of two spaces implies that number of variables of each kind +/// other than Locals are equal. Equality of two spaces implies that number of +/// variables of each kind are equal. +/// +/// PresburgerSpace optionally also supports attaching an Identifier with each +/// non-local variable in the space. This is disabled by default. `resetIds` is +/// used to enable/reset these identifiers. The user can identify each variable +/// in the space as corresponding to some Identifier. Some example use cases +/// are described in the `Identifier` documentation above. The type attached to +/// the Identifier can be different for different variables in the space. +class PresburgerSpace { +public: + static PresburgerSpace getRelationSpace(unsigned numDomain = 0, + unsigned numRange = 0, + unsigned numSymbols = 0, + unsigned numLocals = 0) { + return PresburgerSpace(numDomain, numRange, numSymbols, numLocals); + } + + static PresburgerSpace getSetSpace(unsigned numDims = 0, + unsigned numSymbols = 0, + unsigned numLocals = 0) { + return PresburgerSpace(/*numDomain=*/0, /*numRange=*/numDims, numSymbols, + numLocals); + } + + /// Get the domain/range space of this space. The returned space is a set + /// space. + PresburgerSpace getDomainSpace() const; + PresburgerSpace getRangeSpace() const; + + /// Get the space without local variables. + PresburgerSpace getSpaceWithoutLocals() const; + + unsigned getNumDomainVars() const { return numDomain; } + unsigned getNumRangeVars() const { return numRange; } + unsigned getNumSetDimVars() const { return numRange; } + unsigned getNumSymbolVars() const { return numSymbols; } + unsigned getNumLocalVars() const { return numLocals; } + + unsigned getNumDimVars() const { return numDomain + numRange; } + unsigned getNumDimAndSymbolVars() const { + return numDomain + numRange + numSymbols; + } + unsigned getNumVars() const { + return numDomain + numRange + numSymbols + numLocals; + } + + /// Get the number of vars of the specified kind. + unsigned getNumVarKind(VarKind kind) const; + + /// Return the index at which the specified kind of var starts. + unsigned getVarKindOffset(VarKind kind) const; + + /// Return the index at Which the specified kind of var ends. + unsigned getVarKindEnd(VarKind kind) const; + + /// Get the number of elements of the specified kind in the range + /// [varStart, varLimit). + unsigned getVarKindOverlap(VarKind kind, unsigned varStart, + unsigned varLimit) const; + + /// Return the VarKind of the var at the specified position. + VarKind getVarKindAt(unsigned pos) const; + + /// Insert `num` variables of the specified kind at position `pos`. + /// Positions are relative to the kind of variable. Return the absolute + /// column position (i.e., not relative to the kind of variable) of the + /// first added variable. + /// + /// If identifiers are being used, the newly added variables have no + /// identifiers. + unsigned insertVar(VarKind kind, unsigned pos, unsigned num = 1); + + /// Removes variables of the specified kind in the column range [varStart, + /// varLimit). The range is relative to the kind of variable. + void removeVarRange(VarKind kind, unsigned varStart, unsigned varLimit); + + /// Converts variables of the specified kind in the column range [srcPos, + /// srcPos + num) to variables of the specified kind at position dstPos. The + /// ranges are relative to the kind of variable. + /// + /// srcKind and dstKind must be different. + void convertVarKind(VarKind srcKind, unsigned srcPos, unsigned num, + VarKind dstKind, unsigned dstPos); + + /// Changes the partition between dimensions and symbols. Depending on the new + /// symbol count, either a chunk of dimensional variables immediately before + /// the split become symbols, or some of the symbols immediately after the + /// split become dimensions. + void setVarSymbolSeparation(unsigned newSymbolCount); + + /// Swaps the posA^th variable of kindA and posB^th variable of kindB. + void swapVar(VarKind kindA, VarKind kindB, unsigned posA, unsigned posB); + + /// Returns true if both the spaces are compatible i.e. if both spaces have + /// the same number of variables of each kind (excluding locals). + bool isCompatible(const PresburgerSpace &other) const; + + /// Returns true if both the spaces are equal including local variables i.e. + /// if both spaces have the same number of variables of each kind (including + /// locals). + bool isEqual(const PresburgerSpace &other) const; + + /// Get the identifier of pos^th variable of the specified kind. + Identifier getId(VarKind kind, unsigned pos) const { + assert(kind != VarKind::Local && "Local variables have no identifiers"); + if (!usingIds) + return Identifier(); + return identifiers[getVarKindOffset(kind) + pos]; + } + + ArrayRef getIds(VarKind kind) const { + assert(kind != VarKind::Local && "Local variables have no identifiers"); + assert(usingIds && "Identifiers not enabled for space"); + return {identifiers.data() + getVarKindOffset(kind), getNumVarKind(kind)}; + } + + ArrayRef getIds() const { + assert(usingIds && "Identifiers not enabled for space"); + return identifiers; + } + + /// Set the identifier of pos^th variable of the specified kind. Calls + /// resetIds if identifiers are not enabled. + void setId(VarKind kind, unsigned pos, Identifier id) { + assert(kind != VarKind::Local && "Local variables have no identifiers"); + if (!usingIds) + resetIds(); + identifiers[getVarKindOffset(kind) + pos] = id; + } + + /// Returns if identifiers are being used. + bool isUsingIds() const { return usingIds; } + + /// Reset the stored identifiers in the space. Enables `usingIds` if it was + /// `false` before. + void resetIds() { + identifiers.clear(); + identifiers.resize(getNumDimAndSymbolVars()); + usingIds = true; + } + + /// Disable identifiers being stored in space. + void disableIds() { + identifiers.clear(); + usingIds = false; + } + + /// Check if the spaces are compatible, and the non-local variables having + /// same identifiers are in the same positions. If the space is not using + /// Identifiers, this check is same as isCompatible. + bool isAligned(const PresburgerSpace &other) const; + /// Same as above but only check the specified VarKind. Useful to check if + /// the symbols in two spaces are aligned. + bool isAligned(const PresburgerSpace &other, VarKind kind) const; + + /// Merge and align symbol variables of `this` and `other` with respect to + /// identifiers. After this operation the symbol variables of both spaces have + /// the same identifiers in the same order. + void mergeAndAlignSymbols(PresburgerSpace &other); + + void print(llvm::raw_ostream &os) const; + void dump() const; + +protected: + PresburgerSpace(unsigned numDomain, unsigned numRange, unsigned numSymbols, + unsigned numLocals) + : numDomain(numDomain), numRange(numRange), numSymbols(numSymbols), + numLocals(numLocals) {} + +private: + // Number of variables corresponding to domain variables. + unsigned numDomain; + + // Number of variables corresponding to range variables. + unsigned numRange; + + /// Number of variables corresponding to symbols (unknown but constant for + /// analysis). + unsigned numSymbols; + + /// Number of variables corresponding to locals (variables corresponding + /// to existentially quantified variables). + unsigned numLocals; + + /// Stores whether or not identifiers are being used in this space. + bool usingIds = false; + + /// Stores an identifier for each non-local variable as a `void` pointer. + SmallVector identifiers; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_PRESBURGERSPACE_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/QuasiPolynomial.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/QuasiPolynomial.h new file mode 100644 index 0000000000000000000000000000000000000000..5a0962df89d37a407497f9a998ffebd2c86130bb --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/QuasiPolynomial.h @@ -0,0 +1,80 @@ +//===- QuasiPolynomial.h - QuasiPolynomial Class ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Definition of the QuasiPolynomial class for Barvinok's algorithm, +// which represents a single-valued function on a set of parameters. +// It is an expression of the form +// f(x) = \sum_i c_i * \prod_j ⌊g_{ij}(x)⌋ +// where c_i \in Q and +// g_{ij} : Q^d -> Q are affine functionals over d parameters. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_QUASIPOLYNOMIAL_H +#define MLIR_ANALYSIS_PRESBURGER_QUASIPOLYNOMIAL_H + +#include "mlir/Analysis/Presburger/Fraction.h" +#include "mlir/Analysis/Presburger/PresburgerSpace.h" + +namespace mlir { +namespace presburger { + +// A class to describe quasi-polynomials. +// A quasipolynomial consists of a set of terms. +// The ith term is a constant `coefficients[i]`, multiplied +// by the product of a set of affine functions on n parameters. +// Represents functions f : Q^n -> Q of the form +// +// f(x) = \sum_i c_i * \prod_j ⌊g_{ij}(x)⌋ +// +// where c_i \in Q and +// g_{ij} : Q^n -> Q are affine functionals. +class QuasiPolynomial : public PresburgerSpace { +public: + QuasiPolynomial(unsigned numVars, ArrayRef coeffs = {}, + ArrayRef>> aff = {}); + + QuasiPolynomial(unsigned numVars, const Fraction &constant); + + // Find the number of inputs (numDomain) to the polynomial. + // numSymbols is set to zero. + unsigned getNumInputs() const { + return getNumDomainVars() + getNumSymbolVars(); + } + + const SmallVector &getCoefficients() const { return coefficients; } + + const std::vector>> &getAffine() const { + return affine; + } + + // Arithmetic operations. + QuasiPolynomial operator+(const QuasiPolynomial &x) const; + QuasiPolynomial operator-(const QuasiPolynomial &x) const; + QuasiPolynomial operator*(const QuasiPolynomial &x) const; + QuasiPolynomial operator/(const Fraction &x) const; + + // Removes terms which evaluate to zero from the expression + // and folds affine functions which are constant into the + // constant coefficients. + QuasiPolynomial simplify(); + + // Group together like terms in the expression. + QuasiPolynomial collectTerms(); + + Fraction getConstantTerm(); + +private: + SmallVector coefficients; + std::vector>> affine; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_QUASIPOLYNOMIAL_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Simplex.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Simplex.h new file mode 100644 index 0000000000000000000000000000000000000000..d89bbe37a6b3e0cb760eb4b7bec1779d796438ac --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Simplex.h @@ -0,0 +1,889 @@ +//===- Simplex.h - MLIR Simplex Class ---------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Functionality to perform analysis on an IntegerRelation. In particular, +// support for performing emptiness checks, redundancy checks and obtaining the +// lexicographically minimum rational element in a set. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_SIMPLEX_H +#define MLIR_ANALYSIS_PRESBURGER_SIMPLEX_H + +#include "mlir/Analysis/Presburger/Fraction.h" +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include "mlir/Analysis/Presburger/Matrix.h" +#include "mlir/Analysis/Presburger/PWMAFunction.h" +#include "mlir/Analysis/Presburger/Utils.h" +#include "llvm/ADT/SmallBitVector.h" +#include + +namespace mlir { +namespace presburger { + +class GBRSimplex; + +/// The Simplex class implements a version of the Simplex and Generalized Basis +/// Reduction algorithms, which can perform analysis of integer sets with affine +/// inequalities and equalities. A Simplex can be constructed +/// by specifying the dimensionality of the set. It supports adding affine +/// inequalities and equalities, and can perform emptiness checks, i.e., it can +/// find a solution to the set of constraints if one exists, or say that the +/// set is empty if no solution exists. Furthermore, it can find a subset of +/// these constraints that are redundant, i.e. a subset of constraints that +/// doesn't constrain the affine set further after adding the non-redundant +/// constraints. The LexSimplex class provides support for computing the +/// lexicographic minimum of an IntegerRelation. The SymbolicLexOpt class +/// provides support for computing symbolic lexicographic minimums. All of these +/// classes can be constructed from an IntegerRelation, and all inherit common +/// functionality from SimplexBase. +/// +/// The implementations of the Simplex and SimplexBase classes, other than the +/// functionality for obtaining an integer sample, are based on the paper +/// "Simplify: A Theorem Prover for Program Checking" +/// by D. Detlefs, G. Nelson, J. B. Saxe. +/// +/// We define variables, constraints, and unknowns. Consider the example of a +/// two-dimensional set defined by 1 + 2x + 3y >= 0 and 2x - 3y >= 0. Here, +/// x, y, are variables while 1 + 2x + 3y >= 0, 2x - 3y >= 0 are constraints. +/// Unknowns are either variables or constraints, i.e., x, y, 1 + 2x + 3y >= 0, +/// 2x - 3y >= 0 are all unknowns. +/// +/// The implementation involves a matrix called a tableau, which can be thought +/// of as a 2D matrix of rational numbers having number of rows equal to the +/// number of constraints and number of columns equal to one plus the number of +/// variables. In our implementation, instead of storing rational numbers, we +/// store a common denominator for each row, so it is in fact a matrix of +/// integers with number of rows equal to number of constraints and number of +/// columns equal to _two_ plus the number of variables. For example, instead of +/// storing a row of three rationals [1/2, 2/3, 3], we would store [6, 3, 4, 18] +/// since 3/6 = 1/2, 4/6 = 2/3, and 18/6 = 3. +/// +/// Every row and column except the first and second columns is associated with +/// an unknown and every unknown is associated with a row or column. An unknown +/// associated with a row or column is said to be in row or column orientation +/// respectively. As described above, the first column is the common +/// denominator. The second column represents the constant term, explained in +/// more detail below. These two are _fixed columns_; they always retain their +/// position as the first and second columns. Additionally, LexSimplexBase +/// stores a so-call big M parameter (explained below) in the third column, so +/// LexSimplexBase has three fixed columns. Finally, SymbolicLexSimplex has +/// `nSymbol` variables designated as symbols. These occupy the next `nSymbol` +/// columns, viz. the columns [3, 3 + nSymbol). For more information on symbols, +/// see LexSimplexBase and SymbolicLexSimplex. +/// +/// LexSimplexBase does not directly support variables which can be negative, so +/// we introduce the so-called big M parameter, an artificial variable that is +/// considered to have an arbitrarily large value. We then transform the +/// variables, say x, y, z, ... to M, M + x, M + y, M + z. Since M has been +/// added to these variables, they are now known to have non-negative values. +/// For more details, see the documentation for LexSimplexBase. The big M +/// parameter is not considered a real unknown and is not stored in the `var` +/// data structure; rather the tableau just has an extra fixed column for it +/// just like the constant term. +/// +/// The vectors var and con store information about the variables and +/// constraints respectively, namely, whether they are in row or column +/// position, which row or column they are associated with, and whether they +/// correspond to a variable or a constraint. +/// +/// An unknown is addressed by its index. If the index i is non-negative, then +/// the variable var[i] is being addressed. If the index i is negative, then +/// the constraint con[~i] is being addressed. Effectively this maps +/// 0 -> var[0], 1 -> var[1], -1 -> con[0], -2 -> con[1], etc. rowUnknown[r] and +/// colUnknown[c] are the indexes of the unknowns associated with row r and +/// column c, respectively. +/// +/// The unknowns in column position are together called the basis. Initially the +/// basis is the set of variables -- in our example above, the initial basis is +/// x, y. +/// +/// The unknowns in row position are represented in terms of the basis unknowns. +/// If the basis unknowns are u_1, u_2, ... u_m, and a row in the tableau is +/// d, c, a_1, a_2, ... a_m, this represents the unknown for that row as +/// (c + a_1*u_1 + a_2*u_2 + ... + a_m*u_m)/d. In our running example, if the +/// basis is the initial basis of x, y, then the constraint 1 + 2x + 3y >= 0 +/// would be represented by the row [1, 1, 2, 3]. +/// +/// The association of unknowns to rows and columns can be changed by a process +/// called pivoting, where a row unknown and a column unknown exchange places +/// and the remaining row variables' representation is changed accordingly +/// by eliminating the old column unknown in favour of the new column unknown. +/// If we had pivoted the column for x with the row for 2x - 3y >= 0, +/// the new row for x would be [2, 1, 3] since x = (1*(2x - 3y) + 3*y)/2. +/// See the documentation for the pivot member function for details. +/// +/// The association of unknowns to rows and columns is called the _tableau +/// configuration_. The _sample value_ of an unknown in a particular tableau +/// configuration is its value if all the column unknowns were set to zero. +/// Concretely, for unknowns in column position the sample value is zero; when +/// the big M parameter is not used, for unknowns in row position the sample +/// value is the constant term divided by the common denominator. When the big M +/// parameter is used, if d is the denominator, p is the big M coefficient, and +/// c is the constant term, then the sample value is (p*M + c)/d. Since M is +/// considered to be positive infinity, this is positive (negative) infinity +/// when p is positive or negative, and c/d when p is zero. +/// +/// The tableau configuration is called _consistent_ if the sample value of all +/// restricted unknowns is non-negative. Initially there are no constraints, and +/// the tableau is consistent. When a new constraint is added, its sample value +/// in the current tableau configuration may be negative. In that case, we try +/// to find a series of pivots to bring us to a consistent tableau +/// configuration, i.e. we try to make the new constraint's sample value +/// non-negative without making that of any other constraints negative. (See +/// findPivot and findPivotRow for details.) If this is not possible, then the +/// set of constraints is mutually contradictory and the tableau is marked +/// _empty_, which means the set of constraints has no solution. +/// +/// This SimplexBase class also supports taking snapshots of the current state +/// and rolling back to prior snapshots. This works by maintaining an undo log +/// of operations. Snapshots are just pointers to a particular location in the +/// log, and rolling back to a snapshot is done by reverting each log entry's +/// operation from the end until we reach the snapshot's location. SimplexBase +/// also supports taking a snapshot including the exact set of basis unknowns; +/// if this functionality is used, then on rolling back the exact basis will +/// also be restored. This is used by LexSimplexBase because the lex algorithm, +/// unlike `Simplex`, is sensitive to the exact basis used at a point. +class SimplexBase { +public: + SimplexBase() = delete; + virtual ~SimplexBase() = default; + + /// Returns true if the tableau is empty (has conflicting constraints), + /// false otherwise. + bool isEmpty() const; + + /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n + /// is the current number of variables, then the corresponding inequality is + /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0. + virtual void addInequality(ArrayRef coeffs) = 0; + + /// Returns the number of variables in the tableau. + unsigned getNumVariables() const; + + /// Returns the number of constraints in the tableau. + unsigned getNumConstraints() const; + + /// Add an equality to the tableau. If coeffs is c_0, c_1, ... c_n, where n + /// is the current number of variables, then the corresponding equality is + /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} == 0. + void addEquality(ArrayRef coeffs); + + /// Add new variables to the end of the list of variables. + void appendVariable(unsigned count = 1); + + /// Append a new variable to the simplex and constrain it such that its only + /// integer value is the floor div of `coeffs` and `denom`. + /// + /// `denom` must be positive. + void addDivisionVariable(ArrayRef coeffs, + const DynamicAPInt &denom); + + /// Mark the tableau as being empty. + void markEmpty(); + + /// Get a snapshot of the current state. This is used for rolling back. + /// The same basis will not necessarily be restored on rolling back. + /// The snapshot only captures the set of variables and constraints present + /// in the Simplex. + unsigned getSnapshot() const; + + /// Get a snapshot of the current state including the basis. When rolling + /// back, the exact basis will be restored. + unsigned getSnapshotBasis(); + + /// Rollback to a snapshot. This invalidates all later snapshots. + void rollback(unsigned snapshot); + + /// Add all the constraints from the given IntegerRelation. + void intersectIntegerRelation(const IntegerRelation &rel); + + /// Print the tableau's internal state. + void print(raw_ostream &os) const; + void dump() const; + +protected: + /// Construct a SimplexBase with the specified number of variables and fixed + /// columns. The first overload should be used when there are nosymbols. + /// With the second overload, the specified range of vars will be marked + /// as symbols. With the third overload, `isSymbol` is a bitmask denoting + /// which vars are symbols. The size of `isSymbol` must be `nVar`. + /// + /// For example, Simplex uses two fixed columns: the denominator and the + /// constant term, whereas LexSimplex has an extra fixed column for the + /// so-called big M parameter. For more information see the documentation for + /// LexSimplex. + SimplexBase(unsigned nVar, bool mustUseBigM); + SimplexBase(unsigned nVar, bool mustUseBigM, + const llvm::SmallBitVector &isSymbol); + + enum class Orientation { Row, Column }; + + /// An Unknown is either a variable or a constraint. It is always associated + /// with either a row or column. Whether it's a row or a column is specified + /// by the orientation and pos identifies the specific row or column it is + /// associated with. If the unknown is restricted, then it has a + /// non-negativity constraint associated with it, i.e., its sample value must + /// always be non-negative and if it cannot be made non-negative without + /// violating other constraints, the tableau is empty. + struct Unknown { + Unknown(Orientation oOrientation, bool oRestricted, unsigned oPos, + bool oIsSymbol = false) + : pos(oPos), orientation(oOrientation), restricted(oRestricted), + isSymbol(oIsSymbol) {} + unsigned pos; + Orientation orientation; + bool restricted : 1; + bool isSymbol : 1; + + void print(raw_ostream &os) const { + os << (orientation == Orientation::Row ? "r" : "c"); + os << pos; + if (restricted) + os << " [>=0]"; + } + }; + + struct Pivot { + unsigned row, column; + }; + + /// Return any row that this column can be pivoted with, ignoring tableau + /// consistency. + /// + /// Returns an empty optional if no pivot is possible, which happens only when + /// the column unknown is a variable and no constraint has a non-zero + /// coefficient for it. + std::optional findAnyPivotRow(unsigned col); + + /// Swap the row with the column in the tableau's data structures but not the + /// tableau itself. This is used by pivot. + void swapRowWithCol(unsigned row, unsigned col); + + /// Pivot the row with the column. + void pivot(unsigned row, unsigned col); + void pivot(Pivot pair); + + /// Returns the unknown associated with index. + const Unknown &unknownFromIndex(int index) const; + /// Returns the unknown associated with col. + const Unknown &unknownFromColumn(unsigned col) const; + /// Returns the unknown associated with row. + const Unknown &unknownFromRow(unsigned row) const; + /// Returns the unknown associated with index. + Unknown &unknownFromIndex(int index); + /// Returns the unknown associated with col. + Unknown &unknownFromColumn(unsigned col); + /// Returns the unknown associated with row. + Unknown &unknownFromRow(unsigned row); + + /// Add a new row to the tableau and the associated data structures. The row + /// is initialized to zero. Returns the index of the added row. + unsigned addZeroRow(bool makeRestricted = false); + + /// Add a new row to the tableau and the associated data structures. + /// The new row is considered to be a constraint; the new Unknown lives in + /// con. + /// + /// Returns the index of the new Unknown in con. + unsigned addRow(ArrayRef coeffs, bool makeRestricted = false); + + /// Swap the two rows/columns in the tableau and associated data structures. + void swapRows(unsigned i, unsigned j); + void swapColumns(unsigned i, unsigned j); + + /// Enum to denote operations that need to be undone during rollback. + enum class UndoLogEntry { + RemoveLastConstraint, + RemoveLastVariable, + UnmarkEmpty, + UnmarkLastRedundant, + RestoreBasis + }; + + /// Undo the addition of the last constraint. This will only be called from + /// undo, when rolling back. + virtual void undoLastConstraint() = 0; + + /// Remove the last constraint, which must be in row orientation. + void removeLastConstraintRowOrientation(); + + /// Undo the operation represented by the log entry. + void undo(UndoLogEntry entry); + + /// Return the number of fixed columns, as described in the constructor above, + /// this is the number of columns beyond those for the variables in var. + unsigned getNumFixedCols() const { return usingBigM ? 3u : 2u; } + unsigned getNumRows() const { return tableau.getNumRows(); } + unsigned getNumColumns() const { return tableau.getNumColumns(); } + + /// Stores whether or not a big M column is present in the tableau. + bool usingBigM; + + /// The number of redundant rows in the tableau. These are the first + /// nRedundant rows. + unsigned nRedundant; + + /// The number of parameters. This must be consistent with the number of + /// Unknowns in `var` below that have `isSymbol` set to true. + unsigned nSymbol; + + /// The matrix representing the tableau. + IntMatrix tableau; + + /// This is true if the tableau has been detected to be empty, false + /// otherwise. + bool empty; + + /// Holds a log of operations, used for rolling back to a previous state. + SmallVector undoLog; + + /// Holds a vector of bases. The ith saved basis is the basis that should be + /// restored when processing the ith occurrence of UndoLogEntry::RestoreBasis + /// in undoLog. This is used by getSnapshotBasis. + SmallVector, 8> savedBases; + + /// These hold the indexes of the unknown at a given row or column position. + /// We keep these as signed integers since that makes it convenient to check + /// if an index corresponds to a variable or a constraint by checking the + /// sign. + /// + /// colUnknown is padded with two null indexes at the front since the first + /// two columns don't correspond to any unknowns. + SmallVector rowUnknown, colUnknown; + + /// These hold information about each unknown. + SmallVector con, var; +}; + +/// Simplex class using the lexicographic pivot rule. Used for lexicographic +/// optimization. The implementation of this class is based on the paper +/// "Parametric Integer Programming" by Paul Feautrier. +/// +/// This does not directly support negative-valued variables, so it uses the big +/// M parameter trick to make all the variables non-negative. Basically we +/// introduce an artificial variable M that is considered to have a value of +/// +infinity and instead of the variables x, y, z, we internally use variables +/// M + x, M + y, M + z, which are now guaranteed to be non-negative. See the +/// documentation for SimplexBase for more details. M is also considered to be +/// an integer that is divisible by everything. +/// +/// The whole algorithm is performed with M treated as a symbol; +/// it is just considered to be infinite throughout and it never appears in the +/// final outputs. We will deal with sample values throughout that may in +/// general be some affine expression involving M, like pM + q or aM + b. We can +/// compare these with each other. They have a total order: +/// +/// aM + b < pM + q iff a < p or (a == p and b < q). +/// In particular, aM + b < 0 iff a < 0 or (a == 0 and b < 0). +/// +/// When performing symbolic optimization, sample values will be affine +/// expressions in M and the symbols. For example, we could have sample values +/// aM + bS + c and pM + qS + r, where S is a symbol. Now we have +/// aM + bS + c < pM + qS + r iff (a < p) or (a == p and bS + c < qS + r). +/// bS + c < qS + r can be always true, always false, or neither, +/// depending on the set of values S can take. The symbols are always stored +/// in columns [3, 3 + nSymbols). For more details, see the +/// documentation for SymbolicLexSimplex. +/// +/// Initially all the constraints to be added are added as rows, with no attempt +/// to keep the tableau consistent. Pivots are only performed when some query +/// is made, such as a call to getRationalLexMin. Care is taken to always +/// maintain a lexicopositive basis transform, explained below. +/// +/// Let the variables be x = (x_1, ... x_n). +/// Let the symbols be s = (s_1, ... s_m). Let the basis unknowns at a +/// particular point be y = (y_1, ... y_n). We know that x = A*y + T*s + b for +/// some n x n matrix A, n x m matrix s, and n x 1 column vector b. We want +/// every column in A to be lexicopositive, i.e., have at least one non-zero +/// element, with the first such element being positive. This property is +/// preserved throughout the operation of LexSimplexBase. Note that on +/// construction, the basis transform A is the identity matrix and so every +/// column is lexicopositive. Note that for LexSimplexBase, for the tableau to +/// be consistent we must have non-negative sample values not only for the +/// constraints but also for the variables. So if the tableau is consistent then +/// x >= 0 and y >= 0, by which we mean every element in these vectors is +/// non-negative. (note that this is a different concept from lexicopositivity!) +class LexSimplexBase : public SimplexBase { +public: + ~LexSimplexBase() override = default; + + /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n + /// is the current number of variables, then the corresponding inequality is + /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0. + /// + /// This just adds the inequality to the tableau and does not try to create a + /// consistent tableau configuration. + void addInequality(ArrayRef coeffs) final; + + /// Get a snapshot of the current state. This is used for rolling back. + unsigned getSnapshot() { return SimplexBase::getSnapshotBasis(); } + +protected: + LexSimplexBase(unsigned nVar) : SimplexBase(nVar, /*mustUseBigM=*/true) {} + LexSimplexBase(unsigned nVar, const llvm::SmallBitVector &isSymbol) + : SimplexBase(nVar, /*mustUseBigM=*/true, isSymbol) {} + explicit LexSimplexBase(const IntegerRelation &constraints) + : LexSimplexBase(constraints.getNumVars()) { + intersectIntegerRelation(constraints); + } + explicit LexSimplexBase(const IntegerRelation &constraints, + const llvm::SmallBitVector &isSymbol) + : LexSimplexBase(constraints.getNumVars(), isSymbol) { + intersectIntegerRelation(constraints); + } + + /// Add new symbolic variables to the end of the list of variables. + void appendSymbol(); + + /// Try to move the specified row to column orientation while preserving the + /// lexicopositivity of the basis transform. The row must have a non-positive + /// sample value. If this is not possible, return failure. This occurs when + /// the constraints have no solution or the sample value is zero. + LogicalResult moveRowUnknownToColumn(unsigned row); + + /// Given a row that has a non-integer sample value, add an inequality to cut + /// away this fractional sample value from the polytope without removing any + /// integer points. The integer lexmin, if one existed, remains the same on + /// return. + /// + /// This assumes that the symbolic part of the sample is integral, + /// i.e., if the symbolic sample is (c + aM + b_1*s_1 + ... b_n*s_n)/d, + /// where s_1, ... s_n are symbols, this assumes that + /// (b_1*s_1 + ... + b_n*s_n)/s is integral. + /// + /// Return failure if the tableau became empty, and success if it didn't. + /// Failure status indicates that the polytope was integer empty. + LogicalResult addCut(unsigned row); + + /// Undo the addition of the last constraint. This is only called while + /// rolling back. + void undoLastConstraint() final; + + /// Given two potential pivot columns for a row, return the one that results + /// in the lexicographically smallest sample vector. The row's sample value + /// must be negative. If symbols are involved, the sample value must be + /// negative for all possible assignments to the symbols. + unsigned getLexMinPivotColumn(unsigned row, unsigned colA, + unsigned colB) const; +}; + +/// A class for lexicographic optimization without any symbols. This also +/// provides support for integer-exact redundancy and separateness checks. +class LexSimplex : public LexSimplexBase { +public: + explicit LexSimplex(unsigned nVar) : LexSimplexBase(nVar) {} + // Note that LexSimplex does NOT support symbolic lexmin; + // use SymbolicLexSimplex if that is required. LexSimplex ignores the VarKinds + // of the passed IntegerRelation. Symbols will be treated as ordinary vars. + explicit LexSimplex(const IntegerRelation &constraints) + : LexSimplexBase(constraints) {} + + /// Return the lexicographically minimum rational solution to the constraints. + MaybeOptimum> findRationalLexMin(); + + /// Return the lexicographically minimum integer solution to the constraints. + /// + /// Note: this should be used only when the lexmin is really needed. To obtain + /// any integer sample, use Simplex::findIntegerSample as that is more robust. + MaybeOptimum> findIntegerLexMin(); + + /// Return whether the specified inequality is redundant/separate for the + /// polytope. Redundant means every point satisfies the given inequality, and + /// separate means no point satisfies it. + /// + /// These checks are integer-exact. + bool isSeparateInequality(ArrayRef coeffs); + bool isRedundantInequality(ArrayRef coeffs); + +private: + /// Returns the current sample point, which may contain non-integer (rational) + /// coordinates. Returns an empty optimum when the tableau is empty. + /// + /// Returns an unbounded optimum when the big M parameter is used and a + /// variable has a non-zero big M coefficient, meaning its value is infinite + /// or unbounded. + MaybeOptimum> getRationalSample() const; + + /// Make the tableau configuration consistent. + LogicalResult restoreRationalConsistency(); + + /// Return whether the specified row is violated; + bool rowIsViolated(unsigned row) const; + + /// Get a constraint row that is violated, if one exists. + /// Otherwise, return an empty optional. + std::optional maybeGetViolatedRow() const; + + /// Get a row corresponding to a var that has a non-integral sample value, if + /// one exists. Otherwise, return an empty optional. + std::optional maybeGetNonIntegralVarRow() const; +}; + +/// Represents the result of a symbolic lexicographic optimization computation. +struct SymbolicLexOpt { + SymbolicLexOpt(const PresburgerSpace &space) + : lexopt(space), + unboundedDomain(PresburgerSet::getEmpty(space.getDomainSpace())) {} + + /// This maps assignments of symbols to the corresponding lexopt. + /// Takes no value when no integer sample exists for the assignment or if the + /// lexopt is unbounded. + PWMAFunction lexopt; + /// Contains all assignments to the symbols that made the lexopt unbounded. + /// Note that the symbols of the input set to the symbolic lexopt are dims + /// of this PrebsurgerSet. + PresburgerSet unboundedDomain; +}; + +/// A class to perform symbolic lexicographic optimization, +/// i.e., to find, for every assignment to the symbols the specified +/// `symbolDomain`, the lexicographically minimum value integer value attained +/// by the non-symbol variables. +/// +/// The input is a set parametrized by some symbols, i.e., the constant terms +/// of the constraints in the set are affine expressions in the symbols, and +/// every assignment to the symbols defines a non-symbolic set. +/// +/// Accordingly, the sample values of the rows in our tableau will be affine +/// expressions in the symbols, and every assignment to the symbols will define +/// a non-symbolic LexSimplex. We then run the algorithm of +/// LexSimplex::findIntegerLexMin simultaneously for every value of the symbols +/// in the domain. +/// +/// Often, the pivot to be performed is the same for all values of the symbols, +/// in which case we just do it. For example, if the symbolic sample of a row is +/// negative for all values in the symbol domain, the row needs to be pivoted +/// irrespective of the precise value of the symbols. To answer queries like +/// "Is this symbolic sample always negative in the symbol domain?", we maintain +/// a `LexSimplex domainSimplex` corresponding to the symbol domain. +/// +/// In other cases, it may be that the symbolic sample is violated at some +/// values in the symbol domain and not violated at others. In this case, +/// the pivot to be performed does depend on the value of the symbols. We +/// handle this by splitting the symbol domain. We run the algorithm for the +/// case where the row isn't violated, and then come back and run the case +/// where it is. +class SymbolicLexSimplex : public LexSimplexBase { +public: + /// `constraints` is the set for which the symbolic lexopt will be computed. + /// `symbolDomain` is the set of values of the symbols for which the lexopt + /// will be computed. `symbolDomain` should have a dim var for every symbol in + /// `constraints`, and no other vars. `isSymbol` specifies which vars of + /// `constraints` should be considered as symbols. + /// + /// The resulting SymbolicLexOpt's space will be compatible with that of + /// symbolDomain. + SymbolicLexSimplex(const IntegerRelation &constraints, + const IntegerPolyhedron &symbolDomain, + const llvm::SmallBitVector &isSymbol) + : LexSimplexBase(constraints, isSymbol), domainPoly(symbolDomain), + domainSimplex(symbolDomain) { + // TODO consider supporting this case. It amounts + // to just returning the input constraints. + assert(domainPoly.getNumVars() > 0 && + "there must be some non-symbols to optimize!"); + } + + /// An overload to select some subrange of ids as symbols for lexopt. + /// The symbol ids are the range of ids with absolute index + /// [symbolOffset, symbolOffset + symbolDomain.getNumVars()) + SymbolicLexSimplex(const IntegerRelation &constraints, unsigned symbolOffset, + const IntegerPolyhedron &symbolDomain) + : SymbolicLexSimplex(constraints, symbolDomain, + getSubrangeBitVector(constraints.getNumVars(), + symbolOffset, + symbolDomain.getNumVars())) {} + + /// An overload to select the symbols of `constraints` as symbols for lexopt. + SymbolicLexSimplex(const IntegerRelation &constraints, + const IntegerPolyhedron &symbolDomain) + : SymbolicLexSimplex(constraints, + constraints.getVarKindOffset(VarKind::Symbol), + symbolDomain) { + assert(constraints.getNumSymbolVars() == symbolDomain.getNumVars() && + "symbolDomain must have as many vars as constraints has symbols!"); + } + + /// The lexmin will be stored as a function `lexopt` from symbols to + /// non-symbols in the result. + /// + /// For some values of the symbols, the lexmin may be unbounded. + /// These parts of the symbol domain will be stored in `unboundedDomain`. + /// + /// The spaces of the sets in the result are compatible with the symbolDomain + /// passed in the SymbolicLexSimplex constructor. + SymbolicLexOpt computeSymbolicIntegerLexMin(); + +private: + /// Perform all pivots that do not require branching. + /// + /// Return failure if the tableau became empty, indicating that the polytope + /// is always integer empty in the current symbol domain. + /// Return success otherwise. + LogicalResult doNonBranchingPivots(); + + /// Get a row that is always violated in the current domain, if one exists. + std::optional maybeGetAlwaysViolatedRow(); + + /// Get a row corresponding to a variable with non-integral sample value, if + /// one exists. + std::optional maybeGetNonIntegralVarRow(); + + /// Given a row that has a non-integer sample value, cut away this fractional + /// sample value witahout removing any integer points, i.e., the integer + /// lexmin, if it exists, remains the same after a call to this function. This + /// may add constraints or local variables to the tableau, as well as to the + /// domain. + /// + /// Returns whether the cut constraint could be enforced, i.e. failure if the + /// cut made the polytope empty, and success if it didn't. Failure status + /// indicates that the polytope is always integer empty in the symbol domain + /// at the time of the call. (This function may modify the symbol domain, but + /// failure statu indicates that the polytope was empty for all symbol values + /// in the initial domain.) + LogicalResult addSymbolicCut(unsigned row); + + /// Get the numerator of the symbolic sample of the specific row. + /// This is an affine expression in the symbols with integer coefficients. + /// The last element is the constant term. This ignores the big M coefficient. + SmallVector getSymbolicSampleNumerator(unsigned row) const; + + /// Get an affine inequality in the symbols with integer coefficients that + /// holds iff the symbolic sample of the specified row is non-negative. + SmallVector getSymbolicSampleIneq(unsigned row) const; + + /// Return whether all the coefficients of the symbolic sample are integers. + /// + /// This does not consult the domain to check if the specified expression + /// is always integral despite coefficients being fractional. + bool isSymbolicSampleIntegral(unsigned row) const; + + /// Record a lexmin. The tableau must be consistent with all variables + /// having symbolic samples with integer coefficients. + void recordOutput(SymbolicLexOpt &result) const; + + /// The symbol domain. + IntegerPolyhedron domainPoly; + /// Simplex corresponding to the symbol domain. + LexSimplex domainSimplex; +}; + +/// The Simplex class uses the Normal pivot rule and supports integer emptiness +/// checks as well as detecting redundancies. +/// +/// The Simplex class supports redundancy checking via detectRedundant and +/// isMarkedRedundant. A redundant constraint is one which is never violated as +/// long as the other constraints are not violated, i.e., removing a redundant +/// constraint does not change the set of solutions to the constraints. As a +/// heuristic, constraints that have been marked redundant can be ignored for +/// most operations. Therefore, these constraints are kept in rows 0 to +/// nRedundant - 1, where nRedundant is a member variable that tracks the number +/// of constraints that have been marked redundant. +/// +/// Finding an integer sample is done with the Generalized Basis Reduction +/// algorithm. See the documentation for findIntegerSample and reduceBasis. +class Simplex : public SimplexBase { +public: + enum class Direction { Up, Down }; + + Simplex() = delete; + explicit Simplex(unsigned nVar) : SimplexBase(nVar, /*mustUseBigM=*/false) {} + explicit Simplex(const IntegerRelation &constraints) + : Simplex(constraints.getNumVars()) { + intersectIntegerRelation(constraints); + } + ~Simplex() override = default; + + /// Add an inequality to the tableau. If coeffs is c_0, c_1, ... c_n, where n + /// is the current number of variables, then the corresponding inequality is + /// c_n + c_0*x_0 + c_1*x_1 + ... + c_{n-1}*x_{n-1} >= 0. + /// + /// This also tries to restore the tableau configuration to a consistent + /// state and marks the Simplex empty if this is not possible. + void addInequality(ArrayRef coeffs) final; + + /// Compute the maximum or minimum value of the given row, depending on + /// direction. The specified row is never pivoted. On return, the row may + /// have a negative sample value if the direction is down. + /// + /// Returns a Fraction denoting the optimum, or a null value if no optimum + /// exists, i.e., if the expression is unbounded in this direction. + MaybeOptimum computeRowOptimum(Direction direction, unsigned row); + + /// Compute the maximum or minimum value of the given expression, depending on + /// direction. Should not be called when the Simplex is empty. + /// + /// Returns a Fraction denoting the optimum, or a null value if no optimum + /// exists, i.e., if the expression is unbounded in this direction. + MaybeOptimum computeOptimum(Direction direction, + ArrayRef coeffs); + + /// Returns whether the perpendicular of the specified constraint is a + /// is a direction along which the polytope is bounded. + bool isBoundedAlongConstraint(unsigned constraintIndex); + + /// Returns whether the specified constraint has been marked as redundant. + /// Constraints are numbered from 0 starting at the first added inequality. + /// Equalities are added as a pair of inequalities and so correspond to two + /// inequalities with successive indices. + bool isMarkedRedundant(unsigned constraintIndex) const; + + /// Finds a subset of constraints that is redundant, i.e., such that + /// the set of solutions does not change if these constraints are removed. + /// Marks these constraints as redundant. Whether a specific constraint has + /// been marked redundant can be queried using isMarkedRedundant. + /// + /// The first overload only tries to find redundant constraints with indices + /// in the range [offset, offset + count), by scanning constraints from left + /// to right in this range. If `count` is not provided, all constraints + /// starting at `offset` are scanned, and if neither are provided, all + /// constraints are scanned, starting from 0 and going to the last constraint. + /// + /// As an example, in the set (x) : (x >= 0, x >= 0, x >= 0), calling + /// `detectRedundant` with no parameters will result in the first two + /// constraints being marked redundant. All copies cannot be marked redundant + /// because removing all the constraints changes the set. The first two are + /// the ones marked redundant because we scan from left to right. Thus, when + /// there is some preference among the constraints as to which should be + /// marked redundant with priority when there are multiple possibilities, this + /// could be accomplished by succesive calls to detectRedundant(offset, + /// count). + void detectRedundant(unsigned offset, unsigned count); + void detectRedundant(unsigned offset) { + assert(offset <= con.size() && "invalid offset!"); + detectRedundant(offset, con.size() - offset); + } + void detectRedundant() { detectRedundant(0, con.size()); } + + /// Returns a (min, max) pair denoting the minimum and maximum integer values + /// of the given expression. If no integer value exists, both results will be + /// of kind Empty. + std::pair, MaybeOptimum> + computeIntegerBounds(ArrayRef coeffs); + + /// Check if the simplex takes only one rational value along the + /// direction of `coeffs`. + /// + /// `this` must be nonempty. + bool isFlatAlong(ArrayRef coeffs); + + /// Returns true if the polytope is unbounded, i.e., extends to infinity in + /// some direction. Otherwise, returns false. + bool isUnbounded(); + + /// Make a tableau to represent a pair of points in the given tableaus, one in + /// tableau A and one in B. + static Simplex makeProduct(const Simplex &a, const Simplex &b); + + /// Returns an integer sample point if one exists, or std::nullopt + /// otherwise. This should only be called for bounded sets. + std::optional> findIntegerSample(); + + enum class IneqType { Redundant, Cut, Separate }; + + /// Returns the type of the inequality with coefficients `coeffs`. + /// + /// Possible types are: + /// Redundant The inequality is satisfied in the polytope + /// Cut The inequality is satisfied by some points, but not by others + /// Separate The inequality is not satisfied by any point + IneqType findIneqType(ArrayRef coeffs); + + /// Check if the specified inequality already holds in the polytope. + bool isRedundantInequality(ArrayRef coeffs); + + /// Check if the specified equality already holds in the polytope. + bool isRedundantEquality(ArrayRef coeffs); + + /// Returns true if this Simplex's polytope is a rational subset of `rel`. + /// Otherwise, returns false. + bool isRationalSubsetOf(const IntegerRelation &rel); + + /// Returns the current sample point if it is integral. Otherwise, returns + /// std::nullopt. + std::optional> getSamplePointIfIntegral() const; + + /// Returns the current sample point, which may contain non-integer (rational) + /// coordinates. Returns an empty optional when the tableau is empty. + std::optional> getRationalSample() const; + +private: + friend class GBRSimplex; + + /// Restore the unknown to a non-negative sample value. + /// + /// Returns success if the unknown was successfully restored to a non-negative + /// sample value, failure otherwise. + LogicalResult restoreRow(Unknown &u); + + /// Find a pivot to change the sample value of row in the specified + /// direction while preserving tableau consistency, except that if the + /// direction is down then the pivot may make the specified row take a + /// negative value. The returned pivot row will be row if and only if the + /// unknown is unbounded in the specified direction. + /// + /// Returns a (row, col) pair denoting a pivot, or an empty Optional if + /// no valid pivot exists. + std::optional findPivot(int row, Direction direction) const; + + /// Find a row that can be used to pivot the column in the specified + /// direction. If skipRow is not null, then this row is excluded + /// from consideration. The returned pivot will maintain all constraints + /// except the column itself and skipRow, if it is set. (if these unknowns + /// are restricted). + /// + /// Returns the row to pivot to, or an empty Optional if the column + /// is unbounded in the specified direction. + std::optional findPivotRow(std::optional skipRow, + Direction direction, unsigned col) const; + + /// Undo the addition of the last constraint while preserving tableau + /// consistency. + void undoLastConstraint() final; + + /// Compute the maximum or minimum of the specified Unknown, depending on + /// direction. The specified unknown may be pivoted. If the unknown is + /// restricted, it will have a non-negative sample value on return. + /// Should not be called if the Simplex is empty. + /// + /// Returns a Fraction denoting the optimum, or a null value if no optimum + /// exists, i.e., if the expression is unbounded in this direction. + MaybeOptimum computeOptimum(Direction direction, Unknown &u); + + /// Mark the specified unknown redundant. This operation is added to the undo + /// log and will be undone by rollbacks. The specified unknown must be in row + /// orientation. + void markRowRedundant(Unknown &u); + + /// Reduce the given basis, starting at the specified level, using general + /// basis reduction. + void reduceBasis(IntMatrix &basis, unsigned level); +}; + +/// Takes a snapshot of the simplex state on construction and rolls back to the +/// snapshot on destruction. +/// +/// Useful for performing operations in a "transient context", all changes from +/// which get rolled back on scope exit. +class SimplexRollbackScopeExit { +public: + SimplexRollbackScopeExit(SimplexBase &simplex) : simplex(simplex) { + snapshot = simplex.getSnapshot(); + }; + ~SimplexRollbackScopeExit() { simplex.rollback(snapshot); } + +private: + SimplexBase &simplex; + unsigned snapshot; +}; + +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_SIMPLEX_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Utils.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0e6d18279d67ed5a6cd0cd5fd4d1f77110281b19 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/Presburger/Utils.h @@ -0,0 +1,348 @@ +//===- Utils.h - General utilities for Presburger library ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Utility functions required by the Presburger Library. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_PRESBURGER_UTILS_H +#define MLIR_ANALYSIS_PRESBURGER_UTILS_H + +#include "mlir/Analysis/Presburger/Matrix.h" +#include "llvm/ADT/DynamicAPInt.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallBitVector.h" +#include "llvm/Support/raw_ostream.h" +#include +#include + +namespace mlir { +namespace presburger { +class IntegerRelation; + +/// This class represents the result of operations optimizing something subject +/// to some constraints. If the constraints were not satisfiable the, kind will +/// be Empty. If the optimum is unbounded, the kind is Unbounded, and if the +/// optimum is bounded, the kind will be Bounded and `optimum` holds the optimal +/// value. +enum class OptimumKind { Empty, Unbounded, Bounded }; +template +class MaybeOptimum { +public: +private: + OptimumKind kind = OptimumKind::Empty; + T optimum; + +public: + MaybeOptimum() = default; + MaybeOptimum(OptimumKind kind) : kind(kind) { + assert(kind != OptimumKind::Bounded && + "Bounded optima should be constructed by specifying the optimum!"); + } + MaybeOptimum(const T &optimum) + : kind(OptimumKind::Bounded), optimum(optimum) {} + + OptimumKind getKind() const { return kind; } + bool isBounded() const { return kind == OptimumKind::Bounded; } + bool isUnbounded() const { return kind == OptimumKind::Unbounded; } + bool isEmpty() const { return kind == OptimumKind::Empty; } + + std::optional getOptimumIfBounded() const { return optimum; } + const T &getBoundedOptimum() const { + assert(kind == OptimumKind::Bounded && + "This should be called only for bounded optima"); + return optimum; + } + T &getBoundedOptimum() { + assert(kind == OptimumKind::Bounded && + "This should be called only for bounded optima"); + return optimum; + } + const T &operator*() const { return getBoundedOptimum(); } + T &operator*() { return getBoundedOptimum(); } + const T *operator->() const { return &getBoundedOptimum(); } + T *operator->() { return &getBoundedOptimum(); } + bool operator==(const MaybeOptimum &other) const { + if (kind != other.kind) + return false; + if (kind != OptimumKind::Bounded) + return true; + return optimum == other.optimum; + } + + // Given f that takes a T and returns a U, convert this `MaybeOptimum` to + // a `MaybeOptimum` by applying `f` to the bounded optimum if it exists, or + // returning a MaybeOptimum of the same kind otherwise. + template + auto map(const Function &f) const & -> MaybeOptimum { + if (kind == OptimumKind::Bounded) + return f(optimum); + return kind; + } +}; + +/// `ReprKind` enum is used to set the constraint type in `MaybeLocalRepr`. +enum class ReprKind { Inequality, Equality, None }; + +/// `MaybeLocalRepr` contains the indices of the constraints that can be +/// expressed as a floordiv of an affine function. If it's an `equality` +/// constraint, `equalityIdx` is set, in case of `inequality` the +/// `lowerBoundIdx` and `upperBoundIdx` is set. By default the kind attribute is +/// set to None. +struct MaybeLocalRepr { + ReprKind kind = ReprKind::None; + explicit operator bool() const { return kind != ReprKind::None; } + union { + unsigned equalityIdx; + struct { + unsigned lowerBoundIdx, upperBoundIdx; + } inequalityPair; + } repr; +}; + +/// Class storing division representation of local variables of a constraint +/// system. The coefficients of the dividends are stored in order: +/// [nonLocalVars, localVars, constant]. Each local variable may or may not have +/// a representation. If the local does not have a representation, the dividend +/// of the division has no meaning and the denominator is zero. If it has a +/// representation, the denominator will be positive. +/// +/// The i^th division here, represents the division representation of the +/// variable at position `divOffset + i` in the constraint system. +class DivisionRepr { +public: + DivisionRepr(unsigned numVars, unsigned numDivs) + : dividends(numDivs, numVars + 1), denoms(numDivs, DynamicAPInt(0)) {} + + DivisionRepr(unsigned numVars) : dividends(0, numVars + 1) {} + + unsigned getNumVars() const { return dividends.getNumColumns() - 1; } + unsigned getNumDivs() const { return dividends.getNumRows(); } + unsigned getNumNonDivs() const { return getNumVars() - getNumDivs(); } + // Get the offset from where division variables start. + unsigned getDivOffset() const { return getNumVars() - getNumDivs(); } + + // Check whether the `i^th` division has a division representation or not. + bool hasRepr(unsigned i) const { return denoms[i] != 0; } + // Check whether all the divisions have a division representation or not. + bool hasAllReprs() const { return !llvm::is_contained(denoms, 0); } + + // Clear the division representation of the i^th local variable. + void clearRepr(unsigned i) { denoms[i] = 0; } + + // Get the dividend of the `i^th` division. + MutableArrayRef getDividend(unsigned i) { + return dividends.getRow(i); + } + ArrayRef getDividend(unsigned i) const { + return dividends.getRow(i); + } + + // For a given point containing values for each variable other than the + // division variables, try to find the values for each division variable from + // their division representation. + SmallVector, 4> + divValuesAt(ArrayRef point) const; + + // Get the `i^th` denominator. + DynamicAPInt &getDenom(unsigned i) { return denoms[i]; } + DynamicAPInt getDenom(unsigned i) const { return denoms[i]; } + + ArrayRef getDenoms() const { return denoms; } + + void setDiv(unsigned i, ArrayRef dividend, + const DynamicAPInt &divisor) { + dividends.setRow(i, dividend); + denoms[i] = divisor; + } + + // Find the greatest common divisor (GCD) of the dividends and divisor for + // each valid division. Divide the dividends and divisor by the GCD to + // simplify the expression. + void normalizeDivs(); + + void insertDiv(unsigned pos, ArrayRef dividend, + const DynamicAPInt &divisor); + void insertDiv(unsigned pos, unsigned num = 1); + + /// Removes duplicate divisions. On every possible duplicate division found, + /// `merge(i, j)`, where `i`, `j` are current index of the duplicate + /// divisions, is called and division at index `j` is merged into division at + /// index `i`. If `merge(i, j)` returns `true`, the divisions are merged i.e. + /// `j^th` division gets eliminated and it's each instance is replaced by + /// `i^th` division. If it returns `false`, the divisions are not merged. + /// `merge` can also do side effects, For example it can merge the local + /// variables in IntegerRelation. + void + removeDuplicateDivs(llvm::function_ref merge); + + void print(raw_ostream &os) const; + void dump() const; + +private: + /// Each row of the Matrix represents a single division dividend. The + /// `i^th` row represents the dividend of the variable at `divOffset + i` + /// in the constraint system (and the `i^th` local variable). + IntMatrix dividends; + + /// Denominators of each division. If a denominator of a division is `0`, the + /// division variable is considered to not have a division representation. + /// Otherwise, the denominator is positive. + SmallVector denoms; +}; + +/// If `q` is defined to be equal to `expr floordiv d`, this equivalent to +/// saying that `q` is an integer and `q` is subject to the inequalities +/// `0 <= expr - d*q <= c - 1` (quotient remainder theorem). +/// +/// Rearranging, we get the bounds on `q`: d*q <= expr <= d*q + d - 1. +/// +/// `getDivUpperBound` returns `d*q <= expr`, and +/// `getDivLowerBound` returns `expr <= d*q + d - 1`. +/// +/// The parameter `dividend` corresponds to `expr` above, `divisor` to `d`, and +/// `localVarIdx` to the position of `q` in the coefficient list. +/// +/// The coefficient of `q` in `dividend` must be zero, as it is not allowed for +/// local variable to be a floor division of an expression involving itself. +/// The divisor must be positive. +SmallVector getDivUpperBound(ArrayRef dividend, + const DynamicAPInt &divisor, + unsigned localVarIdx); +SmallVector getDivLowerBound(ArrayRef dividend, + const DynamicAPInt &divisor, + unsigned localVarIdx); + +llvm::SmallBitVector getSubrangeBitVector(unsigned len, unsigned setOffset, + unsigned numSet); + +/// Check if the pos^th variable can be expressed as a floordiv of an affine +/// function of other variables (where the divisor is a positive constant). +/// `foundRepr` contains a boolean for each variable indicating if the +/// explicit representation for that variable has already been computed. +/// Return the given array as an array of DynamicAPInts. +SmallVector getDynamicAPIntVec(ArrayRef range); +/// Return the given array as an array of int64_t. +SmallVector getInt64Vec(ArrayRef range); + +/// Returns the `MaybeLocalRepr` struct which contains the indices of the +/// constraints that can be expressed as a floordiv of an affine function. If +/// the representation could be computed, `dividend` and `divisor` are set, +/// in which case, denominator will be positive. If the representation could +/// not be computed, the kind attribute in `MaybeLocalRepr` is set to None. +MaybeLocalRepr computeSingleVarRepr(const IntegerRelation &cst, + ArrayRef foundRepr, unsigned pos, + MutableArrayRef dividend, + DynamicAPInt &divisor); + +/// The following overload using int64_t is required for a callsite in +/// AffineStructures.h. +MaybeLocalRepr computeSingleVarRepr(const IntegerRelation &cst, + ArrayRef foundRepr, unsigned pos, + SmallVector ÷nd, + unsigned &divisor); + +/// Given two relations, A and B, add additional local vars to the sets such +/// that both have the union of the local vars in each set, without changing +/// the set of points that lie in A and B. +/// +/// While taking union, if a local var in any set has a division representation +/// which is a duplicate of division representation, of another local var in any +/// set, it is not added to the final union of local vars and is instead merged. +/// +/// On every possible merge, `merge(i, j)` is called. `i`, `j` are position +/// of local variables in both sets which are being merged. If `merge(i, j)` +/// returns true, the divisions are merged, otherwise the divisions are not +/// merged. +void mergeLocalVars(IntegerRelation &relA, IntegerRelation &relB, + llvm::function_ref merge); + +/// Compute the gcd of the range. +DynamicAPInt gcdRange(ArrayRef range); + +/// Divide the range by its gcd and return the gcd. +DynamicAPInt normalizeRange(MutableArrayRef range); + +/// Normalize the given (numerator, denominator) pair by dividing out the +/// common factors between them. The numerator here is an affine expression +/// with integer coefficients. The denominator must be positive. +void normalizeDiv(MutableArrayRef num, DynamicAPInt &denom); + +/// Return `coeffs` with all the elements negated. +SmallVector getNegatedCoeffs(ArrayRef coeffs); + +/// Return the complement of the given inequality. +/// +/// The complement of a_1 x_1 + ... + a_n x_ + c >= 0 is +/// a_1 x_1 + ... + a_n x_ + c < 0, i.e., -a_1 x_1 - ... - a_n x_ - c - 1 >= 0, +/// since all the variables are constrained to be integers. +SmallVector getComplementIneq(ArrayRef ineq); + +/// Compute the dot product of two vectors. +/// The vectors must have the same sizes. +Fraction dotProduct(ArrayRef a, ArrayRef b); + +/// Find the product of two polynomials, each given by an array of +/// coefficients. +std::vector multiplyPolynomials(ArrayRef a, + ArrayRef b); + +bool isRangeZero(ArrayRef arr); + +/// Example usage: +/// Print .12, 3.4, 56.7 +/// preAlign = ".", minSpacing = 1, +/// .12 .12 +/// 3.4 3.4 +/// 56.7 56.7 +struct PrintTableMetrics { + // If unknown, set to 0 and pass the struct into updatePrintMetrics. + unsigned maxPreIndent; + unsigned maxPostIndent; + std::string preAlign; +}; + +/// Iterate over each val in the table and update 'm' where +/// .maxPreIndent and .maxPostIndent are initialized to 0. +/// class T is any type that can be handled by llvm::raw_string_ostream. +template +void updatePrintMetrics(T val, PrintTableMetrics &m) { + std::string str; + llvm::raw_string_ostream(str) << val; + if (str.empty()) + return; + unsigned preIndent = str.find(m.preAlign); + preIndent = (preIndent != (unsigned)std::string::npos) ? preIndent + 1 : 0; + m.maxPreIndent = std::max(m.maxPreIndent, preIndent); + m.maxPostIndent = + std::max(m.maxPostIndent, (unsigned int)(str.length() - preIndent)); +} + +/// Print val in the table with metrics specified in 'm'. +template +void printWithPrintMetrics(raw_ostream &os, T val, unsigned minSpacing, + const PrintTableMetrics &m) { + std::string str; + llvm::raw_string_ostream(str) << val; + unsigned preIndent; + if (!str.empty()) { + preIndent = str.find(m.preAlign); + preIndent = (preIndent != (unsigned)std::string::npos) ? preIndent + 1 : 0; + } else { + preIndent = 0; + } + for (unsigned i = 0; i < (minSpacing + m.maxPreIndent - preIndent); ++i) + os << " "; + os << str; + for (unsigned i = 0; i < m.maxPostIndent - (str.length() - preIndent); ++i) + os << " "; +} +} // namespace presburger +} // namespace mlir + +#endif // MLIR_ANALYSIS_PRESBURGER_UTILS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/SliceAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/SliceAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..d082d2d9f758b7438653ab0159d8108719a10ca6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/SliceAnalysis.h @@ -0,0 +1,267 @@ +//===- SliceAnalysis.h - Analysis for Transitive UseDef chains --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_SLICEANALYSIS_H_ +#define MLIR_ANALYSIS_SLICEANALYSIS_H_ + +#include + +#include "mlir/Support/LLVM.h" + +#include "llvm/ADT/SetVector.h" + +namespace mlir { +class BlockArgument; +class Operation; +class Value; + +struct SliceOptions { + /// Type of the condition to limit the propagation of transitive use-defs. + /// This can be used in particular to limit the propagation to a given Scope + /// or to avoid passing through certain types of operation in a configurable + /// manner. + using TransitiveFilter = std::function; + TransitiveFilter filter = nullptr; + + /// Include the top level op in the slice. + bool inclusive = false; + + // TODO: Remove this alias once downstream users are updated. + SliceOptions() {} + SliceOptions(TransitiveFilter filter) : filter(std::move(filter)) {} +}; + +// TODO: Remove this alias once downstream users are updated. +using TransitiveFilter = SliceOptions::TransitiveFilter; + +struct BackwardSliceOptions : public SliceOptions { + using SliceOptions::SliceOptions; + /// When omitBlockArguments is true, the backward slice computation omits + /// traversing any block arguments. When omitBlockArguments is false, the + /// backward slice computation traverses block arguments and asserts that the + /// parent op has a single region with a single block. + bool omitBlockArguments = false; + + /// When omitUsesFromAbove is true, the backward slice computation omits + /// traversing values that are captured from above. + /// TODO: this should default to `false` after users have been updated. + bool omitUsesFromAbove = true; +}; + +using ForwardSliceOptions = SliceOptions; + +/// Fills `forwardSlice` with the computed forward slice (i.e. all +/// the transitive uses of op), **without** including that operation. +/// +/// This additionally takes a TransitiveFilter which acts as a frontier: +/// when looking at uses transitively, an operation that does not pass the +/// filter is never propagated through. This allows in particular to carve out +/// the scope within a ForOp or the scope within an IfOp. +/// +/// The implementation traverses the use chains in postorder traversal for +/// efficiency reasons: if an operation is already in `forwardSlice`, no +/// need to traverse its uses again. Since use-def chains form a DAG, this +/// terminates. +/// +/// Upon return to the root call, `forwardSlice` is filled with a +/// postorder list of uses (i.e. a reverse topological order). To get a proper +/// topological order, we just reverse the order in `forwardSlice` before +/// returning. +/// +/// Example starting from node 0 +/// ============================ +/// +/// 0 +/// ___________|___________ +/// 1 2 3 4 +/// |_______| |______| +/// | | | +/// | 5 6 +/// |___|_____________| +/// | | +/// 7 8 +/// |_______________| +/// | +/// 9 +/// +/// Assuming all local orders match the numbering order: +/// 1. after getting back to the root getForwardSlice, `forwardSlice` may +/// contain: +/// {9, 7, 8, 5, 1, 2, 6, 3, 4} +/// 2. reversing the result of 1. gives: +/// {4, 3, 6, 2, 1, 5, 8, 7, 9} +/// +void getForwardSlice(Operation *op, SetVector *forwardSlice, + const ForwardSliceOptions &options = {}); + +/// Value-rooted version of `getForwardSlice`. Return the union of all forward +/// slices for the uses of the value `root`. +void getForwardSlice(Value root, SetVector *forwardSlice, + const ForwardSliceOptions &options = {}); + +/// Fills `backwardSlice` with the computed backward slice (i.e. +/// all the transitive defs of op), **without** including that operation. +/// +/// This additionally takes a TransitiveFilter which acts as a frontier: +/// when looking at defs transitively, an operation that does not pass the +/// filter is never propagated through. This allows in particular to carve out +/// the scope within a ForOp or the scope within an IfOp. +/// +/// The implementation traverses the def chains in postorder traversal for +/// efficiency reasons: if an operation is already in `backwardSlice`, no +/// need to traverse its definitions again. Since useuse-def chains form a DAG, +/// this terminates. +/// +/// Upon return to the root call, `backwardSlice` is filled with a +/// postorder list of defs. This happens to be a topological order, from the +/// point of view of the use-def chains. +/// +/// Example starting from node 8 +/// ============================ +/// +/// 1 2 3 4 +/// |_______| |______| +/// | | | +/// | 5 6 +/// |___|_____________| +/// | | +/// 7 8 +/// |_______________| +/// | +/// 9 +/// +/// Assuming all local orders match the numbering order: +/// {1, 2, 5, 3, 4, 6} +/// +/// This function returns whether the backwards slice was able to be +/// successfully computed, and failure if it was unable to determine the slice. +LogicalResult getBackwardSlice(Operation *op, + SetVector *backwardSlice, + const BackwardSliceOptions &options = {}); + +/// Value-rooted version of `getBackwardSlice`. Return the union of all backward +/// slices for the op defining or owning the value `root`. +LogicalResult getBackwardSlice(Value root, + SetVector *backwardSlice, + const BackwardSliceOptions &options = {}); + +/// Iteratively computes backward slices and forward slices until +/// a fixed point is reached. Returns an `SetVector` which +/// **includes** the original operation. +/// +/// This allows building a slice (i.e. multi-root DAG where everything +/// that is reachable from an Value in forward and backward direction is +/// contained in the slice). +/// This is the abstraction we need to materialize all the operations for +/// supervectorization without worrying about orderings and Value +/// replacements. +/// +/// Example starting from any node +/// ============================== +/// +/// 1 2 3 4 +/// |_______| |______| +/// | | | | +/// | 5 6___| +/// |___|_____________| | +/// | | | +/// 7 8 | +/// |_______________| | +/// | | +/// 9 10 +/// +/// Return the whole DAG in some topological order. +/// +/// The implementation works by just filling up a worklist with iterative +/// alternate calls to `getBackwardSlice` and `getForwardSlice`. +/// +/// The following section describes some additional implementation +/// considerations for a potentially more efficient implementation but they are +/// just an intuition without proof, we still use a worklist for now. +/// +/// Additional implementation considerations +/// ======================================== +/// Consider the defs-op-uses hourglass. +/// ____ +/// \ / defs (in some topological order) +/// \/ +/// op +/// /\ +/// / \ uses (in some topological order) +/// /____\ +/// +/// We want to iteratively apply `getSlice` to construct the whole +/// list of Operation that are reachable by (use|def)+ from op. +/// We want the resulting slice in topological order. +/// Ideally we would like the ordering to be maintained in-place to avoid +/// copying Operation at each step. Keeping this ordering by construction +/// seems very unclear, so we list invariants in the hope of seeing whether +/// useful properties pop up. +/// +/// In the following: +/// we use |= for set inclusion; +/// we use << for set topological ordering (i.e. each pair is ordered). +/// +/// Assumption: +/// =========== +/// We wish to maintain the following property by a recursive argument: +/// """ +/// defs << {op} < +getSlice(Operation *op, const BackwardSliceOptions &backwardSliceOptions = {}, + const ForwardSliceOptions &forwardSliceOptions = {}); + +/// Utility to match a generic reduction given a list of iteration-carried +/// arguments, `iterCarriedArgs` and the position of the potential reduction +/// argument within the list, `redPos`. If a reduction is matched, returns the +/// reduced value and the topologically-sorted list of combiner operations +/// involved in the reduction. Otherwise, returns a null value. +/// +/// The matching algorithm relies on the following invariants, which are subject +/// to change: +/// 1. The first combiner operation must be a binary operation with the +/// iteration-carried value and the reduced value as operands. +/// 2. The iteration-carried value and combiner operations must be side +/// effect-free, have single result and a single use. +/// 3. Combiner operations must be immediately nested in the region op +/// performing the reduction. +/// 4. Reduction def-use chain must end in a terminator op that yields the +/// next iteration/output values in the same order as the iteration-carried +/// values in `iterCarriedArgs`. +/// 5. `iterCarriedArgs` must contain all the iteration-carried/output values +/// of the region op performing the reduction. +/// +/// This utility is generic enough to detect reductions involving multiple +/// combiner operations (disabled for now) across multiple dialects, including +/// Linalg, Affine and SCF. For the sake of genericity, it does not return +/// specific enum values for the combiner operations since its goal is also +/// matching reductions without pre-defined semantics in core MLIR. It's up to +/// each client to make sense out of the list of combiner operations. It's also +/// up to each client to check for additional invariants on the expected +/// reductions not covered by this generic matching. +Value matchReduction(ArrayRef iterCarriedArgs, unsigned redPos, + SmallVectorImpl &combinerOps); + +} // namespace mlir + +#endif // MLIR_ANALYSIS_SLICEANALYSIS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/SliceWalk.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/SliceWalk.h new file mode 100644 index 0000000000000000000000000000000000000000..eb9ced2ff63b68d2c9a4d0e0a4672816044d8e1f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/SliceWalk.h @@ -0,0 +1,98 @@ +//===- SliceWalk.h - Helpers for performing IR slice walks ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_SLICEWALK_H +#define MLIR_ANALYSIS_SLICEWALK_H + +#include "mlir/IR/ValueRange.h" + +namespace mlir { + +/// A class to signal how to proceed with the walk of the backward slice: +/// - Interrupt: Stops the walk. +/// - AdvanceTo: Continues the walk to user-specified values. +/// - Skip: Continues the walk, but skips the predecessors of the current value. +class WalkContinuation { +public: + enum class WalkAction { + /// Stops the walk. + Interrupt, + /// Continues the walk to user-specified values. + AdvanceTo, + /// Continues the walk, but skips the predecessors of the current value. + Skip + }; + + WalkContinuation(WalkAction action, mlir::ValueRange nextValues) + : action(action), nextValues(nextValues) {} + + /// Allows diagnostics to interrupt the walk. + explicit WalkContinuation(mlir::Diagnostic &&) + : action(WalkAction::Interrupt) {} + + /// Allows diagnostics to interrupt the walk. + explicit WalkContinuation(mlir::InFlightDiagnostic &&) + : action(WalkAction::Interrupt) {} + + /// Creates a continuation that interrupts the walk. + static WalkContinuation interrupt() { + return WalkContinuation(WalkAction::Interrupt, {}); + } + + /// Creates a continuation that adds the user-specified `nextValues` to the + /// work list and advances the walk. + static WalkContinuation advanceTo(mlir::ValueRange nextValues) { + return WalkContinuation(WalkAction::AdvanceTo, nextValues); + } + + /// Creates a continuation that advances the walk without adding any + /// predecessor values to the work list. + static WalkContinuation skip() { + return WalkContinuation(WalkAction::Skip, {}); + } + + /// Returns true if the walk was interrupted. + bool wasInterrupted() const { return action == WalkAction::Interrupt; } + + /// Returns true if the walk was skipped. + bool wasSkipped() const { return action == WalkAction::Skip; } + + /// Returns true if the walk was advanced to user-specified values. + bool wasAdvancedTo() const { return action == WalkAction::AdvanceTo; } + + /// Returns the next values to continue the walk with. + mlir::ArrayRef getNextValues() const { return nextValues; } + +private: + WalkAction action; + /// The next values to continue the walk with. + mlir::SmallVector nextValues; +}; + +/// A callback that is invoked for each value encountered during the walk of the +/// slice. The callback takes the current value, and returns the walk +/// continuation, which determines if the walk should proceed and if yes, with +/// which values. +using WalkCallback = mlir::function_ref; + +/// Walks the slice starting from the `rootValues` using a depth-first +/// traversal. The walk calls the provided `walkCallback` for each value +/// encountered in the slice and uses the returned walk continuation to +/// determine how to proceed. +WalkContinuation walkSlice(mlir::ValueRange rootValues, + WalkCallback walkCallback); + +/// Computes a vector of all control predecessors of `value`. Relies on +/// RegionBranchOpInterface, BranchOpInterface, and SelectLikeOpInterface to +/// determine predecessors. Returns nullopt if `value` has no predecessors or +/// when the relevant operations are missing the interface implementations. +std::optional> getControlFlowPredecessors(Value value); + +} // namespace mlir + +#endif // MLIR_ANALYSIS_SLICEWALK_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/SymbolTableAnalysis.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/SymbolTableAnalysis.h new file mode 100644 index 0000000000000000000000000000000000000000..145627e43aee1232c0972d0d8d8a15ab52552575 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/SymbolTableAnalysis.h @@ -0,0 +1,54 @@ +//===- SymbolTableAnalysis.h - Analysis for cached symbol tables --*- C++ -*-=// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_SYMBOLTABLEANALYSIS_H +#define MLIR_ANALYSIS_SYMBOLTABLEANALYSIS_H + +#include "mlir/IR/SymbolTable.h" +#include "mlir/Pass/AnalysisManager.h" + +namespace mlir { +/// This is a simple analysis that contains a symbol table collection and, for +/// simplicity, a reference to the top-level symbol table. This allows symbol +/// tables to be preserved across passes. Most often, symbol tables are +/// automatically kept up-to-date via the `insert` and `erase` functions. +class SymbolTableAnalysis { +public: + /// Create the symbol table analysis at the provided top-level operation and + /// instantiate the symbol table of the top-level operation. + SymbolTableAnalysis(Operation *op) + : topLevelSymbolTable(symbolTables.getSymbolTable(op)) {} + + /// Get the symbol table collection. + SymbolTableCollection &getSymbolTables() { return symbolTables; } + + /// Get the top-level symbol table. + SymbolTable &getTopLevelSymbolTable() { return topLevelSymbolTable; } + + /// Get the top-level operation. + template + OpT getTopLevelOp() { + return cast(topLevelSymbolTable.getOp()); + } + + /// Symbol tables are kept up-to-date by passes. Assume that the analysis + /// remains valid. + bool isInvalidated(const AnalysisManager::PreservedAnalyses &pa) { + return false; + } + +private: + /// The symbol table collection containing cached symbol tables for all nested + /// symbol table operations. + SymbolTableCollection symbolTables; + /// The symbol table of the top-level operation. + SymbolTable &topLevelSymbolTable; +}; +} // namespace mlir + +#endif // MLIR_ANALYSIS_SYMBOLTABLEANALYSIS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Analysis/TopologicalSortUtils.h b/deps/exla/cache/xla_extension/include/mlir/Analysis/TopologicalSortUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..ee98cd8cb380e4d539e89a8cca54f24adf7e0465 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Analysis/TopologicalSortUtils.h @@ -0,0 +1,117 @@ +//===- TopologicalSortUtils.h - Topological sort utilities ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_ANALYSIS_TOPOLOGICALSORTUTILS_H +#define MLIR_ANALYSIS_TOPOLOGICALSORTUTILS_H + +#include "mlir/IR/Block.h" + +namespace mlir { + +/// Given a block, sort a range operations in said block in topological order. +/// The main purpose is readability of graph regions, potentially faster +/// processing of certain transformations and analyses, or fixing the SSA +/// dominance of blocks that require it after transformations. The function +/// sorts the given operations such that, as much as possible, all users appear +/// after their producers. +/// +/// For example: +/// +/// ```mlir +/// %0 = test.foo +/// %1 = test.bar %0, %2 +/// %2 = test.baz +/// ``` +/// +/// Will become: +/// +/// ```mlir +/// %0 = test.foo +/// %1 = test.baz +/// %2 = test.bar %0, %1 +/// ``` +/// +/// The sort also works on operations with regions and implicit captures. For +/// example: +/// +/// ```mlir +/// %0 = test.foo { +/// test.baz %1 +/// %1 = test.bar %2 +/// } +/// %2 = test.foo +/// ``` +/// +/// Will become: +/// +/// ```mlir +/// %0 = test.foo +/// %1 = test.foo { +/// test.baz %2 +/// %2 = test.bar %0 +/// } +/// ``` +/// +/// Note that the sort is not recursive on nested regions. This sort is stable; +/// if the operations are already topologically sorted, nothing changes. +/// +/// Operations that form cycles are moved to the end of the block in order. If +/// the sort is left with only operations that form a cycle, it breaks the cycle +/// by marking the first encountered operation as ready and moving on. +/// +/// The function optionally accepts a callback that can be provided by users to +/// virtually break cycles early. It is called on top-level operations in the +/// block with value uses at or below those operations. The function should +/// return true to mark that value as ready to be scheduled. +/// +/// For example, if `isOperandReady` is set to always mark edges from `foo.A` to +/// `foo.B` as ready, these operations: +/// +/// ```mlir +/// %0 = foo.B(%1) +/// %1 = foo.C(%2) +/// %2 = foo.A(%0) +/// ``` +/// +/// Are sorted as: +/// +/// ```mlir +/// %0 = foo.A(%2) +/// %1 = foo.C(%0) +/// %2 = foo.B(%1) +/// ``` +bool sortTopologically( + Block *block, iterator_range ops, + function_ref isOperandReady = nullptr); + +/// Given a block, sort its operations in topological order, excluding its +/// terminator if it has one. This sort is stable. +bool sortTopologically( + Block *block, + function_ref isOperandReady = nullptr); + +/// Compute a topological ordering of the given ops. This sort is not stable. +/// +/// Note: If the specified ops contain incomplete/interrupted SSA use-def +/// chains, the result may not actually be a topological sorting with respect to +/// the entire program. +bool computeTopologicalSorting( + MutableArrayRef ops, + function_ref isOperandReady = nullptr); + +/// Gets a list of blocks that is sorted according to dominance. This sort is +/// stable. +SetVector getBlocksSortedByDominance(Region ®ion); + +/// Sorts all operations in `toSort` topologically while also considering region +/// semantics. Does not support multi-sets. +SetVector topologicalSort(const SetVector &toSort); + +} // end namespace mlir + +#endif // MLIR_ANALYSIS_TOPOLOGICALSORTUTILS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeImplementation.h b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeImplementation.h new file mode 100644 index 0000000000000000000000000000000000000000..0ddc531073e232be23dc8fea9779497bc0f3f9a2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeImplementation.h @@ -0,0 +1,525 @@ +//===- BytecodeImplementation.h - MLIR Bytecode Implementation --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header defines various interfaces and utilities necessary for dialects +// to hook into bytecode serialization. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_BYTECODE_BYTECODEIMPLEMENTATION_H +#define MLIR_BYTECODE_BYTECODEIMPLEMENTATION_H + +#include "mlir/IR/Attributes.h" +#include "mlir/IR/Diagnostics.h" +#include "mlir/IR/Dialect.h" +#include "mlir/IR/DialectInterface.h" +#include "mlir/IR/OpImplementation.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/Twine.h" + +namespace mlir { +//===--------------------------------------------------------------------===// +// Dialect Version Interface. +//===--------------------------------------------------------------------===// + +/// This class is used to represent the version of a dialect, for the purpose +/// of polymorphic destruction. +class DialectVersion { +public: + virtual ~DialectVersion() = default; +}; + +//===----------------------------------------------------------------------===// +// DialectBytecodeReader +//===----------------------------------------------------------------------===// + +/// This class defines a virtual interface for reading a bytecode stream, +/// providing hooks into the bytecode reader. As such, this class should only be +/// derived and defined by the main bytecode reader, users (i.e. dialects) +/// should generally only interact with this class via the +/// BytecodeDialectInterface below. +class DialectBytecodeReader { +public: + virtual ~DialectBytecodeReader() = default; + + /// Emit an error to the reader. + virtual InFlightDiagnostic emitError(const Twine &msg = {}) const = 0; + + /// Retrieve the dialect version by name if available. + virtual FailureOr + getDialectVersion(StringRef dialectName) const = 0; + template + FailureOr getDialectVersion() const { + return getDialectVersion(T::getDialectNamespace()); + } + + /// Retrieve the context associated to the reader. + virtual MLIRContext *getContext() const = 0; + + /// Return the bytecode version being read. + virtual uint64_t getBytecodeVersion() const = 0; + + /// Read out a list of elements, invoking the provided callback for each + /// element. The callback function may be in any of the following forms: + /// * LogicalResult(T &) + /// * FailureOr() + template + LogicalResult readList(SmallVectorImpl &result, CallbackFn &&callback) { + uint64_t size; + if (failed(readVarInt(size))) + return failure(); + result.reserve(size); + + for (uint64_t i = 0; i < size; ++i) { + // Check if the callback uses FailureOr, or populates the result by + // reference. + if constexpr (llvm::function_traits>::num_args) { + T element = {}; + if (failed(callback(element))) + return failure(); + result.emplace_back(std::move(element)); + } else { + FailureOr element = callback(); + if (failed(element)) + return failure(); + result.emplace_back(std::move(*element)); + } + } + return success(); + } + + //===--------------------------------------------------------------------===// + // IR + //===--------------------------------------------------------------------===// + + /// Read a reference to the given attribute. + virtual LogicalResult readAttribute(Attribute &result) = 0; + /// Read an optional reference to the given attribute. Returns success even if + /// the Attribute isn't present. + virtual LogicalResult readOptionalAttribute(Attribute &attr) = 0; + + template + LogicalResult readAttributes(SmallVectorImpl &attrs) { + return readList(attrs, [this](T &attr) { return readAttribute(attr); }); + } + template + LogicalResult readAttribute(T &result) { + Attribute baseResult; + if (failed(readAttribute(baseResult))) + return failure(); + if ((result = dyn_cast(baseResult))) + return success(); + return emitError() << "expected " << llvm::getTypeName() + << ", but got: " << baseResult; + } + template + LogicalResult readOptionalAttribute(T &result) { + Attribute baseResult; + if (failed(readOptionalAttribute(baseResult))) + return failure(); + if (!baseResult) + return success(); + if ((result = dyn_cast(baseResult))) + return success(); + return emitError() << "expected " << llvm::getTypeName() + << ", but got: " << baseResult; + } + + /// Read a reference to the given type. + virtual LogicalResult readType(Type &result) = 0; + template + LogicalResult readTypes(SmallVectorImpl &types) { + return readList(types, [this](T &type) { return readType(type); }); + } + template + LogicalResult readType(T &result) { + Type baseResult; + if (failed(readType(baseResult))) + return failure(); + if ((result = dyn_cast(baseResult))) + return success(); + return emitError() << "expected " << llvm::getTypeName() + << ", but got: " << baseResult; + } + + /// Read a handle to a dialect resource. + template + FailureOr readResourceHandle() { + FailureOr handle = readResourceHandle(); + if (failed(handle)) + return failure(); + if (auto *result = dyn_cast(&*handle)) + return std::move(*result); + return emitError() << "provided resource handle differs from the " + "expected resource type"; + } + + //===--------------------------------------------------------------------===// + // Primitives + //===--------------------------------------------------------------------===// + + /// Read a variable width integer. + virtual LogicalResult readVarInt(uint64_t &result) = 0; + + /// Read a signed variable width integer. + virtual LogicalResult readSignedVarInt(int64_t &result) = 0; + LogicalResult readSignedVarInts(SmallVectorImpl &result) { + return readList(result, + [this](int64_t &value) { return readSignedVarInt(value); }); + } + + /// Parse a variable length encoded integer whose low bit is used to encode an + /// unrelated flag, i.e: `(integerValue << 1) | (flag ? 1 : 0)`. + LogicalResult readVarIntWithFlag(uint64_t &result, bool &flag) { + if (failed(readVarInt(result))) + return failure(); + flag = result & 1; + result >>= 1; + return success(); + } + + /// Read a "small" sparse array of integer <= 32 bits elements, where + /// index/value pairs can be compressed when the array is small. + /// Note that only some position of the array will be read and the ones + /// not stored in the bytecode are gonne be left untouched. + /// If the provided array is too small for the stored indices, an error + /// will be returned. + template + LogicalResult readSparseArray(MutableArrayRef array) { + static_assert(sizeof(T) < sizeof(uint64_t), "expect integer < 64 bits"); + static_assert(std::is_integral::value, "expects integer"); + uint64_t nonZeroesCount; + bool useSparseEncoding; + if (failed(readVarIntWithFlag(nonZeroesCount, useSparseEncoding))) + return failure(); + if (nonZeroesCount == 0) + return success(); + if (!useSparseEncoding) { + // This is a simple dense array. + if (nonZeroesCount > array.size()) { + emitError("trying to read an array of ") + << nonZeroesCount << " but only " << array.size() + << " storage available."; + return failure(); + } + for (int64_t index : llvm::seq(0, nonZeroesCount)) { + uint64_t value; + if (failed(readVarInt(value))) + return failure(); + array[index] = value; + } + return success(); + } + // Read sparse encoding + // This is the number of bits used for packing the index with the value. + uint64_t indexBitSize; + if (failed(readVarInt(indexBitSize))) + return failure(); + constexpr uint64_t maxIndexBitSize = 8; + if (indexBitSize > maxIndexBitSize) { + emitError("reading sparse array with indexing above 8 bits: ") + << indexBitSize; + return failure(); + } + for (uint32_t count : llvm::seq(0, nonZeroesCount)) { + (void)count; + uint64_t indexValuePair; + if (failed(readVarInt(indexValuePair))) + return failure(); + uint64_t index = indexValuePair & ~(uint64_t(-1) << (indexBitSize)); + uint64_t value = indexValuePair >> indexBitSize; + if (index >= array.size()) { + emitError("reading a sparse array found index ") + << index << " but only " << array.size() << " storage available."; + return failure(); + } + array[index] = value; + } + return success(); + } + + /// Read an APInt that is known to have been encoded with the given width. + virtual FailureOr readAPIntWithKnownWidth(unsigned bitWidth) = 0; + + /// Read an APFloat that is known to have been encoded with the given + /// semantics. + virtual FailureOr + readAPFloatWithKnownSemantics(const llvm::fltSemantics &semantics) = 0; + + /// Read a string from the bytecode. + virtual LogicalResult readString(StringRef &result) = 0; + + /// Read a blob from the bytecode. + virtual LogicalResult readBlob(ArrayRef &result) = 0; + + /// Read a bool from the bytecode. + virtual LogicalResult readBool(bool &result) = 0; + +private: + /// Read a handle to a dialect resource. + virtual FailureOr readResourceHandle() = 0; +}; + +//===----------------------------------------------------------------------===// +// DialectBytecodeWriter +//===----------------------------------------------------------------------===// + +/// This class defines a virtual interface for writing to a bytecode stream, +/// providing hooks into the bytecode writer. As such, this class should only be +/// derived and defined by the main bytecode writer, users (i.e. dialects) +/// should generally only interact with this class via the +/// BytecodeDialectInterface below. +class DialectBytecodeWriter { +public: + virtual ~DialectBytecodeWriter() = default; + + //===--------------------------------------------------------------------===// + // IR + //===--------------------------------------------------------------------===// + + /// Write out a list of elements, invoking the provided callback for each + /// element. + template + void writeList(RangeT &&range, CallbackFn &&callback) { + writeVarInt(llvm::size(range)); + for (auto &element : range) + callback(element); + } + + /// Write a reference to the given attribute. + virtual void writeAttribute(Attribute attr) = 0; + virtual void writeOptionalAttribute(Attribute attr) = 0; + template + void writeAttributes(ArrayRef attrs) { + writeList(attrs, [this](T attr) { writeAttribute(attr); }); + } + + /// Write a reference to the given type. + virtual void writeType(Type type) = 0; + template + void writeTypes(ArrayRef types) { + writeList(types, [this](T type) { writeType(type); }); + } + + /// Write the given handle to a dialect resource. + virtual void + writeResourceHandle(const AsmDialectResourceHandle &resource) = 0; + + //===--------------------------------------------------------------------===// + // Primitives + //===--------------------------------------------------------------------===// + + /// Write a variable width integer to the output stream. This should be the + /// preferred method for emitting integers whenever possible. + virtual void writeVarInt(uint64_t value) = 0; + + /// Write a signed variable width integer to the output stream. This should be + /// the preferred method for emitting signed integers whenever possible. + virtual void writeSignedVarInt(int64_t value) = 0; + void writeSignedVarInts(ArrayRef value) { + writeList(value, [this](int64_t value) { writeSignedVarInt(value); }); + } + + /// Write a VarInt and a flag packed together. + void writeVarIntWithFlag(uint64_t value, bool flag) { + writeVarInt((value << 1) | (flag ? 1 : 0)); + } + + /// Write out a "small" sparse array of integer <= 32 bits elements, where + /// index/value pairs can be compressed when the array is small. This method + /// will scan the array multiple times and should not be used for large + /// arrays. The optional provided "zero" can be used to adjust for the + /// expected repeated value. We assume here that the array size fits in a 32 + /// bits integer. + template + void writeSparseArray(ArrayRef array) { + static_assert(sizeof(T) < sizeof(uint64_t), "expect integer < 64 bits"); + static_assert(std::is_integral::value, "expects integer"); + uint32_t size = array.size(); + uint32_t nonZeroesCount = 0, lastIndex = 0; + for (uint32_t index : llvm::seq(0, size)) { + if (!array[index]) + continue; + nonZeroesCount++; + lastIndex = index; + } + // If the last position is too large, or the array isn't at least 50% + // sparse, emit it with a dense encoding. + if (lastIndex > 256 || nonZeroesCount > size / 2) { + // Emit the array size and a flag which indicates whether it is sparse. + writeVarIntWithFlag(size, false); + for (const T &elt : array) + writeVarInt(elt); + return; + } + // Emit sparse: first the number of elements we'll write and a flag + // indicating it is a sparse encoding. + writeVarIntWithFlag(nonZeroesCount, true); + if (nonZeroesCount == 0) + return; + // This is the number of bits used for packing the index with the value. + int indexBitSize = llvm::Log2_32_Ceil(lastIndex + 1); + writeVarInt(indexBitSize); + for (uint32_t index : llvm::seq(0, lastIndex + 1)) { + T value = array[index]; + if (!value) + continue; + uint64_t indexValuePair = (value << indexBitSize) | (index); + writeVarInt(indexValuePair); + } + } + + /// Write an APInt to the bytecode stream whose bitwidth will be known + /// externally at read time. This method is useful for encoding APInt values + /// when the width is known via external means, such as via a type. This + /// method should generally only be invoked if you need an APInt, otherwise + /// use the varint methods above. APInt values are generally encoded using + /// zigzag encoding, to enable more efficient encodings for negative values. + virtual void writeAPIntWithKnownWidth(const APInt &value) = 0; + + /// Write an APFloat to the bytecode stream whose semantics will be known + /// externally at read time. This method is useful for encoding APFloat values + /// when the semantics are known via external means, such as via a type. + virtual void writeAPFloatWithKnownSemantics(const APFloat &value) = 0; + + /// Write a string to the bytecode, which is owned by the caller and is + /// guaranteed to not die before the end of the bytecode process. This should + /// only be called if such a guarantee can be made, such as when the string is + /// owned by an attribute or type. + virtual void writeOwnedString(StringRef str) = 0; + + /// Write a blob to the bytecode, which is owned by the caller and is + /// guaranteed to not die before the end of the bytecode process. The blob is + /// written as-is, with no additional compression or compaction. + virtual void writeOwnedBlob(ArrayRef blob) = 0; + + /// Write a bool to the output stream. + virtual void writeOwnedBool(bool value) = 0; + + /// Return the bytecode version being emitted for. + virtual int64_t getBytecodeVersion() const = 0; + + /// Retrieve the dialect version by name if available. + virtual FailureOr + getDialectVersion(StringRef dialectName) const = 0; + + template + FailureOr getDialectVersion() const { + return getDialectVersion(T::getDialectNamespace()); + } +}; + +//===----------------------------------------------------------------------===// +// BytecodeDialectInterface +//===----------------------------------------------------------------------===// + +class BytecodeDialectInterface + : public DialectInterface::Base { +public: + using Base::Base; + + //===--------------------------------------------------------------------===// + // Reading + //===--------------------------------------------------------------------===// + + /// Read an attribute belonging to this dialect from the given reader. This + /// method should return null in the case of failure. Optionally, the dialect + /// version can be accessed through the reader. + virtual Attribute readAttribute(DialectBytecodeReader &reader) const { + reader.emitError() << "dialect " << getDialect()->getNamespace() + << " does not support reading attributes from bytecode"; + return Attribute(); + } + + /// Read a type belonging to this dialect from the given reader. This method + /// should return null in the case of failure. Optionally, the dialect version + /// can be accessed thorugh the reader. + virtual Type readType(DialectBytecodeReader &reader) const { + reader.emitError() << "dialect " << getDialect()->getNamespace() + << " does not support reading types from bytecode"; + return Type(); + } + + //===--------------------------------------------------------------------===// + // Writing + //===--------------------------------------------------------------------===// + + /// Write the given attribute, which belongs to this dialect, to the given + /// writer. This method may return failure to indicate that the given + /// attribute could not be encoded, in which case the textual format will be + /// used to encode this attribute instead. + virtual LogicalResult writeAttribute(Attribute attr, + DialectBytecodeWriter &writer) const { + return failure(); + } + + /// Write the given type, which belongs to this dialect, to the given writer. + /// This method may return failure to indicate that the given type could not + /// be encoded, in which case the textual format will be used to encode this + /// type instead. + virtual LogicalResult writeType(Type type, + DialectBytecodeWriter &writer) const { + return failure(); + } + + /// Write the version of this dialect to the given writer. + virtual void writeVersion(DialectBytecodeWriter &writer) const {} + + // Read the version of this dialect from the provided reader and return it as + // a `unique_ptr` to a dialect version object. + virtual std::unique_ptr + readVersion(DialectBytecodeReader &reader) const { + reader.emitError("Dialect does not support versioning"); + return nullptr; + } + + /// Hook invoked after parsing completed, if a version directive was present + /// and included an entry for the current dialect. This hook offers the + /// opportunity to the dialect to visit the IR and upgrades constructs emitted + /// by the version of the dialect corresponding to the provided version. + virtual LogicalResult + upgradeFromVersion(Operation *topLevelOp, + const DialectVersion &version) const { + return success(); + } +}; + +/// Helper for resource handle reading that returns LogicalResult. +template +static LogicalResult readResourceHandle(DialectBytecodeReader &reader, + FailureOr &value, Ts &&...params) { + FailureOr handle = reader.readResourceHandle(); + if (failed(handle)) + return failure(); + if (auto *result = dyn_cast(&*handle)) { + value = std::move(*result); + return success(); + } + return failure(); +} + +/// Helper method that injects context only if needed, this helps unify some of +/// the attribute construction methods. +template +auto get(MLIRContext *context, Ts &&...params) { + // Prefer a direct `get` method if one exists. + if constexpr (llvm::is_detected::value) { + (void)context; + return T::get(std::forward(params)...); + } else if constexpr (llvm::is_detected::value) { + return T::get(context, std::forward(params)...); + } else { + // Otherwise, pass to the base get. + return T::Base::get(context, std::forward(params)...); + } +} + +} // namespace mlir + +#endif // MLIR_BYTECODE_BYTECODEIMPLEMENTATION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..ceb3b799ad9fd8be6010f2c0827c792a4f75170c --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.cpp.inc @@ -0,0 +1,18 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + + +/// Read the properties for this operation from the bytecode and populate the state. +LogicalResult mlir::BytecodeOpInterface::readProperties(::mlir::DialectBytecodeReader & reader, ::mlir::OperationState & state) { + return getImpl()->readProperties(reader, state); + } + +/// Write the properties for this operation to the bytecode. +void mlir::BytecodeOpInterface::writeProperties(::mlir::DialectBytecodeWriter & writer) { + return getImpl()->writeProperties(getImpl(), getOperation(), writer); + } diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.h b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..98f1fee7f9d3a982415bf5606572fcc449fe0cd5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.h @@ -0,0 +1,23 @@ +//===- BytecodeOpInterface.h - Bytecode interface for MLIR Op ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains the definitions of the BytecodeOpInterface defined in +// `BytecodeOpInterface.td`. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_BYTECODE_BYTECODEOPINTERFACE_H +#define MLIR_BYTECODE_BYTECODEOPINTERFACE_H + +#include "mlir/Bytecode/BytecodeImplementation.h" +#include "mlir/IR/OpDefinition.h" + +/// Include the generated interface declarations. +#include "mlir/Bytecode/BytecodeOpInterface.h.inc" + +#endif // MLIR_BYTECODE_BYTECODEOPINTERFACE_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.h.inc b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..fc8cef002b6ab63028595b1807723a84f4d95632 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeOpInterface.h.inc @@ -0,0 +1,83 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +/// This interface allows operation to control the serialization of their +/// properties. +class BytecodeOpInterface; +namespace detail { +struct BytecodeOpInterfaceInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + LogicalResult (*readProperties)(::mlir::DialectBytecodeReader &, ::mlir::OperationState &); + void (*writeProperties)(const Concept *impl, ::mlir::Operation *, ::mlir::DialectBytecodeWriter &); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::BytecodeOpInterface; + Model() : Concept{readProperties, writeProperties} {} + + static inline LogicalResult readProperties(::mlir::DialectBytecodeReader & reader, ::mlir::OperationState & state); + static inline void writeProperties(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::mlir::DialectBytecodeWriter & writer); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::BytecodeOpInterface; + FallbackModel() : Concept{readProperties, writeProperties} {} + + static inline LogicalResult readProperties(::mlir::DialectBytecodeReader & reader, ::mlir::OperationState & state); + static inline void writeProperties(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::mlir::DialectBytecodeWriter & writer); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteOp; + }; +}; +template +struct BytecodeOpInterfaceTrait; + +} // namespace detail +class BytecodeOpInterface : public ::mlir::OpInterface { +public: + using ::mlir::OpInterface::OpInterface; + template + struct Trait : public detail::BytecodeOpInterfaceTrait {}; + + /// Read the properties for this operation from the bytecode and populate the state. + LogicalResult readProperties(::mlir::DialectBytecodeReader & reader, ::mlir::OperationState & state); + + /// Write the properties for this operation to the bytecode. + void writeProperties(::mlir::DialectBytecodeWriter & writer); +}; +namespace detail { + template + struct BytecodeOpInterfaceTrait : public ::mlir::OpInterface::Trait { + }; +}// namespace detail +} // namespace mlir +namespace mlir { +template +LogicalResult detail::BytecodeOpInterfaceInterfaceTraits::Model::readProperties(::mlir::DialectBytecodeReader & reader, ::mlir::OperationState & state) { + return ConcreteOp::readProperties(reader, state); +} +template +void detail::BytecodeOpInterfaceInterfaceTraits::Model::writeProperties(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::mlir::DialectBytecodeWriter & writer) { + return (llvm::cast(tablegen_opaque_val)).writeProperties(writer); +} +template +LogicalResult detail::BytecodeOpInterfaceInterfaceTraits::FallbackModel::readProperties(::mlir::DialectBytecodeReader & reader, ::mlir::OperationState & state) { + return ConcreteOp::readProperties(reader, state); +} +template +void detail::BytecodeOpInterfaceInterfaceTraits::FallbackModel::writeProperties(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::mlir::DialectBytecodeWriter & writer) { + return static_cast(impl)->writeProperties(tablegen_opaque_val, writer); +} +} // namespace mlir diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeReader.h b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeReader.h new file mode 100644 index 0000000000000000000000000000000000000000..19f74a0750cc90df499edb6c9d6cbdaba4894996 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeReader.h @@ -0,0 +1,96 @@ +//===- BytecodeReader.h - MLIR Bytecode Reader ------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header defines interfaces to read MLIR bytecode files/streams. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_BYTECODE_BYTECODEREADER_H +#define MLIR_BYTECODE_BYTECODEREADER_H + +#include "mlir/IR/AsmState.h" +#include "mlir/Support/LLVM.h" +#include +#include + +namespace llvm { +class MemoryBufferRef; +class SourceMgr; +} // namespace llvm + +namespace mlir { +/// The BytecodeReader allows to load MLIR bytecode files, while keeping the +/// state explicitly available in order to support lazy loading. +/// The `finalize` method must be called before destruction. +class BytecodeReader { +public: + /// Create a bytecode reader for the given buffer. If `lazyLoad` is true, + /// isolated regions aren't loaded eagerly. + explicit BytecodeReader( + llvm::MemoryBufferRef buffer, const ParserConfig &config, bool lazyLoad, + const std::shared_ptr &bufferOwnerRef = {}); + ~BytecodeReader(); + + /// Read the operations defined within the given memory buffer, containing + /// MLIR bytecode, into the provided block. If the reader was created with + /// `lazyLoad` enabled, isolated regions aren't loaded eagerly. + /// The lazyOps call back is invoked for every ops that can be lazy-loaded. + /// This let the client decide if the op should be materialized + /// immediately or delayed. + LogicalResult readTopLevel( + Block *block, llvm::function_ref lazyOps = + [](Operation *) { return false; }); + + /// Return the number of ops that haven't been materialized yet. + int64_t getNumOpsToMaterialize() const; + + /// Return true if the provided op is materializable. + bool isMaterializable(Operation *op); + + /// Materialize the provide operation. The provided operation must be + /// materializable. + /// The lazyOps call back is invoked for every ops that can be lazy-loaded. + /// This let the client decide if the op should be materialized immediately or + /// delayed. + /// !! Using this materialize withing an IR walk() can be confusing: make sure + /// to use a PreOrder traversal !! + LogicalResult materialize( + Operation *op, llvm::function_ref lazyOpsCallback = + [](Operation *) { return false; }); + + /// Finalize the lazy-loading by calling back with every op that hasn't been + /// materialized to let the client decide if the op should be deleted or + /// materialized. The op is materialized if the callback returns true, deleted + /// otherwise. The implementation of the callback must be thread-safe. + LogicalResult finalize(function_ref shouldMaterialize = + [](Operation *) { return true; }); + + class Impl; + +private: + std::unique_ptr impl; +}; + +/// Returns true if the given buffer starts with the magic bytes that signal +/// MLIR bytecode. +bool isBytecode(llvm::MemoryBufferRef buffer); + +/// Read the operations defined within the given memory buffer, containing MLIR +/// bytecode, into the provided block. +LogicalResult readBytecodeFile(llvm::MemoryBufferRef buffer, Block *block, + const ParserConfig &config); +/// An overload with a source manager whose main file buffer is used for +/// parsing. The lifetime of the source manager may be freely extended during +/// parsing such that the source manager is not destroyed before the parsed IR. +LogicalResult +readBytecodeFile(const std::shared_ptr &sourceMgr, + Block *block, const ParserConfig &config); + +} // namespace mlir + +#endif // MLIR_BYTECODE_BYTECODEREADER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeReaderConfig.h b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeReaderConfig.h new file mode 100644 index 0000000000000000000000000000000000000000..c473b5779130f61aa87f519db6ad5c36cceff772 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeReaderConfig.h @@ -0,0 +1,119 @@ +//===- BytecodeReaderConfig.h - MLIR Bytecode Reader Config -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header config for reading MLIR bytecode files/streams. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_BYTECODE_BYTECODEREADERCONFIG_H +#define MLIR_BYTECODE_BYTECODEREADERCONFIG_H + +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" + +namespace mlir { +class Attribute; +class DialectBytecodeReader; +class Type; + +/// A class to interact with the attributes and types parser when parsing MLIR +/// bytecode. +template +class AttrTypeBytecodeReader { +public: + AttrTypeBytecodeReader() = default; + virtual ~AttrTypeBytecodeReader() = default; + + virtual LogicalResult read(DialectBytecodeReader &reader, + StringRef dialectName, T &entry) = 0; + + /// Return an Attribute/Type printer implemented via the given callable, whose + /// form should match that of the `parse` function above. + template >, + bool> = true> + static std::unique_ptr> + fromCallable(CallableT &&readFn) { + struct Processor : public AttrTypeBytecodeReader { + Processor(CallableT &&readFn) + : AttrTypeBytecodeReader(), readFn(std::move(readFn)) {} + LogicalResult read(DialectBytecodeReader &reader, StringRef dialectName, + T &entry) override { + return readFn(reader, dialectName, entry); + } + + std::decay_t readFn; + }; + return std::make_unique(std::forward(readFn)); + } +}; + +//===----------------------------------------------------------------------===// +// BytecodeReaderConfig +//===----------------------------------------------------------------------===// + +/// A class containing bytecode-specific configurations of the `ParserConfig`. +class BytecodeReaderConfig { +public: + BytecodeReaderConfig() = default; + + /// Returns the callbacks available to the parser. + ArrayRef>> + getAttributeCallbacks() const { + return attributeBytecodeParsers; + } + ArrayRef>> + getTypeCallbacks() const { + return typeBytecodeParsers; + } + + /// Attach a custom bytecode parser callback to the configuration for parsing + /// of custom type/attributes encodings. + void attachAttributeCallback( + std::unique_ptr> parser) { + attributeBytecodeParsers.emplace_back(std::move(parser)); + } + void + attachTypeCallback(std::unique_ptr> parser) { + typeBytecodeParsers.emplace_back(std::move(parser)); + } + + /// Attach a custom bytecode parser callback to the configuration for parsing + /// of custom type/attributes encodings. + template + std::enable_if_t>> + attachAttributeCallback(CallableT &&parserFn) { + attachAttributeCallback(AttrTypeBytecodeReader::fromCallable( + std::forward(parserFn))); + } + template + std::enable_if_t>> + attachTypeCallback(CallableT &&parserFn) { + attachTypeCallback(AttrTypeBytecodeReader::fromCallable( + std::forward(parserFn))); + } + +private: + llvm::SmallVector>> + attributeBytecodeParsers; + llvm::SmallVector>> + typeBytecodeParsers; +}; + +} // namespace mlir + +#endif // MLIR_BYTECODE_BYTECODEREADERCONFIG_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeWriter.h b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeWriter.h new file mode 100644 index 0000000000000000000000000000000000000000..c6cff0bc813143e00e3f446a3188df8629c6c4b5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/BytecodeWriter.h @@ -0,0 +1,197 @@ +//===- BytecodeWriter.h - MLIR Bytecode Writer ------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header defines interfaces to write MLIR bytecode files/streams. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_BYTECODE_BYTECODEWRITER_H +#define MLIR_BYTECODE_BYTECODEWRITER_H + +#include "mlir/IR/AsmState.h" +#include "llvm/Config/llvm-config.h" // for LLVM_VERSION_STRING + +namespace mlir { +class DialectBytecodeWriter; +class DialectVersion; +class Operation; + +/// A class to interact with the attributes and types printer when emitting MLIR +/// bytecode. +template +class AttrTypeBytecodeWriter { +public: + AttrTypeBytecodeWriter() = default; + virtual ~AttrTypeBytecodeWriter() = default; + + /// Callback writer API used in IRNumbering, where groups are created and + /// type/attribute components are numbered. At this stage, writer is expected + /// to be a `NumberingDialectWriter`. + virtual LogicalResult write(T entry, std::optional &name, + DialectBytecodeWriter &writer) = 0; + + /// Callback writer API used in BytecodeWriter, where groups are created and + /// type/attribute components are numbered. Here, DialectBytecodeWriter is + /// expected to be an actual writer. The optional stringref specified by + /// the user is ignored, since the group was already specified when numbering + /// the IR. + LogicalResult write(T entry, DialectBytecodeWriter &writer) { + std::optional dummy; + return write(entry, dummy, writer); + } + + /// Return an Attribute/Type printer implemented via the given callable, whose + /// form should match that of the `write` function above. + template &, + DialectBytecodeWriter &)>>, + bool> = true> + static std::unique_ptr> + fromCallable(CallableT &&writeFn) { + struct Processor : public AttrTypeBytecodeWriter { + Processor(CallableT &&writeFn) + : AttrTypeBytecodeWriter(), writeFn(std::move(writeFn)) {} + LogicalResult write(T entry, std::optional &name, + DialectBytecodeWriter &writer) override { + return writeFn(entry, name, writer); + } + + std::decay_t writeFn; + }; + return std::make_unique(std::forward(writeFn)); + } +}; + +/// This class contains the configuration used for the bytecode writer. It +/// controls various aspects of bytecode generation, and contains all of the +/// various bytecode writer hooks. +class BytecodeWriterConfig { +public: + /// `producer` is an optional string that can be used to identify the producer + /// of the bytecode when reading. It has no functional effect on the bytecode + /// serialization. + BytecodeWriterConfig(StringRef producer = "MLIR" LLVM_VERSION_STRING); + /// `map` is a fallback resource map, which when provided will attach resource + /// printers for the fallback resources within the map. + BytecodeWriterConfig(FallbackAsmResourceMap &map, + StringRef producer = "MLIR" LLVM_VERSION_STRING); + BytecodeWriterConfig(BytecodeWriterConfig &&); + ~BytecodeWriterConfig(); + + /// An internal implementation class that contains the state of the + /// configuration. + struct Impl; + + /// Return an instance of the internal implementation. + const Impl &getImpl() const { return *impl; } + + /// Set the desired bytecode version to emit. This method does not validate + /// the desired version. The bytecode writer entry point will return failure + /// if it cannot emit the desired version. + void setDesiredBytecodeVersion(int64_t bytecodeVersion); + + /// Get the set desired bytecode version to emit. + int64_t getDesiredBytecodeVersion() const; + + /// A map containing the dialect versions to emit. + llvm::StringMap> & + getDialectVersionMap() const; + + /// Set a given dialect version to emit on the map. + template + void setDialectVersion(std::unique_ptr dialectVersion) const { + return setDialectVersion(T::getDialectNamespace(), + std::move(dialectVersion)); + } + void setDialectVersion(StringRef dialectName, + std::unique_ptr dialectVersion) const; + + //===--------------------------------------------------------------------===// + // Types and Attributes encoding + //===--------------------------------------------------------------------===// + + /// Retrieve the callbacks. + ArrayRef>> + getAttributeWriterCallbacks() const; + ArrayRef>> + getTypeWriterCallbacks() const; + + /// Attach a custom bytecode printer callback to the configuration for the + /// emission of custom type/attributes encodings. + void attachAttributeCallback( + std::unique_ptr> callback); + void + attachTypeCallback(std::unique_ptr> callback); + + /// Attach a custom bytecode printer callback to the configuration for the + /// emission of custom type/attributes encodings. + template + std::enable_if_t &, + DialectBytecodeWriter &)>>> + attachAttributeCallback(CallableT &&emitFn) { + attachAttributeCallback(AttrTypeBytecodeWriter::fromCallable( + std::forward(emitFn))); + } + template + std::enable_if_t &, + DialectBytecodeWriter &)>>> + attachTypeCallback(CallableT &&emitFn) { + attachTypeCallback(AttrTypeBytecodeWriter::fromCallable( + std::forward(emitFn))); + } + + //===--------------------------------------------------------------------===// + // Resources + //===--------------------------------------------------------------------===// + + /// Set a boolean flag to skip emission of resources into the bytecode file. + void setElideResourceDataFlag(bool shouldElideResourceData = true); + + /// Attach the given resource printer to the writer configuration. + void attachResourcePrinter(std::unique_ptr printer); + + /// Attach an resource printer, in the form of a callable, to the + /// configuration. + template + std::enable_if_t>::value> + attachResourcePrinter(StringRef name, CallableT &&printFn) { + attachResourcePrinter(AsmResourcePrinter::fromCallable( + name, std::forward(printFn))); + } + + /// Attach resource printers to the AsmState for the fallback resources + /// in the given map. + void attachFallbackResourcePrinter(FallbackAsmResourceMap &map) { + for (auto &printer : map.getPrinters()) + attachResourcePrinter(std::move(printer)); + } + +private: + /// A pointer to allocated storage for the impl state. + std::unique_ptr impl; +}; + +//===----------------------------------------------------------------------===// +// Entry Points +//===----------------------------------------------------------------------===// + +/// Write the bytecode for the given operation to the provided output stream. +/// For streams where it matters, the given stream should be in "binary" mode. +/// It only ever fails if setDesiredByteCodeVersion can't be honored. +LogicalResult writeBytecodeToFile(Operation *op, raw_ostream &os, + const BytecodeWriterConfig &config = {}); + +} // namespace mlir + +#endif // MLIR_BYTECODE_BYTECODEWRITER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Bytecode/Encoding.h b/deps/exla/cache/xla_extension/include/mlir/Bytecode/Encoding.h new file mode 100644 index 0000000000000000000000000000000000000000..ac3826929ce7c1c6749c820c573db657642633a6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Bytecode/Encoding.h @@ -0,0 +1,141 @@ +//===- Encoding.h - MLIR binary format encoding information -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header defines enum values describing the structure of MLIR bytecode +// files. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_BYTECODE_ENCODING_H +#define MLIR_BYTECODE_ENCODING_H + +#include "mlir/IR/Value.h" +#include +#include + +namespace mlir { +namespace bytecode { +//===----------------------------------------------------------------------===// +// General constants +//===----------------------------------------------------------------------===// + +enum BytecodeVersion { + /// The minimum supported version of the bytecode. + kMinSupportedVersion = 0, + + /// Dialects versioning was added in version 1. + kDialectVersioning = 1, + + /// Support for lazy-loading of isolated region was added in version 2. + kLazyLoading = 2, + + /// Use-list ordering started to be encoded in version 3. + kUseListOrdering = 3, + + /// Avoid recording unknown locations on block arguments (compression) started + /// in version 4. + kElideUnknownBlockArgLocation = 4, + + /// Support for encoding properties natively in bytecode instead of merged + /// with the discardable attributes. + kNativePropertiesEncoding = 5, + + /// ODS emits operand/result segment_size as native properties instead of + /// an attribute. + kNativePropertiesODSSegmentSize = 6, + + /// The current bytecode version. + kVersion = 6, + + /// An arbitrary value used to fill alignment padding. + kAlignmentByte = 0xCB, +}; + +//===----------------------------------------------------------------------===// +// Sections +//===----------------------------------------------------------------------===// + +namespace Section { +enum ID : uint8_t { + /// This section contains strings referenced within the bytecode. + kString = 0, + + /// This section contains the dialects referenced within an IR module. + kDialect = 1, + + /// This section contains the attributes and types referenced within an IR + /// module. + kAttrType = 2, + + /// This section contains the offsets for the attribute and types within the + /// AttrType section. + kAttrTypeOffset = 3, + + /// This section contains the list of operations serialized into the bytecode, + /// and their nested regions/operations. + kIR = 4, + + /// This section contains the resources of the bytecode. + kResource = 5, + + /// This section contains the offsets of resources within the Resource + /// section. + kResourceOffset = 6, + + /// This section contains the versions of each dialect. + kDialectVersions = 7, + + /// This section contains the properties for the operations. + kProperties = 8, + + /// The total number of section types. + kNumSections = 9, +}; +} // namespace Section + +//===----------------------------------------------------------------------===// +// IR Section +//===----------------------------------------------------------------------===// + +/// This enum represents a mask of all of the potential components of an +/// operation. This mask is used when encoding an operation to indicate which +/// components are present in the bytecode. +namespace OpEncodingMask { +enum : uint8_t { + // clang-format off + kHasAttrs = 0b00000001, + kHasResults = 0b00000010, + kHasOperands = 0b00000100, + kHasSuccessors = 0b00001000, + kHasInlineRegions = 0b00010000, + kHasUseListOrders = 0b00100000, + kHasProperties = 0b01000000, + // clang-format on +}; +} // namespace OpEncodingMask + +/// Get the unique ID of a value use. We encode the unique ID combining an owner +/// number and the argument number such as if ownerID(op1) < ownerID(op2), then +/// useID(op1) < useID(op2). If uses have the same owner, then argNumber(op1) < +/// argNumber(op2) implies useID(op1) < useID(op2). +template +static inline uint64_t getUseID(OperandT &val, unsigned ownerID) { + uint32_t operandNumberID; + if constexpr (std::is_same_v) + operandNumberID = val.getOperandNumber(); + else if constexpr (std::is_same_v) + operandNumberID = val.getArgNumber(); + else + llvm_unreachable("unexpected operand type"); + return (static_cast(ownerID) << 32) | operandNumberID; +} + +} // namespace bytecode +} // namespace mlir + +#endif diff --git a/deps/exla/cache/xla_extension/include/mlir/Config/mlir-config.h b/deps/exla/cache/xla_extension/include/mlir/Config/mlir-config.h new file mode 100644 index 0000000000000000000000000000000000000000..350f7178db06b5aa6fe827ead298eab38dbd682b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Config/mlir-config.h @@ -0,0 +1,46 @@ +//===- mlir-config.h - MLIR configuration ------------------------*- C -*-===*// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +/* This file enumerates variables from the MLIR configuration so that they + can be in exported headers and won't override package specific directives. + Defining the variables here is preferable over specifying them in CMake files + via `target_compile_definitions` because it is easier to ensure that they are + defined consistently across all targets: They are guaranteed to be 0/1 + variables thanks to #cmakedefine01, so we can test with `#if` and find + missing definitions or includes with `-Wundef`. With `#ifdef`, these mistakes + can go unnoticed. + + This is a C header that can be included in the mlir-c headers. */ + +#ifndef MLIR_CONFIG_H +#define MLIR_CONFIG_H + +/* Enable expensive checks to detect invalid pattern API usage. Failed checks + manifest as fatal errors or invalid memory accesses (e.g., accessing + deallocated memory) that cause a crash. Running with ASAN is recommended for + easier debugging. */ +#define MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS 0 + +/* If set, greedy pattern application is randomized: ops on the worklist are + chosen at random. For testing/debugging purposes only. This feature can be + used to ensure that lowering pipelines work correctly regardless of the order + in which ops are processed by the GreedyPatternRewriteDriver. This flag is + numeric seed that is passed to the random number generator. */ +/* #undef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED */ + +/* If set, enables PDL usage. */ +#define MLIR_ENABLE_PDL_IN_PATTERNMATCH 1 + +/* If set, enables features that depend on the NVIDIA's PTX compiler. */ +#define MLIR_ENABLE_NVPTXCOMPILER 0 + +/* If set, enables ROCm-related features in ROCM-related transforms, pipelines, + and targets. */ +#define MLIR_ENABLE_ROCM_CONVERSIONS 0 + +#endif diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/AMDGPUToROCDL/AMDGPUToROCDL.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/AMDGPUToROCDL/AMDGPUToROCDL.h new file mode 100644 index 0000000000000000000000000000000000000000..b550980c4ad017fccf5756212b5c38dad4b96c84 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/AMDGPUToROCDL/AMDGPUToROCDL.h @@ -0,0 +1,41 @@ +//===- AMDGPUToROCDL.h - Convert AMDGPU to ROCDL dialect --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_AMDGPUTOROCDL_AMDGPUTOROCDL_H_ +#define MLIR_CONVERSION_AMDGPUTOROCDL_AMDGPUTOROCDL_H_ + +#include "mlir/Dialect/AMDGPU/Utils/Chipset.h" +#include +#include + +namespace mlir { + +class LLVMTypeConverter; +class RewritePatternSet; +class TypeConverter; +class Pass; + +#define GEN_PASS_DECL_CONVERTAMDGPUTOROCDLPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Note: This function will also add conversions for the AMDGPU-specific +/// address spaces, but those can be added separately using +/// populateAMDGPUMemorySpaceAttributeConversions(). +void populateAMDGPUToROCDLConversionPatterns(LLVMTypeConverter &converter, + RewritePatternSet &patterns, + amdgpu::Chipset chipset); + +/// Remap AMDGPU memory spaces to LLVM address spaces +/// by mapping amdgpu::AddressSpace::fat_raw_buffer to ptr addrspace(7), +/// amdgpu::AddressSpace::buffer_rsrc to ptr addrspace(8), and +/// amdgpu::AddressSpace::fat_strided_buffer to ptr addrspace(9). +void populateAMDGPUMemorySpaceAttributeConversions( + TypeConverter &typeConverter); + +} // namespace mlir + +#endif // MLIR_CONVERSION_AMDGPUTOROCDL_AMDGPUTOROCDL_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/AffineToStandard/AffineToStandard.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/AffineToStandard/AffineToStandard.h new file mode 100644 index 0000000000000000000000000000000000000000..2811d5e4a0f84921989baefaeb6c15afbb523a7e --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/AffineToStandard/AffineToStandard.h @@ -0,0 +1,49 @@ +//===- AffineToStandard.h - Convert Affine to Standard dialect --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_AFFINETOSTANDARD_AFFINETOSTANDARD_H +#define MLIR_CONVERSION_AFFINETOSTANDARD_AFFINETOSTANDARD_H + +#include "mlir/Support/LLVM.h" + +namespace mlir { +class Location; +class OpBuilder; +class Pass; +class RewritePattern; +class RewritePatternSet; +class Value; +class ValueRange; + +namespace affine { +class AffineForOp; +} // namespace affine + +#define GEN_PASS_DECL_LOWERAFFINEPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Collect a set of patterns to convert from the Affine dialect to the Standard +/// dialect, in particular convert structured affine control flow into CFG +/// branch-based control flow. +void populateAffineToStdConversionPatterns(RewritePatternSet &patterns); + +/// Collect a set of patterns to convert vector-related Affine ops to the Vector +/// dialect. +void populateAffineToVectorConversionPatterns(RewritePatternSet &patterns); + +/// Emit code that computes the lower bound of the given affine loop using +/// standard arithmetic operations. +Value lowerAffineLowerBound(affine::AffineForOp op, OpBuilder &builder); + +/// Emit code that computes the upper bound of the given affine loop using +/// standard arithmetic operations. +Value lowerAffineUpperBound(affine::AffineForOp op, OpBuilder &builder); + +} // namespace mlir + +#endif // MLIR_CONVERSION_AFFINETOSTANDARD_AFFINETOSTANDARD_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ArithCommon/AttrToLLVMConverter.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ArithCommon/AttrToLLVMConverter.h new file mode 100644 index 0000000000000000000000000000000000000000..7ffc8613317603740efd62f7e5062043ad9bee42 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ArithCommon/AttrToLLVMConverter.h @@ -0,0 +1,143 @@ +//===- AttrToLLVMConverter.h - Arith attributes conversion ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_ARITHCOMMON_ATTRTOLLVMCONVERTER_H +#define MLIR_CONVERSION_ARITHCOMMON_ATTRTOLLVMCONVERTER_H + +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" + +//===----------------------------------------------------------------------===// +// Support for converting Arith FastMathFlags to LLVM FastmathFlags +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace arith { +/// Maps arithmetic fastmath enum values to LLVM enum values. +LLVM::FastmathFlags +convertArithFastMathFlagsToLLVM(arith::FastMathFlags arithFMF); + +/// Creates an LLVM fastmath attribute from a given arithmetic fastmath +/// attribute. +LLVM::FastmathFlagsAttr +convertArithFastMathAttrToLLVM(arith::FastMathFlagsAttr fmfAttr); + +/// Maps arithmetic overflow enum values to LLVM enum values. +LLVM::IntegerOverflowFlags +convertArithOverflowFlagsToLLVM(arith::IntegerOverflowFlags arithFlags); + +/// Creates an LLVM rounding mode enum value from a given arithmetic rounding +/// mode enum value. +LLVM::RoundingMode +convertArithRoundingModeToLLVM(arith::RoundingMode roundingMode); + +/// Creates an LLVM rounding mode attribute from a given arithmetic rounding +/// mode attribute. +LLVM::RoundingModeAttr +convertArithRoundingModeAttrToLLVM(arith::RoundingModeAttr roundingModeAttr); + +/// Returns an attribute for the default LLVM FP exception behavior. +LLVM::FPExceptionBehaviorAttr +getLLVMDefaultFPExceptionBehavior(MLIRContext &context); + +// Attribute converter that populates a NamedAttrList by removing the fastmath +// attribute from the source operation attributes, and replacing it with an +// equivalent LLVM fastmath attribute. +template +class AttrConvertFastMathToLLVM { +public: + AttrConvertFastMathToLLVM(SourceOp srcOp) { + // Copy the source attributes. + convertedAttr = NamedAttrList{srcOp->getAttrs()}; + // Get the name of the arith fastmath attribute. + StringRef arithFMFAttrName = SourceOp::getFastMathAttrName(); + // Remove the source fastmath attribute. + auto arithFMFAttr = dyn_cast_if_present( + convertedAttr.erase(arithFMFAttrName)); + if (arithFMFAttr) { + StringRef targetAttrName = TargetOp::getFastmathAttrName(); + convertedAttr.set(targetAttrName, + convertArithFastMathAttrToLLVM(arithFMFAttr)); + } + } + + ArrayRef getAttrs() const { return convertedAttr.getAttrs(); } + LLVM::IntegerOverflowFlags getOverflowFlags() const { + return LLVM::IntegerOverflowFlags::none; + } + +private: + NamedAttrList convertedAttr; +}; + +// Attribute converter that populates a NamedAttrList by removing the overflow +// attribute from the source operation attributes, and replacing it with an +// equivalent LLVM overflow attribute. +template +class AttrConvertOverflowToLLVM { +public: + AttrConvertOverflowToLLVM(SourceOp srcOp) { + // Copy the source attributes. + convertedAttr = NamedAttrList{srcOp->getAttrs()}; + // Get the name of the arith overflow attribute. + StringRef arithAttrName = SourceOp::getIntegerOverflowAttrName(); + // Remove the source overflow attribute. + if (auto arithAttr = dyn_cast_if_present( + convertedAttr.erase(arithAttrName))) { + overflowFlags = convertArithOverflowFlagsToLLVM(arithAttr.getValue()); + } + } + + ArrayRef getAttrs() const { return convertedAttr.getAttrs(); } + LLVM::IntegerOverflowFlags getOverflowFlags() const { return overflowFlags; } + +private: + NamedAttrList convertedAttr; + LLVM::IntegerOverflowFlags overflowFlags = LLVM::IntegerOverflowFlags::none; +}; + +template +class AttrConverterConstrainedFPToLLVM { + static_assert(TargetOp::template hasTrait< + LLVM::FPExceptionBehaviorOpInterface::Trait>(), + "Target constrained FP operations must implement " + "LLVM::FPExceptionBehaviorOpInterface"); + +public: + AttrConverterConstrainedFPToLLVM(SourceOp srcOp) { + // Copy the source attributes. + convertedAttr = NamedAttrList{srcOp->getAttrs()}; + + if constexpr (TargetOp::template hasTrait< + LLVM::RoundingModeOpInterface::Trait>()) { + // Get the name of the rounding mode attribute. + StringRef arithAttrName = srcOp.getRoundingModeAttrName(); + // Remove the source attribute. + auto arithAttr = + cast(convertedAttr.erase(arithAttrName)); + // Set the target attribute. + convertedAttr.set(TargetOp::getRoundingModeAttrName(), + convertArithRoundingModeAttrToLLVM(arithAttr)); + } + convertedAttr.set(TargetOp::getFPExceptionBehaviorAttrName(), + getLLVMDefaultFPExceptionBehavior(*srcOp->getContext())); + } + + ArrayRef getAttrs() const { return convertedAttr.getAttrs(); } + LLVM::IntegerOverflowFlags getOverflowFlags() const { + return LLVM::IntegerOverflowFlags::none; + } + +private: + NamedAttrList convertedAttr; +}; + +} // namespace arith +} // namespace mlir + +#endif // MLIR_CONVERSION_ARITHCOMMON_ATTRTOLLVMCONVERTER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ArithToLLVM/ArithToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ArithToLLVM/ArithToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..173fea7c352d93df11a846d5a5726abd1c7df6a4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ArithToLLVM/ArithToLLVM.h @@ -0,0 +1,32 @@ +//===- ArithToLLVM.h - Arith to LLVM dialect conversion ----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_ARITHTOLLVM_ARITHTOLLVM_H +#define MLIR_CONVERSION_ARITHTOLLVM_ARITHTOLLVM_H + +#include + +namespace mlir { + +class DialectRegistry; +class LLVMTypeConverter; +class RewritePatternSet; +class Pass; + +#define GEN_PASS_DECL_ARITHTOLLVMCONVERSIONPASS +#include "mlir/Conversion/Passes.h.inc" + +namespace arith { +void populateArithToLLVMConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns); + +void registerConvertArithToLLVMInterface(DialectRegistry ®istry); +} // namespace arith +} // namespace mlir + +#endif // MLIR_CONVERSION_ARITHTOLLVM_ARITHTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..60441f9faaa60e6fd0e91cb76fa5ac2e1590bd28 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h @@ -0,0 +1,39 @@ +//===- AsyncToLLVM.h - Convert Async to LLVM dialect ------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_ASYNCTOLLVM_ASYNCTOLLVM_H +#define MLIR_CONVERSION_ASYNCTOLLVM_ASYNCTOLLVM_H + +#include + +namespace mlir { + +class ConversionTarget; +class Pass; +class MLIRContext; +class TypeConverter; +class RewritePatternSet; + +#define GEN_PASS_DECL_CONVERTASYNCTOLLVMPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Populates patterns for async structural type conversions. +/// +/// A "structural" type conversion is one where the underlying ops are +/// completely agnostic to the actual types involved and simply need to update +/// their types. An example of this is async.execute -- the async.execute op and +/// the corresponding async.yield ops need to update their types accordingly to +/// the TypeConverter, but otherwise don't care what type conversions are +/// happening. +void populateAsyncStructuralTypeConversionsAndLegality( + TypeConverter &typeConverter, RewritePatternSet &patterns, + ConversionTarget &target); + +} // namespace mlir + +#endif // MLIR_CONVERSION_ASYNCTOLLVM_ASYNCTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexCommon/DivisionConverter.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexCommon/DivisionConverter.h new file mode 100644 index 0000000000000000000000000000000000000000..df97dc2c4eb7d3eac4cc800e5bbbdfddf2371fa5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexCommon/DivisionConverter.h @@ -0,0 +1,48 @@ +//===- DivisionConverter.h - Complex division conversion ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_COMPLEXCOMMON_DIVISIONCONVERTER_H +#define MLIR_CONVERSION_COMPLEXCOMMON_DIVISIONCONVERTER_H + +#include "mlir/Conversion/LLVMCommon/ConversionTarget.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" + +namespace mlir { +namespace complex { +/// convert a complex division to the LLVM dialect using algebraic method +void convertDivToLLVMUsingAlgebraic(ConversionPatternRewriter &rewriter, + Location loc, Value lhsRe, Value lhsIm, + Value rhsRe, Value rhsIm, + LLVM::FastmathFlagsAttr fmf, + Value *resultRe, Value *resultIm); + +/// convert a complex division to the arith/math dialects using algebraic method +void convertDivToStandardUsingAlgebraic(ConversionPatternRewriter &rewriter, + Location loc, Value lhsRe, Value lhsIm, + Value rhsRe, Value rhsIm, + arith::FastMathFlagsAttr fmf, + Value *resultRe, Value *resultIm); + +/// convert a complex division to the LLVM dialect using Smith's method +void convertDivToLLVMUsingRangeReduction(ConversionPatternRewriter &rewriter, + Location loc, Value lhsRe, Value lhsIm, + Value rhsRe, Value rhsIm, + LLVM::FastmathFlagsAttr fmf, + Value *resultRe, Value *resultIm); + +/// convert a complex division to the arith/math dialects using Smith's method +void convertDivToStandardUsingRangeReduction( + ConversionPatternRewriter &rewriter, Location loc, Value lhsRe, Value lhsIm, + Value rhsRe, Value rhsIm, arith::FastMathFlagsAttr fmf, Value *resultRe, + Value *resultIm); + +} // namespace complex +} // namespace mlir + +#endif // MLIR_CONVERSION_COMPLEXCOMMON_DIVISIONCONVERTER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexToLLVM/ComplexToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexToLLVM/ComplexToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..1db75563fe304b6cfa45d39621b8fdeb096358a3 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexToLLVM/ComplexToLLVM.h @@ -0,0 +1,53 @@ +//===- ComplexToLLVM.h - Utils to convert from the complex dialect --------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_COMPLEXTOLLVM_COMPLEXTOLLVM_H_ +#define MLIR_CONVERSION_COMPLEXTOLLVM_COMPLEXTOLLVM_H_ + +#include "mlir/Conversion/LLVMCommon/StructBuilder.h" +#include "mlir/Dialect/Complex/IR/Complex.h" +#include "mlir/Pass/Pass.h" + +namespace mlir { +class DialectRegistry; +class LLVMTypeConverter; +class Pass; +class RewritePatternSet; + +#define GEN_PASS_DECL_CONVERTCOMPLEXTOLLVMPASS +#include "mlir/Conversion/Passes.h.inc" + +class ComplexStructBuilder : public StructBuilder { +public: + /// Construct a helper for the given complex number value. + using StructBuilder::StructBuilder; + /// Build IR creating an `undef` value of the complex number type. + static ComplexStructBuilder poison(OpBuilder &builder, Location loc, + Type type); + + // Build IR extracting the real value from the complex number struct. + Value real(OpBuilder &builder, Location loc); + // Build IR inserting the real value into the complex number struct. + void setReal(OpBuilder &builder, Location loc, Value real); + + // Build IR extracting the imaginary value from the complex number struct. + Value imaginary(OpBuilder &builder, Location loc); + // Build IR inserting the imaginary value into the complex number struct. + void setImaginary(OpBuilder &builder, Location loc, Value imaginary); +}; + +/// Populate the given list with patterns that convert from Complex to LLVM. +void populateComplexToLLVMConversionPatterns( + const LLVMTypeConverter &converter, RewritePatternSet &patterns, + mlir::complex::ComplexRangeFlags complexRange = + mlir::complex::ComplexRangeFlags::basic); + +void registerConvertComplexToLLVMInterface(DialectRegistry ®istry); + +} // namespace mlir + +#endif // MLIR_CONVERSION_COMPLEXTOLLVM_COMPLEXTOLLVM_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexToStandard/ComplexToStandard.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexToStandard/ComplexToStandard.h new file mode 100644 index 0000000000000000000000000000000000000000..509a68314f987431b18a23b1799c98fbc2e04c0e --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ComplexToStandard/ComplexToStandard.h @@ -0,0 +1,30 @@ +//===- ComplexToStandard.h - Utils to convert from the complex dialect ----===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_COMPLEXTOSTANDARD_COMPLEXTOSTANDARD_H_ +#define MLIR_CONVERSION_COMPLEXTOSTANDARD_COMPLEXTOSTANDARD_H_ + +#include "mlir/Dialect/Complex/IR/Complex.h" +#include "mlir/Pass/Pass.h" +#include + +namespace mlir { +class RewritePatternSet; +class Pass; + +#define GEN_PASS_DECL_CONVERTCOMPLEXTOSTANDARDPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Populate the given list with patterns that convert from Complex to Standard. +void populateComplexToStandardConversionPatterns( + RewritePatternSet &patterns, + mlir::complex::ComplexRangeFlags complexRange = + mlir::complex::ComplexRangeFlags::improved); + +} // namespace mlir + +#endif // MLIR_CONVERSION_COMPLEXTOSTANDARD_COMPLEXTOSTANDARD_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..88f18022da9bb1010fe12fd4dc083b9243f51543 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h @@ -0,0 +1,51 @@ +//===- ControlFlowToLLVM.h - ControlFlow to LLVM -----------*- C++ ------*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Define conversions from the ControlFlow dialect to the LLVM IR dialect. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_CONTROLFLOWTOLLVM_CONTROLFLOWTOLLVM_H +#define MLIR_CONVERSION_CONTROLFLOWTOLLVM_CONTROLFLOWTOLLVM_H + +#include + +namespace mlir { +class DialectRegistry; +class LLVMTypeConverter; +class RewritePatternSet; +class Pass; + +#define GEN_PASS_DECL_CONVERTCONTROLFLOWTOLLVMPASS +#include "mlir/Conversion/Passes.h.inc" + +namespace cf { + +/// Collect the patterns to convert from the ControlFlow dialect to LLVM. The +/// conversion patterns capture the LLVMTypeConverter by reference meaning the +/// references have to remain alive during the entire pattern lifetime. +/// +/// Note: This function does not populate the default cf.assert lowering. That +/// is because some platforms have a custom cf.assert lowering. The default +/// lowering can be populated with `populateAssertToLLVMConversionPattern`. +void populateControlFlowToLLVMConversionPatterns( + const LLVMTypeConverter &converter, RewritePatternSet &patterns); + +/// Populate the cf.assert to LLVM conversion pattern. If `abortOnFailure` is +/// set to false, the program execution continues when a condition is +/// unsatisfied. +void populateAssertToLLVMConversionPattern(const LLVMTypeConverter &converter, + RewritePatternSet &patterns, + bool abortOnFailure = true); + +void registerConvertControlFlowToLLVMInterface(DialectRegistry ®istry); + +} // namespace cf +} // namespace mlir + +#endif // MLIR_CONVERSION_CONTROLFLOWTOLLVM_CONTROLFLOWTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToEmitC/ToEmitCInterface.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToEmitC/ToEmitCInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..d438f27006232993f5c28131634962dc519fd45f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToEmitC/ToEmitCInterface.h @@ -0,0 +1,45 @@ +//===- ToEmitCInterface.h - Conversion to EmitC iface ---*- C++ -*-===========// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_CONVERTTOEMITC_TOEMITCINTERFACE_H +#define MLIR_CONVERSION_CONVERTTOEMITC_TOEMITCINTERFACE_H + +#include "mlir/IR/DialectInterface.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OpDefinition.h" + +namespace mlir { +class ConversionTarget; +class TypeConverter; +class MLIRContext; +class Operation; +class RewritePatternSet; +class AnalysisManager; + +class ConvertToEmitCPatternInterface + : public DialectInterface::Base { +public: + ConvertToEmitCPatternInterface(Dialect *dialect) : Base(dialect) {} + + /// Hook for derived dialect interface to provide conversion patterns + /// and mark dialect legal for the conversion target. + virtual void populateConvertToEmitCConversionPatterns( + ConversionTarget &target, TypeConverter &typeConverter, + RewritePatternSet &patterns) const = 0; +}; + +/// Recursively walk the IR and collect all dialects implementing the interface, +/// and populate the conversion patterns. +void populateConversionTargetFromOperation(Operation *op, + ConversionTarget &target, + TypeConverter &typeConverter, + RewritePatternSet &patterns); + +} // namespace mlir + +#endif // MLIR_CONVERSION_CONVERTTOEMITC_TOEMITCINTERFACE_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..7abdd6ade43d0b71d51c37ca2f5e82e178a4fcc1 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.cpp.inc @@ -0,0 +1,13 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + + +/// Populate the dialect conversion target, type converter and pattern set. +void mlir::ConvertToLLVMAttrInterface::populateConvertToLLVMConversionPatterns(::mlir::ConversionTarget& target, ::mlir::LLVMTypeConverter& typeConverter, ::mlir::RewritePatternSet& patternSet) const { + return getImpl()->populateConvertToLLVMConversionPatterns(getImpl(), *this, target, typeConverter, patternSet); + } diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.h.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..cdde912148258c24340618e2d3d74015d0f87181 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.h.inc @@ -0,0 +1,77 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +/// The `ConvertToLLVMAttrInterface` attribute interfaces allows using +/// attributes to configure the convert to LLVM infrastructure, this includes: +/// - The conversion target. +/// - The LLVM type converter. +/// - The pattern set. +/// +/// This interface permits fined grained configuration of the `convert-to-llvm` +/// process. For example, attributes with target information like +/// `#nvvm.target` or `#rodcl.target` can leverage this interface for populating +/// patterns specific to a particular target. +class ConvertToLLVMAttrInterface; +namespace detail { +struct ConvertToLLVMAttrInterfaceInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + void (*populateConvertToLLVMConversionPatterns)(const Concept *impl, ::mlir::Attribute , ::mlir::ConversionTarget&, ::mlir::LLVMTypeConverter&, ::mlir::RewritePatternSet&); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::ConvertToLLVMAttrInterface; + Model() : Concept{populateConvertToLLVMConversionPatterns} {} + + static inline void populateConvertToLLVMConversionPatterns(const Concept *impl, ::mlir::Attribute tablegen_opaque_val, ::mlir::ConversionTarget& target, ::mlir::LLVMTypeConverter& typeConverter, ::mlir::RewritePatternSet& patternSet); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::ConvertToLLVMAttrInterface; + FallbackModel() : Concept{populateConvertToLLVMConversionPatterns} {} + + static inline void populateConvertToLLVMConversionPatterns(const Concept *impl, ::mlir::Attribute tablegen_opaque_val, ::mlir::ConversionTarget& target, ::mlir::LLVMTypeConverter& typeConverter, ::mlir::RewritePatternSet& patternSet); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteAttr; + }; +}; +template +struct ConvertToLLVMAttrInterfaceTrait; + +} // namespace detail +class ConvertToLLVMAttrInterface : public ::mlir::AttributeInterface { +public: + using ::mlir::AttributeInterface::AttributeInterface; + template + struct Trait : public detail::ConvertToLLVMAttrInterfaceTrait {}; + + /// Populate the dialect conversion target, type converter and pattern set. + void populateConvertToLLVMConversionPatterns(::mlir::ConversionTarget& target, ::mlir::LLVMTypeConverter& typeConverter, ::mlir::RewritePatternSet& patternSet) const; +}; +namespace detail { + template + struct ConvertToLLVMAttrInterfaceTrait : public ::mlir::AttributeInterface::Trait { + }; +}// namespace detail +} // namespace mlir +namespace mlir { +template +void detail::ConvertToLLVMAttrInterfaceInterfaceTraits::Model::populateConvertToLLVMConversionPatterns(const Concept *impl, ::mlir::Attribute tablegen_opaque_val, ::mlir::ConversionTarget& target, ::mlir::LLVMTypeConverter& typeConverter, ::mlir::RewritePatternSet& patternSet) { + return (::llvm::cast(tablegen_opaque_val)).populateConvertToLLVMConversionPatterns(target, typeConverter, patternSet); +} +template +void detail::ConvertToLLVMAttrInterfaceInterfaceTraits::FallbackModel::populateConvertToLLVMConversionPatterns(const Concept *impl, ::mlir::Attribute tablegen_opaque_val, ::mlir::ConversionTarget& target, ::mlir::LLVMTypeConverter& typeConverter, ::mlir::RewritePatternSet& patternSet) { + return static_cast(impl)->populateConvertToLLVMConversionPatterns(tablegen_opaque_val, target, typeConverter, patternSet); +} +} // namespace mlir diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..6fd043646acd31015ba7330cd88780101047881f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMInterface.h @@ -0,0 +1,69 @@ +//===- ToLLVMInterface.h - Conversion to LLVM iface ---*- C++ -*-=============// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_CONVERTTOLLVM_TOLLVMINTERFACE_H +#define MLIR_CONVERSION_CONVERTTOLLVM_TOLLVMINTERFACE_H + +#include "mlir/IR/DialectInterface.h" +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/OpDefinition.h" + +namespace mlir { +class ConversionTarget; +class LLVMTypeConverter; +class MLIRContext; +class Operation; +class RewritePatternSet; +class AnalysisManager; + +/// Base class for dialect interfaces providing translation to LLVM IR. +/// Dialects that can be translated should provide an implementation of this +/// interface for the supported operations. The interface may be implemented in +/// a separate library to avoid the "main" dialect library depending on LLVM IR. +/// The interface can be attached using the delayed registration mechanism +/// available in DialectRegistry. +class ConvertToLLVMPatternInterface + : public DialectInterface::Base { +public: + ConvertToLLVMPatternInterface(Dialect *dialect) : Base(dialect) {} + + /// Hook for derived dialect interface to load the dialects they + /// target. The LLVMDialect is implicitly already loaded, but this + /// method allows to load other intermediate dialects used in the + /// conversion, or target dialects like NVVM for example. + virtual void loadDependentDialects(MLIRContext *context) const {} + + /// Hook for derived dialect interface to provide conversion patterns + /// and mark dialect legal for the conversion target. + virtual void populateConvertToLLVMConversionPatterns( + ConversionTarget &target, LLVMTypeConverter &typeConverter, + RewritePatternSet &patterns) const = 0; +}; + +/// Recursively walk the IR and collect all dialects implementing the interface, +/// and populate the conversion patterns. +void populateConversionTargetFromOperation(Operation *op, + ConversionTarget &target, + LLVMTypeConverter &typeConverter, + RewritePatternSet &patterns); + +/// Helper function for populating LLVM conversion patterns. If `op` implements +/// the `ConvertToLLVMOpInterface` interface, then the LLVM conversion pattern +/// attributes provided by the interface will be used to configure the +/// conversion target, type converter, and the pattern set. +void populateOpConvertToLLVMConversionPatterns(Operation *op, + ConversionTarget &target, + LLVMTypeConverter &typeConverter, + RewritePatternSet &patterns); +} // namespace mlir + +#include "mlir/Conversion/ConvertToLLVM/ToLLVMAttrInterface.h.inc" + +#include "mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.h.inc" + +#endif // MLIR_CONVERSION_CONVERTTOLLVM_TOLLVMINTERFACE_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..8db58737835fad044e3514df69a8582327c9bb95 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.cpp.inc @@ -0,0 +1,14 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + + +/// Populate the provided vector with a list of convert to LLVM attributes +/// to apply. +void mlir::ConvertToLLVMOpInterface::getConvertToLLVMConversionAttrs(::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>& attrs) { + return getImpl()->getConvertToLLVMConversionAttrs(getImpl(), getOperation(), attrs); + } diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.h.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..24541004cf66a21c5e46a977054d060fe5ef96b4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMOpInterface.h.inc @@ -0,0 +1,71 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +/// Interface for collecting all convert to LLVM attributes stored in an +/// operation. See `ConvertToLLVMAttrInterface` for more information on these +/// attributes. +class ConvertToLLVMOpInterface; +namespace detail { +struct ConvertToLLVMOpInterfaceInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + void (*getConvertToLLVMConversionAttrs)(const Concept *impl, ::mlir::Operation *, ::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>&); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::ConvertToLLVMOpInterface; + Model() : Concept{getConvertToLLVMConversionAttrs} {} + + static inline void getConvertToLLVMConversionAttrs(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>& attrs); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::ConvertToLLVMOpInterface; + FallbackModel() : Concept{getConvertToLLVMConversionAttrs} {} + + static inline void getConvertToLLVMConversionAttrs(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>& attrs); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteOp; + }; +}; +template +struct ConvertToLLVMOpInterfaceTrait; + +} // namespace detail +class ConvertToLLVMOpInterface : public ::mlir::OpInterface { +public: + using ::mlir::OpInterface::OpInterface; + template + struct Trait : public detail::ConvertToLLVMOpInterfaceTrait {}; + + /// Populate the provided vector with a list of convert to LLVM attributes + /// to apply. + void getConvertToLLVMConversionAttrs(::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>& attrs); +}; +namespace detail { + template + struct ConvertToLLVMOpInterfaceTrait : public ::mlir::OpInterface::Trait { + }; +}// namespace detail +} // namespace mlir +namespace mlir { +template +void detail::ConvertToLLVMOpInterfaceInterfaceTraits::Model::getConvertToLLVMConversionAttrs(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>& attrs) { + return (llvm::cast(tablegen_opaque_val)).getConvertToLLVMConversionAttrs(attrs); +} +template +void detail::ConvertToLLVMOpInterfaceInterfaceTraits::FallbackModel::getConvertToLLVMConversionAttrs(const Concept *impl, ::mlir::Operation *tablegen_opaque_val, ::llvm::SmallVectorImpl<::mlir::ConvertToLLVMAttrInterface>& attrs) { + return static_cast(impl)->getConvertToLLVMConversionAttrs(tablegen_opaque_val, attrs); +} +} // namespace mlir diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMPass.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMPass.h new file mode 100644 index 0000000000000000000000000000000000000000..7de03500f8aaa0ece92e0659eaacb7c76f007598 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ConvertToLLVM/ToLLVMPass.h @@ -0,0 +1,27 @@ +//===- ToLLVMPass.h - Conversion to LLVM pass ---*- C++ -*-===================// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_CONVERTTOLLVM_TOLLVM_PASS_H +#define MLIR_CONVERSION_CONVERTTOLLVM_TOLLVM_PASS_H + +#include + +#include "mlir/Pass/Pass.h" + +namespace mlir { + +#define GEN_PASS_DECL_CONVERTTOLLVMPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Register the extension that will load dependent dialects for LLVM +/// conversion. This is useful to implement a pass similar to "convert-to-llvm". +void registerConvertToLLVMDependentDialectLoading(DialectRegistry ®istry); + +} // namespace mlir + +#endif // MLIR_CONVERSION_CONVERTTOLLVM_TOLLVM_PASS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..b1ea2740c06059e91532cb901b7468e1bb21855f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h @@ -0,0 +1,66 @@ +//===- ConvertFuncToLLVM.h - Convert Func to LLVM ---------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides a set of conversion patterns from the Func dialect to the LLVM IR +// dialect. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_FUNCTOLLVM_CONVERTFUNCTOLLVM_H +#define MLIR_CONVERSION_FUNCTOLLVM_CONVERTFUNCTOLLVM_H + +#include "mlir/Interfaces/FunctionInterfaces.h" + +namespace mlir { + +namespace LLVM { +class LLVMFuncOp; +} // namespace LLVM + +class ConversionPatternRewriter; +class DialectRegistry; +class LLVMTypeConverter; +class RewritePatternSet; +class SymbolTable; + +/// Convert input FunctionOpInterface operation to LLVMFuncOp by using the +/// provided LLVMTypeConverter. Return failure if failed to so. +FailureOr +convertFuncOpToLLVMFuncOp(FunctionOpInterface funcOp, + ConversionPatternRewriter &rewriter, + const LLVMTypeConverter &converter); + +/// Collect the default pattern to convert a FuncOp to the LLVM dialect. If +/// `emitCWrappers` is set, the pattern will also produce functions +/// that pass memref descriptors by pointer-to-structure in addition to the +/// default unpacked form. +void populateFuncToLLVMFuncOpConversionPattern( + const LLVMTypeConverter &converter, RewritePatternSet &patterns); + +/// Collect the patterns to convert from the Func dialect to LLVM. The +/// conversion patterns capture the LLVMTypeConverter and the LowerToLLVMOptions +/// by reference meaning the references have to remain alive during the entire +/// pattern lifetime. +/// +/// The `symbolTable` parameter can be used to speed up function lookups in the +/// module. It's good to provide it, but only if we know that the patterns will +/// be applied to a single module and the symbols referenced by the symbol table +/// will not be removed and new symbols will not be added during the usage of +/// the patterns. If provided, the lookups will have O(calls) cumulative +/// runtime, otherwise O(calls * functions). The symbol table is currently not +/// needed if `converter.getOptions().useBarePtrCallConv` is `true`, but it's +/// not an error to provide it anyway. +void populateFuncToLLVMConversionPatterns( + const LLVMTypeConverter &converter, RewritePatternSet &patterns, + const SymbolTable *symbolTable = nullptr); + +void registerConvertFuncToLLVMInterface(DialectRegistry ®istry); + +} // namespace mlir + +#endif // MLIR_CONVERSION_FUNCTOLLVM_CONVERTFUNCTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h new file mode 100644 index 0000000000000000000000000000000000000000..07a3d9668e6283dd6ae9adf43ed1ad1486162334 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h @@ -0,0 +1,24 @@ +//===- ConvertFuncToLLVMPass.h - Pass entrypoint ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_FUNCTOLLVM_CONVERTFUNCTOLLVMPASS_H_ +#define MLIR_CONVERSION_FUNCTOLLVM_CONVERTFUNCTOLLVMPASS_H_ + +#include +#include + +namespace mlir { +class Pass; + +#define GEN_PASS_DECL_CONVERTFUNCTOLLVMPASS +#define GEN_PASS_DECL_SETLLVMMODULEDATALAYOUTPASS +#include "mlir/Conversion/Passes.h.inc" + +} // namespace mlir + +#endif // MLIR_CONVERSION_FUNCTOLLVM_CONVERTFUNCTOLLVMPASS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/AttrToSPIRVConverter.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/AttrToSPIRVConverter.h new file mode 100644 index 0000000000000000000000000000000000000000..e1dcedba094c03d567eb00c9e5f98a90d0d24236 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/AttrToSPIRVConverter.h @@ -0,0 +1,18 @@ +//===- AttrToSPIRVConverter.h - GPU attributes conversion to SPIR-V - C++ -===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_GPUCOMMON_ATTRTOSPIRVCONVERTER_H_ +#define MLIR_CONVERSION_GPUCOMMON_ATTRTOSPIRVCONVERTER_H_ + +#include +#include + +namespace mlir { +spirv::StorageClass addressSpaceToStorageClass(gpu::AddressSpace addressSpace); +} // namespace mlir + +#endif // MLIR_CONVERSION_GPUCOMMON_ATTRTOSPIRVCONVERTER_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/GPUCommonPass.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/GPUCommonPass.h new file mode 100644 index 0000000000000000000000000000000000000000..25b094ebdecb211210e0bfe870a16acda3645339 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/GPUCommonPass.h @@ -0,0 +1,78 @@ +//===- GPUCommonPass.h - MLIR GPU runtime support -------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_GPUCOMMON_GPUCOMMONPASS_H_ +#define MLIR_CONVERSION_GPUCOMMON_GPUCOMMONPASS_H_ + +#include "mlir/Dialect/GPU/Utils/GPUUtils.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" +#include "mlir/IR/Builders.h" +#include "mlir/IR/Types.h" +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/StringRef.h" +#include + +namespace llvm { +class LLVMContext; +class Module; +} // namespace llvm + +namespace mlir { + +class LLVMTypeConverter; +class Location; +class ModuleOp; +class Operation; +class RewritePatternSet; +class TypeConverter; + +class Pass; + +namespace gpu { +enum class AddressSpace : uint32_t; +class GPUModuleOp; +} // namespace gpu + +namespace LLVM { +class LLVMDialect; +} // namespace LLVM + +#define GEN_PASS_DECL_GPUTOLLVMCONVERSIONPASS +#include "mlir/Conversion/Passes.h.inc" + +using LoweringCallback = std::function( + Operation *, llvm::LLVMContext &, StringRef)>; + +struct FunctionCallBuilder { + FunctionCallBuilder(StringRef functionName, Type returnType, + ArrayRef argumentTypes) + : functionName(functionName), + functionType(LLVM::LLVMFunctionType::get(returnType, argumentTypes)) {} + LLVM::CallOp create(Location loc, OpBuilder &builder, + ArrayRef arguments) const; + + StringRef functionName; + LLVM::LLVMFunctionType functionType; +}; + +/// Collect a set of patterns to convert from the GPU dialect to LLVM and +/// populate converter for gpu types. +void populateGpuToLLVMConversionPatterns( + LLVMTypeConverter &converter, RewritePatternSet &patterns, + bool kernelBarePtrCallConv = false, + bool kernelIntersperseSizeCallConv = false); + +/// A function that maps a MemorySpace enum to a target-specific integer value. +using MemorySpaceMapping = std::function; + +/// Populates memory space attribute conversion rules for lowering +/// gpu.address_space to integer values. +void populateGpuMemorySpaceAttributeConversions( + TypeConverter &typeConverter, const MemorySpaceMapping &mapping); +} // namespace mlir + +#endif // MLIR_CONVERSION_GPUCOMMON_GPUCOMMONPASS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/GPUToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/GPUToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..ad8c39fe676618c9525201dafe804cd8fa9f7fb3 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUCommon/GPUToLLVM.h @@ -0,0 +1,25 @@ +//===- GPUToLLVM.h - Convert GPU to LLVM dialect ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This files declares registration functions for converting GPU to LLVM. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_GPUCOMMON_GPUTOLLVM_H +#define MLIR_CONVERSION_GPUCOMMON_GPUTOLLVM_H + +namespace mlir { +class DialectRegistry; +namespace gpu { +/// Registers the `ConvertToLLVMOpInterface` interface on the `gpu::GPUModuleOP` +/// operation. +void registerConvertGpuToLLVMInterface(DialectRegistry ®istry); +} // namespace gpu +} // namespace mlir + +#endif // MLIR_CONVERSION_GPUCOMMON_GPUTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToNVVM/GPUToNVVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToNVVM/GPUToNVVM.h new file mode 100644 index 0000000000000000000000000000000000000000..6311630a23c8f692d738b0d2cff6eec6ce495a5b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToNVVM/GPUToNVVM.h @@ -0,0 +1,27 @@ +//===- GPUToNVVM.h - Convert GPU to NVVM dialect ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This files declares registration functions for converting GPU to NVVM. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_GPUTONVVM_GPUTONVVM_H +#define MLIR_CONVERSION_GPUTONVVM_GPUTONVVM_H + +namespace mlir { +class DialectRegistry; +namespace NVVM { +/// Registers the `ConvertToLLVMAttrInterface` interface on the +/// `NVVM::NVVMTargetAttr` attribute. This interface populates the conversion +/// target, LLVM type converter, and pattern set for converting GPU operations +/// to NVVM. +void registerConvertGpuToNVVMInterface(DialectRegistry ®istry); +} // namespace NVVM +} // namespace mlir + +#endif // MLIR_CONVERSION_GPUTONVVM_GPUTONVVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h new file mode 100644 index 0000000000000000000000000000000000000000..4c8abea680b668ef5771ec46562dd0d9051dbae5 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h @@ -0,0 +1,62 @@ +//===- GPUToNVVMPass.h - Convert GPU kernel to NVVM dialect -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_GPUTONVVM_GPUTONVVMPASS_H_ +#define MLIR_CONVERSION_GPUTONVVM_GPUTONVVMPASS_H_ + +#include "mlir/Conversion/LLVMCommon/LoweringOptions.h" +#include "mlir/Dialect/LLVMIR/LLVMTypes.h" +#include "mlir/IR/PatternMatch.h" +#include + +namespace mlir { +class LLVMTypeConverter; +class ConversionTarget; +class RewritePatternSet; +class Pass; + +namespace gpu { +class GPUModuleOp; +class MMAMatrixType; +} // namespace gpu + +#define GEN_PASS_DECL_CONVERTGPUOPSTONVVMOPS +#include "mlir/Conversion/Passes.h.inc" + +LLVM::LLVMStructType convertMMAToLLVMType(gpu::MMAMatrixType type); + +/// Configure target to convert from the GPU dialect to NVVM. +void configureGpuToNVVMConversionLegality(ConversionTarget &target); + +/// Configure the LLVM type convert to convert types and address spaces from the +/// GPU dialect to NVVM. +void configureGpuToNVVMTypeConverter(LLVMTypeConverter &converter); + +/// Populate patterns that lower certain arith and math dialect ops to +/// libdevice calls. +void populateLibDeviceConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns, + PatternBenefit benefit = 1); + +/// Collect a set of patterns to convert from the GPU dialect to NVVM. +void populateGpuToNVVMConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns, + PatternBenefit benefit = 1); + +/// Populate GpuSubgroupReduce pattern to NVVM. It generates a specific nvvm +/// op that is not available on every GPU. +void populateGpuSubgroupReduceOpLoweringPattern( + const LLVMTypeConverter &converter, RewritePatternSet &patterns, + PatternBenefit benefit = 1); + +/// Collect a set of patterns to convert WMMA ops from GPU dialect to NVVM. +void populateGpuWMMAToNVVMConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns, + PatternBenefit benefit = 1); +} // namespace mlir + +#endif // MLIR_CONVERSION_GPUTONVVM_GPUTONVVMPASS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToROCDL/GPUToROCDLPass.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToROCDL/GPUToROCDLPass.h new file mode 100644 index 0000000000000000000000000000000000000000..291b809071ce9c093fd8f2faed0e207e4850446d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToROCDL/GPUToROCDLPass.h @@ -0,0 +1,57 @@ +//===- GPUToROCDLPass.h - Convert GPU kernel to ROCDL dialect ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_GPUTOROCDL_GPUTOROCDLPASS_H_ +#define MLIR_CONVERSION_GPUTOROCDL_GPUTOROCDLPASS_H_ + +#include "mlir/Conversion/GPUToROCDL/Runtimes.h" +#include "mlir/Conversion/LLVMCommon/LoweringOptions.h" +#include + +namespace mlir { +class LLVMTypeConverter; +class ConversionTarget; +class RewritePatternSet; + +template +class OperationPass; + +namespace amdgpu { +struct Chipset; +} // namespace amdgpu + +namespace gpu { +class GPUModuleOp; +} // namespace gpu + +#define GEN_PASS_DECL_CONVERTGPUOPSTOROCDLOPS +#include "mlir/Conversion/Passes.h.inc" + +/// Collect a set of patterns to convert from the GPU dialect to ROCDL. +/// If `runtime` is Unknown, gpu.printf will not be lowered +/// The resulting pattern set should be run over a gpu.module op +void populateGpuToROCDLConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns, + gpu::amd::Runtime runtime, + amdgpu::Chipset chipset); + +/// Configure target to convert from the GPU dialect to ROCDL. +void configureGpuToROCDLConversionLegality(ConversionTarget &target); + +/// Creates a pass that lowers GPU dialect operations to ROCDL counterparts. The +/// index bitwidth used for the lowering of the device side index computations +/// is configurable. +std::unique_ptr> +createLowerGpuOpsToROCDLOpsPass( + const std::string &chipset = "gfx900", + unsigned indexBitwidth = kDeriveIndexBitwidthFromDataLayout, + bool useBarePtrCallConv = false, + gpu::amd::Runtime runtime = gpu::amd::Runtime::Unknown); + +} // namespace mlir + +#endif // MLIR_CONVERSION_GPUTOROCDL_GPUTOROCDLPASS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToROCDL/Runtimes.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToROCDL/Runtimes.h new file mode 100644 index 0000000000000000000000000000000000000000..da47d4cf97e7ec1a62365174f4a3544f8fe5a2c8 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/GPUToROCDL/Runtimes.h @@ -0,0 +1,24 @@ +//===- Runtimes.h - Possible runtimes for AMD GPUs ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_GPUTOROCDL_RUNTIMES_H +#define MLIR_CONVERSION_GPUTOROCDL_RUNTIMES_H + +namespace mlir { +namespace gpu { +namespace amd { +/// Potential runtimes for AMD GPU kernels +enum Runtime { + Unknown = 0, + HIP = 1, + OpenCL = 2, +}; +} // end namespace amd +} // end namespace gpu +} // end namespace mlir + +#endif // MLIR_CONVERSION_GPUTOROCDL_RUNTIMES_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/ConversionTarget.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/ConversionTarget.h new file mode 100644 index 0000000000000000000000000000000000000000..facd9f4e7e4e6051486f21df7a175f81666cdf6e --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/ConversionTarget.h @@ -0,0 +1,23 @@ +//===- ConversionTarget.h - LLVM dialect conversion target ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_CONVERSIONTARGET_H +#define MLIR_CONVERSION_LLVMCOMMON_CONVERSIONTARGET_H + +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { +/// Derived class that automatically populates legalization information for +/// different LLVM ops. +class LLVMConversionTarget : public ConversionTarget { +public: + explicit LLVMConversionTarget(MLIRContext &ctx); +}; +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_CONVERSIONTARGET_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/LoweringOptions.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/LoweringOptions.h new file mode 100644 index 0000000000000000000000000000000000000000..c94892fd4f8164ce20d6e69e6c6e1c42aa35d0fe --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/LoweringOptions.h @@ -0,0 +1,74 @@ +//===- LoweringOptions.h - Common config for lowering to LLVM ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides a configuration shared by several conversions targeting the LLVM +// dialect. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_LOWERINGOPTIONS_H +#define MLIR_CONVERSION_LLVMCOMMON_LOWERINGOPTIONS_H + +#include "llvm/IR/DataLayout.h" + +namespace mlir { + +class DataLayout; +class MLIRContext; + +/// Value to pass as bitwidth for the index type when the converter is expected +/// to derive the bitwidth from the LLVM data layout. +static constexpr unsigned kDeriveIndexBitwidthFromDataLayout = 0; + +/// Options to control the LLVM lowering. The struct is used to share lowering +/// options between passes, patterns, and type converter. +class LowerToLLVMOptions { +public: + explicit LowerToLLVMOptions(MLIRContext *ctx); + LowerToLLVMOptions(MLIRContext *ctx, const DataLayout &dl); + + bool useBarePtrCallConv = false; + + enum class AllocLowering { + /// Use malloc for heap allocations. + Malloc, + + /// Use aligned_alloc for heap allocations. + AlignedAlloc, + + /// Do not lower heap allocations. Users must provide their own patterns for + /// AllocOp and DeallocOp lowering. + None + }; + + AllocLowering allocLowering = AllocLowering::Malloc; + + bool useGenericFunctions = false; + + /// The data layout of the module to produce. This must be consistent with the + /// data layout used in the upper levels of the lowering pipeline. + // TODO: this should be replaced by MLIR data layout when one exists. + llvm::DataLayout dataLayout = llvm::DataLayout(""); + + /// Set the index bitwidth to the given value. + void overrideIndexBitwidth(unsigned bitwidth) { + assert(bitwidth != kDeriveIndexBitwidthFromDataLayout && + "can only override to a concrete bitwidth"); + indexBitwidth = bitwidth; + } + + /// Get the index bitwidth. + unsigned getIndexBitwidth() const { return indexBitwidth; } + +private: + unsigned indexBitwidth; +}; + +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_LOWERINGOPTIONS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/MemRefBuilder.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/MemRefBuilder.h new file mode 100644 index 0000000000000000000000000000000000000000..d5055f023cdc8110f714cc55f54197589ba5f3cf --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/MemRefBuilder.h @@ -0,0 +1,276 @@ +//===- MemRefBuilder.h - Helper for LLVM MemRef equivalents -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides a convenience API for emitting IR that inspects or constructs values +// of LLVM dialect structure type that correspond to ranked or unranked memref. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_MEMREFBUILDER_H +#define MLIR_CONVERSION_LLVMCOMMON_MEMREFBUILDER_H + +#include "mlir/Conversion/LLVMCommon/StructBuilder.h" +#include "mlir/IR/OperationSupport.h" + +namespace mlir { + +class LLVMTypeConverter; +class MemRefType; +class UnrankedMemRefType; + +namespace LLVM { +class LLVMPointerType; +} // namespace LLVM + +/// Helper class to produce LLVM dialect operations extracting or inserting +/// elements of a MemRef descriptor. Wraps a Value pointing to the descriptor. +/// The Value may be null, in which case none of the operations are valid. +class MemRefDescriptor : public StructBuilder { +public: + /// Construct a helper for the given descriptor value. + explicit MemRefDescriptor(Value descriptor); + /// Builds IR creating a `poison` value of the descriptor type. + static MemRefDescriptor poison(OpBuilder &builder, Location loc, + Type descriptorType); + /// Builds IR creating a MemRef descriptor that represents `type` and + /// populates it with static shape and stride information extracted from the + /// type. + static MemRefDescriptor + fromStaticShape(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, MemRefType type, + Value memory); + static MemRefDescriptor + fromStaticShape(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, MemRefType type, + Value memory, Value alignedMemory); + + /// Builds IR extracting the allocated pointer from the descriptor. + Value allocatedPtr(OpBuilder &builder, Location loc); + /// Builds IR inserting the allocated pointer into the descriptor. + void setAllocatedPtr(OpBuilder &builder, Location loc, Value ptr); + + /// Builds IR extracting the aligned pointer from the descriptor. + Value alignedPtr(OpBuilder &builder, Location loc); + + /// Builds IR inserting the aligned pointer into the descriptor. + void setAlignedPtr(OpBuilder &builder, Location loc, Value ptr); + + /// Builds IR extracting the offset from the descriptor. + Value offset(OpBuilder &builder, Location loc); + + /// Builds IR inserting the offset into the descriptor. + void setOffset(OpBuilder &builder, Location loc, Value offset); + void setConstantOffset(OpBuilder &builder, Location loc, uint64_t offset); + + /// Builds IR extracting the pos-th size from the descriptor. + Value size(OpBuilder &builder, Location loc, unsigned pos); + Value size(OpBuilder &builder, Location loc, Value pos, int64_t rank); + + /// Builds IR inserting the pos-th size into the descriptor + void setSize(OpBuilder &builder, Location loc, unsigned pos, Value size); + void setConstantSize(OpBuilder &builder, Location loc, unsigned pos, + uint64_t size); + + /// Builds IR extracting the pos-th size from the descriptor. + Value stride(OpBuilder &builder, Location loc, unsigned pos); + + /// Builds IR inserting the pos-th stride into the descriptor + void setStride(OpBuilder &builder, Location loc, unsigned pos, Value stride); + void setConstantStride(OpBuilder &builder, Location loc, unsigned pos, + uint64_t stride); + + /// Returns the type of array element in this descriptor. + Type getIndexType() { return indexType; }; + + /// Returns the (LLVM) pointer type this descriptor contains. + LLVM::LLVMPointerType getElementPtrType(); + + /// Builds IR for getting the start address of the buffer represented + /// by this memref: + /// `memref.alignedPtr + memref.offset * sizeof(type.getElementType())`. + /// \note there is no setter for this one since it is derived from alignedPtr + /// and offset. + Value bufferPtr(OpBuilder &builder, Location loc, + const LLVMTypeConverter &converter, MemRefType type); + + /// Builds IR populating a MemRef descriptor structure from a list of + /// individual values composing that descriptor, in the following order: + /// - allocated pointer; + /// - aligned pointer; + /// - offset; + /// - sizes; + /// - strides; + /// where is the MemRef rank as provided in `type`. + static Value pack(OpBuilder &builder, Location loc, + const LLVMTypeConverter &converter, MemRefType type, + ValueRange values); + + /// Builds IR extracting individual elements of a MemRef descriptor structure + /// and returning them as `results` list. + static void unpack(OpBuilder &builder, Location loc, Value packed, + MemRefType type, SmallVectorImpl &results); + + /// Returns the number of non-aggregate values that would be produced by + /// `unpack`. + static unsigned getNumUnpackedValues(MemRefType type); + +private: + // Cached index type. + Type indexType; +}; + +/// Helper class allowing the user to access a range of Values that correspond +/// to an unpacked memref descriptor using named accessors. This does not own +/// the values. +class MemRefDescriptorView { +public: + /// Constructs the view from a range of values. Infers the rank from the size + /// of the range. + explicit MemRefDescriptorView(ValueRange range); + + /// Returns the allocated pointer Value. + Value allocatedPtr(); + + /// Returns the aligned pointer Value. + Value alignedPtr(); + + /// Returns the offset Value. + Value offset(); + + /// Returns the pos-th size Value. + Value size(unsigned pos); + + /// Returns the pos-th stride Value. + Value stride(unsigned pos); + +private: + /// Rank of the memref the descriptor is pointing to. + int rank; + /// Underlying range of Values. + ValueRange elements; +}; + +class UnrankedMemRefDescriptor : public StructBuilder { +public: + /// Construct a helper for the given descriptor value. + explicit UnrankedMemRefDescriptor(Value descriptor); + /// Builds IR creating an `undef` value of the descriptor type. + static UnrankedMemRefDescriptor poison(OpBuilder &builder, Location loc, + Type descriptorType); + + /// Builds IR extracting the rank from the descriptor + Value rank(OpBuilder &builder, Location loc) const; + /// Builds IR setting the rank in the descriptor + void setRank(OpBuilder &builder, Location loc, Value value); + /// Builds IR extracting ranked memref descriptor ptr + Value memRefDescPtr(OpBuilder &builder, Location loc) const; + /// Builds IR setting ranked memref descriptor ptr + void setMemRefDescPtr(OpBuilder &builder, Location loc, Value value); + + /// Builds IR populating an unranked MemRef descriptor structure from a list + /// of individual constituent values in the following order: + /// - rank of the memref; + /// - pointer to the memref descriptor. + static Value pack(OpBuilder &builder, Location loc, + const LLVMTypeConverter &converter, UnrankedMemRefType type, + ValueRange values); + + /// Builds IR extracting individual elements that compose an unranked memref + /// descriptor and returns them as `results` list. + static void unpack(OpBuilder &builder, Location loc, Value packed, + SmallVectorImpl &results); + + /// Returns the number of non-aggregate values that would be produced by + /// `unpack`. + static unsigned getNumUnpackedValues() { return 2; } + + /// Builds IR computing the sizes in bytes (suitable for opaque allocation) + /// and appends the corresponding values into `sizes`. `addressSpaces` + /// which must have the same length as `values`, is needed to handle layouts + /// where sizeof(ptr addrspace(N)) != sizeof(ptr addrspace(0)). + static void computeSizes(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + ArrayRef values, + ArrayRef addressSpaces, + SmallVectorImpl &sizes); + + /// TODO: The following accessors don't take alignment rules between elements + /// of the descriptor struct into account. For some architectures, it might be + /// necessary to extend them and to use `llvm::DataLayout` contained in + /// `LLVMTypeConverter`. + + /// Builds IR extracting the allocated pointer from the descriptor. + static Value allocatedPtr(OpBuilder &builder, Location loc, + Value memRefDescPtr, + LLVM::LLVMPointerType elemPtrType); + /// Builds IR inserting the allocated pointer into the descriptor. + static void setAllocatedPtr(OpBuilder &builder, Location loc, + Value memRefDescPtr, + LLVM::LLVMPointerType elemPtrType, + Value allocatedPtr); + + /// Builds IR extracting the aligned pointer from the descriptor. + static Value alignedPtr(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value memRefDescPtr, + LLVM::LLVMPointerType elemPtrType); + /// Builds IR inserting the aligned pointer into the descriptor. + static void setAlignedPtr(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value memRefDescPtr, + LLVM::LLVMPointerType elemPtrType, + Value alignedPtr); + + /// Builds IR for getting the pointer to the offset's location. + /// Returns a pointer to a convertType(index), which points to the beggining + /// of a struct {index, index[rank], index[rank]}. + static Value offsetBasePtr(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value memRefDescPtr, + LLVM::LLVMPointerType elemPtrType); + /// Builds IR extracting the offset from the descriptor. + static Value offset(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value memRefDescPtr, LLVM::LLVMPointerType elemPtrType); + /// Builds IR inserting the offset into the descriptor. + static void setOffset(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value memRefDescPtr, LLVM::LLVMPointerType elemPtrType, + Value offset); + + /// Builds IR extracting the pointer to the first element of the size array. + static Value sizeBasePtr(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value memRefDescPtr, + LLVM::LLVMPointerType elemPtrType); + /// Builds IR extracting the size[index] from the descriptor. + static Value size(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, Value sizeBasePtr, + Value index); + /// Builds IR inserting the size[index] into the descriptor. + static void setSize(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, Value sizeBasePtr, + Value index, Value size); + + /// Builds IR extracting the pointer to the first element of the stride array. + static Value strideBasePtr(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value sizeBasePtr, Value rank); + /// Builds IR extracting the stride[index] from the descriptor. + static Value stride(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value strideBasePtr, Value index, Value stride); + /// Builds IR inserting the stride[index] into the descriptor. + static void setStride(OpBuilder &builder, Location loc, + const LLVMTypeConverter &typeConverter, + Value strideBasePtr, Value index, Value stride); +}; + +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_MEMREFBUILDER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/Pattern.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/Pattern.h new file mode 100644 index 0000000000000000000000000000000000000000..7e946495e3e7f851ee51a1b4ae071dd393a029b1 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/Pattern.h @@ -0,0 +1,261 @@ +//===- Pattern.h - Pattern for conversion to the LLVM dialect ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_PATTERN_H +#define MLIR_CONVERSION_LLVMCOMMON_PATTERN_H + +#include "mlir/Conversion/LLVMCommon/MemRefBuilder.h" +#include "mlir/Conversion/LLVMCommon/TypeConverter.h" +#include "mlir/Dialect/LLVMIR/LLVMAttrs.h" +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { +class CallOpInterface; + +namespace LLVM { +namespace detail { +/// Handle generically setting flags as native properties on LLVM operations. +void setNativeProperties(Operation *op, IntegerOverflowFlags overflowFlags); + +/// Replaces the given operation "op" with a new operation of type "targetOp" +/// and given operands. +LogicalResult oneToOneRewrite( + Operation *op, StringRef targetOp, ValueRange operands, + ArrayRef targetAttrs, + const LLVMTypeConverter &typeConverter, ConversionPatternRewriter &rewriter, + IntegerOverflowFlags overflowFlags = IntegerOverflowFlags::none); + +/// Replaces the given operation "op" with a call to an LLVM intrinsic with the +/// specified name "intrinsic" and operands. +/// +/// The rewrite performs a simple one-to-one matching between the op and LLVM +/// intrinsic. For example: +/// +/// ```mlir +/// %res = intr.op %val : vector<16xf32> +/// ``` +/// +/// can be converted to +/// +/// ```mlir +/// %res = llvm.call_intrinsic "intrinsic"(%val) +/// ``` +/// +/// The provided operands must be LLVM-compatible. +/// +/// Upholds a convention that multi-result operations get converted into an +/// operation returning the LLVM IR structure type, in which case individual +/// values are first extracted before replacing the original results. +LogicalResult intrinsicRewrite(Operation *op, StringRef intrinsic, + ValueRange operands, + const LLVMTypeConverter &typeConverter, + RewriterBase &rewriter); + +} // namespace detail + +/// Decomposes a `src` value into a set of values of type `dstType` through +/// series of bitcasts and vector ops. Src and dst types are expected to be int +/// or float types or vector types of them. +SmallVector decomposeValue(OpBuilder &builder, Location loc, Value src, + Type dstType); + +/// Composes a set of `src` values into a single value of type `dstType` through +/// series of bitcasts and vector ops. Inversely to `decomposeValue`, this +/// function is used to combine multiple values into a single value. +Value composeValue(OpBuilder &builder, Location loc, ValueRange src, + Type dstType); + +/// Performs the index computation to get to the element at `indices` of the +/// memory pointed to by `memRefDesc`, using the layout map of `type`. +/// The indices are linearized as: +/// `base_offset + index_0 * stride_0 + ... + index_n * stride_n`. +Value getStridedElementPtr( + OpBuilder &builder, Location loc, const LLVMTypeConverter &converter, + MemRefType type, Value memRefDesc, ValueRange indices, + LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none); +} // namespace LLVM + +/// Base class for operation conversions targeting the LLVM IR dialect. It +/// provides the conversion patterns with access to the LLVMTypeConverter and +/// the LowerToLLVMOptions. The class captures the LLVMTypeConverter and the +/// LowerToLLVMOptions by reference meaning the references have to remain alive +/// during the entire pattern lifetime. +class ConvertToLLVMPattern : public ConversionPattern { +public: + ConvertToLLVMPattern(StringRef rootOpName, MLIRContext *context, + const LLVMTypeConverter &typeConverter, + PatternBenefit benefit = 1); + +protected: + /// Returns the LLVM dialect. + LLVM::LLVMDialect &getDialect() const; + + const LLVMTypeConverter *getTypeConverter() const; + + /// Gets the MLIR type wrapping the LLVM integer type whose bit width is + /// defined by the used type converter. + Type getIndexType() const; + + /// Gets the MLIR type wrapping the LLVM integer type whose bit width + /// corresponds to that of a LLVM pointer type. + Type getIntPtrType(unsigned addressSpace = 0) const; + + /// Gets the MLIR type wrapping the LLVM void type. + Type getVoidType() const; + + /// Get the MLIR type wrapping the LLVM i8* type. + Type getVoidPtrType() const; + + /// Create a constant Op producing a value of `resultType` from an index-typed + /// integer attribute. + static Value createIndexAttrConstant(OpBuilder &builder, Location loc, + Type resultType, int64_t value); + + /// Convenience wrapper for the corresponding helper utility. + /// This is a strided getElementPtr variant with linearized subscripts. + Value getStridedElementPtr( + ConversionPatternRewriter &rewriter, Location loc, MemRefType type, + Value memRefDesc, ValueRange indices, + LLVM::GEPNoWrapFlags noWrapFlags = LLVM::GEPNoWrapFlags::none) const; + + /// Returns if the given memref type is convertible to LLVM and has an + /// identity layout map. + bool isConvertibleAndHasIdentityMaps(MemRefType type) const; + + /// Returns the type of a pointer to an element of the memref. + Type getElementPtrType(MemRefType type) const; + + /// Computes sizes, strides and buffer size of `memRefType` with identity + /// layout. Emits constant ops for the static sizes of `memRefType`, and uses + /// `dynamicSizes` for the others. Emits instructions to compute strides and + /// buffer size from these sizes. + /// + /// For example, memref<4x?xf32> with `sizeInBytes = true` emits: + /// `sizes[0]` = llvm.mlir.constant(4 : index) : i64 + /// `sizes[1]` = `dynamicSizes[0]` + /// `strides[1]` = llvm.mlir.constant(1 : index) : i64 + /// `strides[0]` = `sizes[0]` + /// %size = llvm.mul `sizes[0]`, `sizes[1]` : i64 + /// %nullptr = llvm.mlir.zero : !llvm.ptr + /// %gep = llvm.getelementptr %nullptr[%size] + /// : (!llvm.ptr, i64) -> !llvm.ptr, f32 + /// `sizeBytes` = llvm.ptrtoint %gep : !llvm.ptr to i64 + /// + /// If `sizeInBytes = false`, memref<4x?xf32> emits: + /// `sizes[0]` = llvm.mlir.constant(4 : index) : i64 + /// `sizes[1]` = `dynamicSizes[0]` + /// `strides[1]` = llvm.mlir.constant(1 : index) : i64 + /// `strides[0]` = `sizes[0]` + /// %size = llvm.mul `sizes[0]`, `sizes[1]` : i64 + void getMemRefDescriptorSizes(Location loc, MemRefType memRefType, + ValueRange dynamicSizes, + ConversionPatternRewriter &rewriter, + SmallVectorImpl &sizes, + SmallVectorImpl &strides, Value &size, + bool sizeInBytes = true) const; + + /// Computes the size of type in bytes. + Value getSizeInBytes(Location loc, Type type, + ConversionPatternRewriter &rewriter) const; + + /// Computes total number of elements for the given MemRef and dynamicSizes. + Value getNumElements(Location loc, MemRefType memRefType, + ValueRange dynamicSizes, + ConversionPatternRewriter &rewriter) const; + + /// Creates and populates a canonical memref descriptor struct. + MemRefDescriptor + createMemRefDescriptor(Location loc, MemRefType memRefType, + Value allocatedPtr, Value alignedPtr, + ArrayRef sizes, ArrayRef strides, + ConversionPatternRewriter &rewriter) const; + + /// Copies the memory descriptor for any operands that were unranked + /// descriptors originally to heap-allocated memory (if toDynamic is true) or + /// to stack-allocated memory (otherwise). Also frees the previously used + /// memory (that is assumed to be heap-allocated) if toDynamic is false. + LogicalResult copyUnrankedDescriptors(OpBuilder &builder, Location loc, + TypeRange origTypes, + SmallVectorImpl &operands, + bool toDynamic) const; +}; + +/// Utility class for operation conversions targeting the LLVM dialect that +/// match exactly one source operation. +template +class ConvertOpToLLVMPattern : public ConvertToLLVMPattern { +public: + using OpAdaptor = typename SourceOp::Adaptor; + using OneToNOpAdaptor = + typename SourceOp::template GenericAdaptor>; + + explicit ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter, + PatternBenefit benefit = 1) + : ConvertToLLVMPattern(SourceOp::getOperationName(), + &typeConverter.getContext(), typeConverter, + benefit) {} + + /// Wrappers around the RewritePattern methods that pass the derived op type. + LogicalResult + matchAndRewrite(Operation *op, ArrayRef operands, + ConversionPatternRewriter &rewriter) const final { + auto sourceOp = cast(op); + return matchAndRewrite(sourceOp, OpAdaptor(operands, sourceOp), rewriter); + } + LogicalResult + matchAndRewrite(Operation *op, ArrayRef operands, + ConversionPatternRewriter &rewriter) const final { + auto sourceOp = cast(op); + return matchAndRewrite(sourceOp, OneToNOpAdaptor(operands, sourceOp), + rewriter); + } + + /// Methods that operate on the SourceOp type. One of these must be + /// overridden by the derived pattern class. + virtual LogicalResult + matchAndRewrite(SourceOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const { + llvm_unreachable("matchAndRewrite is not implemented"); + } + virtual LogicalResult + matchAndRewrite(SourceOp op, OneToNOpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const { + SmallVector oneToOneOperands = + getOneToOneAdaptorOperands(adaptor.getOperands()); + return matchAndRewrite(op, OpAdaptor(oneToOneOperands, adaptor), rewriter); + } + +private: + using ConvertToLLVMPattern::matchAndRewrite; +}; + +/// Generic implementation of one-to-one conversion from "SourceOp" to +/// "TargetOp" where the latter belongs to the LLVM dialect or an equivalent. +/// Upholds a convention that multi-result operations get converted into an +/// operation returning the LLVM IR structure type, in which case individual +/// values must be extracted from using LLVM::ExtractValueOp before being used. +template +class OneToOneConvertToLLVMPattern : public ConvertOpToLLVMPattern { +public: + using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern; + using Super = OneToOneConvertToLLVMPattern; + + /// Converts the type of the result to an LLVM type, pass operands as is, + /// preserve attributes. + LogicalResult + matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + return LLVM::detail::oneToOneRewrite(op, TargetOp::getOperationName(), + adaptor.getOperands(), op->getAttrs(), + *this->getTypeConverter(), rewriter); + } +}; + +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_PATTERN_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/PrintCallHelper.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/PrintCallHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..33402301115b7381282d12d4a16c46d2af775fdf --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/PrintCallHelper.h @@ -0,0 +1,34 @@ +//===- PrintCallHelper.h - Helper to emit runtime print calls ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_LLVMIR_PRINTCALLHELPER_H_ +#define MLIR_DIALECT_LLVMIR_PRINTCALLHELPER_H_ + +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" +#include "llvm/ADT/StringRef.h" +#include + +namespace mlir { + +class OpBuilder; +class LLVMTypeConverter; + +namespace LLVM { + +/// Generate IR that prints the given string to stdout. +/// If a custom runtime function is defined via `runtimeFunctionName`, it must +/// have the signature void(char const*). The default function is `printString`. +LogicalResult createPrintStrCall( + OpBuilder &builder, Location loc, ModuleOp moduleOp, StringRef symbolName, + StringRef string, const LLVMTypeConverter &typeConverter, + bool addNewline = true, std::optional runtimeFunctionName = {}); +} // namespace LLVM + +} // namespace mlir + +#endif diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/StructBuilder.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/StructBuilder.h new file mode 100644 index 0000000000000000000000000000000000000000..b6ff1d13abf1dae11c4de70df9be596238fccd88 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/StructBuilder.h @@ -0,0 +1,51 @@ +//===- StructBuilder.h - Helper for building LLVM structs -------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides a convenience API for emitting IR that inspects or constructs values +// of LLVM dialect structure types. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_STRUCTBUILDER_H +#define MLIR_CONVERSION_LLVMCOMMON_STRUCTBUILDER_H + +#include "mlir/IR/Types.h" +#include "mlir/IR/Value.h" + +namespace mlir { + +class OpBuilder; + +/// Helper class to produce LLVM dialect operations extracting or inserting +/// values to a struct. +class StructBuilder { +public: + /// Construct a helper for the given value. + explicit StructBuilder(Value v); + /// Builds IR creating a `poison` value of the descriptor type. + static StructBuilder poison(OpBuilder &builder, Location loc, + Type descriptorType); + + /*implicit*/ operator Value() { return value; } + +protected: + // LLVM value + Value value; + // Cached struct type. + Type structType; + +protected: + /// Builds IR to extract a value from the struct at position pos + Value extractPtr(OpBuilder &builder, Location loc, unsigned pos) const; + /// Builds IR to set a value in the struct at position pos + void setPtr(OpBuilder &builder, Location loc, unsigned pos, Value ptr); +}; + +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_STRUCTBUILDER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/TypeConverter.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/TypeConverter.h new file mode 100644 index 0000000000000000000000000000000000000000..38b5e492a8ed8ff8321021648bfe96d2e8062335 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/TypeConverter.h @@ -0,0 +1,284 @@ +//===- TypeConverter.h - Convert builtin to LLVM dialect types --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Provides a type converter configuration for converting most builtin types to +// LLVM dialect types. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_TYPECONVERTER_H +#define MLIR_CONVERSION_LLVMCOMMON_TYPECONVERTER_H + +#include "mlir/Conversion/LLVMCommon/LoweringOptions.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { + +class DataLayoutAnalysis; +class FunctionOpInterface; +class LowerToLLVMOptions; + +namespace LLVM { +class LLVMDialect; +class LLVMPointerType; +class LLVMFunctionType; +class LLVMStructType; +} // namespace LLVM + +/// Conversion from types to the LLVM IR dialect. +class LLVMTypeConverter : public TypeConverter { + /// Give structFuncArgTypeConverter access to memref-specific functions. + friend LogicalResult + structFuncArgTypeConverter(const LLVMTypeConverter &converter, Type type, + SmallVectorImpl &result); + +public: + using TypeConverter::convertType; + + /// Create an LLVMTypeConverter using the default LowerToLLVMOptions. + /// Optionally takes a data layout analysis to use in conversions. + LLVMTypeConverter(MLIRContext *ctx, + const DataLayoutAnalysis *analysis = nullptr); + + /// Create an LLVMTypeConverter using custom LowerToLLVMOptions. Optionally + /// takes a data layout analysis to use in conversions. + LLVMTypeConverter(MLIRContext *ctx, const LowerToLLVMOptions &options, + const DataLayoutAnalysis *analysis = nullptr); + + /// Convert a function type. The arguments and results are converted one by + /// one and results are packed into a wrapped LLVM IR structure type. `result` + /// is populated with argument mapping. + Type convertFunctionSignature(FunctionType funcTy, bool isVariadic, + bool useBarePtrCallConv, + SignatureConversion &result) const; + + /// Convert a function type. The arguments and results are converted one by + /// one and results are packed into a wrapped LLVM IR structure type. `result` + /// is populated with argument mapping. Converted types of `llvm.byval` and + /// `llvm.byref` function arguments which are not LLVM pointers are overridden + /// with LLVM pointers. Overridden arguments are returned in + /// `byValRefNonPtrAttrs`. + Type convertFunctionSignature(FunctionOpInterface funcOp, bool isVariadic, + bool useBarePtrCallConv, + LLVMTypeConverter::SignatureConversion &result, + SmallVectorImpl> + &byValRefNonPtrAttrs) const; + + /// Convert a non-empty list of types to be returned from a function into an + /// LLVM-compatible type. In particular, if more than one value is returned, + /// create an LLVM dialect structure type with elements that correspond to + /// each of the types converted with `convertCallingConventionType`. + Type packFunctionResults(TypeRange types, + bool useBarePointerCallConv = false) const; + + /// Convert a non-empty list of types of values produced by an operation into + /// an LLVM-compatible type. In particular, if more than one value is + /// produced, create a literal structure with elements that correspond to each + /// of the LLVM-compatible types converted with `convertType`. + Type packOperationResults(TypeRange types) const; + + /// Convert a type in the context of the default or bare pointer calling + /// convention. Calling convention sensitive types, such as MemRefType and + /// UnrankedMemRefType, are converted following the specific rules for the + /// calling convention. Calling convention independent types are converted + /// following the default LLVM type conversions. + Type convertCallingConventionType(Type type, + bool useBarePointerCallConv = false) const; + + /// Promote the bare pointers in 'values' that resulted from memrefs to + /// descriptors. 'stdTypes' holds the types of 'values' before the conversion + /// to the LLVM-IR dialect (i.e., MemRefType, or any other builtin type). + void promoteBarePtrsToDescriptors(ConversionPatternRewriter &rewriter, + Location loc, ArrayRef stdTypes, + SmallVectorImpl &values) const; + + /// Returns the MLIR context. + MLIRContext &getContext() const; + + /// Returns the LLVM dialect. + LLVM::LLVMDialect *getDialect() const { return llvmDialect; } + + const LowerToLLVMOptions &getOptions() const { return options; } + + /// Promote the LLVM representation of all operands including promoting MemRef + /// descriptors to stack and use pointers to struct to avoid the complexity + /// of the platform-specific C/C++ ABI lowering related to struct argument + /// passing. + SmallVector promoteOperands(Location loc, ValueRange opOperands, + ValueRange operands, OpBuilder &builder, + bool useBarePtrCallConv = false) const; + + /// Promote the LLVM struct representation of one MemRef descriptor to stack + /// and use pointer to struct to avoid the complexity of the platform-specific + /// C/C++ ABI lowering related to struct argument passing. + Value promoteOneMemRefDescriptor(Location loc, Value operand, + OpBuilder &builder) const; + + /// Converts the function type to a C-compatible format, in particular using + /// pointers to memref descriptors for arguments. Also converts the return + /// type to a pointer argument if it is a struct. Returns true if this + /// was the case. + std::pair + convertFunctionTypeCWrapper(FunctionType type) const; + + /// Returns the data layout to use during and after conversion. + const llvm::DataLayout &getDataLayout() const { return options.dataLayout; } + + /// Returns the data layout analysis to query during conversion. + const DataLayoutAnalysis *getDataLayoutAnalysis() const { + return dataLayoutAnalysis; + } + + /// Gets the LLVM representation of the index type. The returned type is an + /// integer type with the size configured for this type converter. + Type getIndexType() const; + + /// Gets the bitwidth of the index type when converted to LLVM. + unsigned getIndexTypeBitwidth() const { return options.getIndexBitwidth(); } + + /// Gets the pointer bitwidth. + unsigned getPointerBitwidth(unsigned addressSpace = 0) const; + + /// Returns the size of the memref descriptor object in bytes. + unsigned getMemRefDescriptorSize(MemRefType type, + const DataLayout &layout) const; + + /// Returns the size of the unranked memref descriptor object in bytes. + unsigned getUnrankedMemRefDescriptorSize(UnrankedMemRefType type, + const DataLayout &layout) const; + + /// Return the LLVM address space corresponding to the memory space of the + /// memref type `type` or failure if the memory space cannot be converted to + /// an integer. + FailureOr getMemRefAddressSpace(BaseMemRefType type) const; + + /// Check if a memref type can be converted to a bare pointer. + static bool canConvertToBarePtr(BaseMemRefType type); + + /// Convert a memref type into a list of LLVM IR types that will form the + /// memref descriptor. If `unpackAggregates` is true the `sizes` and `strides` + /// arrays in the descriptors are unpacked to individual index-typed elements, + /// else they are kept as rank-sized arrays of index type. In particular, + /// the list will contain: + /// - two pointers to the memref element type, followed by + /// - an index-typed offset, followed by + /// - (if unpackAggregates = true) + /// - one index-typed size per dimension of the memref, followed by + /// - one index-typed stride per dimension of the memref. + /// - (if unpackArrregates = false) + /// - one rank-sized array of index-type for the size of each dimension + /// - one rank-sized array of index-type for the stride of each dimension + /// + /// For example, memref is converted to the following list: + /// - `!llvm<"float*">` (allocated pointer), + /// - `!llvm<"float*">` (aligned pointer), + /// - `i64` (offset), + /// - `i64`, `i64` (sizes), + /// - `i64`, `i64` (strides). + /// These types can be recomposed to a memref descriptor struct. + SmallVector getMemRefDescriptorFields(MemRefType type, + bool unpackAggregates) const; + + /// Convert an unranked memref type into a list of non-aggregate LLVM IR types + /// that will form the unranked memref descriptor. In particular, this list + /// contains: + /// - an integer rank, followed by + /// - a pointer to the memref descriptor struct. + /// For example, memref<*xf32> is converted to the following list: + /// i64 (rank) + /// !llvm<"i8*"> (type-erased pointer). + /// These types can be recomposed to a unranked memref descriptor struct. + SmallVector getUnrankedMemRefDescriptorFields() const; + +protected: + /// Pointer to the LLVM dialect. + LLVM::LLVMDialect *llvmDialect; + + // Recursive structure detection. + // We store one entry per thread here, and rely on locking. + DenseMap>> conversionCallStack; + llvm::sys::SmartRWMutex callStackMutex; + SmallVector &getCurrentThreadRecursiveStack(); + +private: + /// Convert a function type. The arguments and results are converted one by + /// one. Additionally, if the function returns more than one value, pack the + /// results into an LLVM IR structure type so that the converted function type + /// returns at most one result. + Type convertFunctionType(FunctionType type) const; + + /// Common implementation for `convertFunctionSignature` methods. Convert a + /// function type. The arguments and results are converted one by one and + /// results are packed into a wrapped LLVM IR structure type. `result` is + /// populated with argument mapping. If `byValRefNonPtrAttrs` is provided, + /// converted types of `llvm.byval` and `llvm.byref` function arguments which + /// are not LLVM pointers are overridden with LLVM pointers. `llvm.byval` and + /// `llvm.byref` arguments that were already converted to LLVM pointer types + /// are removed from 'byValRefNonPtrAttrs`. + Type convertFunctionSignatureImpl( + FunctionType funcTy, bool isVariadic, bool useBarePtrCallConv, + LLVMTypeConverter::SignatureConversion &result, + SmallVectorImpl> *byValRefNonPtrAttrs) + const; + + /// Convert the index type. Uses llvmModule data layout to create an integer + /// of the pointer bitwidth. + Type convertIndexType(IndexType type) const; + + /// Convert an integer type `i*` to `!llvm<"i*">`. + Type convertIntegerType(IntegerType type) const; + + /// Convert a floating point type: `f16` to `f16`, `f32` to + /// `f32` and `f64` to `f64`. `bf16` is not supported + /// by LLVM. 8-bit float types are converted to 8-bit integers as this is how + /// all LLVM backends that support them currently represent them. + Type convertFloatType(FloatType type) const; + + /// Convert complex number type: `complex` to `!llvm<"{ half, half }">`, + /// `complex` to `!llvm<"{ float, float }">`, and `complex` to + /// `!llvm<"{ double, double }">`. `complex` is not supported. + Type convertComplexType(ComplexType type) const; + + /// Convert a memref type into an LLVM type that captures the relevant data. + Type convertMemRefType(MemRefType type) const; + + /// Convert an unranked memref type to an LLVM type that captures the + /// runtime rank and a pointer to the static ranked memref desc + Type convertUnrankedMemRefType(UnrankedMemRefType type) const; + + /// Convert a memref type to a bare pointer to the memref element type. + Type convertMemRefToBarePtr(BaseMemRefType type) const; + + /// Convert a 1D vector type into an LLVM vector type. + FailureOr convertVectorType(VectorType type) const; + + /// Options for customizing the llvm lowering. + LowerToLLVMOptions options; + + /// Data layout analysis mapping scopes to layouts active in them. + const DataLayoutAnalysis *dataLayoutAnalysis; +}; + +/// Callback to convert function argument types. It converts a MemRef function +/// argument to a list of non-aggregate types containing descriptor +/// information, and an UnrankedmemRef function argument to a list containing +/// the rank and a pointer to a descriptor struct. +LogicalResult structFuncArgTypeConverter(const LLVMTypeConverter &converter, + Type type, + SmallVectorImpl &result); + +/// Callback to convert function argument types. It converts MemRef function +/// arguments to bare pointers to the MemRef element type. +LogicalResult barePtrFuncArgTypeConverter(const LLVMTypeConverter &converter, + Type type, + SmallVectorImpl &result); + +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_TYPECONVERTER_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/VectorPattern.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/VectorPattern.h new file mode 100644 index 0000000000000000000000000000000000000000..964281592cc65e176d24f10319948789401804f2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/LLVMCommon/VectorPattern.h @@ -0,0 +1,112 @@ +//===- VectorPattern.h - Conversion pattern to the LLVM dialect -*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_LLVMCOMMON_VECTORPATTERN_H +#define MLIR_CONVERSION_LLVMCOMMON_VECTORPATTERN_H + +#include "mlir/Conversion/LLVMCommon/Pattern.h" +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { + +namespace LLVM { +namespace detail { +// Helper struct to "unroll" operations on n-D vectors in terms of operations on +// 1-D LLVM vectors. +struct NDVectorTypeInfo { + // LLVM array struct which encodes n-D vectors. + Type llvmNDVectorTy; + // LLVM vector type which encodes the inner 1-D vector type. + Type llvm1DVectorTy; + // Multiplicity of llvmNDVectorTy to llvm1DVectorTy. + SmallVector arraySizes; +}; + +// For >1-D vector types, extracts the necessary information to iterate over all +// 1-D subvectors in the underlying llrepresentation of the n-D vector +// Iterates on the llvm array type until we hit a non-array type (which is +// asserted to be an llvm vector type). +NDVectorTypeInfo extractNDVectorTypeInfo(VectorType vectorType, + const LLVMTypeConverter &converter); + +// Express `linearIndex` in terms of coordinates of `basis`. +// Returns the empty vector when linearIndex is out of the range [0, P] where +// P is the product of all the basis coordinates. +// +// Prerequisites: +// Basis is an array of nonnegative integers (signed type inherited from +// vector shape type). +SmallVector getCoordinates(ArrayRef basis, + unsigned linearIndex); + +// Iterate of linear index, convert to coords space and insert splatted 1-D +// vector in each position. +void nDVectorIterate(const NDVectorTypeInfo &info, OpBuilder &builder, + function_ref)> fun); + +LogicalResult handleMultidimensionalVectors( + Operation *op, ValueRange operands, const LLVMTypeConverter &typeConverter, + std::function createOperand, + ConversionPatternRewriter &rewriter); + +LogicalResult vectorOneToOneRewrite( + Operation *op, StringRef targetOp, ValueRange operands, + ArrayRef targetAttrs, + const LLVMTypeConverter &typeConverter, ConversionPatternRewriter &rewriter, + IntegerOverflowFlags overflowFlags = IntegerOverflowFlags::none); +} // namespace detail +} // namespace LLVM + +// Default attribute conversion class, which passes all source attributes +// through to the target op, unmodified. +template +class AttrConvertPassThrough { +public: + AttrConvertPassThrough(SourceOp srcOp) : srcAttrs(srcOp->getAttrs()) {} + + ArrayRef getAttrs() const { return srcAttrs; } + LLVM::IntegerOverflowFlags getOverflowFlags() const { + return LLVM::IntegerOverflowFlags::none; + } + +private: + ArrayRef srcAttrs; +}; + +/// Basic lowering implementation to rewrite Ops with just one result to the +/// LLVM Dialect. This supports higher-dimensional vector types. +/// The AttrConvert template template parameter should be a template class +/// with SourceOp and TargetOp type parameters, a constructor that takes +/// a SourceOp instance, and a getAttrs() method that returns +/// ArrayRef. +template typename AttrConvert = + AttrConvertPassThrough> +class VectorConvertToLLVMPattern : public ConvertOpToLLVMPattern { +public: + using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern; + using Super = VectorConvertToLLVMPattern; + + LogicalResult + matchAndRewrite(SourceOp op, typename SourceOp::Adaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + static_assert( + std::is_base_of, SourceOp>::value, + "expected single result op"); + // Determine attributes for the target op + AttrConvert attrConvert(op); + + return LLVM::detail::vectorOneToOneRewrite( + op, TargetOp::getOperationName(), adaptor.getOperands(), + attrConvert.getAttrs(), *this->getTypeConverter(), rewriter, + attrConvert.getOverflowFlags()); + } +}; +} // namespace mlir + +#endif // MLIR_CONVERSION_LLVMCOMMON_VECTORPATTERN_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToLLVM/MathToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToLLVM/MathToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..0c1203e1e3c0e35d0e857655f99fa5d973ee1362 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToLLVM/MathToLLVM.h @@ -0,0 +1,34 @@ +//===- MathToLLVM.h - Math to LLVM dialect conversion -----------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_MATHTOLLVM_MATHTOLLVM_H +#define MLIR_CONVERSION_MATHTOLLVM_MATHTOLLVM_H + +#include "mlir/IR/PatternMatch.h" +#include + +namespace mlir { + +class DialectRegistry; +class LLVMTypeConverter; +class RewritePatternSet; +class Pass; + +#define GEN_PASS_DECL_CONVERTMATHTOLLVMPASS +#include "mlir/Conversion/Passes.h.inc" + +void populateMathToLLVMConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns, + bool approximateLog1p = true, + PatternBenefit benefit = 1); + +void registerConvertMathToLLVMInterface(DialectRegistry ®istry); + +} // namespace mlir + +#endif // MLIR_CONVERSION_MATHTOLLVM_MATHTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToLibm/MathToLibm.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToLibm/MathToLibm.h new file mode 100644 index 0000000000000000000000000000000000000000..75f077d9ab2865a099ee9bdd9fb315090d0f01b4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToLibm/MathToLibm.h @@ -0,0 +1,28 @@ +//===- MathToLibm.h - Utils to convert from the complex dialect --------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_MATHTOLIBM_MATHTOLIBM_H_ +#define MLIR_CONVERSION_MATHTOLIBM_MATHTOLIBM_H_ + +#include "mlir/IR/PatternMatch.h" +#include "mlir/Pass/Pass.h" + +namespace mlir { +template +class OperationPass; + +#define GEN_PASS_DECL_CONVERTMATHTOLIBMPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Populate the given list with patterns that convert from Math to Libm calls. +/// If log1pBenefit is present, use it instead of benefit for the Log1p op. +void populateMathToLibmConversionPatterns(RewritePatternSet &patterns, + PatternBenefit benefit = 1); + +} // namespace mlir + +#endif // MLIR_CONVERSION_MATHTOLIBM_MATHTOLIBM_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToROCDL/MathToROCDL.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToROCDL/MathToROCDL.h new file mode 100644 index 0000000000000000000000000000000000000000..46573e7966cccce739b86ecbf481b6e698e61ea6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/MathToROCDL/MathToROCDL.h @@ -0,0 +1,26 @@ +//===- MathToROCDL.h - Utils to convert from the complex dialect --------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_MATHTOROCDL_MATHTOROCDL_H_ +#define MLIR_CONVERSION_MATHTOROCDL_MATHTOROCDL_H_ + +#include "mlir/Conversion/LLVMCommon/TypeConverter.h" +#include "mlir/IR/PatternMatch.h" +#include + +namespace mlir { +class Pass; + +#define GEN_PASS_DECL_CONVERTMATHTOROCDL +#include "mlir/Conversion/Passes.h.inc" + +/// Populate the given list with patterns that convert from Math to ROCDL calls. +void populateMathToROCDLConversionPatterns(const LLVMTypeConverter &converter, + RewritePatternSet &patterns); +} // namespace mlir + +#endif // MLIR_CONVERSION_MATHTOROCDL_MATHTOROCDL_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..996a64baf9dd58501ad815f677365c164d659c52 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h @@ -0,0 +1,32 @@ +//===- MemRefToLLVM.h - MemRef to LLVM dialect conversion -------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_MEMREFTOLLVM_MEMREFTOLLVM_H +#define MLIR_CONVERSION_MEMREFTOLLVM_MEMREFTOLLVM_H + +#include + +namespace mlir { +class DialectRegistry; +class Pass; +class LLVMTypeConverter; +class RewritePatternSet; + +#define GEN_PASS_DECL_FINALIZEMEMREFTOLLVMCONVERSIONPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Collect a set of patterns to convert memory-related operations from the +/// MemRef dialect to the LLVM dialect. +void populateFinalizeMemRefToLLVMConversionPatterns( + const LLVMTypeConverter &converter, RewritePatternSet &patterns); + +void registerConvertMemRefToLLVMInterface(DialectRegistry ®istry); + +} // namespace mlir + +#endif // MLIR_CONVERSION_MEMREFTOLLVM_MEMREFTOLLVM_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/PDLToPDLInterp/PDLToPDLInterp.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/PDLToPDLInterp/PDLToPDLInterp.h new file mode 100644 index 0000000000000000000000000000000000000000..c6a647245f82b9ddf3ad44f01252d676792dccc4 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/PDLToPDLInterp/PDLToPDLInterp.h @@ -0,0 +1,37 @@ +//===- PDLToPDLInterp.h - PDL to PDL Interpreter conversion -----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file provides a pass for PDL to PDL Interpreter dialect conversion. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_PDLTOPDLINTERP_PDLTOPDLINTERP_H +#define MLIR_CONVERSION_PDLTOPDLINTERP_PDLTOPDLINTERP_H + +#include "mlir/Pass/Pass.h" +#include "mlir/Support/LLVM.h" + +namespace mlir { +class ModuleOp; +class Operation; +template +class OperationPass; +class PDLPatternConfigSet; + +#define GEN_PASS_DECL_CONVERTPDLTOPDLINTERPPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Creates and returns a pass to convert PDL ops to PDL interpreter ops. +/// `configMap` holds a map of the configurations for each pattern being +/// compiled. +std::unique_ptr> createConvertPDLToPDLInterpPass( + DenseMap &configMap); + +} // namespace mlir + +#endif // MLIR_CONVERSION_PDLTOPDLINTERP_PDLTOPDLINTERP_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.capi.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.capi.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..1ddf19cfb303f8730c9eab86ae6b1b2e34b79445 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.capi.cpp.inc @@ -0,0 +1,616 @@ +/* Autogenerated by mlir-tblgen; don't manually edit. */ +//===----------------------------------------------------------------------===// +// Conversion Group Registration +//===----------------------------------------------------------------------===// + +void mlirRegisterConversionPasses(void) { + registerConversionPasses(); +} + +MlirPass mlirCreateConversionArithToAMDGPUConversionPass(void) { + return wrap(createArithToAMDGPUConversionPass().release()); +} +void mlirRegisterConversionArithToAMDGPUConversionPass(void) { + registerArithToAMDGPUConversionPass(); +} + + +MlirPass mlirCreateConversionArithToArmSMEConversionPass(void) { + return wrap(createArithToArmSMEConversionPass().release()); +} +void mlirRegisterConversionArithToArmSMEConversionPass(void) { + registerArithToArmSMEConversionPass(); +} + + +MlirPass mlirCreateConversionArithToLLVMConversionPass(void) { + return wrap(createArithToLLVMConversionPass().release()); +} +void mlirRegisterConversionArithToLLVMConversionPass(void) { + registerArithToLLVMConversionPass(); +} + + +MlirPass mlirCreateConversionConvertAMDGPUToROCDLPass(void) { + return wrap(createConvertAMDGPUToROCDLPass().release()); +} +void mlirRegisterConversionConvertAMDGPUToROCDLPass(void) { + registerConvertAMDGPUToROCDLPass(); +} + + +MlirPass mlirCreateConversionConvertAffineForToGPUPass(void) { + return wrap(createConvertAffineForToGPUPass().release()); +} +void mlirRegisterConversionConvertAffineForToGPUPass(void) { + registerConvertAffineForToGPUPass(); +} + + +MlirPass mlirCreateConversionConvertArithToEmitC(void) { + return wrap(createConvertArithToEmitC().release()); +} +void mlirRegisterConversionConvertArithToEmitC(void) { + registerConvertArithToEmitC(); +} + + +MlirPass mlirCreateConversionConvertArithToSPIRVPass(void) { + return wrap(createConvertArithToSPIRVPass().release()); +} +void mlirRegisterConversionConvertArithToSPIRVPass(void) { + registerConvertArithToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertArmNeon2dToIntrPass(void) { + return wrap(createConvertArmNeon2dToIntrPass().release()); +} +void mlirRegisterConversionConvertArmNeon2dToIntrPass(void) { + registerConvertArmNeon2dToIntrPass(); +} + + +MlirPass mlirCreateConversionConvertArmSMEToLLVM(void) { + return wrap(mlir::createConvertArmSMEToLLVMPass().release()); +} +void mlirRegisterConversionConvertArmSMEToLLVM(void) { + registerConvertArmSMEToLLVM(); +} + + +MlirPass mlirCreateConversionConvertArmSMEToSCFPass(void) { + return wrap(createConvertArmSMEToSCFPass().release()); +} +void mlirRegisterConversionConvertArmSMEToSCFPass(void) { + registerConvertArmSMEToSCFPass(); +} + + +MlirPass mlirCreateConversionConvertAsyncToLLVMPass(void) { + return wrap(createConvertAsyncToLLVMPass().release()); +} +void mlirRegisterConversionConvertAsyncToLLVMPass(void) { + registerConvertAsyncToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertBufferizationToMemRefPass(void) { + return wrap(createConvertBufferizationToMemRefPass().release()); +} +void mlirRegisterConversionConvertBufferizationToMemRefPass(void) { + registerConvertBufferizationToMemRefPass(); +} + + +MlirPass mlirCreateConversionConvertComplexToLLVMPass(void) { + return wrap(createConvertComplexToLLVMPass().release()); +} +void mlirRegisterConversionConvertComplexToLLVMPass(void) { + registerConvertComplexToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertComplexToLibm(void) { + return wrap(createConvertComplexToLibm().release()); +} +void mlirRegisterConversionConvertComplexToLibm(void) { + registerConvertComplexToLibm(); +} + + +MlirPass mlirCreateConversionConvertComplexToSPIRVPass(void) { + return wrap(createConvertComplexToSPIRVPass().release()); +} +void mlirRegisterConversionConvertComplexToSPIRVPass(void) { + registerConvertComplexToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertComplexToStandardPass(void) { + return wrap(createConvertComplexToStandardPass().release()); +} +void mlirRegisterConversionConvertComplexToStandardPass(void) { + registerConvertComplexToStandardPass(); +} + + +MlirPass mlirCreateConversionConvertControlFlowToLLVMPass(void) { + return wrap(createConvertControlFlowToLLVMPass().release()); +} +void mlirRegisterConversionConvertControlFlowToLLVMPass(void) { + registerConvertControlFlowToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertControlFlowToSPIRVPass(void) { + return wrap(createConvertControlFlowToSPIRVPass().release()); +} +void mlirRegisterConversionConvertControlFlowToSPIRVPass(void) { + registerConvertControlFlowToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertFuncToEmitC(void) { + return wrap(createConvertFuncToEmitC().release()); +} +void mlirRegisterConversionConvertFuncToEmitC(void) { + registerConvertFuncToEmitC(); +} + + +MlirPass mlirCreateConversionConvertFuncToLLVMPass(void) { + return wrap(createConvertFuncToLLVMPass().release()); +} +void mlirRegisterConversionConvertFuncToLLVMPass(void) { + registerConvertFuncToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertFuncToSPIRVPass(void) { + return wrap(createConvertFuncToSPIRVPass().release()); +} +void mlirRegisterConversionConvertFuncToSPIRVPass(void) { + registerConvertFuncToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertGPUToSPIRV(void) { + return wrap(mlir::createConvertGPUToSPIRVPass().release()); +} +void mlirRegisterConversionConvertGPUToSPIRV(void) { + registerConvertGPUToSPIRV(); +} + + +MlirPass mlirCreateConversionConvertGpuOpsToLLVMSPVOps(void) { + return wrap(createConvertGpuOpsToLLVMSPVOps().release()); +} +void mlirRegisterConversionConvertGpuOpsToLLVMSPVOps(void) { + registerConvertGpuOpsToLLVMSPVOps(); +} + + +MlirPass mlirCreateConversionConvertGpuOpsToNVVMOps(void) { + return wrap(createConvertGpuOpsToNVVMOps().release()); +} +void mlirRegisterConversionConvertGpuOpsToNVVMOps(void) { + registerConvertGpuOpsToNVVMOps(); +} + + +MlirPass mlirCreateConversionConvertGpuOpsToROCDLOps(void) { + return wrap(mlir::createLowerGpuOpsToROCDLOpsPass().release()); +} +void mlirRegisterConversionConvertGpuOpsToROCDLOps(void) { + registerConvertGpuOpsToROCDLOps(); +} + + +MlirPass mlirCreateConversionConvertIndexToLLVMPass(void) { + return wrap(createConvertIndexToLLVMPass().release()); +} +void mlirRegisterConversionConvertIndexToLLVMPass(void) { + registerConvertIndexToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertIndexToSPIRVPass(void) { + return wrap(createConvertIndexToSPIRVPass().release()); +} +void mlirRegisterConversionConvertIndexToSPIRVPass(void) { + registerConvertIndexToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertLinalgToStandardPass(void) { + return wrap(createConvertLinalgToStandardPass().release()); +} +void mlirRegisterConversionConvertLinalgToStandardPass(void) { + registerConvertLinalgToStandardPass(); +} + + +MlirPass mlirCreateConversionConvertMathToEmitC(void) { + return wrap(createConvertMathToEmitC().release()); +} +void mlirRegisterConversionConvertMathToEmitC(void) { + registerConvertMathToEmitC(); +} + + +MlirPass mlirCreateConversionConvertMathToFuncs(void) { + return wrap(createConvertMathToFuncs().release()); +} +void mlirRegisterConversionConvertMathToFuncs(void) { + registerConvertMathToFuncs(); +} + + +MlirPass mlirCreateConversionConvertMathToLLVMPass(void) { + return wrap(createConvertMathToLLVMPass().release()); +} +void mlirRegisterConversionConvertMathToLLVMPass(void) { + registerConvertMathToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertMathToLibmPass(void) { + return wrap(createConvertMathToLibmPass().release()); +} +void mlirRegisterConversionConvertMathToLibmPass(void) { + registerConvertMathToLibmPass(); +} + + +MlirPass mlirCreateConversionConvertMathToROCDL(void) { + return wrap(createConvertMathToROCDL().release()); +} +void mlirRegisterConversionConvertMathToROCDL(void) { + registerConvertMathToROCDL(); +} + + +MlirPass mlirCreateConversionConvertMathToSPIRVPass(void) { + return wrap(createConvertMathToSPIRVPass().release()); +} +void mlirRegisterConversionConvertMathToSPIRVPass(void) { + registerConvertMathToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertMemRefToEmitC(void) { + return wrap(createConvertMemRefToEmitC().release()); +} +void mlirRegisterConversionConvertMemRefToEmitC(void) { + registerConvertMemRefToEmitC(); +} + + +MlirPass mlirCreateConversionConvertMemRefToSPIRVPass(void) { + return wrap(createConvertMemRefToSPIRVPass().release()); +} +void mlirRegisterConversionConvertMemRefToSPIRVPass(void) { + registerConvertMemRefToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertMeshToMPIPass(void) { + return wrap(createConvertMeshToMPIPass().release()); +} +void mlirRegisterConversionConvertMeshToMPIPass(void) { + registerConvertMeshToMPIPass(); +} + + +MlirPass mlirCreateConversionConvertNVGPUToNVVMPass(void) { + return wrap(createConvertNVGPUToNVVMPass().release()); +} +void mlirRegisterConversionConvertNVGPUToNVVMPass(void) { + registerConvertNVGPUToNVVMPass(); +} + + +MlirPass mlirCreateConversionConvertNVVMToLLVMPass(void) { + return wrap(createConvertNVVMToLLVMPass().release()); +} +void mlirRegisterConversionConvertNVVMToLLVMPass(void) { + registerConvertNVVMToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertOpenACCToSCFPass(void) { + return wrap(createConvertOpenACCToSCFPass().release()); +} +void mlirRegisterConversionConvertOpenACCToSCFPass(void) { + registerConvertOpenACCToSCFPass(); +} + + +MlirPass mlirCreateConversionConvertOpenMPToLLVMPass(void) { + return wrap(createConvertOpenMPToLLVMPass().release()); +} +void mlirRegisterConversionConvertOpenMPToLLVMPass(void) { + registerConvertOpenMPToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertPDLToPDLInterpPass(void) { + return wrap(createConvertPDLToPDLInterpPass().release()); +} +void mlirRegisterConversionConvertPDLToPDLInterpPass(void) { + registerConvertPDLToPDLInterpPass(); +} + + +MlirPass mlirCreateConversionConvertParallelLoopToGpuPass(void) { + return wrap(createConvertParallelLoopToGpuPass().release()); +} +void mlirRegisterConversionConvertParallelLoopToGpuPass(void) { + registerConvertParallelLoopToGpuPass(); +} + + +MlirPass mlirCreateConversionConvertSCFToOpenMPPass(void) { + return wrap(createConvertSCFToOpenMPPass().release()); +} +void mlirRegisterConversionConvertSCFToOpenMPPass(void) { + registerConvertSCFToOpenMPPass(); +} + + +MlirPass mlirCreateConversionConvertSPIRVToLLVMPass(void) { + return wrap(createConvertSPIRVToLLVMPass().release()); +} +void mlirRegisterConversionConvertSPIRVToLLVMPass(void) { + registerConvertSPIRVToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertShapeConstraintsPass(void) { + return wrap(createConvertShapeConstraintsPass().release()); +} +void mlirRegisterConversionConvertShapeConstraintsPass(void) { + registerConvertShapeConstraintsPass(); +} + + +MlirPass mlirCreateConversionConvertShapeToStandardPass(void) { + return wrap(createConvertShapeToStandardPass().release()); +} +void mlirRegisterConversionConvertShapeToStandardPass(void) { + registerConvertShapeToStandardPass(); +} + + +MlirPass mlirCreateConversionConvertTensorToLinalgPass(void) { + return wrap(createConvertTensorToLinalgPass().release()); +} +void mlirRegisterConversionConvertTensorToLinalgPass(void) { + registerConvertTensorToLinalgPass(); +} + + +MlirPass mlirCreateConversionConvertTensorToSPIRVPass(void) { + return wrap(createConvertTensorToSPIRVPass().release()); +} +void mlirRegisterConversionConvertTensorToSPIRVPass(void) { + registerConvertTensorToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertToEmitC(void) { + return wrap(createConvertToEmitC().release()); +} +void mlirRegisterConversionConvertToEmitC(void) { + registerConvertToEmitC(); +} + + +MlirPass mlirCreateConversionConvertToLLVMPass(void) { + return wrap(createConvertToLLVMPass().release()); +} +void mlirRegisterConversionConvertToLLVMPass(void) { + registerConvertToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertVectorToArmSMEPass(void) { + return wrap(createConvertVectorToArmSMEPass().release()); +} +void mlirRegisterConversionConvertVectorToArmSMEPass(void) { + registerConvertVectorToArmSMEPass(); +} + + +MlirPass mlirCreateConversionConvertVectorToGPU(void) { + return wrap(mlir::createConvertVectorToGPUPass().release()); +} +void mlirRegisterConversionConvertVectorToGPU(void) { + registerConvertVectorToGPU(); +} + + +MlirPass mlirCreateConversionConvertVectorToLLVMPass(void) { + return wrap(createConvertVectorToLLVMPass().release()); +} +void mlirRegisterConversionConvertVectorToLLVMPass(void) { + registerConvertVectorToLLVMPass(); +} + + +MlirPass mlirCreateConversionConvertVectorToSCF(void) { + return wrap(mlir::createConvertVectorToSCFPass().release()); +} +void mlirRegisterConversionConvertVectorToSCF(void) { + registerConvertVectorToSCF(); +} + + +MlirPass mlirCreateConversionConvertVectorToSPIRVPass(void) { + return wrap(createConvertVectorToSPIRVPass().release()); +} +void mlirRegisterConversionConvertVectorToSPIRVPass(void) { + registerConvertVectorToSPIRVPass(); +} + + +MlirPass mlirCreateConversionConvertVectorToXeGPU(void) { + return wrap(createConvertVectorToXeGPU().release()); +} +void mlirRegisterConversionConvertVectorToXeGPU(void) { + registerConvertVectorToXeGPU(); +} + + +MlirPass mlirCreateConversionFinalizeMemRefToLLVMConversionPass(void) { + return wrap(createFinalizeMemRefToLLVMConversionPass().release()); +} +void mlirRegisterConversionFinalizeMemRefToLLVMConversionPass(void) { + registerFinalizeMemRefToLLVMConversionPass(); +} + + +MlirPass mlirCreateConversionGpuToLLVMConversionPass(void) { + return wrap(createGpuToLLVMConversionPass().release()); +} +void mlirRegisterConversionGpuToLLVMConversionPass(void) { + registerGpuToLLVMConversionPass(); +} + + +MlirPass mlirCreateConversionLiftControlFlowToSCFPass(void) { + return wrap(createLiftControlFlowToSCFPass().release()); +} +void mlirRegisterConversionLiftControlFlowToSCFPass(void) { + registerLiftControlFlowToSCFPass(); +} + + +MlirPass mlirCreateConversionLowerAffinePass(void) { + return wrap(createLowerAffinePass().release()); +} +void mlirRegisterConversionLowerAffinePass(void) { + registerLowerAffinePass(); +} + + +MlirPass mlirCreateConversionLowerHostCodeToLLVMPass(void) { + return wrap(createLowerHostCodeToLLVMPass().release()); +} +void mlirRegisterConversionLowerHostCodeToLLVMPass(void) { + registerLowerHostCodeToLLVMPass(); +} + + +MlirPass mlirCreateConversionMapMemRefStorageClass(void) { + return wrap(mlir::createMapMemRefStorageClassPass().release()); +} +void mlirRegisterConversionMapMemRefStorageClass(void) { + registerMapMemRefStorageClass(); +} + + +MlirPass mlirCreateConversionReconcileUnrealizedCastsPass(void) { + return wrap(createReconcileUnrealizedCastsPass().release()); +} +void mlirRegisterConversionReconcileUnrealizedCastsPass(void) { + registerReconcileUnrealizedCastsPass(); +} + + +MlirPass mlirCreateConversionSCFToControlFlowPass(void) { + return wrap(createSCFToControlFlowPass().release()); +} +void mlirRegisterConversionSCFToControlFlowPass(void) { + registerSCFToControlFlowPass(); +} + + +MlirPass mlirCreateConversionSCFToEmitC(void) { + return wrap(createSCFToEmitC().release()); +} +void mlirRegisterConversionSCFToEmitC(void) { + registerSCFToEmitC(); +} + + +MlirPass mlirCreateConversionSCFToSPIRV(void) { + return wrap(createSCFToSPIRV().release()); +} +void mlirRegisterConversionSCFToSPIRV(void) { + registerSCFToSPIRV(); +} + + +MlirPass mlirCreateConversionSetLLVMModuleDataLayoutPass(void) { + return wrap(createSetLLVMModuleDataLayoutPass().release()); +} +void mlirRegisterConversionSetLLVMModuleDataLayoutPass(void) { + registerSetLLVMModuleDataLayoutPass(); +} + + +MlirPass mlirCreateConversionTosaToArithPass(void) { + return wrap(createTosaToArithPass().release()); +} +void mlirRegisterConversionTosaToArithPass(void) { + registerTosaToArithPass(); +} + + +MlirPass mlirCreateConversionTosaToLinalg(void) { + return wrap(tosa::createTosaToLinalg().release()); +} +void mlirRegisterConversionTosaToLinalg(void) { + registerTosaToLinalg(); +} + + +MlirPass mlirCreateConversionTosaToLinalgNamed(void) { + return wrap(tosa::createTosaToLinalgNamed().release()); +} +void mlirRegisterConversionTosaToLinalgNamed(void) { + registerTosaToLinalgNamed(); +} + + +MlirPass mlirCreateConversionTosaToMLProgram(void) { + return wrap(createTosaToMLProgram().release()); +} +void mlirRegisterConversionTosaToMLProgram(void) { + registerTosaToMLProgram(); +} + + +MlirPass mlirCreateConversionTosaToSCFPass(void) { + return wrap(createTosaToSCFPass().release()); +} +void mlirRegisterConversionTosaToSCFPass(void) { + registerTosaToSCFPass(); +} + + +MlirPass mlirCreateConversionTosaToTensorPass(void) { + return wrap(createTosaToTensorPass().release()); +} +void mlirRegisterConversionTosaToTensorPass(void) { + registerTosaToTensorPass(); +} + + +MlirPass mlirCreateConversionUBToLLVMConversionPass(void) { + return wrap(createUBToLLVMConversionPass().release()); +} +void mlirRegisterConversionUBToLLVMConversionPass(void) { + registerUBToLLVMConversionPass(); +} + + +MlirPass mlirCreateConversionUBToSPIRVConversionPass(void) { + return wrap(createUBToSPIRVConversionPass().release()); +} +void mlirRegisterConversionUBToSPIRVConversionPass(void) { + registerUBToSPIRVConversionPass(); +} + diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.capi.h.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.capi.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..f4def66f88099f07aeb2c2587c568cae83b0ff6f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.capi.h.inc @@ -0,0 +1,397 @@ + +/* Autogenerated by mlir-tblgen; don't manually edit. */ + +#include "mlir-c/Pass.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Registration for the entire group +MLIR_CAPI_EXPORTED void mlirRegisterConversionPasses(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionArithToAMDGPUConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionArithToAMDGPUConversionPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionArithToArmSMEConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionArithToArmSMEConversionPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionArithToLLVMConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionArithToLLVMConversionPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertAMDGPUToROCDLPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertAMDGPUToROCDLPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertAffineForToGPUPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertAffineForToGPUPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertArithToEmitC(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertArithToEmitC(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertArithToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertArithToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertArmNeon2dToIntrPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertArmNeon2dToIntrPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertArmSMEToLLVM(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertArmSMEToLLVM(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertArmSMEToSCFPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertArmSMEToSCFPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertAsyncToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertAsyncToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertBufferizationToMemRefPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertBufferizationToMemRefPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertComplexToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertComplexToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertComplexToLibm(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertComplexToLibm(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertComplexToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertComplexToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertComplexToStandardPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertComplexToStandardPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertControlFlowToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertControlFlowToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertControlFlowToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertControlFlowToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertFuncToEmitC(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertFuncToEmitC(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertFuncToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertFuncToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertFuncToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertFuncToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertGPUToSPIRV(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertGPUToSPIRV(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertGpuOpsToLLVMSPVOps(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertGpuOpsToLLVMSPVOps(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertGpuOpsToNVVMOps(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertGpuOpsToNVVMOps(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertGpuOpsToROCDLOps(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertGpuOpsToROCDLOps(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertIndexToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertIndexToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertIndexToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertIndexToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertLinalgToStandardPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertLinalgToStandardPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMathToEmitC(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMathToEmitC(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMathToFuncs(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMathToFuncs(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMathToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMathToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMathToLibmPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMathToLibmPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMathToROCDL(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMathToROCDL(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMathToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMathToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMemRefToEmitC(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMemRefToEmitC(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMemRefToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMemRefToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertMeshToMPIPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertMeshToMPIPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertNVGPUToNVVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertNVGPUToNVVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertNVVMToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertNVVMToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertOpenACCToSCFPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertOpenACCToSCFPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertOpenMPToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertOpenMPToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertPDLToPDLInterpPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertPDLToPDLInterpPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertParallelLoopToGpuPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertParallelLoopToGpuPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertSCFToOpenMPPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertSCFToOpenMPPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertSPIRVToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertSPIRVToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertShapeConstraintsPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertShapeConstraintsPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertShapeToStandardPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertShapeToStandardPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertTensorToLinalgPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertTensorToLinalgPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertTensorToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertTensorToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertToEmitC(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertToEmitC(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertVectorToArmSMEPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertVectorToArmSMEPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertVectorToGPU(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertVectorToGPU(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertVectorToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertVectorToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertVectorToSCF(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertVectorToSCF(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertVectorToSPIRVPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertVectorToSPIRVPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionConvertVectorToXeGPU(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionConvertVectorToXeGPU(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionFinalizeMemRefToLLVMConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionFinalizeMemRefToLLVMConversionPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionGpuToLLVMConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionGpuToLLVMConversionPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionLiftControlFlowToSCFPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionLiftControlFlowToSCFPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionLowerAffinePass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionLowerAffinePass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionLowerHostCodeToLLVMPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionLowerHostCodeToLLVMPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionMapMemRefStorageClass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionMapMemRefStorageClass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionReconcileUnrealizedCastsPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionReconcileUnrealizedCastsPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionSCFToControlFlowPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionSCFToControlFlowPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionSCFToEmitC(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionSCFToEmitC(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionSCFToSPIRV(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionSCFToSPIRV(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionSetLLVMModuleDataLayoutPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionSetLLVMModuleDataLayoutPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionTosaToArithPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionTosaToArithPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionTosaToLinalg(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionTosaToLinalg(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionTosaToLinalgNamed(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionTosaToLinalgNamed(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionTosaToMLProgram(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionTosaToMLProgram(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionTosaToSCFPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionTosaToSCFPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionTosaToTensorPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionTosaToTensorPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionUBToLLVMConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionUBToLLVMConversionPass(void); + + +/* Create Conversion Pass. */ +MLIR_CAPI_EXPORTED MlirPass mlirCreateConversionUBToSPIRVConversionPass(void); +MLIR_CAPI_EXPORTED void mlirRegisterConversionUBToSPIRVConversionPass(void); + + + +#ifdef __cplusplus +} +#endif diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.h.inc b/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..af401ad28549377b4efd9b8d8b9d89707a6a205f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/Passes.h.inc @@ -0,0 +1,11802 @@ +/* Autogenerated by mlir-tblgen; don't manually edit */ + +#ifdef GEN_PASS_DECL +// Generate declarations for all passes. +#define GEN_PASS_DECL_ARITHTOAMDGPUCONVERSIONPASS +#define GEN_PASS_DECL_ARITHTOARMSMECONVERSIONPASS +#define GEN_PASS_DECL_ARITHTOLLVMCONVERSIONPASS +#define GEN_PASS_DECL_CONVERTAMDGPUTOROCDLPASS +#define GEN_PASS_DECL_CONVERTAFFINEFORTOGPUPASS +#define GEN_PASS_DECL_CONVERTARITHTOEMITC +#define GEN_PASS_DECL_CONVERTARITHTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTARMNEON2DTOINTRPASS +#define GEN_PASS_DECL_CONVERTARMSMETOLLVM +#define GEN_PASS_DECL_CONVERTARMSMETOSCFPASS +#define GEN_PASS_DECL_CONVERTASYNCTOLLVMPASS +#define GEN_PASS_DECL_CONVERTBUFFERIZATIONTOMEMREFPASS +#define GEN_PASS_DECL_CONVERTCOMPLEXTOLLVMPASS +#define GEN_PASS_DECL_CONVERTCOMPLEXTOLIBM +#define GEN_PASS_DECL_CONVERTCOMPLEXTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTCOMPLEXTOSTANDARDPASS +#define GEN_PASS_DECL_CONVERTCONTROLFLOWTOLLVMPASS +#define GEN_PASS_DECL_CONVERTCONTROLFLOWTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTFUNCTOEMITC +#define GEN_PASS_DECL_CONVERTFUNCTOLLVMPASS +#define GEN_PASS_DECL_CONVERTFUNCTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTGPUTOSPIRV +#define GEN_PASS_DECL_CONVERTGPUOPSTOLLVMSPVOPS +#define GEN_PASS_DECL_CONVERTGPUOPSTONVVMOPS +#define GEN_PASS_DECL_CONVERTGPUOPSTOROCDLOPS +#define GEN_PASS_DECL_CONVERTINDEXTOLLVMPASS +#define GEN_PASS_DECL_CONVERTINDEXTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTLINALGTOSTANDARDPASS +#define GEN_PASS_DECL_CONVERTMATHTOEMITC +#define GEN_PASS_DECL_CONVERTMATHTOFUNCS +#define GEN_PASS_DECL_CONVERTMATHTOLLVMPASS +#define GEN_PASS_DECL_CONVERTMATHTOLIBMPASS +#define GEN_PASS_DECL_CONVERTMATHTOROCDL +#define GEN_PASS_DECL_CONVERTMATHTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTMEMREFTOEMITC +#define GEN_PASS_DECL_CONVERTMEMREFTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTMESHTOMPIPASS +#define GEN_PASS_DECL_CONVERTNVGPUTONVVMPASS +#define GEN_PASS_DECL_CONVERTNVVMTOLLVMPASS +#define GEN_PASS_DECL_CONVERTOPENACCTOSCFPASS +#define GEN_PASS_DECL_CONVERTOPENMPTOLLVMPASS +#define GEN_PASS_DECL_CONVERTPDLTOPDLINTERPPASS +#define GEN_PASS_DECL_CONVERTPARALLELLOOPTOGPUPASS +#define GEN_PASS_DECL_CONVERTSCFTOOPENMPPASS +#define GEN_PASS_DECL_CONVERTSPIRVTOLLVMPASS +#define GEN_PASS_DECL_CONVERTSHAPECONSTRAINTSPASS +#define GEN_PASS_DECL_CONVERTSHAPETOSTANDARDPASS +#define GEN_PASS_DECL_CONVERTTENSORTOLINALGPASS +#define GEN_PASS_DECL_CONVERTTENSORTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTTOEMITC +#define GEN_PASS_DECL_CONVERTTOLLVMPASS +#define GEN_PASS_DECL_CONVERTVECTORTOARMSMEPASS +#define GEN_PASS_DECL_CONVERTVECTORTOGPU +#define GEN_PASS_DECL_CONVERTVECTORTOLLVMPASS +#define GEN_PASS_DECL_CONVERTVECTORTOSCF +#define GEN_PASS_DECL_CONVERTVECTORTOSPIRVPASS +#define GEN_PASS_DECL_CONVERTVECTORTOXEGPU +#define GEN_PASS_DECL_FINALIZEMEMREFTOLLVMCONVERSIONPASS +#define GEN_PASS_DECL_GPUTOLLVMCONVERSIONPASS +#define GEN_PASS_DECL_LIFTCONTROLFLOWTOSCFPASS +#define GEN_PASS_DECL_LOWERAFFINEPASS +#define GEN_PASS_DECL_LOWERHOSTCODETOLLVMPASS +#define GEN_PASS_DECL_MAPMEMREFSTORAGECLASS +#define GEN_PASS_DECL_RECONCILEUNREALIZEDCASTSPASS +#define GEN_PASS_DECL_SCFTOCONTROLFLOWPASS +#define GEN_PASS_DECL_SCFTOEMITC +#define GEN_PASS_DECL_SCFTOSPIRV +#define GEN_PASS_DECL_SETLLVMMODULEDATALAYOUTPASS +#define GEN_PASS_DECL_TOSATOARITHPASS +#define GEN_PASS_DECL_TOSATOLINALG +#define GEN_PASS_DECL_TOSATOLINALGNAMED +#define GEN_PASS_DECL_TOSATOMLPROGRAM +#define GEN_PASS_DECL_TOSATOSCFPASS +#define GEN_PASS_DECL_TOSATOTENSORPASS +#define GEN_PASS_DECL_UBTOLLVMCONVERSIONPASS +#define GEN_PASS_DECL_UBTOSPIRVCONVERSIONPASS +#undef GEN_PASS_DECL +#endif // GEN_PASS_DECL + +//===----------------------------------------------------------------------===// +// ArithToAMDGPUConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ARITHTOAMDGPUCONVERSIONPASS +struct ArithToAMDGPUConversionPassOptions { + std::string chipset = "gfx000"; + bool saturateFP8Truncf = false; + bool allowPackedF16Rtz = false; +}; +std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass(); +std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass(ArithToAMDGPUConversionPassOptions options); +#undef GEN_PASS_DECL_ARITHTOAMDGPUCONVERSIONPASS +#endif // GEN_PASS_DECL_ARITHTOAMDGPUCONVERSIONPASS +#ifdef GEN_PASS_DEF_ARITHTOAMDGPUCONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass(ArithToAMDGPUConversionPassOptions options); +} // namespace impl +namespace impl { + +template +class ArithToAMDGPUConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = ArithToAMDGPUConversionPassBase; + + ArithToAMDGPUConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ArithToAMDGPUConversionPassBase(const ArithToAMDGPUConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + ArithToAMDGPUConversionPassBase& operator=(const ArithToAMDGPUConversionPassBase &) = delete; + ArithToAMDGPUConversionPassBase(ArithToAMDGPUConversionPassBase &&) = delete; + ArithToAMDGPUConversionPassBase& operator=(ArithToAMDGPUConversionPassBase &&) = delete; + ~ArithToAMDGPUConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-amdgpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-amdgpu"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith operations to AMDGPU-specific implementations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ArithToAMDGPUConversionPass"); + } + ::llvm::StringRef getName() const override { return "ArithToAMDGPUConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ArithToAMDGPUConversionPassBase) + + ArithToAMDGPUConversionPassBase(ArithToAMDGPUConversionPassOptions options) : ArithToAMDGPUConversionPassBase() { + chipset = std::move(options.chipset); + saturateFP8Truncf = std::move(options.saturateFP8Truncf); + allowPackedF16Rtz = std::move(options.allowPackedF16Rtz); + } +protected: + ::mlir::Pass::Option chipset{*this, "chipset", ::llvm::cl::desc("Chipset that these operations will run on"), ::llvm::cl::init("gfx000")}; + ::mlir::Pass::Option saturateFP8Truncf{*this, "saturate-fp8-truncf", ::llvm::cl::desc("Use saturating truncation for 8-bit float types"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option allowPackedF16Rtz{*this, "allow-packed-f16-round-to-zero", ::llvm::cl::desc("Whether we should allow f32->f16 packed round-to-zero conversion"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass(ArithToAMDGPUConversionPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass() { + return impl::createArithToAMDGPUConversionPass(); +} + +std::unique_ptr<::mlir::Pass> createArithToAMDGPUConversionPass(ArithToAMDGPUConversionPassOptions options) { + return impl::createArithToAMDGPUConversionPass(std::move(options)); +} +#undef GEN_PASS_DEF_ARITHTOAMDGPUCONVERSIONPASS +#endif // GEN_PASS_DEF_ARITHTOAMDGPUCONVERSIONPASS + +//===----------------------------------------------------------------------===// +// ArithToArmSMEConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ARITHTOARMSMECONVERSIONPASS +std::unique_ptr<::mlir::Pass> createArithToArmSMEConversionPass(); +#undef GEN_PASS_DECL_ARITHTOARMSMECONVERSIONPASS +#endif // GEN_PASS_DECL_ARITHTOARMSMECONVERSIONPASS +#ifdef GEN_PASS_DEF_ARITHTOARMSMECONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createArithToArmSMEConversionPass(); +} // namespace impl +namespace impl { + +template +class ArithToArmSMEConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = ArithToArmSMEConversionPassBase; + + ArithToArmSMEConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ArithToArmSMEConversionPassBase(const ArithToArmSMEConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + ArithToArmSMEConversionPassBase& operator=(const ArithToArmSMEConversionPassBase &) = delete; + ArithToArmSMEConversionPassBase(ArithToArmSMEConversionPassBase &&) = delete; + ArithToArmSMEConversionPassBase& operator=(ArithToArmSMEConversionPassBase &&) = delete; + ~ArithToArmSMEConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-arm-sme"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-arm-sme"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to ArmSME dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ArithToArmSMEConversionPass"); + } + ::llvm::StringRef getName() const override { return "ArithToArmSMEConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ArithToArmSMEConversionPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createArithToArmSMEConversionPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createArithToArmSMEConversionPass() { + return impl::createArithToArmSMEConversionPass(); +} +#undef GEN_PASS_DEF_ARITHTOARMSMECONVERSIONPASS +#endif // GEN_PASS_DEF_ARITHTOARMSMECONVERSIONPASS + +//===----------------------------------------------------------------------===// +// ArithToLLVMConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_ARITHTOLLVMCONVERSIONPASS +struct ArithToLLVMConversionPassOptions { + unsigned indexBitwidth = 0; +}; +std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass(); +std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass(ArithToLLVMConversionPassOptions options); +#undef GEN_PASS_DECL_ARITHTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DECL_ARITHTOLLVMCONVERSIONPASS +#ifdef GEN_PASS_DEF_ARITHTOLLVMCONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass(ArithToLLVMConversionPassOptions options); +} // namespace impl +namespace impl { + +template +class ArithToLLVMConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = ArithToLLVMConversionPassBase; + + ArithToLLVMConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ArithToLLVMConversionPassBase(const ArithToLLVMConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + ArithToLLVMConversionPassBase& operator=(const ArithToLLVMConversionPassBase &) = delete; + ArithToLLVMConversionPassBase(ArithToLLVMConversionPassBase &&) = delete; + ArithToLLVMConversionPassBase& operator=(ArithToLLVMConversionPassBase &&) = delete; + ~ArithToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ArithToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "ArithToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ArithToLLVMConversionPassBase) + + ArithToLLVMConversionPassBase(ArithToLLVMConversionPassOptions options) : ArithToLLVMConversionPassBase() { + indexBitwidth = std::move(options.indexBitwidth); + } +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +private: + + friend std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass(ArithToLLVMConversionPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass() { + return impl::createArithToLLVMConversionPass(); +} + +std::unique_ptr<::mlir::Pass> createArithToLLVMConversionPass(ArithToLLVMConversionPassOptions options) { + return impl::createArithToLLVMConversionPass(std::move(options)); +} +#undef GEN_PASS_DEF_ARITHTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DEF_ARITHTOLLVMCONVERSIONPASS + +//===----------------------------------------------------------------------===// +// ConvertAMDGPUToROCDLPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTAMDGPUTOROCDLPASS +struct ConvertAMDGPUToROCDLPassOptions { + std::string chipset = "gfx000"; +}; +std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass(); +std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass(ConvertAMDGPUToROCDLPassOptions options); +#undef GEN_PASS_DECL_CONVERTAMDGPUTOROCDLPASS +#endif // GEN_PASS_DECL_CONVERTAMDGPUTOROCDLPASS +#ifdef GEN_PASS_DEF_CONVERTAMDGPUTOROCDLPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass(ConvertAMDGPUToROCDLPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertAMDGPUToROCDLPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertAMDGPUToROCDLPassBase; + + ConvertAMDGPUToROCDLPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertAMDGPUToROCDLPassBase(const ConvertAMDGPUToROCDLPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertAMDGPUToROCDLPassBase& operator=(const ConvertAMDGPUToROCDLPassBase &) = delete; + ConvertAMDGPUToROCDLPassBase(ConvertAMDGPUToROCDLPassBase &&) = delete; + ConvertAMDGPUToROCDLPassBase& operator=(ConvertAMDGPUToROCDLPassBase &&) = delete; + ~ConvertAMDGPUToROCDLPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-amdgpu-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "convert-amdgpu-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Convert AMDGPU dialect to ROCDL dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAMDGPUToROCDLPass"); + } + ::llvm::StringRef getName() const override { return "ConvertAMDGPUToROCDLPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAMDGPUToROCDLPassBase) + + ConvertAMDGPUToROCDLPassBase(ConvertAMDGPUToROCDLPassOptions options) : ConvertAMDGPUToROCDLPassBase() { + chipset = std::move(options.chipset); + } +protected: + ::mlir::Pass::Option chipset{*this, "chipset", ::llvm::cl::desc("Chipset that these operations will run on"), ::llvm::cl::init("gfx000")}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass(ConvertAMDGPUToROCDLPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass() { + return impl::createConvertAMDGPUToROCDLPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertAMDGPUToROCDLPass(ConvertAMDGPUToROCDLPassOptions options) { + return impl::createConvertAMDGPUToROCDLPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTAMDGPUTOROCDLPASS +#endif // GEN_PASS_DEF_CONVERTAMDGPUTOROCDLPASS + +//===----------------------------------------------------------------------===// +// ConvertAffineForToGPUPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTAFFINEFORTOGPUPASS +struct ConvertAffineForToGPUPassOptions { + unsigned numBlockDims = 1u; + unsigned numThreadDims = 1u; +}; +std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass(); +std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass(ConvertAffineForToGPUPassOptions options); +#undef GEN_PASS_DECL_CONVERTAFFINEFORTOGPUPASS +#endif // GEN_PASS_DECL_CONVERTAFFINEFORTOGPUPASS +#ifdef GEN_PASS_DEF_CONVERTAFFINEFORTOGPUPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass(ConvertAffineForToGPUPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertAffineForToGPUPassBase : public ::mlir::InterfacePass { +public: + using Base = ConvertAffineForToGPUPassBase; + + ConvertAffineForToGPUPassBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + ConvertAffineForToGPUPassBase(const ConvertAffineForToGPUPassBase &other) : ::mlir::InterfacePass(other) {} + ConvertAffineForToGPUPassBase& operator=(const ConvertAffineForToGPUPassBase &) = delete; + ConvertAffineForToGPUPassBase(ConvertAffineForToGPUPassBase &&) = delete; + ConvertAffineForToGPUPassBase& operator=(ConvertAffineForToGPUPassBase &&) = delete; + ~ConvertAffineForToGPUPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-affine-for-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-affine-for-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Convert top-level AffineFor Ops to GPU kernels"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAffineForToGPUPass"); + } + ::llvm::StringRef getName() const override { return "ConvertAffineForToGPUPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAffineForToGPUPassBase) + + ConvertAffineForToGPUPassBase(ConvertAffineForToGPUPassOptions options) : ConvertAffineForToGPUPassBase() { + numBlockDims = std::move(options.numBlockDims); + numThreadDims = std::move(options.numThreadDims); + } +protected: + ::mlir::Pass::Option numBlockDims{*this, "gpu-block-dims", ::llvm::cl::desc("Number of GPU block dimensions for mapping"), ::llvm::cl::init(1u)}; + ::mlir::Pass::Option numThreadDims{*this, "gpu-thread-dims", ::llvm::cl::desc("Number of GPU thread dimensions for mapping"), ::llvm::cl::init(1u)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass(ConvertAffineForToGPUPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass() { + return impl::createConvertAffineForToGPUPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertAffineForToGPUPass(ConvertAffineForToGPUPassOptions options) { + return impl::createConvertAffineForToGPUPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTAFFINEFORTOGPUPASS +#endif // GEN_PASS_DEF_CONVERTAFFINEFORTOGPUPASS + +//===----------------------------------------------------------------------===// +// ConvertArithToEmitC +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTARITHTOEMITC +std::unique_ptr<::mlir::Pass> createConvertArithToEmitC(); +#undef GEN_PASS_DECL_CONVERTARITHTOEMITC +#endif // GEN_PASS_DECL_CONVERTARITHTOEMITC +#ifdef GEN_PASS_DEF_CONVERTARITHTOEMITC + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertArithToEmitC(); +} // namespace impl +namespace impl { + +template +class ConvertArithToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArithToEmitCBase; + + ConvertArithToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArithToEmitCBase(const ConvertArithToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArithToEmitCBase& operator=(const ConvertArithToEmitCBase &) = delete; + ConvertArithToEmitCBase(ConvertArithToEmitCBase &&) = delete; + ConvertArithToEmitCBase& operator=(ConvertArithToEmitCBase &&) = delete; + ~ConvertArithToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to EmitC dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArithToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertArithToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArithToEmitCBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertArithToEmitC() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertArithToEmitC() { + return impl::createConvertArithToEmitC(); +} +#undef GEN_PASS_DEF_CONVERTARITHTOEMITC +#endif // GEN_PASS_DEF_CONVERTARITHTOEMITC + +//===----------------------------------------------------------------------===// +// ConvertArithToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTARITHTOSPIRVPASS +struct ConvertArithToSPIRVPassOptions { + bool emulateLT32BitScalarTypes = true; +}; +std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass(); +std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass(ConvertArithToSPIRVPassOptions options); +#undef GEN_PASS_DECL_CONVERTARITHTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTARITHTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTARITHTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass(ConvertArithToSPIRVPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertArithToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArithToSPIRVPassBase; + + ConvertArithToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArithToSPIRVPassBase(const ConvertArithToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArithToSPIRVPassBase& operator=(const ConvertArithToSPIRVPassBase &) = delete; + ConvertArithToSPIRVPassBase(ConvertArithToSPIRVPassBase &&) = delete; + ConvertArithToSPIRVPassBase& operator=(ConvertArithToSPIRVPassBase &&) = delete; + ~ConvertArithToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArithToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertArithToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArithToSPIRVPassBase) + + ConvertArithToSPIRVPassBase(ConvertArithToSPIRVPassOptions options) : ConvertArithToSPIRVPassBase() { + emulateLT32BitScalarTypes = std::move(options.emulateLT32BitScalarTypes); + } +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass(ConvertArithToSPIRVPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass() { + return impl::createConvertArithToSPIRVPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertArithToSPIRVPass(ConvertArithToSPIRVPassOptions options) { + return impl::createConvertArithToSPIRVPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTARITHTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTARITHTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertArmNeon2dToIntrPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTARMNEON2DTOINTRPASS +std::unique_ptr<::mlir::Pass> createConvertArmNeon2dToIntrPass(); +#undef GEN_PASS_DECL_CONVERTARMNEON2DTOINTRPASS +#endif // GEN_PASS_DECL_CONVERTARMNEON2DTOINTRPASS +#ifdef GEN_PASS_DEF_CONVERTARMNEON2DTOINTRPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertArmNeon2dToIntrPass(); +} // namespace impl +namespace impl { + +template +class ConvertArmNeon2dToIntrPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArmNeon2dToIntrPassBase; + + ConvertArmNeon2dToIntrPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArmNeon2dToIntrPassBase(const ConvertArmNeon2dToIntrPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArmNeon2dToIntrPassBase& operator=(const ConvertArmNeon2dToIntrPassBase &) = delete; + ConvertArmNeon2dToIntrPassBase(ConvertArmNeon2dToIntrPassBase &&) = delete; + ConvertArmNeon2dToIntrPassBase& operator=(ConvertArmNeon2dToIntrPassBase &&) = delete; + ~ConvertArmNeon2dToIntrPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("arm-neon-2d-to-intr"); + } + ::llvm::StringRef getArgument() const override { return "arm-neon-2d-to-intr"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arm NEON structured ops to intrinsics"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArmNeon2dToIntrPass"); + } + ::llvm::StringRef getName() const override { return "ConvertArmNeon2dToIntrPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArmNeon2dToIntrPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertArmNeon2dToIntrPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertArmNeon2dToIntrPass() { + return impl::createConvertArmNeon2dToIntrPass(); +} +#undef GEN_PASS_DEF_CONVERTARMNEON2DTOINTRPASS +#endif // GEN_PASS_DEF_CONVERTARMNEON2DTOINTRPASS + +//===----------------------------------------------------------------------===// +// ConvertArmSMEToLLVM +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTARMSMETOLLVM +struct ConvertArmSMEToLLVMOptions { + bool dumpTileLiveRanges = false; +}; +#undef GEN_PASS_DECL_CONVERTARMSMETOLLVM +#endif // GEN_PASS_DECL_CONVERTARMSMETOLLVM +#ifdef GEN_PASS_DEF_CONVERTARMSMETOLLVM +namespace impl { + +template +class ConvertArmSMEToLLVMBase : public ::mlir::InterfacePass { +public: + using Base = ConvertArmSMEToLLVMBase; + + ConvertArmSMEToLLVMBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + ConvertArmSMEToLLVMBase(const ConvertArmSMEToLLVMBase &other) : ::mlir::InterfacePass(other) {} + ConvertArmSMEToLLVMBase& operator=(const ConvertArmSMEToLLVMBase &) = delete; + ConvertArmSMEToLLVMBase(ConvertArmSMEToLLVMBase &&) = delete; + ConvertArmSMEToLLVMBase& operator=(ConvertArmSMEToLLVMBase &&) = delete; + ~ConvertArmSMEToLLVMBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arm-sme-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-arm-sme-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the ArmSME dialect into the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArmSMEToLLVM"); + } + ::llvm::StringRef getName() const override { return "ConvertArmSMEToLLVM"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArmSMEToLLVMBase) + + ConvertArmSMEToLLVMBase(ConvertArmSMEToLLVMOptions options) : ConvertArmSMEToLLVMBase() { + dumpTileLiveRanges = std::move(options.dumpTileLiveRanges); + } +protected: + ::mlir::Pass::Option dumpTileLiveRanges{*this, "dump-tile-live-ranges", ::llvm::cl::desc("Dump the live ranges of SME tiles (for debugging)"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTARMSMETOLLVM +#endif // GEN_PASS_DEF_CONVERTARMSMETOLLVM + +//===----------------------------------------------------------------------===// +// ConvertArmSMEToSCFPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTARMSMETOSCFPASS +std::unique_ptr<::mlir::Pass> createConvertArmSMEToSCFPass(); +#undef GEN_PASS_DECL_CONVERTARMSMETOSCFPASS +#endif // GEN_PASS_DECL_CONVERTARMSMETOSCFPASS +#ifdef GEN_PASS_DEF_CONVERTARMSMETOSCFPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertArmSMEToSCFPass(); +} // namespace impl +namespace impl { + +template +class ConvertArmSMEToSCFPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArmSMEToSCFPassBase; + + ConvertArmSMEToSCFPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArmSMEToSCFPassBase(const ConvertArmSMEToSCFPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArmSMEToSCFPassBase& operator=(const ConvertArmSMEToSCFPassBase &) = delete; + ConvertArmSMEToSCFPassBase(ConvertArmSMEToSCFPassBase &&) = delete; + ConvertArmSMEToSCFPassBase& operator=(ConvertArmSMEToSCFPassBase &&) = delete; + ~ConvertArmSMEToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arm-sme-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "convert-arm-sme-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the ArmSME dialect into the SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArmSMEToSCFPass"); + } + ::llvm::StringRef getName() const override { return "ConvertArmSMEToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArmSMEToSCFPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertArmSMEToSCFPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertArmSMEToSCFPass() { + return impl::createConvertArmSMEToSCFPass(); +} +#undef GEN_PASS_DEF_CONVERTARMSMETOSCFPASS +#endif // GEN_PASS_DEF_CONVERTARMSMETOSCFPASS + +//===----------------------------------------------------------------------===// +// ConvertAsyncToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTASYNCTOLLVMPASS +std::unique_ptr<::mlir::Pass> createConvertAsyncToLLVMPass(); +#undef GEN_PASS_DECL_CONVERTASYNCTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTASYNCTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTASYNCTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertAsyncToLLVMPass(); +} // namespace impl +namespace impl { + +template +class ConvertAsyncToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertAsyncToLLVMPassBase; + + ConvertAsyncToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertAsyncToLLVMPassBase(const ConvertAsyncToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertAsyncToLLVMPassBase& operator=(const ConvertAsyncToLLVMPassBase &) = delete; + ConvertAsyncToLLVMPassBase(ConvertAsyncToLLVMPassBase &&) = delete; + ConvertAsyncToLLVMPassBase& operator=(ConvertAsyncToLLVMPassBase &&) = delete; + ~ConvertAsyncToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-async-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-async-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert the operations from the async dialect into the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAsyncToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertAsyncToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAsyncToLLVMPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertAsyncToLLVMPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertAsyncToLLVMPass() { + return impl::createConvertAsyncToLLVMPass(); +} +#undef GEN_PASS_DEF_CONVERTASYNCTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTASYNCTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertBufferizationToMemRefPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTBUFFERIZATIONTOMEMREFPASS +std::unique_ptr<::mlir::Pass> createConvertBufferizationToMemRefPass(); +#undef GEN_PASS_DECL_CONVERTBUFFERIZATIONTOMEMREFPASS +#endif // GEN_PASS_DECL_CONVERTBUFFERIZATIONTOMEMREFPASS +#ifdef GEN_PASS_DEF_CONVERTBUFFERIZATIONTOMEMREFPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertBufferizationToMemRefPass(); +} // namespace impl +namespace impl { + +template +class ConvertBufferizationToMemRefPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertBufferizationToMemRefPassBase; + + ConvertBufferizationToMemRefPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertBufferizationToMemRefPassBase(const ConvertBufferizationToMemRefPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertBufferizationToMemRefPassBase& operator=(const ConvertBufferizationToMemRefPassBase &) = delete; + ConvertBufferizationToMemRefPassBase(ConvertBufferizationToMemRefPassBase &&) = delete; + ConvertBufferizationToMemRefPassBase& operator=(ConvertBufferizationToMemRefPassBase &&) = delete; + ~ConvertBufferizationToMemRefPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-bufferization-to-memref"); + } + ::llvm::StringRef getArgument() const override { return "convert-bufferization-to-memref"; } + + ::llvm::StringRef getDescription() const override { return "Convert operations from the Bufferization dialect to the MemRef dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertBufferizationToMemRefPass"); + } + ::llvm::StringRef getName() const override { return "ConvertBufferizationToMemRefPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertBufferizationToMemRefPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertBufferizationToMemRefPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertBufferizationToMemRefPass() { + return impl::createConvertBufferizationToMemRefPass(); +} +#undef GEN_PASS_DEF_CONVERTBUFFERIZATIONTOMEMREFPASS +#endif // GEN_PASS_DEF_CONVERTBUFFERIZATIONTOMEMREFPASS + +//===----------------------------------------------------------------------===// +// ConvertComplexToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCOMPLEXTOLLVMPASS +struct ConvertComplexToLLVMPassOptions { + ::mlir::complex::ComplexRangeFlags complexRange = ::mlir::complex::ComplexRangeFlags::basic; +}; +std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass(ConvertComplexToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTCOMPLEXTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTCOMPLEXTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTCOMPLEXTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass(ConvertComplexToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertComplexToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertComplexToLLVMPassBase; + + ConvertComplexToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertComplexToLLVMPassBase(const ConvertComplexToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertComplexToLLVMPassBase& operator=(const ConvertComplexToLLVMPassBase &) = delete; + ConvertComplexToLLVMPassBase(ConvertComplexToLLVMPassBase &&) = delete; + ConvertComplexToLLVMPassBase& operator=(ConvertComplexToLLVMPassBase &&) = delete; + ~ConvertComplexToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToLLVMPassBase) + + ConvertComplexToLLVMPassBase(ConvertComplexToLLVMPassOptions options) : ConvertComplexToLLVMPassBase() { + complexRange = std::move(options.complexRange); + } +protected: + ::mlir::Pass::Option<::mlir::complex::ComplexRangeFlags> complexRange{*this, "complex-range", ::llvm::cl::desc("Control the intermediate calculation of complex number division"), ::llvm::cl::init(::mlir::complex::ComplexRangeFlags::basic), ::llvm::cl::values( + clEnumValN(::mlir::complex::ComplexRangeFlags::improved, "improved", "improved"), + clEnumValN(::mlir::complex::ComplexRangeFlags::basic, "basic", "basic (default)"), + clEnumValN(::mlir::complex::ComplexRangeFlags::none, "none", "none") + )}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass(ConvertComplexToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass() { + return impl::createConvertComplexToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertComplexToLLVMPass(ConvertComplexToLLVMPassOptions options) { + return impl::createConvertComplexToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTCOMPLEXTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTCOMPLEXTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertComplexToLibm +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCOMPLEXTOLIBM +std::unique_ptr<::mlir::Pass> createConvertComplexToLibm(); +#undef GEN_PASS_DECL_CONVERTCOMPLEXTOLIBM +#endif // GEN_PASS_DECL_CONVERTCOMPLEXTOLIBM +#ifdef GEN_PASS_DEF_CONVERTCOMPLEXTOLIBM + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertComplexToLibm(); +} // namespace impl +namespace impl { + +template +class ConvertComplexToLibmBase : public ::mlir::OperationPass { +public: + using Base = ConvertComplexToLibmBase; + + ConvertComplexToLibmBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertComplexToLibmBase(const ConvertComplexToLibmBase &other) : ::mlir::OperationPass(other) {} + ConvertComplexToLibmBase& operator=(const ConvertComplexToLibmBase &) = delete; + ConvertComplexToLibmBase(ConvertComplexToLibmBase &&) = delete; + ConvertComplexToLibmBase& operator=(ConvertComplexToLibmBase &&) = delete; + ~ConvertComplexToLibmBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-libm"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-libm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to libm calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToLibm"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToLibm"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToLibmBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertComplexToLibm() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertComplexToLibm() { + return impl::createConvertComplexToLibm(); +} +#undef GEN_PASS_DEF_CONVERTCOMPLEXTOLIBM +#endif // GEN_PASS_DEF_CONVERTCOMPLEXTOLIBM + +//===----------------------------------------------------------------------===// +// ConvertComplexToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCOMPLEXTOSPIRVPASS +std::unique_ptr<::mlir::Pass> createConvertComplexToSPIRVPass(); +#undef GEN_PASS_DECL_CONVERTCOMPLEXTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTCOMPLEXTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTCOMPLEXTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertComplexToSPIRVPass(); +} // namespace impl +namespace impl { + +template +class ConvertComplexToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertComplexToSPIRVPassBase; + + ConvertComplexToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertComplexToSPIRVPassBase(const ConvertComplexToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertComplexToSPIRVPassBase& operator=(const ConvertComplexToSPIRVPassBase &) = delete; + ConvertComplexToSPIRVPassBase(ConvertComplexToSPIRVPassBase &&) = delete; + ConvertComplexToSPIRVPassBase& operator=(ConvertComplexToSPIRVPassBase &&) = delete; + ~ConvertComplexToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to SPIRV dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToSPIRVPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertComplexToSPIRVPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertComplexToSPIRVPass() { + return impl::createConvertComplexToSPIRVPass(); +} +#undef GEN_PASS_DEF_CONVERTCOMPLEXTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTCOMPLEXTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertComplexToStandardPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCOMPLEXTOSTANDARDPASS +struct ConvertComplexToStandardPassOptions { + ::mlir::complex::ComplexRangeFlags complexRange = ::mlir::complex::ComplexRangeFlags::improved; +}; +std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass(); +std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass(ConvertComplexToStandardPassOptions options); +#undef GEN_PASS_DECL_CONVERTCOMPLEXTOSTANDARDPASS +#endif // GEN_PASS_DECL_CONVERTCOMPLEXTOSTANDARDPASS +#ifdef GEN_PASS_DEF_CONVERTCOMPLEXTOSTANDARDPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass(ConvertComplexToStandardPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertComplexToStandardPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertComplexToStandardPassBase; + + ConvertComplexToStandardPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertComplexToStandardPassBase(const ConvertComplexToStandardPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertComplexToStandardPassBase& operator=(const ConvertComplexToStandardPassBase &) = delete; + ConvertComplexToStandardPassBase(ConvertComplexToStandardPassBase &&) = delete; + ConvertComplexToStandardPassBase& operator=(ConvertComplexToStandardPassBase &&) = delete; + ~ConvertComplexToStandardPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-standard"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-standard"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToStandardPass"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToStandardPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToStandardPassBase) + + ConvertComplexToStandardPassBase(ConvertComplexToStandardPassOptions options) : ConvertComplexToStandardPassBase() { + complexRange = std::move(options.complexRange); + } +protected: + ::mlir::Pass::Option<::mlir::complex::ComplexRangeFlags> complexRange{*this, "complex-range", ::llvm::cl::desc("Control the intermediate calculation of complex number division"), ::llvm::cl::init(::mlir::complex::ComplexRangeFlags::improved), ::llvm::cl::values( + clEnumValN(::mlir::complex::ComplexRangeFlags::improved, "improved", "improved (default)"), + clEnumValN(::mlir::complex::ComplexRangeFlags::basic, "basic", "basic"), + clEnumValN(::mlir::complex::ComplexRangeFlags::none, "none", "none") + )}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass(ConvertComplexToStandardPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass() { + return impl::createConvertComplexToStandardPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertComplexToStandardPass(ConvertComplexToStandardPassOptions options) { + return impl::createConvertComplexToStandardPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTCOMPLEXTOSTANDARDPASS +#endif // GEN_PASS_DEF_CONVERTCOMPLEXTOSTANDARDPASS + +//===----------------------------------------------------------------------===// +// ConvertControlFlowToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCONTROLFLOWTOLLVMPASS +struct ConvertControlFlowToLLVMPassOptions { + unsigned indexBitwidth = 0; +}; +std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass(ConvertControlFlowToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTCONTROLFLOWTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTCONTROLFLOWTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTCONTROLFLOWTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass(ConvertControlFlowToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertControlFlowToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertControlFlowToLLVMPassBase; + + ConvertControlFlowToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertControlFlowToLLVMPassBase(const ConvertControlFlowToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertControlFlowToLLVMPassBase& operator=(const ConvertControlFlowToLLVMPassBase &) = delete; + ConvertControlFlowToLLVMPassBase(ConvertControlFlowToLLVMPassBase &&) = delete; + ConvertControlFlowToLLVMPassBase& operator=(ConvertControlFlowToLLVMPassBase &&) = delete; + ~ConvertControlFlowToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-cf-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-cf-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert ControlFlow operations to the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertControlFlowToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertControlFlowToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertControlFlowToLLVMPassBase) + + ConvertControlFlowToLLVMPassBase(ConvertControlFlowToLLVMPassOptions options) : ConvertControlFlowToLLVMPassBase() { + indexBitwidth = std::move(options.indexBitwidth); + } +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass(ConvertControlFlowToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass() { + return impl::createConvertControlFlowToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertControlFlowToLLVMPass(ConvertControlFlowToLLVMPassOptions options) { + return impl::createConvertControlFlowToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTCONTROLFLOWTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTCONTROLFLOWTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertControlFlowToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTCONTROLFLOWTOSPIRVPASS +struct ConvertControlFlowToSPIRVPassOptions { + bool emulateLT32BitScalarTypes = true; +}; +std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass(); +std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass(ConvertControlFlowToSPIRVPassOptions options); +#undef GEN_PASS_DECL_CONVERTCONTROLFLOWTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTCONTROLFLOWTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTCONTROLFLOWTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass(ConvertControlFlowToSPIRVPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertControlFlowToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertControlFlowToSPIRVPassBase; + + ConvertControlFlowToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertControlFlowToSPIRVPassBase(const ConvertControlFlowToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertControlFlowToSPIRVPassBase& operator=(const ConvertControlFlowToSPIRVPassBase &) = delete; + ConvertControlFlowToSPIRVPassBase(ConvertControlFlowToSPIRVPassBase &&) = delete; + ConvertControlFlowToSPIRVPassBase& operator=(ConvertControlFlowToSPIRVPassBase &&) = delete; + ~ConvertControlFlowToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-cf-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-cf-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert ControlFlow dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertControlFlowToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertControlFlowToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertControlFlowToSPIRVPassBase) + + ConvertControlFlowToSPIRVPassBase(ConvertControlFlowToSPIRVPassOptions options) : ConvertControlFlowToSPIRVPassBase() { + emulateLT32BitScalarTypes = std::move(options.emulateLT32BitScalarTypes); + } +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass(ConvertControlFlowToSPIRVPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass() { + return impl::createConvertControlFlowToSPIRVPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertControlFlowToSPIRVPass(ConvertControlFlowToSPIRVPassOptions options) { + return impl::createConvertControlFlowToSPIRVPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTCONTROLFLOWTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTCONTROLFLOWTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertFuncToEmitC +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTFUNCTOEMITC +std::unique_ptr<::mlir::Pass> createConvertFuncToEmitC(); +#undef GEN_PASS_DECL_CONVERTFUNCTOEMITC +#endif // GEN_PASS_DECL_CONVERTFUNCTOEMITC +#ifdef GEN_PASS_DEF_CONVERTFUNCTOEMITC + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertFuncToEmitC(); +} // namespace impl +namespace impl { + +template +class ConvertFuncToEmitCBase : public ::mlir::OperationPass { +public: + using Base = ConvertFuncToEmitCBase; + + ConvertFuncToEmitCBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertFuncToEmitCBase(const ConvertFuncToEmitCBase &other) : ::mlir::OperationPass(other) {} + ConvertFuncToEmitCBase& operator=(const ConvertFuncToEmitCBase &) = delete; + ConvertFuncToEmitCBase(ConvertFuncToEmitCBase &&) = delete; + ConvertFuncToEmitCBase& operator=(ConvertFuncToEmitCBase &&) = delete; + ~ConvertFuncToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-func-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-func-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert Func dialect to EmitC dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertFuncToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertFuncToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertFuncToEmitCBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertFuncToEmitC() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertFuncToEmitC() { + return impl::createConvertFuncToEmitC(); +} +#undef GEN_PASS_DEF_CONVERTFUNCTOEMITC +#endif // GEN_PASS_DEF_CONVERTFUNCTOEMITC + +//===----------------------------------------------------------------------===// +// ConvertFuncToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTFUNCTOLLVMPASS +struct ConvertFuncToLLVMPassOptions { + bool useBarePtrCallConv = false; + unsigned indexBitwidth = 0; +}; +std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass(ConvertFuncToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTFUNCTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTFUNCTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTFUNCTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass(ConvertFuncToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertFuncToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertFuncToLLVMPassBase; + + ConvertFuncToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertFuncToLLVMPassBase(const ConvertFuncToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertFuncToLLVMPassBase& operator=(const ConvertFuncToLLVMPassBase &) = delete; + ConvertFuncToLLVMPassBase(ConvertFuncToLLVMPassBase &&) = delete; + ConvertFuncToLLVMPassBase& operator=(ConvertFuncToLLVMPassBase &&) = delete; + ~ConvertFuncToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-func-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-func-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert from the Func dialect to the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertFuncToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertFuncToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertFuncToLLVMPassBase) + + ConvertFuncToLLVMPassBase(ConvertFuncToLLVMPassOptions options) : ConvertFuncToLLVMPassBase() { + useBarePtrCallConv = std::move(options.useBarePtrCallConv); + indexBitwidth = std::move(options.indexBitwidth); + } +protected: + ::mlir::Pass::Option useBarePtrCallConv{*this, "use-bare-ptr-memref-call-conv", ::llvm::cl::desc("Replace FuncOp's MemRef arguments with bare pointers to the MemRef element types"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass(ConvertFuncToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass() { + return impl::createConvertFuncToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertFuncToLLVMPass(ConvertFuncToLLVMPassOptions options) { + return impl::createConvertFuncToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTFUNCTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTFUNCTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertFuncToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTFUNCTOSPIRVPASS +struct ConvertFuncToSPIRVPassOptions { + bool emulateLT32BitScalarTypes = true; +}; +std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass(); +std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass(ConvertFuncToSPIRVPassOptions options); +#undef GEN_PASS_DECL_CONVERTFUNCTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTFUNCTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTFUNCTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass(ConvertFuncToSPIRVPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertFuncToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertFuncToSPIRVPassBase; + + ConvertFuncToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertFuncToSPIRVPassBase(const ConvertFuncToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertFuncToSPIRVPassBase& operator=(const ConvertFuncToSPIRVPassBase &) = delete; + ConvertFuncToSPIRVPassBase(ConvertFuncToSPIRVPassBase &&) = delete; + ConvertFuncToSPIRVPassBase& operator=(ConvertFuncToSPIRVPassBase &&) = delete; + ~ConvertFuncToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-func-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-func-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Func dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertFuncToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertFuncToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertFuncToSPIRVPassBase) + + ConvertFuncToSPIRVPassBase(ConvertFuncToSPIRVPassOptions options) : ConvertFuncToSPIRVPassBase() { + emulateLT32BitScalarTypes = std::move(options.emulateLT32BitScalarTypes); + } +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass(ConvertFuncToSPIRVPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass() { + return impl::createConvertFuncToSPIRVPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertFuncToSPIRVPass(ConvertFuncToSPIRVPassOptions options) { + return impl::createConvertFuncToSPIRVPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTFUNCTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTFUNCTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertGPUToSPIRV +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTGPUTOSPIRV +struct ConvertGPUToSPIRVOptions { + bool use64bitIndex = false; +}; +#undef GEN_PASS_DECL_CONVERTGPUTOSPIRV +#endif // GEN_PASS_DECL_CONVERTGPUTOSPIRV +#ifdef GEN_PASS_DEF_CONVERTGPUTOSPIRV +namespace impl { + +template +class ConvertGPUToSPIRVBase : public ::mlir::OperationPass { +public: + using Base = ConvertGPUToSPIRVBase; + + ConvertGPUToSPIRVBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGPUToSPIRVBase(const ConvertGPUToSPIRVBase &other) : ::mlir::OperationPass(other) {} + ConvertGPUToSPIRVBase& operator=(const ConvertGPUToSPIRVBase &) = delete; + ConvertGPUToSPIRVBase(ConvertGPUToSPIRVBase &&) = delete; + ConvertGPUToSPIRVBase& operator=(ConvertGPUToSPIRVBase &&) = delete; + ~ConvertGPUToSPIRVBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert GPU dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGPUToSPIRV"); + } + ::llvm::StringRef getName() const override { return "ConvertGPUToSPIRV"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGPUToSPIRVBase) + + ConvertGPUToSPIRVBase(ConvertGPUToSPIRVOptions options) : ConvertGPUToSPIRVBase() { + use64bitIndex = std::move(options.use64bitIndex); + } +protected: + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTGPUTOSPIRV +#endif // GEN_PASS_DEF_CONVERTGPUTOSPIRV + +//===----------------------------------------------------------------------===// +// ConvertGpuOpsToLLVMSPVOps +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTGPUOPSTOLLVMSPVOPS +struct ConvertGpuOpsToLLVMSPVOpsOptions { + bool use64bitIndex = false; +}; +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps(); +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps(ConvertGpuOpsToLLVMSPVOpsOptions options); +#undef GEN_PASS_DECL_CONVERTGPUOPSTOLLVMSPVOPS +#endif // GEN_PASS_DECL_CONVERTGPUOPSTOLLVMSPVOPS +#ifdef GEN_PASS_DEF_CONVERTGPUOPSTOLLVMSPVOPS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps(ConvertGpuOpsToLLVMSPVOpsOptions options); +} // namespace impl +namespace impl { + +template +class ConvertGpuOpsToLLVMSPVOpsBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuOpsToLLVMSPVOpsBase; + + ConvertGpuOpsToLLVMSPVOpsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuOpsToLLVMSPVOpsBase(const ConvertGpuOpsToLLVMSPVOpsBase &other) : ::mlir::OperationPass(other) {} + ConvertGpuOpsToLLVMSPVOpsBase& operator=(const ConvertGpuOpsToLLVMSPVOpsBase &) = delete; + ConvertGpuOpsToLLVMSPVOpsBase(ConvertGpuOpsToLLVMSPVOpsBase &&) = delete; + ConvertGpuOpsToLLVMSPVOpsBase& operator=(ConvertGpuOpsToLLVMSPVOpsBase &&) = delete; + ~ConvertGpuOpsToLLVMSPVOpsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-llvm-spv"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-llvm-spv"; } + + ::llvm::StringRef getDescription() const override { return "Generate LLVM operations to be ingested by a SPIR-V backend for gpu operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuOpsToLLVMSPVOps"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuOpsToLLVMSPVOps"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuOpsToLLVMSPVOpsBase) + + ConvertGpuOpsToLLVMSPVOpsBase(ConvertGpuOpsToLLVMSPVOpsOptions options) : ConvertGpuOpsToLLVMSPVOpsBase() { + use64bitIndex = std::move(options.use64bitIndex); + } +protected: + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps(ConvertGpuOpsToLLVMSPVOpsOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps() { + return impl::createConvertGpuOpsToLLVMSPVOps(); +} + +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToLLVMSPVOps(ConvertGpuOpsToLLVMSPVOpsOptions options) { + return impl::createConvertGpuOpsToLLVMSPVOps(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTGPUOPSTOLLVMSPVOPS +#endif // GEN_PASS_DEF_CONVERTGPUOPSTOLLVMSPVOPS + +//===----------------------------------------------------------------------===// +// ConvertGpuOpsToNVVMOps +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTGPUOPSTONVVMOPS +struct ConvertGpuOpsToNVVMOpsOptions { + unsigned indexBitwidth = 0; + bool hasRedux = false; + bool useBarePtrCallConv = false; + ::llvm::SmallVector allowedDialects; +}; +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps(); +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps(ConvertGpuOpsToNVVMOpsOptions options); +#undef GEN_PASS_DECL_CONVERTGPUOPSTONVVMOPS +#endif // GEN_PASS_DECL_CONVERTGPUOPSTONVVMOPS +#ifdef GEN_PASS_DEF_CONVERTGPUOPSTONVVMOPS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps(ConvertGpuOpsToNVVMOpsOptions options); +} // namespace impl +namespace impl { + +template +class ConvertGpuOpsToNVVMOpsBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuOpsToNVVMOpsBase; + + ConvertGpuOpsToNVVMOpsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuOpsToNVVMOpsBase(const ConvertGpuOpsToNVVMOpsBase &other) : ::mlir::OperationPass(other) {} + ConvertGpuOpsToNVVMOpsBase& operator=(const ConvertGpuOpsToNVVMOpsBase &) = delete; + ConvertGpuOpsToNVVMOpsBase(ConvertGpuOpsToNVVMOpsBase &&) = delete; + ConvertGpuOpsToNVVMOpsBase& operator=(ConvertGpuOpsToNVVMOpsBase &&) = delete; + ~ConvertGpuOpsToNVVMOpsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-nvvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-nvvm"; } + + ::llvm::StringRef getDescription() const override { return "Generate NVVM operations for gpu operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuOpsToNVVMOps"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuOpsToNVVMOps"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuOpsToNVVMOpsBase) + + ConvertGpuOpsToNVVMOpsBase(ConvertGpuOpsToNVVMOpsOptions options) : ConvertGpuOpsToNVVMOpsBase() { + indexBitwidth = std::move(options.indexBitwidth); + hasRedux = std::move(options.hasRedux); + useBarePtrCallConv = std::move(options.useBarePtrCallConv); + allowedDialects = std::move(options.allowedDialects); + } +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; + ::mlir::Pass::Option hasRedux{*this, "has-redux", ::llvm::cl::desc("Target gpu supports redux"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option useBarePtrCallConv{*this, "use-bare-ptr-memref-call-conv", ::llvm::cl::desc("Replace memref arguments in GPU functions with bare pointers. All memrefs must have static shape."), ::llvm::cl::init(false)}; + ::mlir::Pass::ListOption allowedDialects{*this, "allowed-dialects", ::llvm::cl::desc("Run conversion patterns of only the specified dialects")}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps(ConvertGpuOpsToNVVMOpsOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps() { + return impl::createConvertGpuOpsToNVVMOps(); +} + +std::unique_ptr<::mlir::Pass> createConvertGpuOpsToNVVMOps(ConvertGpuOpsToNVVMOpsOptions options) { + return impl::createConvertGpuOpsToNVVMOps(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTGPUOPSTONVVMOPS +#endif // GEN_PASS_DEF_CONVERTGPUOPSTONVVMOPS + +//===----------------------------------------------------------------------===// +// ConvertGpuOpsToROCDLOps +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTGPUOPSTOROCDLOPS +struct ConvertGpuOpsToROCDLOpsOptions { + std::string chipset = "gfx000"; + unsigned indexBitwidth = 0; + bool useBarePtrCallConv = false; + ::mlir::gpu::amd::Runtime runtime = ::mlir::gpu::amd::Runtime::Unknown; + ::llvm::SmallVector allowedDialects; +}; +#undef GEN_PASS_DECL_CONVERTGPUOPSTOROCDLOPS +#endif // GEN_PASS_DECL_CONVERTGPUOPSTOROCDLOPS +#ifdef GEN_PASS_DEF_CONVERTGPUOPSTOROCDLOPS +namespace impl { + +template +class ConvertGpuOpsToROCDLOpsBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuOpsToROCDLOpsBase; + + ConvertGpuOpsToROCDLOpsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuOpsToROCDLOpsBase(const ConvertGpuOpsToROCDLOpsBase &other) : ::mlir::OperationPass(other) {} + ConvertGpuOpsToROCDLOpsBase& operator=(const ConvertGpuOpsToROCDLOpsBase &) = delete; + ConvertGpuOpsToROCDLOpsBase(ConvertGpuOpsToROCDLOpsBase &&) = delete; + ConvertGpuOpsToROCDLOpsBase& operator=(ConvertGpuOpsToROCDLOpsBase &&) = delete; + ~ConvertGpuOpsToROCDLOpsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Generate ROCDL operations for gpu operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuOpsToROCDLOps"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuOpsToROCDLOps"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuOpsToROCDLOpsBase) + + ConvertGpuOpsToROCDLOpsBase(ConvertGpuOpsToROCDLOpsOptions options) : ConvertGpuOpsToROCDLOpsBase() { + chipset = std::move(options.chipset); + indexBitwidth = std::move(options.indexBitwidth); + useBarePtrCallConv = std::move(options.useBarePtrCallConv); + runtime = std::move(options.runtime); + allowedDialects = std::move(options.allowedDialects); + } +protected: + ::mlir::Pass::Option chipset{*this, "chipset", ::llvm::cl::desc("Chipset that these operations will run on"), ::llvm::cl::init("gfx000")}; + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; + ::mlir::Pass::Option useBarePtrCallConv{*this, "use-bare-ptr-memref-call-conv", ::llvm::cl::desc("Replace memref arguments in GPU functions with bare pointers.All memrefs must have static shape"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option<::mlir::gpu::amd::Runtime> runtime{*this, "runtime", ::llvm::cl::desc("Runtime code will be run on (default is Unknown, can also use HIP or OpenCL)"), ::llvm::cl::init(::mlir::gpu::amd::Runtime::Unknown), ::llvm::cl::values( + clEnumValN(::mlir::gpu::amd::Runtime::Unknown, "unknown", + "Unknown (default)"), + clEnumValN(::mlir::gpu::amd::Runtime::HIP, "HIP", "HIP"), + clEnumValN(::mlir::gpu::amd::Runtime::OpenCL, "OpenCL", + "OpenCL"))}; + ::mlir::Pass::ListOption allowedDialects{*this, "allowed-dialects", ::llvm::cl::desc("Run conversion patterns of only the specified dialects")}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTGPUOPSTOROCDLOPS +#endif // GEN_PASS_DEF_CONVERTGPUOPSTOROCDLOPS + +//===----------------------------------------------------------------------===// +// ConvertIndexToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTINDEXTOLLVMPASS +struct ConvertIndexToLLVMPassOptions { + unsigned indexBitwidth = 0; +}; +std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass(ConvertIndexToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTINDEXTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTINDEXTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTINDEXTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass(ConvertIndexToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertIndexToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertIndexToLLVMPassBase; + + ConvertIndexToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertIndexToLLVMPassBase(const ConvertIndexToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertIndexToLLVMPassBase& operator=(const ConvertIndexToLLVMPassBase &) = delete; + ConvertIndexToLLVMPassBase(ConvertIndexToLLVMPassBase &&) = delete; + ConvertIndexToLLVMPassBase& operator=(ConvertIndexToLLVMPassBase &&) = delete; + ~ConvertIndexToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-index-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-index-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lower the `index` dialect to the `llvm` dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertIndexToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertIndexToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert<::mlir::LLVM::LLVMDialect>(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertIndexToLLVMPassBase) + + ConvertIndexToLLVMPassBase(ConvertIndexToLLVMPassOptions options) : ConvertIndexToLLVMPassBase() { + indexBitwidth = std::move(options.indexBitwidth); + } +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass(ConvertIndexToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass() { + return impl::createConvertIndexToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertIndexToLLVMPass(ConvertIndexToLLVMPassOptions options) { + return impl::createConvertIndexToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTINDEXTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTINDEXTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertIndexToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTINDEXTOSPIRVPASS +struct ConvertIndexToSPIRVPassOptions { + bool use64bitIndex = false; +}; +std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass(); +std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass(ConvertIndexToSPIRVPassOptions options); +#undef GEN_PASS_DECL_CONVERTINDEXTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTINDEXTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTINDEXTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass(ConvertIndexToSPIRVPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertIndexToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertIndexToSPIRVPassBase; + + ConvertIndexToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertIndexToSPIRVPassBase(const ConvertIndexToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertIndexToSPIRVPassBase& operator=(const ConvertIndexToSPIRVPassBase &) = delete; + ConvertIndexToSPIRVPassBase(ConvertIndexToSPIRVPassBase &&) = delete; + ConvertIndexToSPIRVPassBase& operator=(ConvertIndexToSPIRVPassBase &&) = delete; + ~ConvertIndexToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-index-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-index-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Lower the `index` dialect to the `spirv` dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertIndexToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertIndexToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert<::mlir::spirv::SPIRVDialect>(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertIndexToSPIRVPassBase) + + ConvertIndexToSPIRVPassBase(ConvertIndexToSPIRVPassOptions options) : ConvertIndexToSPIRVPassBase() { + use64bitIndex = std::move(options.use64bitIndex); + } +protected: + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass(ConvertIndexToSPIRVPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass() { + return impl::createConvertIndexToSPIRVPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertIndexToSPIRVPass(ConvertIndexToSPIRVPassOptions options) { + return impl::createConvertIndexToSPIRVPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTINDEXTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTINDEXTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertLinalgToStandardPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTLINALGTOSTANDARDPASS +std::unique_ptr<::mlir::Pass> createConvertLinalgToStandardPass(); +#undef GEN_PASS_DECL_CONVERTLINALGTOSTANDARDPASS +#endif // GEN_PASS_DECL_CONVERTLINALGTOSTANDARDPASS +#ifdef GEN_PASS_DEF_CONVERTLINALGTOSTANDARDPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertLinalgToStandardPass(); +} // namespace impl +namespace impl { + +template +class ConvertLinalgToStandardPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLinalgToStandardPassBase; + + ConvertLinalgToStandardPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLinalgToStandardPassBase(const ConvertLinalgToStandardPassBase &other) : ::mlir::OperationPass(other) {} + ConvertLinalgToStandardPassBase& operator=(const ConvertLinalgToStandardPassBase &) = delete; + ConvertLinalgToStandardPassBase(ConvertLinalgToStandardPassBase &&) = delete; + ConvertLinalgToStandardPassBase& operator=(ConvertLinalgToStandardPassBase &&) = delete; + ~ConvertLinalgToStandardPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-linalg-to-std"); + } + ::llvm::StringRef getArgument() const override { return "convert-linalg-to-std"; } + + ::llvm::StringRef getDescription() const override { return "Convert the operations from the linalg dialect into the Standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLinalgToStandardPass"); + } + ::llvm::StringRef getName() const override { return "ConvertLinalgToStandardPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLinalgToStandardPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertLinalgToStandardPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertLinalgToStandardPass() { + return impl::createConvertLinalgToStandardPass(); +} +#undef GEN_PASS_DEF_CONVERTLINALGTOSTANDARDPASS +#endif // GEN_PASS_DEF_CONVERTLINALGTOSTANDARDPASS + +//===----------------------------------------------------------------------===// +// ConvertMathToEmitC +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMATHTOEMITC +struct ConvertMathToEmitCOptions { + ::mlir::emitc::LanguageTarget languageTarget = ::mlir::emitc::LanguageTarget::c99; +}; +std::unique_ptr<::mlir::Pass> createConvertMathToEmitC(); +std::unique_ptr<::mlir::Pass> createConvertMathToEmitC(ConvertMathToEmitCOptions options); +#undef GEN_PASS_DECL_CONVERTMATHTOEMITC +#endif // GEN_PASS_DECL_CONVERTMATHTOEMITC +#ifdef GEN_PASS_DEF_CONVERTMATHTOEMITC + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToEmitC(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToEmitC(ConvertMathToEmitCOptions options); +} // namespace impl +namespace impl { + +template +class ConvertMathToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMathToEmitCBase; + + ConvertMathToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMathToEmitCBase(const ConvertMathToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMathToEmitCBase& operator=(const ConvertMathToEmitCBase &) = delete; + ConvertMathToEmitCBase(ConvertMathToEmitCBase &&) = delete; + ConvertMathToEmitCBase& operator=(ConvertMathToEmitCBase &&) = delete; + ~ConvertMathToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert some Math operations to EmitC call_opaque operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToEmitCBase) + + ConvertMathToEmitCBase(ConvertMathToEmitCOptions options) : ConvertMathToEmitCBase() { + languageTarget = std::move(options.languageTarget); + } +protected: + ::mlir::Pass::Option<::mlir::emitc::LanguageTarget> languageTarget{*this, "language-target", ::llvm::cl::desc("Select the language standard target for callees (c99 or cpp11)."), ::llvm::cl::init(::mlir::emitc::LanguageTarget::c99), ::llvm::cl::values( + clEnumValN(::mlir::emitc::LanguageTarget::c99, "c99", "c99"), + clEnumValN(::mlir::emitc::LanguageTarget::cpp11, "cpp11", "cpp11") + )}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMathToEmitC() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertMathToEmitC(ConvertMathToEmitCOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMathToEmitC() { + return impl::createConvertMathToEmitC(); +} + +std::unique_ptr<::mlir::Pass> createConvertMathToEmitC(ConvertMathToEmitCOptions options) { + return impl::createConvertMathToEmitC(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTMATHTOEMITC +#endif // GEN_PASS_DEF_CONVERTMATHTOEMITC + +//===----------------------------------------------------------------------===// +// ConvertMathToFuncs +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMATHTOFUNCS +struct ConvertMathToFuncsOptions { + unsigned minWidthOfFPowIExponent = 1; + bool convertCtlz = false; +}; +std::unique_ptr<::mlir::Pass> createConvertMathToFuncs(); +std::unique_ptr<::mlir::Pass> createConvertMathToFuncs(ConvertMathToFuncsOptions options); +#undef GEN_PASS_DECL_CONVERTMATHTOFUNCS +#endif // GEN_PASS_DECL_CONVERTMATHTOFUNCS +#ifdef GEN_PASS_DEF_CONVERTMATHTOFUNCS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToFuncs(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToFuncs(ConvertMathToFuncsOptions options); +} // namespace impl +namespace impl { + +template +class ConvertMathToFuncsBase : public ::mlir::OperationPass { +public: + using Base = ConvertMathToFuncsBase; + + ConvertMathToFuncsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMathToFuncsBase(const ConvertMathToFuncsBase &other) : ::mlir::OperationPass(other) {} + ConvertMathToFuncsBase& operator=(const ConvertMathToFuncsBase &) = delete; + ConvertMathToFuncsBase(ConvertMathToFuncsBase &&) = delete; + ConvertMathToFuncsBase& operator=(ConvertMathToFuncsBase &&) = delete; + ~ConvertMathToFuncsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-funcs"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-funcs"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math operations to calls of outlined implementations."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToFuncs"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToFuncs"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToFuncsBase) + + ConvertMathToFuncsBase(ConvertMathToFuncsOptions options) : ConvertMathToFuncsBase() { + minWidthOfFPowIExponent = std::move(options.minWidthOfFPowIExponent); + convertCtlz = std::move(options.convertCtlz); + } +protected: + ::mlir::Pass::Option minWidthOfFPowIExponent{*this, "min-width-of-fpowi-exponent", ::llvm::cl::desc("Convert FPowI only if the width of its exponent's integer type is greater than or equal to this value"), ::llvm::cl::init(1)}; + ::mlir::Pass::Option convertCtlz{*this, "convert-ctlz", ::llvm::cl::desc("Convert math.ctlz to a software implementation. Enable for targets that do not natively support ctlz."), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMathToFuncs() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertMathToFuncs(ConvertMathToFuncsOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMathToFuncs() { + return impl::createConvertMathToFuncs(); +} + +std::unique_ptr<::mlir::Pass> createConvertMathToFuncs(ConvertMathToFuncsOptions options) { + return impl::createConvertMathToFuncs(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTMATHTOFUNCS +#endif // GEN_PASS_DEF_CONVERTMATHTOFUNCS + +//===----------------------------------------------------------------------===// +// ConvertMathToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMATHTOLLVMPASS +struct ConvertMathToLLVMPassOptions { + bool approximateLog1p = true; +}; +std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass(ConvertMathToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTMATHTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTMATHTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTMATHTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass(ConvertMathToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertMathToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMathToLLVMPassBase; + + ConvertMathToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMathToLLVMPassBase(const ConvertMathToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMathToLLVMPassBase& operator=(const ConvertMathToLLVMPassBase &) = delete; + ConvertMathToLLVMPassBase(ConvertMathToLLVMPassBase &&) = delete; + ConvertMathToLLVMPassBase& operator=(ConvertMathToLLVMPassBase &&) = delete; + ~ConvertMathToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToLLVMPassBase) + + ConvertMathToLLVMPassBase(ConvertMathToLLVMPassOptions options) : ConvertMathToLLVMPassBase() { + approximateLog1p = std::move(options.approximateLog1p); + } +protected: + ::mlir::Pass::Option approximateLog1p{*this, "approximate-log1p", ::llvm::cl::desc("Enable approximation of Log1p."), ::llvm::cl::init(true)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass(ConvertMathToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass() { + return impl::createConvertMathToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertMathToLLVMPass(ConvertMathToLLVMPassOptions options) { + return impl::createConvertMathToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTMATHTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTMATHTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertMathToLibmPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMATHTOLIBMPASS +std::unique_ptr<::mlir::Pass> createConvertMathToLibmPass(); +#undef GEN_PASS_DECL_CONVERTMATHTOLIBMPASS +#endif // GEN_PASS_DECL_CONVERTMATHTOLIBMPASS +#ifdef GEN_PASS_DEF_CONVERTMATHTOLIBMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToLibmPass(); +} // namespace impl +namespace impl { + +template +class ConvertMathToLibmPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertMathToLibmPassBase; + + ConvertMathToLibmPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMathToLibmPassBase(const ConvertMathToLibmPassBase &other) : ::mlir::OperationPass(other) {} + ConvertMathToLibmPassBase& operator=(const ConvertMathToLibmPassBase &) = delete; + ConvertMathToLibmPassBase(ConvertMathToLibmPassBase &&) = delete; + ConvertMathToLibmPassBase& operator=(ConvertMathToLibmPassBase &&) = delete; + ~ConvertMathToLibmPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-libm"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-libm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to libm calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToLibmPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToLibmPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToLibmPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMathToLibmPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMathToLibmPass() { + return impl::createConvertMathToLibmPass(); +} +#undef GEN_PASS_DEF_CONVERTMATHTOLIBMPASS +#endif // GEN_PASS_DEF_CONVERTMATHTOLIBMPASS + +//===----------------------------------------------------------------------===// +// ConvertMathToROCDL +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMATHTOROCDL +std::unique_ptr<::mlir::Pass> createConvertMathToROCDL(); +#undef GEN_PASS_DECL_CONVERTMATHTOROCDL +#endif // GEN_PASS_DECL_CONVERTMATHTOROCDL +#ifdef GEN_PASS_DEF_CONVERTMATHTOROCDL + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToROCDL(); +} // namespace impl +namespace impl { + +template +class ConvertMathToROCDLBase : public ::mlir::OperationPass { +public: + using Base = ConvertMathToROCDLBase; + + ConvertMathToROCDLBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMathToROCDLBase(const ConvertMathToROCDLBase &other) : ::mlir::OperationPass(other) {} + ConvertMathToROCDLBase& operator=(const ConvertMathToROCDLBase &) = delete; + ConvertMathToROCDLBase(ConvertMathToROCDLBase &&) = delete; + ConvertMathToROCDLBase& operator=(ConvertMathToROCDLBase &&) = delete; + ~ConvertMathToROCDLBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to ROCDL library calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToROCDL"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToROCDL"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToROCDLBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMathToROCDL() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMathToROCDL() { + return impl::createConvertMathToROCDL(); +} +#undef GEN_PASS_DEF_CONVERTMATHTOROCDL +#endif // GEN_PASS_DEF_CONVERTMATHTOROCDL + +//===----------------------------------------------------------------------===// +// ConvertMathToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMATHTOSPIRVPASS +std::unique_ptr<::mlir::Pass> createConvertMathToSPIRVPass(); +#undef GEN_PASS_DECL_CONVERTMATHTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTMATHTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTMATHTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMathToSPIRVPass(); +} // namespace impl +namespace impl { + +template +class ConvertMathToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMathToSPIRVPassBase; + + ConvertMathToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMathToSPIRVPassBase(const ConvertMathToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMathToSPIRVPassBase& operator=(const ConvertMathToSPIRVPassBase &) = delete; + ConvertMathToSPIRVPassBase(ConvertMathToSPIRVPassBase &&) = delete; + ConvertMathToSPIRVPassBase& operator=(ConvertMathToSPIRVPassBase &&) = delete; + ~ConvertMathToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToSPIRVPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMathToSPIRVPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMathToSPIRVPass() { + return impl::createConvertMathToSPIRVPass(); +} +#undef GEN_PASS_DEF_CONVERTMATHTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTMATHTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertMemRefToEmitC +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMEMREFTOEMITC +std::unique_ptr<::mlir::Pass> createConvertMemRefToEmitC(); +#undef GEN_PASS_DECL_CONVERTMEMREFTOEMITC +#endif // GEN_PASS_DECL_CONVERTMEMREFTOEMITC +#ifdef GEN_PASS_DEF_CONVERTMEMREFTOEMITC + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMemRefToEmitC(); +} // namespace impl +namespace impl { + +template +class ConvertMemRefToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMemRefToEmitCBase; + + ConvertMemRefToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMemRefToEmitCBase(const ConvertMemRefToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMemRefToEmitCBase& operator=(const ConvertMemRefToEmitCBase &) = delete; + ConvertMemRefToEmitCBase(ConvertMemRefToEmitCBase &&) = delete; + ConvertMemRefToEmitCBase& operator=(ConvertMemRefToEmitCBase &&) = delete; + ~ConvertMemRefToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-memref-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-memref-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert MemRef dialect to EmitC dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMemRefToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertMemRefToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMemRefToEmitCBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMemRefToEmitC() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMemRefToEmitC() { + return impl::createConvertMemRefToEmitC(); +} +#undef GEN_PASS_DEF_CONVERTMEMREFTOEMITC +#endif // GEN_PASS_DEF_CONVERTMEMREFTOEMITC + +//===----------------------------------------------------------------------===// +// ConvertMemRefToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMEMREFTOSPIRVPASS +struct ConvertMemRefToSPIRVPassOptions { + int boolNumBits = 8; + bool use64bitIndex = false; +}; +std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass(); +std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass(ConvertMemRefToSPIRVPassOptions options); +#undef GEN_PASS_DECL_CONVERTMEMREFTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTMEMREFTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTMEMREFTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass(ConvertMemRefToSPIRVPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertMemRefToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMemRefToSPIRVPassBase; + + ConvertMemRefToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMemRefToSPIRVPassBase(const ConvertMemRefToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMemRefToSPIRVPassBase& operator=(const ConvertMemRefToSPIRVPassBase &) = delete; + ConvertMemRefToSPIRVPassBase(ConvertMemRefToSPIRVPassBase &&) = delete; + ConvertMemRefToSPIRVPassBase& operator=(ConvertMemRefToSPIRVPassBase &&) = delete; + ~ConvertMemRefToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-memref-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-memref-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert MemRef dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMemRefToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMemRefToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMemRefToSPIRVPassBase) + + ConvertMemRefToSPIRVPassBase(ConvertMemRefToSPIRVPassOptions options) : ConvertMemRefToSPIRVPassBase() { + boolNumBits = std::move(options.boolNumBits); + use64bitIndex = std::move(options.use64bitIndex); + } +protected: + ::mlir::Pass::Option boolNumBits{*this, "bool-num-bits", ::llvm::cl::desc("The number of bits to store a boolean value"), ::llvm::cl::init(8)}; + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass(ConvertMemRefToSPIRVPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass() { + return impl::createConvertMemRefToSPIRVPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertMemRefToSPIRVPass(ConvertMemRefToSPIRVPassOptions options) { + return impl::createConvertMemRefToSPIRVPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTMEMREFTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTMEMREFTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertMeshToMPIPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTMESHTOMPIPASS +std::unique_ptr<::mlir::Pass> createConvertMeshToMPIPass(); +#undef GEN_PASS_DECL_CONVERTMESHTOMPIPASS +#endif // GEN_PASS_DECL_CONVERTMESHTOMPIPASS +#ifdef GEN_PASS_DEF_CONVERTMESHTOMPIPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertMeshToMPIPass(); +} // namespace impl +namespace impl { + +template +class ConvertMeshToMPIPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMeshToMPIPassBase; + + ConvertMeshToMPIPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMeshToMPIPassBase(const ConvertMeshToMPIPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMeshToMPIPassBase& operator=(const ConvertMeshToMPIPassBase &) = delete; + ConvertMeshToMPIPassBase(ConvertMeshToMPIPassBase &&) = delete; + ConvertMeshToMPIPassBase& operator=(ConvertMeshToMPIPassBase &&) = delete; + ~ConvertMeshToMPIPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-mesh-to-mpi"); + } + ::llvm::StringRef getArgument() const override { return "convert-mesh-to-mpi"; } + + ::llvm::StringRef getDescription() const override { return "Convert Mesh dialect to MPI dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMeshToMPIPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMeshToMPIPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMeshToMPIPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertMeshToMPIPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertMeshToMPIPass() { + return impl::createConvertMeshToMPIPass(); +} +#undef GEN_PASS_DEF_CONVERTMESHTOMPIPASS +#endif // GEN_PASS_DEF_CONVERTMESHTOMPIPASS + +//===----------------------------------------------------------------------===// +// ConvertNVGPUToNVVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTNVGPUTONVVMPASS +std::unique_ptr<::mlir::Pass> createConvertNVGPUToNVVMPass(); +#undef GEN_PASS_DECL_CONVERTNVGPUTONVVMPASS +#endif // GEN_PASS_DECL_CONVERTNVGPUTONVVMPASS +#ifdef GEN_PASS_DEF_CONVERTNVGPUTONVVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertNVGPUToNVVMPass(); +} // namespace impl +namespace impl { + +template +class ConvertNVGPUToNVVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertNVGPUToNVVMPassBase; + + ConvertNVGPUToNVVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertNVGPUToNVVMPassBase(const ConvertNVGPUToNVVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertNVGPUToNVVMPassBase& operator=(const ConvertNVGPUToNVVMPassBase &) = delete; + ConvertNVGPUToNVVMPassBase(ConvertNVGPUToNVVMPassBase &&) = delete; + ConvertNVGPUToNVVMPassBase& operator=(ConvertNVGPUToNVVMPassBase &&) = delete; + ~ConvertNVGPUToNVVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-nvgpu-to-nvvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-nvgpu-to-nvvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert NVGPU dialect to NVVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertNVGPUToNVVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertNVGPUToNVVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertNVGPUToNVVMPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertNVGPUToNVVMPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertNVGPUToNVVMPass() { + return impl::createConvertNVGPUToNVVMPass(); +} +#undef GEN_PASS_DEF_CONVERTNVGPUTONVVMPASS +#endif // GEN_PASS_DEF_CONVERTNVGPUTONVVMPASS + +//===----------------------------------------------------------------------===// +// ConvertNVVMToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTNVVMTOLLVMPASS +std::unique_ptr<::mlir::Pass> createConvertNVVMToLLVMPass(); +#undef GEN_PASS_DECL_CONVERTNVVMTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTNVVMTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTNVVMTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertNVVMToLLVMPass(); +} // namespace impl +namespace impl { + +template +class ConvertNVVMToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertNVVMToLLVMPassBase; + + ConvertNVVMToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertNVVMToLLVMPassBase(const ConvertNVVMToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertNVVMToLLVMPassBase& operator=(const ConvertNVVMToLLVMPassBase &) = delete; + ConvertNVVMToLLVMPassBase(ConvertNVVMToLLVMPassBase &&) = delete; + ConvertNVVMToLLVMPassBase& operator=(ConvertNVVMToLLVMPassBase &&) = delete; + ~ConvertNVVMToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-nvvm-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-nvvm-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert NVVM to PTX with Inline Assembly in LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertNVVMToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertNVVMToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertNVVMToLLVMPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertNVVMToLLVMPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertNVVMToLLVMPass() { + return impl::createConvertNVVMToLLVMPass(); +} +#undef GEN_PASS_DEF_CONVERTNVVMTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTNVVMTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertOpenACCToSCFPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTOPENACCTOSCFPASS +std::unique_ptr<::mlir::Pass> createConvertOpenACCToSCFPass(); +#undef GEN_PASS_DECL_CONVERTOPENACCTOSCFPASS +#endif // GEN_PASS_DECL_CONVERTOPENACCTOSCFPASS +#ifdef GEN_PASS_DEF_CONVERTOPENACCTOSCFPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertOpenACCToSCFPass(); +} // namespace impl +namespace impl { + +template +class ConvertOpenACCToSCFPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertOpenACCToSCFPassBase; + + ConvertOpenACCToSCFPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertOpenACCToSCFPassBase(const ConvertOpenACCToSCFPassBase &other) : ::mlir::OperationPass(other) {} + ConvertOpenACCToSCFPassBase& operator=(const ConvertOpenACCToSCFPassBase &) = delete; + ConvertOpenACCToSCFPassBase(ConvertOpenACCToSCFPassBase &&) = delete; + ConvertOpenACCToSCFPassBase& operator=(ConvertOpenACCToSCFPassBase &&) = delete; + ~ConvertOpenACCToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-openacc-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "convert-openacc-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Convert the OpenACC ops to OpenACC with SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertOpenACCToSCFPass"); + } + ::llvm::StringRef getName() const override { return "ConvertOpenACCToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertOpenACCToSCFPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertOpenACCToSCFPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertOpenACCToSCFPass() { + return impl::createConvertOpenACCToSCFPass(); +} +#undef GEN_PASS_DEF_CONVERTOPENACCTOSCFPASS +#endif // GEN_PASS_DEF_CONVERTOPENACCTOSCFPASS + +//===----------------------------------------------------------------------===// +// ConvertOpenMPToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTOPENMPTOLLVMPASS +std::unique_ptr<::mlir::Pass> createConvertOpenMPToLLVMPass(); +#undef GEN_PASS_DECL_CONVERTOPENMPTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTOPENMPTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTOPENMPTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertOpenMPToLLVMPass(); +} // namespace impl +namespace impl { + +template +class ConvertOpenMPToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertOpenMPToLLVMPassBase; + + ConvertOpenMPToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertOpenMPToLLVMPassBase(const ConvertOpenMPToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertOpenMPToLLVMPassBase& operator=(const ConvertOpenMPToLLVMPassBase &) = delete; + ConvertOpenMPToLLVMPassBase(ConvertOpenMPToLLVMPassBase &&) = delete; + ConvertOpenMPToLLVMPassBase& operator=(ConvertOpenMPToLLVMPassBase &&) = delete; + ~ConvertOpenMPToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-openmp-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-openmp-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert the OpenMP ops to OpenMP ops with LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertOpenMPToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertOpenMPToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertOpenMPToLLVMPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertOpenMPToLLVMPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertOpenMPToLLVMPass() { + return impl::createConvertOpenMPToLLVMPass(); +} +#undef GEN_PASS_DEF_CONVERTOPENMPTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTOPENMPTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertPDLToPDLInterpPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTPDLTOPDLINTERPPASS +std::unique_ptr<::mlir::Pass> createConvertPDLToPDLInterpPass(); +#undef GEN_PASS_DECL_CONVERTPDLTOPDLINTERPPASS +#endif // GEN_PASS_DECL_CONVERTPDLTOPDLINTERPPASS +#ifdef GEN_PASS_DEF_CONVERTPDLTOPDLINTERPPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertPDLToPDLInterpPass(); +} // namespace impl +namespace impl { + +template +class ConvertPDLToPDLInterpPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertPDLToPDLInterpPassBase; + + ConvertPDLToPDLInterpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertPDLToPDLInterpPassBase(const ConvertPDLToPDLInterpPassBase &other) : ::mlir::OperationPass(other) {} + ConvertPDLToPDLInterpPassBase& operator=(const ConvertPDLToPDLInterpPassBase &) = delete; + ConvertPDLToPDLInterpPassBase(ConvertPDLToPDLInterpPassBase &&) = delete; + ConvertPDLToPDLInterpPassBase& operator=(ConvertPDLToPDLInterpPassBase &&) = delete; + ~ConvertPDLToPDLInterpPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-pdl-to-pdl-interp"); + } + ::llvm::StringRef getArgument() const override { return "convert-pdl-to-pdl-interp"; } + + ::llvm::StringRef getDescription() const override { return "Convert PDL ops to PDL interpreter ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertPDLToPDLInterpPass"); + } + ::llvm::StringRef getName() const override { return "ConvertPDLToPDLInterpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertPDLToPDLInterpPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertPDLToPDLInterpPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertPDLToPDLInterpPass() { + return impl::createConvertPDLToPDLInterpPass(); +} +#undef GEN_PASS_DEF_CONVERTPDLTOPDLINTERPPASS +#endif // GEN_PASS_DEF_CONVERTPDLTOPDLINTERPPASS + +//===----------------------------------------------------------------------===// +// ConvertParallelLoopToGpuPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTPARALLELLOOPTOGPUPASS +std::unique_ptr<::mlir::Pass> createConvertParallelLoopToGpuPass(); +#undef GEN_PASS_DECL_CONVERTPARALLELLOOPTOGPUPASS +#endif // GEN_PASS_DECL_CONVERTPARALLELLOOPTOGPUPASS +#ifdef GEN_PASS_DEF_CONVERTPARALLELLOOPTOGPUPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertParallelLoopToGpuPass(); +} // namespace impl +namespace impl { + +template +class ConvertParallelLoopToGpuPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertParallelLoopToGpuPassBase; + + ConvertParallelLoopToGpuPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertParallelLoopToGpuPassBase(const ConvertParallelLoopToGpuPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertParallelLoopToGpuPassBase& operator=(const ConvertParallelLoopToGpuPassBase &) = delete; + ConvertParallelLoopToGpuPassBase(ConvertParallelLoopToGpuPassBase &&) = delete; + ConvertParallelLoopToGpuPassBase& operator=(ConvertParallelLoopToGpuPassBase &&) = delete; + ~ConvertParallelLoopToGpuPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-parallel-loops-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-parallel-loops-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Convert mapped scf.parallel ops to gpu launch operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertParallelLoopToGpuPass"); + } + ::llvm::StringRef getName() const override { return "ConvertParallelLoopToGpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertParallelLoopToGpuPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertParallelLoopToGpuPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertParallelLoopToGpuPass() { + return impl::createConvertParallelLoopToGpuPass(); +} +#undef GEN_PASS_DEF_CONVERTPARALLELLOOPTOGPUPASS +#endif // GEN_PASS_DEF_CONVERTPARALLELLOOPTOGPUPASS + +//===----------------------------------------------------------------------===// +// ConvertSCFToOpenMPPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTSCFTOOPENMPPASS +struct ConvertSCFToOpenMPPassOptions { + unsigned numThreads = 0; +}; +std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass(); +std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass(ConvertSCFToOpenMPPassOptions options); +#undef GEN_PASS_DECL_CONVERTSCFTOOPENMPPASS +#endif // GEN_PASS_DECL_CONVERTSCFTOOPENMPPASS +#ifdef GEN_PASS_DEF_CONVERTSCFTOOPENMPPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass(ConvertSCFToOpenMPPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertSCFToOpenMPPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertSCFToOpenMPPassBase; + + ConvertSCFToOpenMPPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertSCFToOpenMPPassBase(const ConvertSCFToOpenMPPassBase &other) : ::mlir::OperationPass(other) {} + ConvertSCFToOpenMPPassBase& operator=(const ConvertSCFToOpenMPPassBase &) = delete; + ConvertSCFToOpenMPPassBase(ConvertSCFToOpenMPPassBase &&) = delete; + ConvertSCFToOpenMPPassBase& operator=(ConvertSCFToOpenMPPassBase &&) = delete; + ~ConvertSCFToOpenMPPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-openmp"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-openmp"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF parallel loop to OpenMP parallel + workshare constructs."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertSCFToOpenMPPass"); + } + ::llvm::StringRef getName() const override { return "ConvertSCFToOpenMPPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertSCFToOpenMPPassBase) + + ConvertSCFToOpenMPPassBase(ConvertSCFToOpenMPPassOptions options) : ConvertSCFToOpenMPPassBase() { + numThreads = std::move(options.numThreads); + } +protected: + ::mlir::Pass::Option numThreads{*this, "num-threads", ::llvm::cl::desc("Number of threads to use"), ::llvm::cl::init(0)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass(ConvertSCFToOpenMPPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass() { + return impl::createConvertSCFToOpenMPPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertSCFToOpenMPPass(ConvertSCFToOpenMPPassOptions options) { + return impl::createConvertSCFToOpenMPPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTSCFTOOPENMPPASS +#endif // GEN_PASS_DEF_CONVERTSCFTOOPENMPPASS + +//===----------------------------------------------------------------------===// +// ConvertSPIRVToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTSPIRVTOLLVMPASS +struct ConvertSPIRVToLLVMPassOptions { + ::mlir::spirv::ClientAPI clientAPI = ::mlir::spirv::ClientAPI::Unknown; +}; +std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass(ConvertSPIRVToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTSPIRVTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTSPIRVTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTSPIRVTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass(ConvertSPIRVToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertSPIRVToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertSPIRVToLLVMPassBase; + + ConvertSPIRVToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertSPIRVToLLVMPassBase(const ConvertSPIRVToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertSPIRVToLLVMPassBase& operator=(const ConvertSPIRVToLLVMPassBase &) = delete; + ConvertSPIRVToLLVMPassBase(ConvertSPIRVToLLVMPassBase &&) = delete; + ConvertSPIRVToLLVMPassBase& operator=(ConvertSPIRVToLLVMPassBase &&) = delete; + ~ConvertSPIRVToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-spirv-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-spirv-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert SPIR-V dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertSPIRVToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertSPIRVToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertSPIRVToLLVMPassBase) + + ConvertSPIRVToLLVMPassBase(ConvertSPIRVToLLVMPassOptions options) : ConvertSPIRVToLLVMPassBase() { + clientAPI = std::move(options.clientAPI); + } +protected: + ::mlir::Pass::Option<::mlir::spirv::ClientAPI> clientAPI{*this, "client-api", ::llvm::cl::desc("Derive StorageClass to address space mapping from the client API"), ::llvm::cl::init(::mlir::spirv::ClientAPI::Unknown), ::llvm::cl::values( + clEnumValN(::mlir::spirv::ClientAPI::Unknown, "Unknown", "Unknown (default)"), + clEnumValN(::mlir::spirv::ClientAPI::Metal, "Metal", "Metal"), + clEnumValN(::mlir::spirv::ClientAPI::OpenCL, "OpenCL", "OpenCL"), + clEnumValN(::mlir::spirv::ClientAPI::Vulkan, "Vulkan", "Vulkan"), + clEnumValN(::mlir::spirv::ClientAPI::WebGPU, "WebGPU", "WebGPU") + )}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass(ConvertSPIRVToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass() { + return impl::createConvertSPIRVToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertSPIRVToLLVMPass(ConvertSPIRVToLLVMPassOptions options) { + return impl::createConvertSPIRVToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTSPIRVTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTSPIRVTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertShapeConstraintsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTSHAPECONSTRAINTSPASS +std::unique_ptr<::mlir::Pass> createConvertShapeConstraintsPass(); +#undef GEN_PASS_DECL_CONVERTSHAPECONSTRAINTSPASS +#endif // GEN_PASS_DECL_CONVERTSHAPECONSTRAINTSPASS +#ifdef GEN_PASS_DEF_CONVERTSHAPECONSTRAINTSPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertShapeConstraintsPass(); +} // namespace impl +namespace impl { + +template +class ConvertShapeConstraintsPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertShapeConstraintsPassBase; + + ConvertShapeConstraintsPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertShapeConstraintsPassBase(const ConvertShapeConstraintsPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertShapeConstraintsPassBase& operator=(const ConvertShapeConstraintsPassBase &) = delete; + ConvertShapeConstraintsPassBase(ConvertShapeConstraintsPassBase &&) = delete; + ConvertShapeConstraintsPassBase& operator=(ConvertShapeConstraintsPassBase &&) = delete; + ~ConvertShapeConstraintsPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-shape-constraints"); + } + ::llvm::StringRef getArgument() const override { return "convert-shape-constraints"; } + + ::llvm::StringRef getDescription() const override { return "Convert shape constraint operations to the standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertShapeConstraintsPass"); + } + ::llvm::StringRef getName() const override { return "ConvertShapeConstraintsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertShapeConstraintsPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertShapeConstraintsPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertShapeConstraintsPass() { + return impl::createConvertShapeConstraintsPass(); +} +#undef GEN_PASS_DEF_CONVERTSHAPECONSTRAINTSPASS +#endif // GEN_PASS_DEF_CONVERTSHAPECONSTRAINTSPASS + +//===----------------------------------------------------------------------===// +// ConvertShapeToStandardPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTSHAPETOSTANDARDPASS +std::unique_ptr<::mlir::Pass> createConvertShapeToStandardPass(); +#undef GEN_PASS_DECL_CONVERTSHAPETOSTANDARDPASS +#endif // GEN_PASS_DECL_CONVERTSHAPETOSTANDARDPASS +#ifdef GEN_PASS_DEF_CONVERTSHAPETOSTANDARDPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertShapeToStandardPass(); +} // namespace impl +namespace impl { + +template +class ConvertShapeToStandardPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertShapeToStandardPassBase; + + ConvertShapeToStandardPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertShapeToStandardPassBase(const ConvertShapeToStandardPassBase &other) : ::mlir::OperationPass(other) {} + ConvertShapeToStandardPassBase& operator=(const ConvertShapeToStandardPassBase &) = delete; + ConvertShapeToStandardPassBase(ConvertShapeToStandardPassBase &&) = delete; + ConvertShapeToStandardPassBase& operator=(ConvertShapeToStandardPassBase &&) = delete; + ~ConvertShapeToStandardPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-shape-to-std"); + } + ::llvm::StringRef getArgument() const override { return "convert-shape-to-std"; } + + ::llvm::StringRef getDescription() const override { return "Convert operations from the shape dialect into the standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertShapeToStandardPass"); + } + ::llvm::StringRef getName() const override { return "ConvertShapeToStandardPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertShapeToStandardPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertShapeToStandardPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertShapeToStandardPass() { + return impl::createConvertShapeToStandardPass(); +} +#undef GEN_PASS_DEF_CONVERTSHAPETOSTANDARDPASS +#endif // GEN_PASS_DEF_CONVERTSHAPETOSTANDARDPASS + +//===----------------------------------------------------------------------===// +// ConvertTensorToLinalgPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTTENSORTOLINALGPASS +std::unique_ptr<::mlir::Pass> createConvertTensorToLinalgPass(); +#undef GEN_PASS_DECL_CONVERTTENSORTOLINALGPASS +#endif // GEN_PASS_DECL_CONVERTTENSORTOLINALGPASS +#ifdef GEN_PASS_DEF_CONVERTTENSORTOLINALGPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertTensorToLinalgPass(); +} // namespace impl +namespace impl { + +template +class ConvertTensorToLinalgPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertTensorToLinalgPassBase; + + ConvertTensorToLinalgPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertTensorToLinalgPassBase(const ConvertTensorToLinalgPassBase &other) : ::mlir::OperationPass(other) {} + ConvertTensorToLinalgPassBase& operator=(const ConvertTensorToLinalgPassBase &) = delete; + ConvertTensorToLinalgPassBase(ConvertTensorToLinalgPassBase &&) = delete; + ConvertTensorToLinalgPassBase& operator=(ConvertTensorToLinalgPassBase &&) = delete; + ~ConvertTensorToLinalgPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-tensor-to-linalg"); + } + ::llvm::StringRef getArgument() const override { return "convert-tensor-to-linalg"; } + + ::llvm::StringRef getDescription() const override { return "Convert some Tensor dialect ops to Linalg dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertTensorToLinalgPass"); + } + ::llvm::StringRef getName() const override { return "ConvertTensorToLinalgPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertTensorToLinalgPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertTensorToLinalgPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertTensorToLinalgPass() { + return impl::createConvertTensorToLinalgPass(); +} +#undef GEN_PASS_DEF_CONVERTTENSORTOLINALGPASS +#endif // GEN_PASS_DEF_CONVERTTENSORTOLINALGPASS + +//===----------------------------------------------------------------------===// +// ConvertTensorToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTTENSORTOSPIRVPASS +struct ConvertTensorToSPIRVPassOptions { + bool emulateLT32BitScalarTypes = true; +}; +std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass(); +std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass(ConvertTensorToSPIRVPassOptions options); +#undef GEN_PASS_DECL_CONVERTTENSORTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTTENSORTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTTENSORTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass(ConvertTensorToSPIRVPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertTensorToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertTensorToSPIRVPassBase; + + ConvertTensorToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertTensorToSPIRVPassBase(const ConvertTensorToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertTensorToSPIRVPassBase& operator=(const ConvertTensorToSPIRVPassBase &) = delete; + ConvertTensorToSPIRVPassBase(ConvertTensorToSPIRVPassBase &&) = delete; + ConvertTensorToSPIRVPassBase& operator=(ConvertTensorToSPIRVPassBase &&) = delete; + ~ConvertTensorToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-tensor-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-tensor-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Tensor dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertTensorToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertTensorToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertTensorToSPIRVPassBase) + + ConvertTensorToSPIRVPassBase(ConvertTensorToSPIRVPassOptions options) : ConvertTensorToSPIRVPassBase() { + emulateLT32BitScalarTypes = std::move(options.emulateLT32BitScalarTypes); + } +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass(ConvertTensorToSPIRVPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass() { + return impl::createConvertTensorToSPIRVPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertTensorToSPIRVPass(ConvertTensorToSPIRVPassOptions options) { + return impl::createConvertTensorToSPIRVPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTTENSORTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTTENSORTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertToEmitC +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTTOEMITC +struct ConvertToEmitCOptions { + ::llvm::SmallVector filterDialects; +}; +std::unique_ptr<::mlir::Pass> createConvertToEmitC(); +std::unique_ptr<::mlir::Pass> createConvertToEmitC(ConvertToEmitCOptions options); +#undef GEN_PASS_DECL_CONVERTTOEMITC +#endif // GEN_PASS_DECL_CONVERTTOEMITC +#ifdef GEN_PASS_DEF_CONVERTTOEMITC + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertToEmitC(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertToEmitC(ConvertToEmitCOptions options); +} // namespace impl +namespace impl { + +template +class ConvertToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertToEmitCBase; + + ConvertToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertToEmitCBase(const ConvertToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertToEmitCBase& operator=(const ConvertToEmitCBase &) = delete; + ConvertToEmitCBase(ConvertToEmitCBase &&) = delete; + ConvertToEmitCBase& operator=(ConvertToEmitCBase &&) = delete; + ~ConvertToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert to EmitC dialect via dialect interfaces"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertToEmitCBase) + + ConvertToEmitCBase(ConvertToEmitCOptions options) : ConvertToEmitCBase() { + filterDialects = std::move(options.filterDialects); + } +protected: + ::mlir::Pass::ListOption filterDialects{*this, "filter-dialects", ::llvm::cl::desc("Test conversion patterns of only the specified dialects")}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertToEmitC() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertToEmitC(ConvertToEmitCOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertToEmitC() { + return impl::createConvertToEmitC(); +} + +std::unique_ptr<::mlir::Pass> createConvertToEmitC(ConvertToEmitCOptions options) { + return impl::createConvertToEmitC(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTTOEMITC +#endif // GEN_PASS_DEF_CONVERTTOEMITC + +//===----------------------------------------------------------------------===// +// ConvertToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTTOLLVMPASS +struct ConvertToLLVMPassOptions { + ::llvm::SmallVector filterDialects; + bool useDynamic = false; +}; +std::unique_ptr<::mlir::Pass> createConvertToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertToLLVMPass(ConvertToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertToLLVMPass(ConvertToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertToLLVMPassBase; + + ConvertToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertToLLVMPassBase(const ConvertToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertToLLVMPassBase& operator=(const ConvertToLLVMPassBase &) = delete; + ConvertToLLVMPassBase(ConvertToLLVMPassBase &&) = delete; + ConvertToLLVMPassBase& operator=(ConvertToLLVMPassBase &&) = delete; + ~ConvertToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert to LLVM via dialect interfaces found in the input IR"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertToLLVMPassBase) + + ConvertToLLVMPassBase(ConvertToLLVMPassOptions options) : ConvertToLLVMPassBase() { + filterDialects = std::move(options.filterDialects); + useDynamic = std::move(options.useDynamic); + } +protected: + ::mlir::Pass::ListOption filterDialects{*this, "filter-dialects", ::llvm::cl::desc("Test conversion patterns of only the specified dialects")}; + ::mlir::Pass::Option useDynamic{*this, "dynamic", ::llvm::cl::desc("Use op conversion attributes to configure the conversion"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertToLLVMPass(ConvertToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertToLLVMPass() { + return impl::createConvertToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertToLLVMPass(ConvertToLLVMPassOptions options) { + return impl::createConvertToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertVectorToArmSMEPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTVECTORTOARMSMEPASS +std::unique_ptr<::mlir::Pass> createConvertVectorToArmSMEPass(); +#undef GEN_PASS_DECL_CONVERTVECTORTOARMSMEPASS +#endif // GEN_PASS_DECL_CONVERTVECTORTOARMSMEPASS +#ifdef GEN_PASS_DEF_CONVERTVECTORTOARMSMEPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertVectorToArmSMEPass(); +} // namespace impl +namespace impl { + +template +class ConvertVectorToArmSMEPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToArmSMEPassBase; + + ConvertVectorToArmSMEPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToArmSMEPassBase(const ConvertVectorToArmSMEPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToArmSMEPassBase& operator=(const ConvertVectorToArmSMEPassBase &) = delete; + ConvertVectorToArmSMEPassBase(ConvertVectorToArmSMEPassBase &&) = delete; + ConvertVectorToArmSMEPassBase& operator=(ConvertVectorToArmSMEPassBase &&) = delete; + ~ConvertVectorToArmSMEPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-arm-sme"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-arm-sme"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the ArmSME dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToArmSMEPass"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToArmSMEPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToArmSMEPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertVectorToArmSMEPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertVectorToArmSMEPass() { + return impl::createConvertVectorToArmSMEPass(); +} +#undef GEN_PASS_DEF_CONVERTVECTORTOARMSMEPASS +#endif // GEN_PASS_DEF_CONVERTVECTORTOARMSMEPASS + +//===----------------------------------------------------------------------===// +// ConvertVectorToGPU +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTVECTORTOGPU +struct ConvertVectorToGPUOptions { + bool useNvGpu = false; +}; +#undef GEN_PASS_DECL_CONVERTVECTORTOGPU +#endif // GEN_PASS_DECL_CONVERTVECTORTOGPU +#ifdef GEN_PASS_DEF_CONVERTVECTORTOGPU +namespace impl { + +template +class ConvertVectorToGPUBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToGPUBase; + + ConvertVectorToGPUBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToGPUBase(const ConvertVectorToGPUBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToGPUBase& operator=(const ConvertVectorToGPUBase &) = delete; + ConvertVectorToGPUBase(ConvertVectorToGPUBase &&) = delete; + ConvertVectorToGPUBase& operator=(ConvertVectorToGPUBase &&) = delete; + ~ConvertVectorToGPUBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the GPU dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToGPU"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToGPU"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToGPUBase) + + ConvertVectorToGPUBase(ConvertVectorToGPUOptions options) : ConvertVectorToGPUBase() { + useNvGpu = std::move(options.useNvGpu); + } +protected: + ::mlir::Pass::Option useNvGpu{*this, "use-nvgpu", ::llvm::cl::desc("convert to NvGPU ops instead of GPU dialect ops"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTVECTORTOGPU +#endif // GEN_PASS_DEF_CONVERTVECTORTOGPU + +//===----------------------------------------------------------------------===// +// ConvertVectorToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTVECTORTOLLVMPASS +struct ConvertVectorToLLVMPassOptions { + bool reassociateFPReductions = false; + bool force32BitVectorIndices = true; + bool useVectorAlignment = false; + bool amx = false; + bool armNeon = false; + bool armSVE = false; + bool armI8MM = false; + bool x86Vector = false; + vector::VectorContractLowering vectorContractLowering = vector::VectorContractLowering::Dot; + vector::VectorTransposeLowering vectorTransposeLowering = vector::VectorTransposeLowering::EltWise; +}; +std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass(); +std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass(ConvertVectorToLLVMPassOptions options); +#undef GEN_PASS_DECL_CONVERTVECTORTOLLVMPASS +#endif // GEN_PASS_DECL_CONVERTVECTORTOLLVMPASS +#ifdef GEN_PASS_DEF_CONVERTVECTORTOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass(ConvertVectorToLLVMPassOptions options); +} // namespace impl +namespace impl { + +template +class ConvertVectorToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToLLVMPassBase; + + ConvertVectorToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToLLVMPassBase(const ConvertVectorToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToLLVMPassBase& operator=(const ConvertVectorToLLVMPassBase &) = delete; + ConvertVectorToLLVMPassBase(ConvertVectorToLLVMPassBase &&) = delete; + ConvertVectorToLLVMPassBase& operator=(ConvertVectorToLLVMPassBase &&) = delete; + ~ConvertVectorToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToLLVMPassBase) + + ConvertVectorToLLVMPassBase(ConvertVectorToLLVMPassOptions options) : ConvertVectorToLLVMPassBase() { + reassociateFPReductions = std::move(options.reassociateFPReductions); + force32BitVectorIndices = std::move(options.force32BitVectorIndices); + useVectorAlignment = std::move(options.useVectorAlignment); + amx = std::move(options.amx); + armNeon = std::move(options.armNeon); + armSVE = std::move(options.armSVE); + armI8MM = std::move(options.armI8MM); + x86Vector = std::move(options.x86Vector); + vectorContractLowering = std::move(options.vectorContractLowering); + vectorTransposeLowering = std::move(options.vectorTransposeLowering); + } +protected: + ::mlir::Pass::Option reassociateFPReductions{*this, "reassociate-fp-reductions", ::llvm::cl::desc("Allows llvm to reassociate floating-point reductions for speed"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option force32BitVectorIndices{*this, "force-32bit-vector-indices", ::llvm::cl::desc("Allows compiler to assume vector indices fit in 32-bit if that yields faster code"), ::llvm::cl::init(true)}; + ::mlir::Pass::Option useVectorAlignment{*this, "use-vector-alignment", ::llvm::cl::desc("Use the preferred alignment of a vector type in load/store operations instead of the alignment of the element type of the memref. This flag is intended for use with hardware which requiresvector alignment, or in application contexts where it is known all vector access are naturally aligned. "), ::llvm::cl::init(false)}; + ::mlir::Pass::Option amx{*this, "enable-amx", ::llvm::cl::desc("Enables the use of AMX dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option armNeon{*this, "enable-arm-neon", ::llvm::cl::desc("Enables the use of ArmNeon dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option armSVE{*this, "enable-arm-sve", ::llvm::cl::desc("Enables the use of ArmSVE dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option armI8MM{*this, "enable-arm-i8mm", ::llvm::cl::desc("Enables the use of Arm FEAT_I8MM instructions while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option x86Vector{*this, "enable-x86vector", ::llvm::cl::desc("Enables the use of X86Vector dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option vectorContractLowering{*this, "vector-contract-lowering", ::llvm::cl::desc("control the lowering of `vector.contract` operations."), ::llvm::cl::init(vector::VectorContractLowering::Dot), ::llvm::cl::values( + clEnumValN(::mlir::vector::VectorContractLowering::Dot, "dot", + "Progressively lower to finer grained `vector.contract` and dot-products. (default)"), + clEnumValN(::mlir::vector::VectorContractLowering::Matmul, "matmul", + "Lower to `vector.matrix_multiply`, maps 1-1 to LLVM matrix intrinsics."), + clEnumValN(::mlir::vector::VectorContractLowering::OuterProduct, "outerproduct", + "Lower to `vector.outerproduct`."), + clEnumValN(::mlir::vector::VectorContractLowering::ParallelArith, "parallelarith", + "Lower contract with all reduction dimensions unrolled to 1 to a vector elementwise operations.") + )}; + ::mlir::Pass::Option vectorTransposeLowering{*this, "vector-transpose-lowering", ::llvm::cl::desc("control the lowering of `vector.transpose` operations."), ::llvm::cl::init(vector::VectorTransposeLowering::EltWise), ::llvm::cl::values( + clEnumValN(::mlir::vector::VectorTransposeLowering::EltWise, "eltwise", + "Lower transpose into element-wise extract and inserts (default)"), + clEnumValN(::mlir::vector::VectorTransposeLowering::Flat, "flat", + "Lower 2-D transpose to `vector.flat_transpose`, maps 1-1 to LLVM matrix intrinsics"), + clEnumValN(::mlir::vector::VectorTransposeLowering::Shuffle1D, "shuffle1d", + "Lower 2-D transpose to `vector.shuffle` on 1-D vector."), + clEnumValN(::mlir::vector::VectorTransposeLowering::Shuffle16x16, "shuffle16x16", + "Lower 2-D transpose to `vector.shuffle` on 16x16 vector.") + )}; +private: + + friend std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass(ConvertVectorToLLVMPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass() { + return impl::createConvertVectorToLLVMPass(); +} + +std::unique_ptr<::mlir::Pass> createConvertVectorToLLVMPass(ConvertVectorToLLVMPassOptions options) { + return impl::createConvertVectorToLLVMPass(std::move(options)); +} +#undef GEN_PASS_DEF_CONVERTVECTORTOLLVMPASS +#endif // GEN_PASS_DEF_CONVERTVECTORTOLLVMPASS + +//===----------------------------------------------------------------------===// +// ConvertVectorToSCF +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTVECTORTOSCF +struct ConvertVectorToSCFOptions { + bool fullUnroll = false; + unsigned targetRank = 1; + bool lowerTensors = false; + bool lowerScalable = false; +}; +#undef GEN_PASS_DECL_CONVERTVECTORTOSCF +#endif // GEN_PASS_DECL_CONVERTVECTORTOSCF +#ifdef GEN_PASS_DEF_CONVERTVECTORTOSCF +namespace impl { + +template +class ConvertVectorToSCFBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToSCFBase; + + ConvertVectorToSCFBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToSCFBase(const ConvertVectorToSCFBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToSCFBase& operator=(const ConvertVectorToSCFBase &) = delete; + ConvertVectorToSCFBase(ConvertVectorToSCFBase &&) = delete; + ConvertVectorToSCFBase& operator=(ConvertVectorToSCFBase &&) = delete; + ~ConvertVectorToSCFBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToSCF"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToSCF"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToSCFBase) + + ConvertVectorToSCFBase(ConvertVectorToSCFOptions options) : ConvertVectorToSCFBase() { + fullUnroll = std::move(options.fullUnroll); + targetRank = std::move(options.targetRank); + lowerTensors = std::move(options.lowerTensors); + lowerScalable = std::move(options.lowerScalable); + } +protected: + ::mlir::Pass::Option fullUnroll{*this, "full-unroll", ::llvm::cl::desc("Perform full unrolling when converting vector transfers to SCF"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option targetRank{*this, "target-rank", ::llvm::cl::desc("Target vector rank to which transfer ops should be lowered"), ::llvm::cl::init(1)}; + ::mlir::Pass::Option lowerTensors{*this, "lower-tensors", ::llvm::cl::desc("Lower transfer ops that operate on tensors"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option lowerScalable{*this, "lower-scalable", ::llvm::cl::desc("Add scalable vector specific lowerings (that introduce loops)"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_CONVERTVECTORTOSCF +#endif // GEN_PASS_DEF_CONVERTVECTORTOSCF + +//===----------------------------------------------------------------------===// +// ConvertVectorToSPIRVPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTVECTORTOSPIRVPASS +std::unique_ptr<::mlir::Pass> createConvertVectorToSPIRVPass(); +#undef GEN_PASS_DECL_CONVERTVECTORTOSPIRVPASS +#endif // GEN_PASS_DECL_CONVERTVECTORTOSPIRVPASS +#ifdef GEN_PASS_DEF_CONVERTVECTORTOSPIRVPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertVectorToSPIRVPass(); +} // namespace impl +namespace impl { + +template +class ConvertVectorToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToSPIRVPassBase; + + ConvertVectorToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToSPIRVPassBase(const ConvertVectorToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToSPIRVPassBase& operator=(const ConvertVectorToSPIRVPassBase &) = delete; + ConvertVectorToSPIRVPassBase(ConvertVectorToSPIRVPassBase &&) = delete; + ConvertVectorToSPIRVPassBase& operator=(ConvertVectorToSPIRVPassBase &&) = delete; + ~ConvertVectorToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Vector dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToSPIRVPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertVectorToSPIRVPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertVectorToSPIRVPass() { + return impl::createConvertVectorToSPIRVPass(); +} +#undef GEN_PASS_DEF_CONVERTVECTORTOSPIRVPASS +#endif // GEN_PASS_DEF_CONVERTVECTORTOSPIRVPASS + +//===----------------------------------------------------------------------===// +// ConvertVectorToXeGPU +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_CONVERTVECTORTOXEGPU +std::unique_ptr<::mlir::Pass> createConvertVectorToXeGPU(); +#undef GEN_PASS_DECL_CONVERTVECTORTOXEGPU +#endif // GEN_PASS_DECL_CONVERTVECTORTOXEGPU +#ifdef GEN_PASS_DEF_CONVERTVECTORTOXEGPU + +namespace impl { + std::unique_ptr<::mlir::Pass> createConvertVectorToXeGPU(); +} // namespace impl +namespace impl { + +template +class ConvertVectorToXeGPUBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToXeGPUBase; + + ConvertVectorToXeGPUBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToXeGPUBase(const ConvertVectorToXeGPUBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToXeGPUBase& operator=(const ConvertVectorToXeGPUBase &) = delete; + ConvertVectorToXeGPUBase(ConvertVectorToXeGPUBase &&) = delete; + ConvertVectorToXeGPUBase& operator=(ConvertVectorToXeGPUBase &&) = delete; + ~ConvertVectorToXeGPUBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-xegpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-xegpu"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the XeGPU dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToXeGPU"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToXeGPU"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToXeGPUBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createConvertVectorToXeGPU() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createConvertVectorToXeGPU() { + return impl::createConvertVectorToXeGPU(); +} +#undef GEN_PASS_DEF_CONVERTVECTORTOXEGPU +#endif // GEN_PASS_DEF_CONVERTVECTORTOXEGPU + +//===----------------------------------------------------------------------===// +// FinalizeMemRefToLLVMConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_FINALIZEMEMREFTOLLVMCONVERSIONPASS +struct FinalizeMemRefToLLVMConversionPassOptions { + bool useAlignedAlloc = false; + unsigned indexBitwidth = 0; + bool useGenericFunctions = false; +}; +std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass(); +std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass(FinalizeMemRefToLLVMConversionPassOptions options); +#undef GEN_PASS_DECL_FINALIZEMEMREFTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DECL_FINALIZEMEMREFTOLLVMCONVERSIONPASS +#ifdef GEN_PASS_DEF_FINALIZEMEMREFTOLLVMCONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass(FinalizeMemRefToLLVMConversionPassOptions options); +} // namespace impl +namespace impl { + +template +class FinalizeMemRefToLLVMConversionPassBase : public ::mlir::OperationPass { +public: + using Base = FinalizeMemRefToLLVMConversionPassBase; + + FinalizeMemRefToLLVMConversionPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + FinalizeMemRefToLLVMConversionPassBase(const FinalizeMemRefToLLVMConversionPassBase &other) : ::mlir::OperationPass(other) {} + FinalizeMemRefToLLVMConversionPassBase& operator=(const FinalizeMemRefToLLVMConversionPassBase &) = delete; + FinalizeMemRefToLLVMConversionPassBase(FinalizeMemRefToLLVMConversionPassBase &&) = delete; + FinalizeMemRefToLLVMConversionPassBase& operator=(FinalizeMemRefToLLVMConversionPassBase &&) = delete; + ~FinalizeMemRefToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("finalize-memref-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "finalize-memref-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Finalize MemRef dialect to LLVM dialect conversion"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("FinalizeMemRefToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "FinalizeMemRefToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FinalizeMemRefToLLVMConversionPassBase) + + FinalizeMemRefToLLVMConversionPassBase(FinalizeMemRefToLLVMConversionPassOptions options) : FinalizeMemRefToLLVMConversionPassBase() { + useAlignedAlloc = std::move(options.useAlignedAlloc); + indexBitwidth = std::move(options.indexBitwidth); + useGenericFunctions = std::move(options.useGenericFunctions); + } +protected: + ::mlir::Pass::Option useAlignedAlloc{*this, "use-aligned-alloc", ::llvm::cl::desc("Use aligned_alloc in place of malloc for heap allocations"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; + ::mlir::Pass::Option useGenericFunctions{*this, "use-generic-functions", ::llvm::cl::desc("Use generic allocation and deallocation functions instead of the classic 'malloc', 'aligned_alloc' and 'free' functions"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass(FinalizeMemRefToLLVMConversionPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass() { + return impl::createFinalizeMemRefToLLVMConversionPass(); +} + +std::unique_ptr<::mlir::Pass> createFinalizeMemRefToLLVMConversionPass(FinalizeMemRefToLLVMConversionPassOptions options) { + return impl::createFinalizeMemRefToLLVMConversionPass(std::move(options)); +} +#undef GEN_PASS_DEF_FINALIZEMEMREFTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DEF_FINALIZEMEMREFTOLLVMCONVERSIONPASS + +//===----------------------------------------------------------------------===// +// GpuToLLVMConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_GPUTOLLVMCONVERSIONPASS +struct GpuToLLVMConversionPassOptions { + bool hostBarePtrCallConv = false; + bool kernelBarePtrCallConv = false; + bool kernelIntersperseSizeCallConv = false; +}; +std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass(); +std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass(GpuToLLVMConversionPassOptions options); +#undef GEN_PASS_DECL_GPUTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DECL_GPUTOLLVMCONVERSIONPASS +#ifdef GEN_PASS_DEF_GPUTOLLVMCONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass(GpuToLLVMConversionPassOptions options); +} // namespace impl +namespace impl { + +template +class GpuToLLVMConversionPassBase : public ::mlir::OperationPass { +public: + using Base = GpuToLLVMConversionPassBase; + + GpuToLLVMConversionPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + GpuToLLVMConversionPassBase(const GpuToLLVMConversionPassBase &other) : ::mlir::OperationPass(other) {} + GpuToLLVMConversionPassBase& operator=(const GpuToLLVMConversionPassBase &) = delete; + GpuToLLVMConversionPassBase(GpuToLLVMConversionPassBase &&) = delete; + GpuToLLVMConversionPassBase& operator=(GpuToLLVMConversionPassBase &&) = delete; + ~GpuToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gpu-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "gpu-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert GPU dialect to LLVM dialect with GPU runtime calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("GpuToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "GpuToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GpuToLLVMConversionPassBase) + + GpuToLLVMConversionPassBase(GpuToLLVMConversionPassOptions options) : GpuToLLVMConversionPassBase() { + hostBarePtrCallConv = std::move(options.hostBarePtrCallConv); + kernelBarePtrCallConv = std::move(options.kernelBarePtrCallConv); + kernelIntersperseSizeCallConv = std::move(options.kernelIntersperseSizeCallConv); + } +protected: + ::mlir::Pass::Option hostBarePtrCallConv{*this, "use-bare-pointers-for-host", ::llvm::cl::desc("Use bare pointers to pass memref arguments to host functions. All memrefs must have static shape."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option kernelBarePtrCallConv{*this, "use-bare-pointers-for-kernels", ::llvm::cl::desc("Use bare pointers to pass memref arguments to kernels. The kernel must use the same setting for this option."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option kernelIntersperseSizeCallConv{*this, "intersperse-sizes-for-kernels", ::llvm::cl::desc("Inserts a size_t argument following each memref argument, containing the static size in bytes of the buffer. Incompatible arguments are rejected. This is intended for use by the Vulkan runtime with the kernel bare pointer calling convention, to enable dynamic binding of buffers as arguments without static type info."), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass(GpuToLLVMConversionPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass() { + return impl::createGpuToLLVMConversionPass(); +} + +std::unique_ptr<::mlir::Pass> createGpuToLLVMConversionPass(GpuToLLVMConversionPassOptions options) { + return impl::createGpuToLLVMConversionPass(std::move(options)); +} +#undef GEN_PASS_DEF_GPUTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DEF_GPUTOLLVMCONVERSIONPASS + +//===----------------------------------------------------------------------===// +// LiftControlFlowToSCFPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LIFTCONTROLFLOWTOSCFPASS +std::unique_ptr<::mlir::Pass> createLiftControlFlowToSCFPass(); +#undef GEN_PASS_DECL_LIFTCONTROLFLOWTOSCFPASS +#endif // GEN_PASS_DECL_LIFTCONTROLFLOWTOSCFPASS +#ifdef GEN_PASS_DEF_LIFTCONTROLFLOWTOSCFPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createLiftControlFlowToSCFPass(); +} // namespace impl +namespace impl { + +template +class LiftControlFlowToSCFPassBase : public ::mlir::OperationPass<> { +public: + using Base = LiftControlFlowToSCFPassBase; + + LiftControlFlowToSCFPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + LiftControlFlowToSCFPassBase(const LiftControlFlowToSCFPassBase &other) : ::mlir::OperationPass<>(other) {} + LiftControlFlowToSCFPassBase& operator=(const LiftControlFlowToSCFPassBase &) = delete; + LiftControlFlowToSCFPassBase(LiftControlFlowToSCFPassBase &&) = delete; + LiftControlFlowToSCFPassBase& operator=(LiftControlFlowToSCFPassBase &&) = delete; + ~LiftControlFlowToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lift-cf-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "lift-cf-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lift ControlFlow dialect to SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LiftControlFlowToSCFPass"); + } + ::llvm::StringRef getName() const override { return "LiftControlFlowToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LiftControlFlowToSCFPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createLiftControlFlowToSCFPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createLiftControlFlowToSCFPass() { + return impl::createLiftControlFlowToSCFPass(); +} +#undef GEN_PASS_DEF_LIFTCONTROLFLOWTOSCFPASS +#endif // GEN_PASS_DEF_LIFTCONTROLFLOWTOSCFPASS + +//===----------------------------------------------------------------------===// +// LowerAffinePass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LOWERAFFINEPASS +std::unique_ptr<::mlir::Pass> createLowerAffinePass(); +#undef GEN_PASS_DECL_LOWERAFFINEPASS +#endif // GEN_PASS_DECL_LOWERAFFINEPASS +#ifdef GEN_PASS_DEF_LOWERAFFINEPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createLowerAffinePass(); +} // namespace impl +namespace impl { + +template +class LowerAffinePassBase : public ::mlir::OperationPass<> { +public: + using Base = LowerAffinePassBase; + + LowerAffinePassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + LowerAffinePassBase(const LowerAffinePassBase &other) : ::mlir::OperationPass<>(other) {} + LowerAffinePassBase& operator=(const LowerAffinePassBase &) = delete; + LowerAffinePassBase(LowerAffinePassBase &&) = delete; + LowerAffinePassBase& operator=(LowerAffinePassBase &&) = delete; + ~LowerAffinePassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lower-affine"); + } + ::llvm::StringRef getArgument() const override { return "lower-affine"; } + + ::llvm::StringRef getDescription() const override { return "Lower Affine operations to a combination of Arith and SCF operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LowerAffinePass"); + } + ::llvm::StringRef getName() const override { return "LowerAffinePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LowerAffinePassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createLowerAffinePass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createLowerAffinePass() { + return impl::createLowerAffinePass(); +} +#undef GEN_PASS_DEF_LOWERAFFINEPASS +#endif // GEN_PASS_DEF_LOWERAFFINEPASS + +//===----------------------------------------------------------------------===// +// LowerHostCodeToLLVMPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_LOWERHOSTCODETOLLVMPASS +std::unique_ptr<::mlir::Pass> createLowerHostCodeToLLVMPass(); +#undef GEN_PASS_DECL_LOWERHOSTCODETOLLVMPASS +#endif // GEN_PASS_DECL_LOWERHOSTCODETOLLVMPASS +#ifdef GEN_PASS_DEF_LOWERHOSTCODETOLLVMPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createLowerHostCodeToLLVMPass(); +} // namespace impl +namespace impl { + +template +class LowerHostCodeToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = LowerHostCodeToLLVMPassBase; + + LowerHostCodeToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LowerHostCodeToLLVMPassBase(const LowerHostCodeToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + LowerHostCodeToLLVMPassBase& operator=(const LowerHostCodeToLLVMPassBase &) = delete; + LowerHostCodeToLLVMPassBase(LowerHostCodeToLLVMPassBase &&) = delete; + LowerHostCodeToLLVMPassBase& operator=(LowerHostCodeToLLVMPassBase &&) = delete; + ~LowerHostCodeToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lower-host-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "lower-host-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lowers the host module code and `gpu.launch_func` to LLVM"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LowerHostCodeToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "LowerHostCodeToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LowerHostCodeToLLVMPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createLowerHostCodeToLLVMPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createLowerHostCodeToLLVMPass() { + return impl::createLowerHostCodeToLLVMPass(); +} +#undef GEN_PASS_DEF_LOWERHOSTCODETOLLVMPASS +#endif // GEN_PASS_DEF_LOWERHOSTCODETOLLVMPASS + +//===----------------------------------------------------------------------===// +// MapMemRefStorageClass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_MAPMEMREFSTORAGECLASS +struct MapMemRefStorageClassOptions { + std::string clientAPI = "vulkan"; +}; +#undef GEN_PASS_DECL_MAPMEMREFSTORAGECLASS +#endif // GEN_PASS_DECL_MAPMEMREFSTORAGECLASS +#ifdef GEN_PASS_DEF_MAPMEMREFSTORAGECLASS +namespace impl { + +template +class MapMemRefStorageClassBase : public ::mlir::OperationPass<> { +public: + using Base = MapMemRefStorageClassBase; + + MapMemRefStorageClassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + MapMemRefStorageClassBase(const MapMemRefStorageClassBase &other) : ::mlir::OperationPass<>(other) {} + MapMemRefStorageClassBase& operator=(const MapMemRefStorageClassBase &) = delete; + MapMemRefStorageClassBase(MapMemRefStorageClassBase &&) = delete; + MapMemRefStorageClassBase& operator=(MapMemRefStorageClassBase &&) = delete; + ~MapMemRefStorageClassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("map-memref-spirv-storage-class"); + } + ::llvm::StringRef getArgument() const override { return "map-memref-spirv-storage-class"; } + + ::llvm::StringRef getDescription() const override { return "Map numeric MemRef memory spaces to SPIR-V storage classes"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("MapMemRefStorageClass"); + } + ::llvm::StringRef getName() const override { return "MapMemRefStorageClass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(MapMemRefStorageClassBase) + + MapMemRefStorageClassBase(MapMemRefStorageClassOptions options) : MapMemRefStorageClassBase() { + clientAPI = std::move(options.clientAPI); + } +protected: + ::mlir::Pass::Option clientAPI{*this, "client-api", ::llvm::cl::desc("The client API to use for populating mappings"), ::llvm::cl::init("vulkan")}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_MAPMEMREFSTORAGECLASS +#endif // GEN_PASS_DEF_MAPMEMREFSTORAGECLASS + +//===----------------------------------------------------------------------===// +// ReconcileUnrealizedCastsPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_RECONCILEUNREALIZEDCASTSPASS +std::unique_ptr<::mlir::Pass> createReconcileUnrealizedCastsPass(); +#undef GEN_PASS_DECL_RECONCILEUNREALIZEDCASTSPASS +#endif // GEN_PASS_DECL_RECONCILEUNREALIZEDCASTSPASS +#ifdef GEN_PASS_DEF_RECONCILEUNREALIZEDCASTSPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createReconcileUnrealizedCastsPass(); +} // namespace impl +namespace impl { + +template +class ReconcileUnrealizedCastsPassBase : public ::mlir::OperationPass<> { +public: + using Base = ReconcileUnrealizedCastsPassBase; + + ReconcileUnrealizedCastsPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ReconcileUnrealizedCastsPassBase(const ReconcileUnrealizedCastsPassBase &other) : ::mlir::OperationPass<>(other) {} + ReconcileUnrealizedCastsPassBase& operator=(const ReconcileUnrealizedCastsPassBase &) = delete; + ReconcileUnrealizedCastsPassBase(ReconcileUnrealizedCastsPassBase &&) = delete; + ReconcileUnrealizedCastsPassBase& operator=(ReconcileUnrealizedCastsPassBase &&) = delete; + ~ReconcileUnrealizedCastsPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("reconcile-unrealized-casts"); + } + ::llvm::StringRef getArgument() const override { return "reconcile-unrealized-casts"; } + + ::llvm::StringRef getDescription() const override { return "Simplify and eliminate unrealized conversion casts"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ReconcileUnrealizedCastsPass"); + } + ::llvm::StringRef getName() const override { return "ReconcileUnrealizedCastsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ReconcileUnrealizedCastsPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createReconcileUnrealizedCastsPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createReconcileUnrealizedCastsPass() { + return impl::createReconcileUnrealizedCastsPass(); +} +#undef GEN_PASS_DEF_RECONCILEUNREALIZEDCASTSPASS +#endif // GEN_PASS_DEF_RECONCILEUNREALIZEDCASTSPASS + +//===----------------------------------------------------------------------===// +// SCFToControlFlowPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SCFTOCONTROLFLOWPASS +std::unique_ptr<::mlir::Pass> createSCFToControlFlowPass(); +#undef GEN_PASS_DECL_SCFTOCONTROLFLOWPASS +#endif // GEN_PASS_DECL_SCFTOCONTROLFLOWPASS +#ifdef GEN_PASS_DEF_SCFTOCONTROLFLOWPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createSCFToControlFlowPass(); +} // namespace impl +namespace impl { + +template +class SCFToControlFlowPassBase : public ::mlir::OperationPass<> { +public: + using Base = SCFToControlFlowPassBase; + + SCFToControlFlowPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + SCFToControlFlowPassBase(const SCFToControlFlowPassBase &other) : ::mlir::OperationPass<>(other) {} + SCFToControlFlowPassBase& operator=(const SCFToControlFlowPassBase &) = delete; + SCFToControlFlowPassBase(SCFToControlFlowPassBase &&) = delete; + SCFToControlFlowPassBase& operator=(SCFToControlFlowPassBase &&) = delete; + ~SCFToControlFlowPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-cf"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-cf"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF dialect to ControlFlow dialect, replacing structured control flow with a CFG"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SCFToControlFlowPass"); + } + ::llvm::StringRef getName() const override { return "SCFToControlFlowPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SCFToControlFlowPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createSCFToControlFlowPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createSCFToControlFlowPass() { + return impl::createSCFToControlFlowPass(); +} +#undef GEN_PASS_DEF_SCFTOCONTROLFLOWPASS +#endif // GEN_PASS_DEF_SCFTOCONTROLFLOWPASS + +//===----------------------------------------------------------------------===// +// SCFToEmitC +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SCFTOEMITC +std::unique_ptr<::mlir::Pass> createSCFToEmitC(); +#undef GEN_PASS_DECL_SCFTOEMITC +#endif // GEN_PASS_DECL_SCFTOEMITC +#ifdef GEN_PASS_DEF_SCFTOEMITC + +namespace impl { + std::unique_ptr<::mlir::Pass> createSCFToEmitC(); +} // namespace impl +namespace impl { + +template +class SCFToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = SCFToEmitCBase; + + SCFToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + SCFToEmitCBase(const SCFToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + SCFToEmitCBase& operator=(const SCFToEmitCBase &) = delete; + SCFToEmitCBase(SCFToEmitCBase &&) = delete; + SCFToEmitCBase& operator=(SCFToEmitCBase &&) = delete; + ~SCFToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF dialect to EmitC dialect, maintaining structured control flow"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SCFToEmitC"); + } + ::llvm::StringRef getName() const override { return "SCFToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SCFToEmitCBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createSCFToEmitC() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createSCFToEmitC() { + return impl::createSCFToEmitC(); +} +#undef GEN_PASS_DEF_SCFTOEMITC +#endif // GEN_PASS_DEF_SCFTOEMITC + +//===----------------------------------------------------------------------===// +// SCFToSPIRV +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SCFTOSPIRV +std::unique_ptr<::mlir::Pass> createSCFToSPIRV(); +#undef GEN_PASS_DECL_SCFTOSPIRV +#endif // GEN_PASS_DECL_SCFTOSPIRV +#ifdef GEN_PASS_DEF_SCFTOSPIRV + +namespace impl { + std::unique_ptr<::mlir::Pass> createSCFToSPIRV(); +} // namespace impl +namespace impl { + +template +class SCFToSPIRVBase : public ::mlir::OperationPass<> { +public: + using Base = SCFToSPIRVBase; + + SCFToSPIRVBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + SCFToSPIRVBase(const SCFToSPIRVBase &other) : ::mlir::OperationPass<>(other) {} + SCFToSPIRVBase& operator=(const SCFToSPIRVBase &) = delete; + SCFToSPIRVBase(SCFToSPIRVBase &&) = delete; + SCFToSPIRVBase& operator=(SCFToSPIRVBase &&) = delete; + ~SCFToSPIRVBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF dialect to SPIR-V dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SCFToSPIRV"); + } + ::llvm::StringRef getName() const override { return "SCFToSPIRV"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SCFToSPIRVBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createSCFToSPIRV() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createSCFToSPIRV() { + return impl::createSCFToSPIRV(); +} +#undef GEN_PASS_DEF_SCFTOSPIRV +#endif // GEN_PASS_DEF_SCFTOSPIRV + +//===----------------------------------------------------------------------===// +// SetLLVMModuleDataLayoutPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_SETLLVMMODULEDATALAYOUTPASS +struct SetLLVMModuleDataLayoutPassOptions { + std::string dataLayout = ""; +}; +std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass(); +std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass(SetLLVMModuleDataLayoutPassOptions options); +#undef GEN_PASS_DECL_SETLLVMMODULEDATALAYOUTPASS +#endif // GEN_PASS_DECL_SETLLVMMODULEDATALAYOUTPASS +#ifdef GEN_PASS_DEF_SETLLVMMODULEDATALAYOUTPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass(SetLLVMModuleDataLayoutPassOptions options); +} // namespace impl +namespace impl { + +template +class SetLLVMModuleDataLayoutPassBase : public ::mlir::OperationPass { +public: + using Base = SetLLVMModuleDataLayoutPassBase; + + SetLLVMModuleDataLayoutPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + SetLLVMModuleDataLayoutPassBase(const SetLLVMModuleDataLayoutPassBase &other) : ::mlir::OperationPass(other) {} + SetLLVMModuleDataLayoutPassBase& operator=(const SetLLVMModuleDataLayoutPassBase &) = delete; + SetLLVMModuleDataLayoutPassBase(SetLLVMModuleDataLayoutPassBase &&) = delete; + SetLLVMModuleDataLayoutPassBase& operator=(SetLLVMModuleDataLayoutPassBase &&) = delete; + ~SetLLVMModuleDataLayoutPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("set-llvm-module-datalayout"); + } + ::llvm::StringRef getArgument() const override { return "set-llvm-module-datalayout"; } + + ::llvm::StringRef getDescription() const override { return "Attach a datalayout string as a module attribute"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SetLLVMModuleDataLayoutPass"); + } + ::llvm::StringRef getName() const override { return "SetLLVMModuleDataLayoutPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SetLLVMModuleDataLayoutPassBase) + + SetLLVMModuleDataLayoutPassBase(SetLLVMModuleDataLayoutPassOptions options) : SetLLVMModuleDataLayoutPassBase() { + dataLayout = std::move(options.dataLayout); + } +protected: + ::mlir::Pass::Option dataLayout{*this, "data-layout", ::llvm::cl::desc("String description (LLVM format) of the data layout that is expected on the produced module"), ::llvm::cl::init("")}; +private: + + friend std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass(SetLLVMModuleDataLayoutPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass() { + return impl::createSetLLVMModuleDataLayoutPass(); +} + +std::unique_ptr<::mlir::Pass> createSetLLVMModuleDataLayoutPass(SetLLVMModuleDataLayoutPassOptions options) { + return impl::createSetLLVMModuleDataLayoutPass(std::move(options)); +} +#undef GEN_PASS_DEF_SETLLVMMODULEDATALAYOUTPASS +#endif // GEN_PASS_DEF_SETLLVMMODULEDATALAYOUTPASS + +//===----------------------------------------------------------------------===// +// TosaToArithPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TOSATOARITHPASS +struct TosaToArithPassOptions { + bool includeApplyRescale = false; + bool use32Bit = false; +}; +std::unique_ptr<::mlir::Pass> createTosaToArithPass(); +std::unique_ptr<::mlir::Pass> createTosaToArithPass(TosaToArithPassOptions options); +#undef GEN_PASS_DECL_TOSATOARITHPASS +#endif // GEN_PASS_DECL_TOSATOARITHPASS +#ifdef GEN_PASS_DEF_TOSATOARITHPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createTosaToArithPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createTosaToArithPass(TosaToArithPassOptions options); +} // namespace impl +namespace impl { + +template +class TosaToArithPassBase : public ::mlir::OperationPass<> { +public: + using Base = TosaToArithPassBase; + + TosaToArithPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + TosaToArithPassBase(const TosaToArithPassBase &other) : ::mlir::OperationPass<>(other) {} + TosaToArithPassBase& operator=(const TosaToArithPassBase &) = delete; + TosaToArithPassBase(TosaToArithPassBase &&) = delete; + TosaToArithPassBase& operator=(TosaToArithPassBase &&) = delete; + ~TosaToArithPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-arith"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-arith"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the Arith dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToArithPass"); + } + ::llvm::StringRef getName() const override { return "TosaToArithPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToArithPassBase) + + TosaToArithPassBase(TosaToArithPassOptions options) : TosaToArithPassBase() { + includeApplyRescale = std::move(options.includeApplyRescale); + use32Bit = std::move(options.use32Bit); + } +protected: + ::mlir::Pass::Option includeApplyRescale{*this, "include-apply-rescale", ::llvm::cl::desc("Whether to include the lowering for tosa.apply_rescale to arith"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option use32Bit{*this, "use-32-bit", ::llvm::cl::desc("Whether to prioritze lowering to 32-bit operations"), ::llvm::cl::init(false)}; +private: + + friend std::unique_ptr<::mlir::Pass> createTosaToArithPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createTosaToArithPass(TosaToArithPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createTosaToArithPass() { + return impl::createTosaToArithPass(); +} + +std::unique_ptr<::mlir::Pass> createTosaToArithPass(TosaToArithPassOptions options) { + return impl::createTosaToArithPass(std::move(options)); +} +#undef GEN_PASS_DEF_TOSATOARITHPASS +#endif // GEN_PASS_DEF_TOSATOARITHPASS + +//===----------------------------------------------------------------------===// +// TosaToLinalg +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TOSATOLINALG +struct TosaToLinalgOptions { + bool disableTosaDecompositions = false; + bool aggressiveReduceConstant = false; +}; +#undef GEN_PASS_DECL_TOSATOLINALG +#endif // GEN_PASS_DECL_TOSATOLINALG +#ifdef GEN_PASS_DEF_TOSATOLINALG +namespace impl { + +template +class TosaToLinalgBase : public ::mlir::InterfacePass { +public: + using Base = TosaToLinalgBase; + + TosaToLinalgBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + TosaToLinalgBase(const TosaToLinalgBase &other) : ::mlir::InterfacePass(other) {} + TosaToLinalgBase& operator=(const TosaToLinalgBase &) = delete; + TosaToLinalgBase(TosaToLinalgBase &&) = delete; + TosaToLinalgBase& operator=(TosaToLinalgBase &&) = delete; + ~TosaToLinalgBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-linalg"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-linalg"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to LinAlg on tensors"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToLinalg"); + } + ::llvm::StringRef getName() const override { return "TosaToLinalg"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToLinalgBase) + + TosaToLinalgBase(TosaToLinalgOptions options) : TosaToLinalgBase() { + disableTosaDecompositions = std::move(options.disableTosaDecompositions); + aggressiveReduceConstant = std::move(options.aggressiveReduceConstant); + } +protected: + ::mlir::Pass::Option disableTosaDecompositions{*this, "disable-tosa-decompositions", ::llvm::cl::desc("Disable tosa decompositions pass"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option aggressiveReduceConstant{*this, "aggressive-reduce-constant", ::llvm::cl::desc("Always perform the reduce constant optimization"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TOSATOLINALG +#endif // GEN_PASS_DEF_TOSATOLINALG + +//===----------------------------------------------------------------------===// +// TosaToLinalgNamed +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TOSATOLINALGNAMED +struct TosaToLinalgNamedOptions { + bool preferConv2DKernelLayoutHWCF = false; +}; +#undef GEN_PASS_DECL_TOSATOLINALGNAMED +#endif // GEN_PASS_DECL_TOSATOLINALGNAMED +#ifdef GEN_PASS_DEF_TOSATOLINALGNAMED +namespace impl { + +template +class TosaToLinalgNamedBase : public ::mlir::InterfacePass { +public: + using Base = TosaToLinalgNamedBase; + + TosaToLinalgNamedBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + TosaToLinalgNamedBase(const TosaToLinalgNamedBase &other) : ::mlir::InterfacePass(other) {} + TosaToLinalgNamedBase& operator=(const TosaToLinalgNamedBase &) = delete; + TosaToLinalgNamedBase(TosaToLinalgNamedBase &&) = delete; + TosaToLinalgNamedBase& operator=(TosaToLinalgNamedBase &&) = delete; + ~TosaToLinalgNamedBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-linalg-named"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-linalg-named"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to LinAlg named operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToLinalgNamed"); + } + ::llvm::StringRef getName() const override { return "TosaToLinalgNamed"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToLinalgNamedBase) + + TosaToLinalgNamedBase(TosaToLinalgNamedOptions options) : TosaToLinalgNamedBase() { + preferConv2DKernelLayoutHWCF = std::move(options.preferConv2DKernelLayoutHWCF); + } +protected: + ::mlir::Pass::Option preferConv2DKernelLayoutHWCF{*this, "prefer-conv2d-kernel-layout-hwcf", ::llvm::cl::desc("Prefer generating linalg.conv_2d_nhwc_hwcf over linalg.conv_2d_nhwc_fhwc"), ::llvm::cl::init(false)}; +private: +}; +} // namespace impl +#undef GEN_PASS_DEF_TOSATOLINALGNAMED +#endif // GEN_PASS_DEF_TOSATOLINALGNAMED + +//===----------------------------------------------------------------------===// +// TosaToMLProgram +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TOSATOMLPROGRAM +std::unique_ptr<::mlir::Pass> createTosaToMLProgram(); +#undef GEN_PASS_DECL_TOSATOMLPROGRAM +#endif // GEN_PASS_DECL_TOSATOMLPROGRAM +#ifdef GEN_PASS_DEF_TOSATOMLPROGRAM + +namespace impl { + std::unique_ptr<::mlir::Pass> createTosaToMLProgram(); +} // namespace impl +namespace impl { + +template +class TosaToMLProgramBase : public ::mlir::OperationPass { +public: + using Base = TosaToMLProgramBase; + + TosaToMLProgramBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TosaToMLProgramBase(const TosaToMLProgramBase &other) : ::mlir::OperationPass(other) {} + TosaToMLProgramBase& operator=(const TosaToMLProgramBase &) = delete; + TosaToMLProgramBase(TosaToMLProgramBase &&) = delete; + TosaToMLProgramBase& operator=(TosaToMLProgramBase &&) = delete; + ~TosaToMLProgramBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-mlprogram"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-mlprogram"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the MLProgram dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToMLProgram"); + } + ::llvm::StringRef getName() const override { return "TosaToMLProgram"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToMLProgramBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createTosaToMLProgram() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createTosaToMLProgram() { + return impl::createTosaToMLProgram(); +} +#undef GEN_PASS_DEF_TOSATOMLPROGRAM +#endif // GEN_PASS_DEF_TOSATOMLPROGRAM + +//===----------------------------------------------------------------------===// +// TosaToSCFPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TOSATOSCFPASS +std::unique_ptr<::mlir::Pass> createTosaToSCFPass(); +#undef GEN_PASS_DECL_TOSATOSCFPASS +#endif // GEN_PASS_DECL_TOSATOSCFPASS +#ifdef GEN_PASS_DEF_TOSATOSCFPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createTosaToSCFPass(); +} // namespace impl +namespace impl { + +template +class TosaToSCFPassBase : public ::mlir::OperationPass<> { +public: + using Base = TosaToSCFPassBase; + + TosaToSCFPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + TosaToSCFPassBase(const TosaToSCFPassBase &other) : ::mlir::OperationPass<>(other) {} + TosaToSCFPassBase& operator=(const TosaToSCFPassBase &) = delete; + TosaToSCFPassBase(TosaToSCFPassBase &&) = delete; + TosaToSCFPassBase& operator=(TosaToSCFPassBase &&) = delete; + ~TosaToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToSCFPass"); + } + ::llvm::StringRef getName() const override { return "TosaToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToSCFPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createTosaToSCFPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createTosaToSCFPass() { + return impl::createTosaToSCFPass(); +} +#undef GEN_PASS_DEF_TOSATOSCFPASS +#endif // GEN_PASS_DEF_TOSATOSCFPASS + +//===----------------------------------------------------------------------===// +// TosaToTensorPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_TOSATOTENSORPASS +std::unique_ptr<::mlir::Pass> createTosaToTensorPass(); +#undef GEN_PASS_DECL_TOSATOTENSORPASS +#endif // GEN_PASS_DECL_TOSATOTENSORPASS +#ifdef GEN_PASS_DEF_TOSATOTENSORPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createTosaToTensorPass(); +} // namespace impl +namespace impl { + +template +class TosaToTensorPassBase : public ::mlir::OperationPass<> { +public: + using Base = TosaToTensorPassBase; + + TosaToTensorPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + TosaToTensorPassBase(const TosaToTensorPassBase &other) : ::mlir::OperationPass<>(other) {} + TosaToTensorPassBase& operator=(const TosaToTensorPassBase &) = delete; + TosaToTensorPassBase(TosaToTensorPassBase &&) = delete; + TosaToTensorPassBase& operator=(TosaToTensorPassBase &&) = delete; + ~TosaToTensorPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-tensor"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-tensor"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the Tensor dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToTensorPass"); + } + ::llvm::StringRef getName() const override { return "TosaToTensorPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToTensorPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createTosaToTensorPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createTosaToTensorPass() { + return impl::createTosaToTensorPass(); +} +#undef GEN_PASS_DEF_TOSATOTENSORPASS +#endif // GEN_PASS_DEF_TOSATOTENSORPASS + +//===----------------------------------------------------------------------===// +// UBToLLVMConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_UBTOLLVMCONVERSIONPASS +struct UBToLLVMConversionPassOptions { + unsigned indexBitwidth = 0; +}; +std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass(); +std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass(UBToLLVMConversionPassOptions options); +#undef GEN_PASS_DECL_UBTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DECL_UBTOLLVMCONVERSIONPASS +#ifdef GEN_PASS_DEF_UBTOLLVMCONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass(); +} // namespace impl + +namespace impl { + std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass(UBToLLVMConversionPassOptions options); +} // namespace impl +namespace impl { + +template +class UBToLLVMConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = UBToLLVMConversionPassBase; + + UBToLLVMConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + UBToLLVMConversionPassBase(const UBToLLVMConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + UBToLLVMConversionPassBase& operator=(const UBToLLVMConversionPassBase &) = delete; + UBToLLVMConversionPassBase(UBToLLVMConversionPassBase &&) = delete; + UBToLLVMConversionPassBase& operator=(UBToLLVMConversionPassBase &&) = delete; + ~UBToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-ub-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-ub-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert UB dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("UBToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "UBToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(UBToLLVMConversionPassBase) + + UBToLLVMConversionPassBase(UBToLLVMConversionPassOptions options) : UBToLLVMConversionPassBase() { + indexBitwidth = std::move(options.indexBitwidth); + } +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +private: + + friend std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass() { + return std::make_unique(); + } + + friend std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass(UBToLLVMConversionPassOptions options) { + return std::make_unique(std::move(options)); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass() { + return impl::createUBToLLVMConversionPass(); +} + +std::unique_ptr<::mlir::Pass> createUBToLLVMConversionPass(UBToLLVMConversionPassOptions options) { + return impl::createUBToLLVMConversionPass(std::move(options)); +} +#undef GEN_PASS_DEF_UBTOLLVMCONVERSIONPASS +#endif // GEN_PASS_DEF_UBTOLLVMCONVERSIONPASS + +//===----------------------------------------------------------------------===// +// UBToSPIRVConversionPass +//===----------------------------------------------------------------------===// +#ifdef GEN_PASS_DECL_UBTOSPIRVCONVERSIONPASS +std::unique_ptr<::mlir::Pass> createUBToSPIRVConversionPass(); +#undef GEN_PASS_DECL_UBTOSPIRVCONVERSIONPASS +#endif // GEN_PASS_DECL_UBTOSPIRVCONVERSIONPASS +#ifdef GEN_PASS_DEF_UBTOSPIRVCONVERSIONPASS + +namespace impl { + std::unique_ptr<::mlir::Pass> createUBToSPIRVConversionPass(); +} // namespace impl +namespace impl { + +template +class UBToSPIRVConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = UBToSPIRVConversionPassBase; + + UBToSPIRVConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + UBToSPIRVConversionPassBase(const UBToSPIRVConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + UBToSPIRVConversionPassBase& operator=(const UBToSPIRVConversionPassBase &) = delete; + UBToSPIRVConversionPassBase(UBToSPIRVConversionPassBase &&) = delete; + UBToSPIRVConversionPassBase& operator=(UBToSPIRVConversionPassBase &&) = delete; + ~UBToSPIRVConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-ub-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-ub-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert UB dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("UBToSPIRVConversionPass"); + } + ::llvm::StringRef getName() const override { return "UBToSPIRVConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Return the dialect that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(UBToSPIRVConversionPassBase) + +protected: +private: + + friend std::unique_ptr<::mlir::Pass> createUBToSPIRVConversionPass() { + return std::make_unique(); + } +}; +} // namespace impl + +std::unique_ptr<::mlir::Pass> createUBToSPIRVConversionPass() { + return impl::createUBToSPIRVConversionPass(); +} +#undef GEN_PASS_DEF_UBTOSPIRVCONVERSIONPASS +#endif // GEN_PASS_DEF_UBTOSPIRVCONVERSIONPASS +#ifdef GEN_PASS_REGISTRATION + +//===----------------------------------------------------------------------===// +// ArithToAMDGPUConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerArithToAMDGPUConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createArithToAMDGPUConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerArithToAMDGPUConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createArithToAMDGPUConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ArithToArmSMEConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerArithToArmSMEConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createArithToArmSMEConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerArithToArmSMEConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createArithToArmSMEConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ArithToLLVMConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerArithToLLVMConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createArithToLLVMConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerArithToLLVMConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createArithToLLVMConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertAMDGPUToROCDLPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertAMDGPUToROCDLPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertAMDGPUToROCDLPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertAMDGPUToROCDLPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertAMDGPUToROCDLPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertAffineForToGPUPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertAffineForToGPUPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertAffineForToGPUPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertAffineForToGPUPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertAffineForToGPUPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertArithToEmitC Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertArithToEmitC() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArithToEmitC(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertArithToEmitCPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArithToEmitC(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertArithToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertArithToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArithToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertArithToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArithToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertArmNeon2dToIntrPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertArmNeon2dToIntrPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArmNeon2dToIntrPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertArmNeon2dToIntrPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArmNeon2dToIntrPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertArmSMEToLLVM Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertArmSMEToLLVM() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertArmSMEToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertArmSMEToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertArmSMEToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertArmSMEToSCFPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertArmSMEToSCFPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArmSMEToSCFPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertArmSMEToSCFPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertArmSMEToSCFPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertAsyncToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertAsyncToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertAsyncToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertAsyncToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertAsyncToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertBufferizationToMemRefPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertBufferizationToMemRefPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertBufferizationToMemRefPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertBufferizationToMemRefPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertBufferizationToMemRefPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertComplexToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertComplexToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertComplexToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertComplexToLibm Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertComplexToLibm() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToLibm(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertComplexToLibmPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToLibm(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertComplexToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertComplexToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertComplexToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertComplexToStandardPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertComplexToStandardPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToStandardPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertComplexToStandardPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertComplexToStandardPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertControlFlowToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertControlFlowToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertControlFlowToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertControlFlowToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertControlFlowToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertControlFlowToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertControlFlowToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertControlFlowToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertControlFlowToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertControlFlowToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertFuncToEmitC Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertFuncToEmitC() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertFuncToEmitC(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertFuncToEmitCPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertFuncToEmitC(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertFuncToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertFuncToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertFuncToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertFuncToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertFuncToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertFuncToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertFuncToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertFuncToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertFuncToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertFuncToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertGPUToSPIRV Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertGPUToSPIRV() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertGPUToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertGPUToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertGPUToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertGpuOpsToLLVMSPVOps Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertGpuOpsToLLVMSPVOps() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertGpuOpsToLLVMSPVOps(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertGpuOpsToLLVMSPVOpsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertGpuOpsToLLVMSPVOps(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertGpuOpsToNVVMOps Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertGpuOpsToNVVMOps() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertGpuOpsToNVVMOps(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertGpuOpsToNVVMOpsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertGpuOpsToNVVMOps(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertGpuOpsToROCDLOps Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertGpuOpsToROCDLOps() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createLowerGpuOpsToROCDLOpsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertGpuOpsToROCDLOpsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createLowerGpuOpsToROCDLOpsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertIndexToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertIndexToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertIndexToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertIndexToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertIndexToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertIndexToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertIndexToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertIndexToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertIndexToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertIndexToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertLinalgToStandardPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertLinalgToStandardPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLinalgToStandardPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertLinalgToStandardPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertLinalgToStandardPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMathToEmitC Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMathToEmitC() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToEmitC(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMathToEmitCPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToEmitC(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMathToFuncs Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMathToFuncs() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToFuncs(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMathToFuncsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToFuncs(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMathToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMathToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMathToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMathToLibmPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMathToLibmPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToLibmPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMathToLibmPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToLibmPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMathToROCDL Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMathToROCDL() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToROCDL(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMathToROCDLPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToROCDL(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMathToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMathToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMathToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMathToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMemRefToEmitC Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMemRefToEmitC() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMemRefToEmitC(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMemRefToEmitCPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMemRefToEmitC(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMemRefToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMemRefToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMemRefToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMemRefToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMemRefToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertMeshToMPIPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertMeshToMPIPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMeshToMPIPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertMeshToMPIPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertMeshToMPIPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertNVGPUToNVVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertNVGPUToNVVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertNVGPUToNVVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertNVGPUToNVVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertNVGPUToNVVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertNVVMToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertNVVMToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertNVVMToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertNVVMToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertNVVMToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertOpenACCToSCFPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertOpenACCToSCFPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertOpenACCToSCFPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertOpenACCToSCFPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertOpenACCToSCFPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertOpenMPToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertOpenMPToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertOpenMPToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertOpenMPToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertOpenMPToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertPDLToPDLInterpPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertPDLToPDLInterpPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertPDLToPDLInterpPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertPDLToPDLInterpPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertPDLToPDLInterpPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertParallelLoopToGpuPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertParallelLoopToGpuPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertParallelLoopToGpuPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertParallelLoopToGpuPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertParallelLoopToGpuPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertSCFToOpenMPPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertSCFToOpenMPPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertSCFToOpenMPPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertSCFToOpenMPPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertSCFToOpenMPPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertSPIRVToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertSPIRVToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertSPIRVToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertSPIRVToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertSPIRVToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertShapeConstraintsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertShapeConstraintsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertShapeConstraintsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertShapeConstraintsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertShapeConstraintsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertShapeToStandardPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertShapeToStandardPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertShapeToStandardPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertShapeToStandardPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertShapeToStandardPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertTensorToLinalgPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertTensorToLinalgPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertTensorToLinalgPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertTensorToLinalgPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertTensorToLinalgPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertTensorToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertTensorToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertTensorToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertTensorToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertTensorToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertToEmitC Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertToEmitC() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertToEmitC(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertToEmitCPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertToEmitC(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertVectorToArmSMEPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertVectorToArmSMEPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToArmSMEPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertVectorToArmSMEPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToArmSMEPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertVectorToGPU Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertVectorToGPU() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertVectorToGPUPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertVectorToGPUPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertVectorToGPUPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertVectorToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertVectorToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertVectorToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertVectorToSCF Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertVectorToSCF() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertVectorToSCFPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertVectorToSCFPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createConvertVectorToSCFPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertVectorToSPIRVPass Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertVectorToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToSPIRVPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertVectorToSPIRVPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToSPIRVPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ConvertVectorToXeGPU Registration +//===----------------------------------------------------------------------===// + +inline void registerConvertVectorToXeGPU() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToXeGPU(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerConvertVectorToXeGPUPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createConvertVectorToXeGPU(); + }); +} + +//===----------------------------------------------------------------------===// +// FinalizeMemRefToLLVMConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerFinalizeMemRefToLLVMConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createFinalizeMemRefToLLVMConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerFinalizeMemRefToLLVMConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createFinalizeMemRefToLLVMConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// GpuToLLVMConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerGpuToLLVMConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createGpuToLLVMConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerGpuToLLVMConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createGpuToLLVMConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LiftControlFlowToSCFPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLiftControlFlowToSCFPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLiftControlFlowToSCFPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLiftControlFlowToSCFPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLiftControlFlowToSCFPass(); + }); +} + +//===----------------------------------------------------------------------===// +// LowerAffinePass Registration +//===----------------------------------------------------------------------===// + +inline void registerLowerAffinePass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLowerAffinePass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLowerAffinePassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLowerAffinePass(); + }); +} + +//===----------------------------------------------------------------------===// +// LowerHostCodeToLLVMPass Registration +//===----------------------------------------------------------------------===// + +inline void registerLowerHostCodeToLLVMPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLowerHostCodeToLLVMPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerLowerHostCodeToLLVMPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createLowerHostCodeToLLVMPass(); + }); +} + +//===----------------------------------------------------------------------===// +// MapMemRefStorageClass Registration +//===----------------------------------------------------------------------===// + +inline void registerMapMemRefStorageClass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createMapMemRefStorageClassPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerMapMemRefStorageClassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return mlir::createMapMemRefStorageClassPass(); + }); +} + +//===----------------------------------------------------------------------===// +// ReconcileUnrealizedCastsPass Registration +//===----------------------------------------------------------------------===// + +inline void registerReconcileUnrealizedCastsPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createReconcileUnrealizedCastsPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerReconcileUnrealizedCastsPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createReconcileUnrealizedCastsPass(); + }); +} + +//===----------------------------------------------------------------------===// +// SCFToControlFlowPass Registration +//===----------------------------------------------------------------------===// + +inline void registerSCFToControlFlowPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSCFToControlFlowPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerSCFToControlFlowPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSCFToControlFlowPass(); + }); +} + +//===----------------------------------------------------------------------===// +// SCFToEmitC Registration +//===----------------------------------------------------------------------===// + +inline void registerSCFToEmitC() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSCFToEmitC(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerSCFToEmitCPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSCFToEmitC(); + }); +} + +//===----------------------------------------------------------------------===// +// SCFToSPIRV Registration +//===----------------------------------------------------------------------===// + +inline void registerSCFToSPIRV() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSCFToSPIRV(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerSCFToSPIRVPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSCFToSPIRV(); + }); +} + +//===----------------------------------------------------------------------===// +// SetLLVMModuleDataLayoutPass Registration +//===----------------------------------------------------------------------===// + +inline void registerSetLLVMModuleDataLayoutPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSetLLVMModuleDataLayoutPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerSetLLVMModuleDataLayoutPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createSetLLVMModuleDataLayoutPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TosaToArithPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTosaToArithPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToArithPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTosaToArithPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToArithPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TosaToLinalg Registration +//===----------------------------------------------------------------------===// + +inline void registerTosaToLinalg() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return tosa::createTosaToLinalg(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTosaToLinalgPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return tosa::createTosaToLinalg(); + }); +} + +//===----------------------------------------------------------------------===// +// TosaToLinalgNamed Registration +//===----------------------------------------------------------------------===// + +inline void registerTosaToLinalgNamed() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return tosa::createTosaToLinalgNamed(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTosaToLinalgNamedPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return tosa::createTosaToLinalgNamed(); + }); +} + +//===----------------------------------------------------------------------===// +// TosaToMLProgram Registration +//===----------------------------------------------------------------------===// + +inline void registerTosaToMLProgram() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToMLProgram(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTosaToMLProgramPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToMLProgram(); + }); +} + +//===----------------------------------------------------------------------===// +// TosaToSCFPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTosaToSCFPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToSCFPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTosaToSCFPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToSCFPass(); + }); +} + +//===----------------------------------------------------------------------===// +// TosaToTensorPass Registration +//===----------------------------------------------------------------------===// + +inline void registerTosaToTensorPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToTensorPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerTosaToTensorPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createTosaToTensorPass(); + }); +} + +//===----------------------------------------------------------------------===// +// UBToLLVMConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerUBToLLVMConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createUBToLLVMConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerUBToLLVMConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createUBToLLVMConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// UBToSPIRVConversionPass Registration +//===----------------------------------------------------------------------===// + +inline void registerUBToSPIRVConversionPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createUBToSPIRVConversionPass(); + }); +} + +// Old registration code, kept for temporary backwards compatibility. +inline void registerUBToSPIRVConversionPassPass() { + ::mlir::registerPass([]() -> std::unique_ptr<::mlir::Pass> { + return createUBToSPIRVConversionPass(); + }); +} + +//===----------------------------------------------------------------------===// +// Conversion Registration +//===----------------------------------------------------------------------===// + +inline void registerConversionPasses() { + registerArithToAMDGPUConversionPass(); + registerArithToArmSMEConversionPass(); + registerArithToLLVMConversionPass(); + registerConvertAMDGPUToROCDLPass(); + registerConvertAffineForToGPUPass(); + registerConvertArithToEmitC(); + registerConvertArithToSPIRVPass(); + registerConvertArmNeon2dToIntrPass(); + registerConvertArmSMEToLLVM(); + registerConvertArmSMEToSCFPass(); + registerConvertAsyncToLLVMPass(); + registerConvertBufferizationToMemRefPass(); + registerConvertComplexToLLVMPass(); + registerConvertComplexToLibm(); + registerConvertComplexToSPIRVPass(); + registerConvertComplexToStandardPass(); + registerConvertControlFlowToLLVMPass(); + registerConvertControlFlowToSPIRVPass(); + registerConvertFuncToEmitC(); + registerConvertFuncToLLVMPass(); + registerConvertFuncToSPIRVPass(); + registerConvertGPUToSPIRV(); + registerConvertGpuOpsToLLVMSPVOps(); + registerConvertGpuOpsToNVVMOps(); + registerConvertGpuOpsToROCDLOps(); + registerConvertIndexToLLVMPass(); + registerConvertIndexToSPIRVPass(); + registerConvertLinalgToStandardPass(); + registerConvertMathToEmitC(); + registerConvertMathToFuncs(); + registerConvertMathToLLVMPass(); + registerConvertMathToLibmPass(); + registerConvertMathToROCDL(); + registerConvertMathToSPIRVPass(); + registerConvertMemRefToEmitC(); + registerConvertMemRefToSPIRVPass(); + registerConvertMeshToMPIPass(); + registerConvertNVGPUToNVVMPass(); + registerConvertNVVMToLLVMPass(); + registerConvertOpenACCToSCFPass(); + registerConvertOpenMPToLLVMPass(); + registerConvertPDLToPDLInterpPass(); + registerConvertParallelLoopToGpuPass(); + registerConvertSCFToOpenMPPass(); + registerConvertSPIRVToLLVMPass(); + registerConvertShapeConstraintsPass(); + registerConvertShapeToStandardPass(); + registerConvertTensorToLinalgPass(); + registerConvertTensorToSPIRVPass(); + registerConvertToEmitC(); + registerConvertToLLVMPass(); + registerConvertVectorToArmSMEPass(); + registerConvertVectorToGPU(); + registerConvertVectorToLLVMPass(); + registerConvertVectorToSCF(); + registerConvertVectorToSPIRVPass(); + registerConvertVectorToXeGPU(); + registerFinalizeMemRefToLLVMConversionPass(); + registerGpuToLLVMConversionPass(); + registerLiftControlFlowToSCFPass(); + registerLowerAffinePass(); + registerLowerHostCodeToLLVMPass(); + registerMapMemRefStorageClass(); + registerReconcileUnrealizedCastsPass(); + registerSCFToControlFlowPass(); + registerSCFToEmitC(); + registerSCFToSPIRV(); + registerSetLLVMModuleDataLayoutPass(); + registerTosaToArithPass(); + registerTosaToLinalg(); + registerTosaToLinalgNamed(); + registerTosaToMLProgram(); + registerTosaToSCFPass(); + registerTosaToTensorPass(); + registerUBToLLVMConversionPass(); + registerUBToSPIRVConversionPass(); +} +#undef GEN_PASS_REGISTRATION +#endif // GEN_PASS_REGISTRATION +// Deprecated. Please use the new per-pass macros. +#ifdef GEN_PASS_CLASSES + +template +class ArithToAMDGPUConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = ArithToAMDGPUConversionPassBase; + + ArithToAMDGPUConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ArithToAMDGPUConversionPassBase(const ArithToAMDGPUConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + ArithToAMDGPUConversionPassBase& operator=(const ArithToAMDGPUConversionPassBase &) = delete; + ArithToAMDGPUConversionPassBase(ArithToAMDGPUConversionPassBase &&) = delete; + ArithToAMDGPUConversionPassBase& operator=(ArithToAMDGPUConversionPassBase &&) = delete; + ~ArithToAMDGPUConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-amdgpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-amdgpu"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith operations to AMDGPU-specific implementations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ArithToAMDGPUConversionPass"); + } + ::llvm::StringRef getName() const override { return "ArithToAMDGPUConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ArithToAMDGPUConversionPassBase) + +protected: + ::mlir::Pass::Option chipset{*this, "chipset", ::llvm::cl::desc("Chipset that these operations will run on"), ::llvm::cl::init("gfx000")}; + ::mlir::Pass::Option saturateFP8Truncf{*this, "saturate-fp8-truncf", ::llvm::cl::desc("Use saturating truncation for 8-bit float types"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option allowPackedF16Rtz{*this, "allow-packed-f16-round-to-zero", ::llvm::cl::desc("Whether we should allow f32->f16 packed round-to-zero conversion"), ::llvm::cl::init(false)}; +}; + +template +class ArithToArmSMEConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = ArithToArmSMEConversionPassBase; + + ArithToArmSMEConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ArithToArmSMEConversionPassBase(const ArithToArmSMEConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + ArithToArmSMEConversionPassBase& operator=(const ArithToArmSMEConversionPassBase &) = delete; + ArithToArmSMEConversionPassBase(ArithToArmSMEConversionPassBase &&) = delete; + ArithToArmSMEConversionPassBase& operator=(ArithToArmSMEConversionPassBase &&) = delete; + ~ArithToArmSMEConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-arm-sme"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-arm-sme"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to ArmSME dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ArithToArmSMEConversionPass"); + } + ::llvm::StringRef getName() const override { return "ArithToArmSMEConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ArithToArmSMEConversionPassBase) + +protected: +}; + +template +class ArithToLLVMConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = ArithToLLVMConversionPassBase; + + ArithToLLVMConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ArithToLLVMConversionPassBase(const ArithToLLVMConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + ArithToLLVMConversionPassBase& operator=(const ArithToLLVMConversionPassBase &) = delete; + ArithToLLVMConversionPassBase(ArithToLLVMConversionPassBase &&) = delete; + ArithToLLVMConversionPassBase& operator=(ArithToLLVMConversionPassBase &&) = delete; + ~ArithToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ArithToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "ArithToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ArithToLLVMConversionPassBase) + +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +}; + +template +class ConvertAMDGPUToROCDLPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertAMDGPUToROCDLPassBase; + + ConvertAMDGPUToROCDLPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertAMDGPUToROCDLPassBase(const ConvertAMDGPUToROCDLPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertAMDGPUToROCDLPassBase& operator=(const ConvertAMDGPUToROCDLPassBase &) = delete; + ConvertAMDGPUToROCDLPassBase(ConvertAMDGPUToROCDLPassBase &&) = delete; + ConvertAMDGPUToROCDLPassBase& operator=(ConvertAMDGPUToROCDLPassBase &&) = delete; + ~ConvertAMDGPUToROCDLPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-amdgpu-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "convert-amdgpu-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Convert AMDGPU dialect to ROCDL dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAMDGPUToROCDLPass"); + } + ::llvm::StringRef getName() const override { return "ConvertAMDGPUToROCDLPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAMDGPUToROCDLPassBase) + +protected: + ::mlir::Pass::Option chipset{*this, "chipset", ::llvm::cl::desc("Chipset that these operations will run on"), ::llvm::cl::init("gfx000")}; +}; + +template +class ConvertAffineForToGPUPassBase : public ::mlir::InterfacePass { +public: + using Base = ConvertAffineForToGPUPassBase; + + ConvertAffineForToGPUPassBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + ConvertAffineForToGPUPassBase(const ConvertAffineForToGPUPassBase &other) : ::mlir::InterfacePass(other) {} + ConvertAffineForToGPUPassBase& operator=(const ConvertAffineForToGPUPassBase &) = delete; + ConvertAffineForToGPUPassBase(ConvertAffineForToGPUPassBase &&) = delete; + ConvertAffineForToGPUPassBase& operator=(ConvertAffineForToGPUPassBase &&) = delete; + ~ConvertAffineForToGPUPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-affine-for-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-affine-for-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Convert top-level AffineFor Ops to GPU kernels"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAffineForToGPUPass"); + } + ::llvm::StringRef getName() const override { return "ConvertAffineForToGPUPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAffineForToGPUPassBase) + +protected: + ::mlir::Pass::Option numBlockDims{*this, "gpu-block-dims", ::llvm::cl::desc("Number of GPU block dimensions for mapping"), ::llvm::cl::init(1u)}; + ::mlir::Pass::Option numThreadDims{*this, "gpu-thread-dims", ::llvm::cl::desc("Number of GPU thread dimensions for mapping"), ::llvm::cl::init(1u)}; +}; + +template +class ConvertArithToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArithToEmitCBase; + + ConvertArithToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArithToEmitCBase(const ConvertArithToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArithToEmitCBase& operator=(const ConvertArithToEmitCBase &) = delete; + ConvertArithToEmitCBase(ConvertArithToEmitCBase &&) = delete; + ConvertArithToEmitCBase& operator=(ConvertArithToEmitCBase &&) = delete; + ~ConvertArithToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to EmitC dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArithToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertArithToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArithToEmitCBase) + +protected: +}; + +template +class ConvertArithToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArithToSPIRVPassBase; + + ConvertArithToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArithToSPIRVPassBase(const ConvertArithToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArithToSPIRVPassBase& operator=(const ConvertArithToSPIRVPassBase &) = delete; + ConvertArithToSPIRVPassBase(ConvertArithToSPIRVPassBase &&) = delete; + ConvertArithToSPIRVPassBase& operator=(ConvertArithToSPIRVPassBase &&) = delete; + ~ConvertArithToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arith-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-arith-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arith dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArithToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertArithToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArithToSPIRVPassBase) + +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +}; + +template +class ConvertArmNeon2dToIntrPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArmNeon2dToIntrPassBase; + + ConvertArmNeon2dToIntrPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArmNeon2dToIntrPassBase(const ConvertArmNeon2dToIntrPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArmNeon2dToIntrPassBase& operator=(const ConvertArmNeon2dToIntrPassBase &) = delete; + ConvertArmNeon2dToIntrPassBase(ConvertArmNeon2dToIntrPassBase &&) = delete; + ConvertArmNeon2dToIntrPassBase& operator=(ConvertArmNeon2dToIntrPassBase &&) = delete; + ~ConvertArmNeon2dToIntrPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("arm-neon-2d-to-intr"); + } + ::llvm::StringRef getArgument() const override { return "arm-neon-2d-to-intr"; } + + ::llvm::StringRef getDescription() const override { return "Convert Arm NEON structured ops to intrinsics"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArmNeon2dToIntrPass"); + } + ::llvm::StringRef getName() const override { return "ConvertArmNeon2dToIntrPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArmNeon2dToIntrPassBase) + +protected: +}; + +template +class ConvertArmSMEToLLVMBase : public ::mlir::InterfacePass { +public: + using Base = ConvertArmSMEToLLVMBase; + + ConvertArmSMEToLLVMBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + ConvertArmSMEToLLVMBase(const ConvertArmSMEToLLVMBase &other) : ::mlir::InterfacePass(other) {} + ConvertArmSMEToLLVMBase& operator=(const ConvertArmSMEToLLVMBase &) = delete; + ConvertArmSMEToLLVMBase(ConvertArmSMEToLLVMBase &&) = delete; + ConvertArmSMEToLLVMBase& operator=(ConvertArmSMEToLLVMBase &&) = delete; + ~ConvertArmSMEToLLVMBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arm-sme-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-arm-sme-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the ArmSME dialect into the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArmSMEToLLVM"); + } + ::llvm::StringRef getName() const override { return "ConvertArmSMEToLLVM"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArmSMEToLLVMBase) + +protected: + ::mlir::Pass::Option dumpTileLiveRanges{*this, "dump-tile-live-ranges", ::llvm::cl::desc("Dump the live ranges of SME tiles (for debugging)"), ::llvm::cl::init(false)}; +}; + +template +class ConvertArmSMEToSCFPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertArmSMEToSCFPassBase; + + ConvertArmSMEToSCFPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertArmSMEToSCFPassBase(const ConvertArmSMEToSCFPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertArmSMEToSCFPassBase& operator=(const ConvertArmSMEToSCFPassBase &) = delete; + ConvertArmSMEToSCFPassBase(ConvertArmSMEToSCFPassBase &&) = delete; + ConvertArmSMEToSCFPassBase& operator=(ConvertArmSMEToSCFPassBase &&) = delete; + ~ConvertArmSMEToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-arm-sme-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "convert-arm-sme-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the ArmSME dialect into the SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertArmSMEToSCFPass"); + } + ::llvm::StringRef getName() const override { return "ConvertArmSMEToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertArmSMEToSCFPassBase) + +protected: +}; + +template +class ConvertAsyncToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertAsyncToLLVMPassBase; + + ConvertAsyncToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertAsyncToLLVMPassBase(const ConvertAsyncToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertAsyncToLLVMPassBase& operator=(const ConvertAsyncToLLVMPassBase &) = delete; + ConvertAsyncToLLVMPassBase(ConvertAsyncToLLVMPassBase &&) = delete; + ConvertAsyncToLLVMPassBase& operator=(ConvertAsyncToLLVMPassBase &&) = delete; + ~ConvertAsyncToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-async-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-async-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert the operations from the async dialect into the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertAsyncToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertAsyncToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertAsyncToLLVMPassBase) + +protected: +}; + +template +class ConvertBufferizationToMemRefPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertBufferizationToMemRefPassBase; + + ConvertBufferizationToMemRefPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertBufferizationToMemRefPassBase(const ConvertBufferizationToMemRefPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertBufferizationToMemRefPassBase& operator=(const ConvertBufferizationToMemRefPassBase &) = delete; + ConvertBufferizationToMemRefPassBase(ConvertBufferizationToMemRefPassBase &&) = delete; + ConvertBufferizationToMemRefPassBase& operator=(ConvertBufferizationToMemRefPassBase &&) = delete; + ~ConvertBufferizationToMemRefPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-bufferization-to-memref"); + } + ::llvm::StringRef getArgument() const override { return "convert-bufferization-to-memref"; } + + ::llvm::StringRef getDescription() const override { return "Convert operations from the Bufferization dialect to the MemRef dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertBufferizationToMemRefPass"); + } + ::llvm::StringRef getName() const override { return "ConvertBufferizationToMemRefPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertBufferizationToMemRefPassBase) + +protected: +}; + +template +class ConvertComplexToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertComplexToLLVMPassBase; + + ConvertComplexToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertComplexToLLVMPassBase(const ConvertComplexToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertComplexToLLVMPassBase& operator=(const ConvertComplexToLLVMPassBase &) = delete; + ConvertComplexToLLVMPassBase(ConvertComplexToLLVMPassBase &&) = delete; + ConvertComplexToLLVMPassBase& operator=(ConvertComplexToLLVMPassBase &&) = delete; + ~ConvertComplexToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToLLVMPassBase) + +protected: + ::mlir::Pass::Option<::mlir::complex::ComplexRangeFlags> complexRange{*this, "complex-range", ::llvm::cl::desc("Control the intermediate calculation of complex number division"), ::llvm::cl::init(::mlir::complex::ComplexRangeFlags::basic), ::llvm::cl::values( + clEnumValN(::mlir::complex::ComplexRangeFlags::improved, "improved", "improved"), + clEnumValN(::mlir::complex::ComplexRangeFlags::basic, "basic", "basic (default)"), + clEnumValN(::mlir::complex::ComplexRangeFlags::none, "none", "none") + )}; +}; + +template +class ConvertComplexToLibmBase : public ::mlir::OperationPass { +public: + using Base = ConvertComplexToLibmBase; + + ConvertComplexToLibmBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertComplexToLibmBase(const ConvertComplexToLibmBase &other) : ::mlir::OperationPass(other) {} + ConvertComplexToLibmBase& operator=(const ConvertComplexToLibmBase &) = delete; + ConvertComplexToLibmBase(ConvertComplexToLibmBase &&) = delete; + ConvertComplexToLibmBase& operator=(ConvertComplexToLibmBase &&) = delete; + ~ConvertComplexToLibmBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-libm"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-libm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to libm calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToLibm"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToLibm"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToLibmBase) + +protected: +}; + +template +class ConvertComplexToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertComplexToSPIRVPassBase; + + ConvertComplexToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertComplexToSPIRVPassBase(const ConvertComplexToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertComplexToSPIRVPassBase& operator=(const ConvertComplexToSPIRVPassBase &) = delete; + ConvertComplexToSPIRVPassBase(ConvertComplexToSPIRVPassBase &&) = delete; + ConvertComplexToSPIRVPassBase& operator=(ConvertComplexToSPIRVPassBase &&) = delete; + ~ConvertComplexToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to SPIRV dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToSPIRVPassBase) + +protected: +}; + +template +class ConvertComplexToStandardPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertComplexToStandardPassBase; + + ConvertComplexToStandardPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertComplexToStandardPassBase(const ConvertComplexToStandardPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertComplexToStandardPassBase& operator=(const ConvertComplexToStandardPassBase &) = delete; + ConvertComplexToStandardPassBase(ConvertComplexToStandardPassBase &&) = delete; + ConvertComplexToStandardPassBase& operator=(ConvertComplexToStandardPassBase &&) = delete; + ~ConvertComplexToStandardPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-complex-to-standard"); + } + ::llvm::StringRef getArgument() const override { return "convert-complex-to-standard"; } + + ::llvm::StringRef getDescription() const override { return "Convert Complex dialect to standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertComplexToStandardPass"); + } + ::llvm::StringRef getName() const override { return "ConvertComplexToStandardPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertComplexToStandardPassBase) + +protected: + ::mlir::Pass::Option<::mlir::complex::ComplexRangeFlags> complexRange{*this, "complex-range", ::llvm::cl::desc("Control the intermediate calculation of complex number division"), ::llvm::cl::init(::mlir::complex::ComplexRangeFlags::improved), ::llvm::cl::values( + clEnumValN(::mlir::complex::ComplexRangeFlags::improved, "improved", "improved (default)"), + clEnumValN(::mlir::complex::ComplexRangeFlags::basic, "basic", "basic"), + clEnumValN(::mlir::complex::ComplexRangeFlags::none, "none", "none") + )}; +}; + +template +class ConvertControlFlowToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertControlFlowToLLVMPassBase; + + ConvertControlFlowToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertControlFlowToLLVMPassBase(const ConvertControlFlowToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertControlFlowToLLVMPassBase& operator=(const ConvertControlFlowToLLVMPassBase &) = delete; + ConvertControlFlowToLLVMPassBase(ConvertControlFlowToLLVMPassBase &&) = delete; + ConvertControlFlowToLLVMPassBase& operator=(ConvertControlFlowToLLVMPassBase &&) = delete; + ~ConvertControlFlowToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-cf-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-cf-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert ControlFlow operations to the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertControlFlowToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertControlFlowToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertControlFlowToLLVMPassBase) + +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +}; + +template +class ConvertControlFlowToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertControlFlowToSPIRVPassBase; + + ConvertControlFlowToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertControlFlowToSPIRVPassBase(const ConvertControlFlowToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertControlFlowToSPIRVPassBase& operator=(const ConvertControlFlowToSPIRVPassBase &) = delete; + ConvertControlFlowToSPIRVPassBase(ConvertControlFlowToSPIRVPassBase &&) = delete; + ConvertControlFlowToSPIRVPassBase& operator=(ConvertControlFlowToSPIRVPassBase &&) = delete; + ~ConvertControlFlowToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-cf-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-cf-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert ControlFlow dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertControlFlowToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertControlFlowToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertControlFlowToSPIRVPassBase) + +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +}; + +template +class ConvertFuncToEmitCBase : public ::mlir::OperationPass { +public: + using Base = ConvertFuncToEmitCBase; + + ConvertFuncToEmitCBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertFuncToEmitCBase(const ConvertFuncToEmitCBase &other) : ::mlir::OperationPass(other) {} + ConvertFuncToEmitCBase& operator=(const ConvertFuncToEmitCBase &) = delete; + ConvertFuncToEmitCBase(ConvertFuncToEmitCBase &&) = delete; + ConvertFuncToEmitCBase& operator=(ConvertFuncToEmitCBase &&) = delete; + ~ConvertFuncToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-func-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-func-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert Func dialect to EmitC dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertFuncToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertFuncToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertFuncToEmitCBase) + +protected: +}; + +template +class ConvertFuncToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertFuncToLLVMPassBase; + + ConvertFuncToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertFuncToLLVMPassBase(const ConvertFuncToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertFuncToLLVMPassBase& operator=(const ConvertFuncToLLVMPassBase &) = delete; + ConvertFuncToLLVMPassBase(ConvertFuncToLLVMPassBase &&) = delete; + ConvertFuncToLLVMPassBase& operator=(ConvertFuncToLLVMPassBase &&) = delete; + ~ConvertFuncToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-func-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-func-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert from the Func dialect to the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertFuncToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertFuncToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertFuncToLLVMPassBase) + +protected: + ::mlir::Pass::Option useBarePtrCallConv{*this, "use-bare-ptr-memref-call-conv", ::llvm::cl::desc("Replace FuncOp's MemRef arguments with bare pointers to the MemRef element types"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +}; + +template +class ConvertFuncToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertFuncToSPIRVPassBase; + + ConvertFuncToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertFuncToSPIRVPassBase(const ConvertFuncToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertFuncToSPIRVPassBase& operator=(const ConvertFuncToSPIRVPassBase &) = delete; + ConvertFuncToSPIRVPassBase(ConvertFuncToSPIRVPassBase &&) = delete; + ConvertFuncToSPIRVPassBase& operator=(ConvertFuncToSPIRVPassBase &&) = delete; + ~ConvertFuncToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-func-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-func-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Func dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertFuncToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertFuncToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertFuncToSPIRVPassBase) + +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +}; + +template +class ConvertGPUToSPIRVBase : public ::mlir::OperationPass { +public: + using Base = ConvertGPUToSPIRVBase; + + ConvertGPUToSPIRVBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGPUToSPIRVBase(const ConvertGPUToSPIRVBase &other) : ::mlir::OperationPass(other) {} + ConvertGPUToSPIRVBase& operator=(const ConvertGPUToSPIRVBase &) = delete; + ConvertGPUToSPIRVBase(ConvertGPUToSPIRVBase &&) = delete; + ConvertGPUToSPIRVBase& operator=(ConvertGPUToSPIRVBase &&) = delete; + ~ConvertGPUToSPIRVBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert GPU dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGPUToSPIRV"); + } + ::llvm::StringRef getName() const override { return "ConvertGPUToSPIRV"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGPUToSPIRVBase) + +protected: + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +}; + +template +class ConvertGpuOpsToLLVMSPVOpsBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuOpsToLLVMSPVOpsBase; + + ConvertGpuOpsToLLVMSPVOpsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuOpsToLLVMSPVOpsBase(const ConvertGpuOpsToLLVMSPVOpsBase &other) : ::mlir::OperationPass(other) {} + ConvertGpuOpsToLLVMSPVOpsBase& operator=(const ConvertGpuOpsToLLVMSPVOpsBase &) = delete; + ConvertGpuOpsToLLVMSPVOpsBase(ConvertGpuOpsToLLVMSPVOpsBase &&) = delete; + ConvertGpuOpsToLLVMSPVOpsBase& operator=(ConvertGpuOpsToLLVMSPVOpsBase &&) = delete; + ~ConvertGpuOpsToLLVMSPVOpsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-llvm-spv"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-llvm-spv"; } + + ::llvm::StringRef getDescription() const override { return "Generate LLVM operations to be ingested by a SPIR-V backend for gpu operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuOpsToLLVMSPVOps"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuOpsToLLVMSPVOps"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuOpsToLLVMSPVOpsBase) + +protected: + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +}; + +template +class ConvertGpuOpsToNVVMOpsBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuOpsToNVVMOpsBase; + + ConvertGpuOpsToNVVMOpsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuOpsToNVVMOpsBase(const ConvertGpuOpsToNVVMOpsBase &other) : ::mlir::OperationPass(other) {} + ConvertGpuOpsToNVVMOpsBase& operator=(const ConvertGpuOpsToNVVMOpsBase &) = delete; + ConvertGpuOpsToNVVMOpsBase(ConvertGpuOpsToNVVMOpsBase &&) = delete; + ConvertGpuOpsToNVVMOpsBase& operator=(ConvertGpuOpsToNVVMOpsBase &&) = delete; + ~ConvertGpuOpsToNVVMOpsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-nvvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-nvvm"; } + + ::llvm::StringRef getDescription() const override { return "Generate NVVM operations for gpu operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuOpsToNVVMOps"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuOpsToNVVMOps"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuOpsToNVVMOpsBase) + +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; + ::mlir::Pass::Option hasRedux{*this, "has-redux", ::llvm::cl::desc("Target gpu supports redux"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option useBarePtrCallConv{*this, "use-bare-ptr-memref-call-conv", ::llvm::cl::desc("Replace memref arguments in GPU functions with bare pointers. All memrefs must have static shape."), ::llvm::cl::init(false)}; + ::mlir::Pass::ListOption allowedDialects{*this, "allowed-dialects", ::llvm::cl::desc("Run conversion patterns of only the specified dialects")}; +}; + +template +class ConvertGpuOpsToROCDLOpsBase : public ::mlir::OperationPass { +public: + using Base = ConvertGpuOpsToROCDLOpsBase; + + ConvertGpuOpsToROCDLOpsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertGpuOpsToROCDLOpsBase(const ConvertGpuOpsToROCDLOpsBase &other) : ::mlir::OperationPass(other) {} + ConvertGpuOpsToROCDLOpsBase& operator=(const ConvertGpuOpsToROCDLOpsBase &) = delete; + ConvertGpuOpsToROCDLOpsBase(ConvertGpuOpsToROCDLOpsBase &&) = delete; + ConvertGpuOpsToROCDLOpsBase& operator=(ConvertGpuOpsToROCDLOpsBase &&) = delete; + ~ConvertGpuOpsToROCDLOpsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-gpu-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "convert-gpu-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Generate ROCDL operations for gpu operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertGpuOpsToROCDLOps"); + } + ::llvm::StringRef getName() const override { return "ConvertGpuOpsToROCDLOps"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertGpuOpsToROCDLOpsBase) + +protected: + ::mlir::Pass::Option chipset{*this, "chipset", ::llvm::cl::desc("Chipset that these operations will run on"), ::llvm::cl::init("gfx000")}; + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; + ::mlir::Pass::Option useBarePtrCallConv{*this, "use-bare-ptr-memref-call-conv", ::llvm::cl::desc("Replace memref arguments in GPU functions with bare pointers.All memrefs must have static shape"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option<::mlir::gpu::amd::Runtime> runtime{*this, "runtime", ::llvm::cl::desc("Runtime code will be run on (default is Unknown, can also use HIP or OpenCL)"), ::llvm::cl::init(::mlir::gpu::amd::Runtime::Unknown), ::llvm::cl::values( + clEnumValN(::mlir::gpu::amd::Runtime::Unknown, "unknown", + "Unknown (default)"), + clEnumValN(::mlir::gpu::amd::Runtime::HIP, "HIP", "HIP"), + clEnumValN(::mlir::gpu::amd::Runtime::OpenCL, "OpenCL", + "OpenCL"))}; + ::mlir::Pass::ListOption allowedDialects{*this, "allowed-dialects", ::llvm::cl::desc("Run conversion patterns of only the specified dialects")}; +}; + +template +class ConvertIndexToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertIndexToLLVMPassBase; + + ConvertIndexToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertIndexToLLVMPassBase(const ConvertIndexToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertIndexToLLVMPassBase& operator=(const ConvertIndexToLLVMPassBase &) = delete; + ConvertIndexToLLVMPassBase(ConvertIndexToLLVMPassBase &&) = delete; + ConvertIndexToLLVMPassBase& operator=(ConvertIndexToLLVMPassBase &&) = delete; + ~ConvertIndexToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-index-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-index-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lower the `index` dialect to the `llvm` dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertIndexToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertIndexToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert<::mlir::LLVM::LLVMDialect>(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertIndexToLLVMPassBase) + +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +}; + +template +class ConvertIndexToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertIndexToSPIRVPassBase; + + ConvertIndexToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertIndexToSPIRVPassBase(const ConvertIndexToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertIndexToSPIRVPassBase& operator=(const ConvertIndexToSPIRVPassBase &) = delete; + ConvertIndexToSPIRVPassBase(ConvertIndexToSPIRVPassBase &&) = delete; + ConvertIndexToSPIRVPassBase& operator=(ConvertIndexToSPIRVPassBase &&) = delete; + ~ConvertIndexToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-index-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-index-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Lower the `index` dialect to the `spirv` dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertIndexToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertIndexToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert<::mlir::spirv::SPIRVDialect>(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertIndexToSPIRVPassBase) + +protected: + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +}; + +template +class ConvertLinalgToStandardPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertLinalgToStandardPassBase; + + ConvertLinalgToStandardPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertLinalgToStandardPassBase(const ConvertLinalgToStandardPassBase &other) : ::mlir::OperationPass(other) {} + ConvertLinalgToStandardPassBase& operator=(const ConvertLinalgToStandardPassBase &) = delete; + ConvertLinalgToStandardPassBase(ConvertLinalgToStandardPassBase &&) = delete; + ConvertLinalgToStandardPassBase& operator=(ConvertLinalgToStandardPassBase &&) = delete; + ~ConvertLinalgToStandardPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-linalg-to-std"); + } + ::llvm::StringRef getArgument() const override { return "convert-linalg-to-std"; } + + ::llvm::StringRef getDescription() const override { return "Convert the operations from the linalg dialect into the Standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertLinalgToStandardPass"); + } + ::llvm::StringRef getName() const override { return "ConvertLinalgToStandardPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertLinalgToStandardPassBase) + +protected: +}; + +template +class ConvertMathToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMathToEmitCBase; + + ConvertMathToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMathToEmitCBase(const ConvertMathToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMathToEmitCBase& operator=(const ConvertMathToEmitCBase &) = delete; + ConvertMathToEmitCBase(ConvertMathToEmitCBase &&) = delete; + ConvertMathToEmitCBase& operator=(ConvertMathToEmitCBase &&) = delete; + ~ConvertMathToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert some Math operations to EmitC call_opaque operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToEmitCBase) + +protected: + ::mlir::Pass::Option<::mlir::emitc::LanguageTarget> languageTarget{*this, "language-target", ::llvm::cl::desc("Select the language standard target for callees (c99 or cpp11)."), ::llvm::cl::init(::mlir::emitc::LanguageTarget::c99), ::llvm::cl::values( + clEnumValN(::mlir::emitc::LanguageTarget::c99, "c99", "c99"), + clEnumValN(::mlir::emitc::LanguageTarget::cpp11, "cpp11", "cpp11") + )}; +}; + +template +class ConvertMathToFuncsBase : public ::mlir::OperationPass { +public: + using Base = ConvertMathToFuncsBase; + + ConvertMathToFuncsBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMathToFuncsBase(const ConvertMathToFuncsBase &other) : ::mlir::OperationPass(other) {} + ConvertMathToFuncsBase& operator=(const ConvertMathToFuncsBase &) = delete; + ConvertMathToFuncsBase(ConvertMathToFuncsBase &&) = delete; + ConvertMathToFuncsBase& operator=(ConvertMathToFuncsBase &&) = delete; + ~ConvertMathToFuncsBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-funcs"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-funcs"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math operations to calls of outlined implementations."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToFuncs"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToFuncs"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToFuncsBase) + +protected: + ::mlir::Pass::Option minWidthOfFPowIExponent{*this, "min-width-of-fpowi-exponent", ::llvm::cl::desc("Convert FPowI only if the width of its exponent's integer type is greater than or equal to this value"), ::llvm::cl::init(1)}; + ::mlir::Pass::Option convertCtlz{*this, "convert-ctlz", ::llvm::cl::desc("Convert math.ctlz to a software implementation. Enable for targets that do not natively support ctlz."), ::llvm::cl::init(false)}; +}; + +template +class ConvertMathToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMathToLLVMPassBase; + + ConvertMathToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMathToLLVMPassBase(const ConvertMathToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMathToLLVMPassBase& operator=(const ConvertMathToLLVMPassBase &) = delete; + ConvertMathToLLVMPassBase(ConvertMathToLLVMPassBase &&) = delete; + ConvertMathToLLVMPassBase& operator=(ConvertMathToLLVMPassBase &&) = delete; + ~ConvertMathToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToLLVMPassBase) + +protected: + ::mlir::Pass::Option approximateLog1p{*this, "approximate-log1p", ::llvm::cl::desc("Enable approximation of Log1p."), ::llvm::cl::init(true)}; +}; + +template +class ConvertMathToLibmPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertMathToLibmPassBase; + + ConvertMathToLibmPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMathToLibmPassBase(const ConvertMathToLibmPassBase &other) : ::mlir::OperationPass(other) {} + ConvertMathToLibmPassBase& operator=(const ConvertMathToLibmPassBase &) = delete; + ConvertMathToLibmPassBase(ConvertMathToLibmPassBase &&) = delete; + ConvertMathToLibmPassBase& operator=(ConvertMathToLibmPassBase &&) = delete; + ~ConvertMathToLibmPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-libm"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-libm"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to libm calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToLibmPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToLibmPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToLibmPassBase) + +protected: +}; + +template +class ConvertMathToROCDLBase : public ::mlir::OperationPass { +public: + using Base = ConvertMathToROCDLBase; + + ConvertMathToROCDLBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertMathToROCDLBase(const ConvertMathToROCDLBase &other) : ::mlir::OperationPass(other) {} + ConvertMathToROCDLBase& operator=(const ConvertMathToROCDLBase &) = delete; + ConvertMathToROCDLBase(ConvertMathToROCDLBase &&) = delete; + ConvertMathToROCDLBase& operator=(ConvertMathToROCDLBase &&) = delete; + ~ConvertMathToROCDLBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-rocdl"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-rocdl"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to ROCDL library calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToROCDL"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToROCDL"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToROCDLBase) + +protected: +}; + +template +class ConvertMathToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMathToSPIRVPassBase; + + ConvertMathToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMathToSPIRVPassBase(const ConvertMathToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMathToSPIRVPassBase& operator=(const ConvertMathToSPIRVPassBase &) = delete; + ConvertMathToSPIRVPassBase(ConvertMathToSPIRVPassBase &&) = delete; + ConvertMathToSPIRVPassBase& operator=(ConvertMathToSPIRVPassBase &&) = delete; + ~ConvertMathToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-math-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-math-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Math dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMathToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMathToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMathToSPIRVPassBase) + +protected: +}; + +template +class ConvertMemRefToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMemRefToEmitCBase; + + ConvertMemRefToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMemRefToEmitCBase(const ConvertMemRefToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMemRefToEmitCBase& operator=(const ConvertMemRefToEmitCBase &) = delete; + ConvertMemRefToEmitCBase(ConvertMemRefToEmitCBase &&) = delete; + ConvertMemRefToEmitCBase& operator=(ConvertMemRefToEmitCBase &&) = delete; + ~ConvertMemRefToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-memref-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-memref-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert MemRef dialect to EmitC dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMemRefToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertMemRefToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMemRefToEmitCBase) + +protected: +}; + +template +class ConvertMemRefToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMemRefToSPIRVPassBase; + + ConvertMemRefToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMemRefToSPIRVPassBase(const ConvertMemRefToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMemRefToSPIRVPassBase& operator=(const ConvertMemRefToSPIRVPassBase &) = delete; + ConvertMemRefToSPIRVPassBase(ConvertMemRefToSPIRVPassBase &&) = delete; + ConvertMemRefToSPIRVPassBase& operator=(ConvertMemRefToSPIRVPassBase &&) = delete; + ~ConvertMemRefToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-memref-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-memref-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert MemRef dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMemRefToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMemRefToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMemRefToSPIRVPassBase) + +protected: + ::mlir::Pass::Option boolNumBits{*this, "bool-num-bits", ::llvm::cl::desc("The number of bits to store a boolean value"), ::llvm::cl::init(8)}; + ::mlir::Pass::Option use64bitIndex{*this, "use-64bit-index", ::llvm::cl::desc("Use 64-bit integers to convert index types"), ::llvm::cl::init(false)}; +}; + +template +class ConvertMeshToMPIPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertMeshToMPIPassBase; + + ConvertMeshToMPIPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertMeshToMPIPassBase(const ConvertMeshToMPIPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertMeshToMPIPassBase& operator=(const ConvertMeshToMPIPassBase &) = delete; + ConvertMeshToMPIPassBase(ConvertMeshToMPIPassBase &&) = delete; + ConvertMeshToMPIPassBase& operator=(ConvertMeshToMPIPassBase &&) = delete; + ~ConvertMeshToMPIPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-mesh-to-mpi"); + } + ::llvm::StringRef getArgument() const override { return "convert-mesh-to-mpi"; } + + ::llvm::StringRef getDescription() const override { return "Convert Mesh dialect to MPI dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertMeshToMPIPass"); + } + ::llvm::StringRef getName() const override { return "ConvertMeshToMPIPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertMeshToMPIPassBase) + +protected: +}; + +template +class ConvertNVGPUToNVVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertNVGPUToNVVMPassBase; + + ConvertNVGPUToNVVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertNVGPUToNVVMPassBase(const ConvertNVGPUToNVVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertNVGPUToNVVMPassBase& operator=(const ConvertNVGPUToNVVMPassBase &) = delete; + ConvertNVGPUToNVVMPassBase(ConvertNVGPUToNVVMPassBase &&) = delete; + ConvertNVGPUToNVVMPassBase& operator=(ConvertNVGPUToNVVMPassBase &&) = delete; + ~ConvertNVGPUToNVVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-nvgpu-to-nvvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-nvgpu-to-nvvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert NVGPU dialect to NVVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertNVGPUToNVVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertNVGPUToNVVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertNVGPUToNVVMPassBase) + +protected: +}; + +template +class ConvertNVVMToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertNVVMToLLVMPassBase; + + ConvertNVVMToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertNVVMToLLVMPassBase(const ConvertNVVMToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertNVVMToLLVMPassBase& operator=(const ConvertNVVMToLLVMPassBase &) = delete; + ConvertNVVMToLLVMPassBase(ConvertNVVMToLLVMPassBase &&) = delete; + ConvertNVVMToLLVMPassBase& operator=(ConvertNVVMToLLVMPassBase &&) = delete; + ~ConvertNVVMToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-nvvm-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-nvvm-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert NVVM to PTX with Inline Assembly in LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertNVVMToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertNVVMToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertNVVMToLLVMPassBase) + +protected: +}; + +template +class ConvertOpenACCToSCFPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertOpenACCToSCFPassBase; + + ConvertOpenACCToSCFPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertOpenACCToSCFPassBase(const ConvertOpenACCToSCFPassBase &other) : ::mlir::OperationPass(other) {} + ConvertOpenACCToSCFPassBase& operator=(const ConvertOpenACCToSCFPassBase &) = delete; + ConvertOpenACCToSCFPassBase(ConvertOpenACCToSCFPassBase &&) = delete; + ConvertOpenACCToSCFPassBase& operator=(ConvertOpenACCToSCFPassBase &&) = delete; + ~ConvertOpenACCToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-openacc-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "convert-openacc-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Convert the OpenACC ops to OpenACC with SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertOpenACCToSCFPass"); + } + ::llvm::StringRef getName() const override { return "ConvertOpenACCToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertOpenACCToSCFPassBase) + +protected: +}; + +template +class ConvertOpenMPToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertOpenMPToLLVMPassBase; + + ConvertOpenMPToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertOpenMPToLLVMPassBase(const ConvertOpenMPToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertOpenMPToLLVMPassBase& operator=(const ConvertOpenMPToLLVMPassBase &) = delete; + ConvertOpenMPToLLVMPassBase(ConvertOpenMPToLLVMPassBase &&) = delete; + ConvertOpenMPToLLVMPassBase& operator=(ConvertOpenMPToLLVMPassBase &&) = delete; + ~ConvertOpenMPToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-openmp-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-openmp-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert the OpenMP ops to OpenMP ops with LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertOpenMPToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertOpenMPToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertOpenMPToLLVMPassBase) + +protected: +}; + +template +class ConvertPDLToPDLInterpPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertPDLToPDLInterpPassBase; + + ConvertPDLToPDLInterpPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertPDLToPDLInterpPassBase(const ConvertPDLToPDLInterpPassBase &other) : ::mlir::OperationPass(other) {} + ConvertPDLToPDLInterpPassBase& operator=(const ConvertPDLToPDLInterpPassBase &) = delete; + ConvertPDLToPDLInterpPassBase(ConvertPDLToPDLInterpPassBase &&) = delete; + ConvertPDLToPDLInterpPassBase& operator=(ConvertPDLToPDLInterpPassBase &&) = delete; + ~ConvertPDLToPDLInterpPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-pdl-to-pdl-interp"); + } + ::llvm::StringRef getArgument() const override { return "convert-pdl-to-pdl-interp"; } + + ::llvm::StringRef getDescription() const override { return "Convert PDL ops to PDL interpreter ops"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertPDLToPDLInterpPass"); + } + ::llvm::StringRef getName() const override { return "ConvertPDLToPDLInterpPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertPDLToPDLInterpPassBase) + +protected: +}; + +template +class ConvertParallelLoopToGpuPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertParallelLoopToGpuPassBase; + + ConvertParallelLoopToGpuPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertParallelLoopToGpuPassBase(const ConvertParallelLoopToGpuPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertParallelLoopToGpuPassBase& operator=(const ConvertParallelLoopToGpuPassBase &) = delete; + ConvertParallelLoopToGpuPassBase(ConvertParallelLoopToGpuPassBase &&) = delete; + ConvertParallelLoopToGpuPassBase& operator=(ConvertParallelLoopToGpuPassBase &&) = delete; + ~ConvertParallelLoopToGpuPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-parallel-loops-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-parallel-loops-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Convert mapped scf.parallel ops to gpu launch operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertParallelLoopToGpuPass"); + } + ::llvm::StringRef getName() const override { return "ConvertParallelLoopToGpuPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertParallelLoopToGpuPassBase) + +protected: +}; + +template +class ConvertSCFToOpenMPPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertSCFToOpenMPPassBase; + + ConvertSCFToOpenMPPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertSCFToOpenMPPassBase(const ConvertSCFToOpenMPPassBase &other) : ::mlir::OperationPass(other) {} + ConvertSCFToOpenMPPassBase& operator=(const ConvertSCFToOpenMPPassBase &) = delete; + ConvertSCFToOpenMPPassBase(ConvertSCFToOpenMPPassBase &&) = delete; + ConvertSCFToOpenMPPassBase& operator=(ConvertSCFToOpenMPPassBase &&) = delete; + ~ConvertSCFToOpenMPPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-openmp"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-openmp"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF parallel loop to OpenMP parallel + workshare constructs."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertSCFToOpenMPPass"); + } + ::llvm::StringRef getName() const override { return "ConvertSCFToOpenMPPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertSCFToOpenMPPassBase) + +protected: + ::mlir::Pass::Option numThreads{*this, "num-threads", ::llvm::cl::desc("Number of threads to use"), ::llvm::cl::init(0)}; +}; + +template +class ConvertSPIRVToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertSPIRVToLLVMPassBase; + + ConvertSPIRVToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertSPIRVToLLVMPassBase(const ConvertSPIRVToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + ConvertSPIRVToLLVMPassBase& operator=(const ConvertSPIRVToLLVMPassBase &) = delete; + ConvertSPIRVToLLVMPassBase(ConvertSPIRVToLLVMPassBase &&) = delete; + ConvertSPIRVToLLVMPassBase& operator=(ConvertSPIRVToLLVMPassBase &&) = delete; + ~ConvertSPIRVToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-spirv-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-spirv-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert SPIR-V dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertSPIRVToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertSPIRVToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertSPIRVToLLVMPassBase) + +protected: + ::mlir::Pass::Option<::mlir::spirv::ClientAPI> clientAPI{*this, "client-api", ::llvm::cl::desc("Derive StorageClass to address space mapping from the client API"), ::llvm::cl::init(::mlir::spirv::ClientAPI::Unknown), ::llvm::cl::values( + clEnumValN(::mlir::spirv::ClientAPI::Unknown, "Unknown", "Unknown (default)"), + clEnumValN(::mlir::spirv::ClientAPI::Metal, "Metal", "Metal"), + clEnumValN(::mlir::spirv::ClientAPI::OpenCL, "OpenCL", "OpenCL"), + clEnumValN(::mlir::spirv::ClientAPI::Vulkan, "Vulkan", "Vulkan"), + clEnumValN(::mlir::spirv::ClientAPI::WebGPU, "WebGPU", "WebGPU") + )}; +}; + +template +class ConvertShapeConstraintsPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertShapeConstraintsPassBase; + + ConvertShapeConstraintsPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertShapeConstraintsPassBase(const ConvertShapeConstraintsPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertShapeConstraintsPassBase& operator=(const ConvertShapeConstraintsPassBase &) = delete; + ConvertShapeConstraintsPassBase(ConvertShapeConstraintsPassBase &&) = delete; + ConvertShapeConstraintsPassBase& operator=(ConvertShapeConstraintsPassBase &&) = delete; + ~ConvertShapeConstraintsPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-shape-constraints"); + } + ::llvm::StringRef getArgument() const override { return "convert-shape-constraints"; } + + ::llvm::StringRef getDescription() const override { return "Convert shape constraint operations to the standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertShapeConstraintsPass"); + } + ::llvm::StringRef getName() const override { return "ConvertShapeConstraintsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertShapeConstraintsPassBase) + +protected: +}; + +template +class ConvertShapeToStandardPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertShapeToStandardPassBase; + + ConvertShapeToStandardPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertShapeToStandardPassBase(const ConvertShapeToStandardPassBase &other) : ::mlir::OperationPass(other) {} + ConvertShapeToStandardPassBase& operator=(const ConvertShapeToStandardPassBase &) = delete; + ConvertShapeToStandardPassBase(ConvertShapeToStandardPassBase &&) = delete; + ConvertShapeToStandardPassBase& operator=(ConvertShapeToStandardPassBase &&) = delete; + ~ConvertShapeToStandardPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-shape-to-std"); + } + ::llvm::StringRef getArgument() const override { return "convert-shape-to-std"; } + + ::llvm::StringRef getDescription() const override { return "Convert operations from the shape dialect into the standard dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertShapeToStandardPass"); + } + ::llvm::StringRef getName() const override { return "ConvertShapeToStandardPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertShapeToStandardPassBase) + +protected: +}; + +template +class ConvertTensorToLinalgPassBase : public ::mlir::OperationPass { +public: + using Base = ConvertTensorToLinalgPassBase; + + ConvertTensorToLinalgPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + ConvertTensorToLinalgPassBase(const ConvertTensorToLinalgPassBase &other) : ::mlir::OperationPass(other) {} + ConvertTensorToLinalgPassBase& operator=(const ConvertTensorToLinalgPassBase &) = delete; + ConvertTensorToLinalgPassBase(ConvertTensorToLinalgPassBase &&) = delete; + ConvertTensorToLinalgPassBase& operator=(ConvertTensorToLinalgPassBase &&) = delete; + ~ConvertTensorToLinalgPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-tensor-to-linalg"); + } + ::llvm::StringRef getArgument() const override { return "convert-tensor-to-linalg"; } + + ::llvm::StringRef getDescription() const override { return "Convert some Tensor dialect ops to Linalg dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertTensorToLinalgPass"); + } + ::llvm::StringRef getName() const override { return "ConvertTensorToLinalgPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertTensorToLinalgPassBase) + +protected: +}; + +template +class ConvertTensorToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertTensorToSPIRVPassBase; + + ConvertTensorToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertTensorToSPIRVPassBase(const ConvertTensorToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertTensorToSPIRVPassBase& operator=(const ConvertTensorToSPIRVPassBase &) = delete; + ConvertTensorToSPIRVPassBase(ConvertTensorToSPIRVPassBase &&) = delete; + ConvertTensorToSPIRVPassBase& operator=(ConvertTensorToSPIRVPassBase &&) = delete; + ~ConvertTensorToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-tensor-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-tensor-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Tensor dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertTensorToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertTensorToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertTensorToSPIRVPassBase) + +protected: + ::mlir::Pass::Option emulateLT32BitScalarTypes{*this, "emulate-lt-32-bit-scalar-types", ::llvm::cl::desc("Emulate narrower scalar types with 32-bit ones if not supported by the target"), ::llvm::cl::init(true)}; +}; + +template +class ConvertToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertToEmitCBase; + + ConvertToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertToEmitCBase(const ConvertToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + ConvertToEmitCBase& operator=(const ConvertToEmitCBase &) = delete; + ConvertToEmitCBase(ConvertToEmitCBase &&) = delete; + ConvertToEmitCBase& operator=(ConvertToEmitCBase &&) = delete; + ~ConvertToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert to EmitC dialect via dialect interfaces"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertToEmitC"); + } + ::llvm::StringRef getName() const override { return "ConvertToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertToEmitCBase) + +protected: + ::mlir::Pass::ListOption filterDialects{*this, "filter-dialects", ::llvm::cl::desc("Test conversion patterns of only the specified dialects")}; +}; + +template +class ConvertToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertToLLVMPassBase; + + ConvertToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertToLLVMPassBase(const ConvertToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertToLLVMPassBase& operator=(const ConvertToLLVMPassBase &) = delete; + ConvertToLLVMPassBase(ConvertToLLVMPassBase &&) = delete; + ConvertToLLVMPassBase& operator=(ConvertToLLVMPassBase &&) = delete; + ~ConvertToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert to LLVM via dialect interfaces found in the input IR"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertToLLVMPassBase) + +protected: + ::mlir::Pass::ListOption filterDialects{*this, "filter-dialects", ::llvm::cl::desc("Test conversion patterns of only the specified dialects")}; + ::mlir::Pass::Option useDynamic{*this, "dynamic", ::llvm::cl::desc("Use op conversion attributes to configure the conversion"), ::llvm::cl::init(false)}; +}; + +template +class ConvertVectorToArmSMEPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToArmSMEPassBase; + + ConvertVectorToArmSMEPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToArmSMEPassBase(const ConvertVectorToArmSMEPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToArmSMEPassBase& operator=(const ConvertVectorToArmSMEPassBase &) = delete; + ConvertVectorToArmSMEPassBase(ConvertVectorToArmSMEPassBase &&) = delete; + ConvertVectorToArmSMEPassBase& operator=(ConvertVectorToArmSMEPassBase &&) = delete; + ~ConvertVectorToArmSMEPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-arm-sme"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-arm-sme"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the ArmSME dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToArmSMEPass"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToArmSMEPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToArmSMEPassBase) + +protected: +}; + +template +class ConvertVectorToGPUBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToGPUBase; + + ConvertVectorToGPUBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToGPUBase(const ConvertVectorToGPUBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToGPUBase& operator=(const ConvertVectorToGPUBase &) = delete; + ConvertVectorToGPUBase(ConvertVectorToGPUBase &&) = delete; + ConvertVectorToGPUBase& operator=(ConvertVectorToGPUBase &&) = delete; + ~ConvertVectorToGPUBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-gpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-gpu"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the GPU dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToGPU"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToGPU"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToGPUBase) + +protected: + ::mlir::Pass::Option useNvGpu{*this, "use-nvgpu", ::llvm::cl::desc("convert to NvGPU ops instead of GPU dialect ops"), ::llvm::cl::init(false)}; +}; + +template +class ConvertVectorToLLVMPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToLLVMPassBase; + + ConvertVectorToLLVMPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToLLVMPassBase(const ConvertVectorToLLVMPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToLLVMPassBase& operator=(const ConvertVectorToLLVMPassBase &) = delete; + ConvertVectorToLLVMPassBase(ConvertVectorToLLVMPassBase &&) = delete; + ConvertVectorToLLVMPassBase& operator=(ConvertVectorToLLVMPassBase &&) = delete; + ~ConvertVectorToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToLLVMPassBase) + +protected: + ::mlir::Pass::Option reassociateFPReductions{*this, "reassociate-fp-reductions", ::llvm::cl::desc("Allows llvm to reassociate floating-point reductions for speed"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option force32BitVectorIndices{*this, "force-32bit-vector-indices", ::llvm::cl::desc("Allows compiler to assume vector indices fit in 32-bit if that yields faster code"), ::llvm::cl::init(true)}; + ::mlir::Pass::Option useVectorAlignment{*this, "use-vector-alignment", ::llvm::cl::desc("Use the preferred alignment of a vector type in load/store operations instead of the alignment of the element type of the memref. This flag is intended for use with hardware which requiresvector alignment, or in application contexts where it is known all vector access are naturally aligned. "), ::llvm::cl::init(false)}; + ::mlir::Pass::Option amx{*this, "enable-amx", ::llvm::cl::desc("Enables the use of AMX dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option armNeon{*this, "enable-arm-neon", ::llvm::cl::desc("Enables the use of ArmNeon dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option armSVE{*this, "enable-arm-sve", ::llvm::cl::desc("Enables the use of ArmSVE dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option armI8MM{*this, "enable-arm-i8mm", ::llvm::cl::desc("Enables the use of Arm FEAT_I8MM instructions while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option x86Vector{*this, "enable-x86vector", ::llvm::cl::desc("Enables the use of X86Vector dialect while lowering the vector dialect."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option vectorContractLowering{*this, "vector-contract-lowering", ::llvm::cl::desc("control the lowering of `vector.contract` operations."), ::llvm::cl::init(vector::VectorContractLowering::Dot), ::llvm::cl::values( + clEnumValN(::mlir::vector::VectorContractLowering::Dot, "dot", + "Progressively lower to finer grained `vector.contract` and dot-products. (default)"), + clEnumValN(::mlir::vector::VectorContractLowering::Matmul, "matmul", + "Lower to `vector.matrix_multiply`, maps 1-1 to LLVM matrix intrinsics."), + clEnumValN(::mlir::vector::VectorContractLowering::OuterProduct, "outerproduct", + "Lower to `vector.outerproduct`."), + clEnumValN(::mlir::vector::VectorContractLowering::ParallelArith, "parallelarith", + "Lower contract with all reduction dimensions unrolled to 1 to a vector elementwise operations.") + )}; + ::mlir::Pass::Option vectorTransposeLowering{*this, "vector-transpose-lowering", ::llvm::cl::desc("control the lowering of `vector.transpose` operations."), ::llvm::cl::init(vector::VectorTransposeLowering::EltWise), ::llvm::cl::values( + clEnumValN(::mlir::vector::VectorTransposeLowering::EltWise, "eltwise", + "Lower transpose into element-wise extract and inserts (default)"), + clEnumValN(::mlir::vector::VectorTransposeLowering::Flat, "flat", + "Lower 2-D transpose to `vector.flat_transpose`, maps 1-1 to LLVM matrix intrinsics"), + clEnumValN(::mlir::vector::VectorTransposeLowering::Shuffle1D, "shuffle1d", + "Lower 2-D transpose to `vector.shuffle` on 1-D vector."), + clEnumValN(::mlir::vector::VectorTransposeLowering::Shuffle16x16, "shuffle16x16", + "Lower 2-D transpose to `vector.shuffle` on 16x16 vector.") + )}; +}; + +template +class ConvertVectorToSCFBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToSCFBase; + + ConvertVectorToSCFBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToSCFBase(const ConvertVectorToSCFBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToSCFBase& operator=(const ConvertVectorToSCFBase &) = delete; + ConvertVectorToSCFBase(ConvertVectorToSCFBase &&) = delete; + ConvertVectorToSCFBase& operator=(ConvertVectorToSCFBase &&) = delete; + ~ConvertVectorToSCFBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToSCF"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToSCF"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToSCFBase) + +protected: + ::mlir::Pass::Option fullUnroll{*this, "full-unroll", ::llvm::cl::desc("Perform full unrolling when converting vector transfers to SCF"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option targetRank{*this, "target-rank", ::llvm::cl::desc("Target vector rank to which transfer ops should be lowered"), ::llvm::cl::init(1)}; + ::mlir::Pass::Option lowerTensors{*this, "lower-tensors", ::llvm::cl::desc("Lower transfer ops that operate on tensors"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option lowerScalable{*this, "lower-scalable", ::llvm::cl::desc("Add scalable vector specific lowerings (that introduce loops)"), ::llvm::cl::init(false)}; +}; + +template +class ConvertVectorToSPIRVPassBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToSPIRVPassBase; + + ConvertVectorToSPIRVPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToSPIRVPassBase(const ConvertVectorToSPIRVPassBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToSPIRVPassBase& operator=(const ConvertVectorToSPIRVPassBase &) = delete; + ConvertVectorToSPIRVPassBase(ConvertVectorToSPIRVPassBase &&) = delete; + ConvertVectorToSPIRVPassBase& operator=(ConvertVectorToSPIRVPassBase &&) = delete; + ~ConvertVectorToSPIRVPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert Vector dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToSPIRVPass"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToSPIRVPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToSPIRVPassBase) + +protected: +}; + +template +class ConvertVectorToXeGPUBase : public ::mlir::OperationPass<> { +public: + using Base = ConvertVectorToXeGPUBase; + + ConvertVectorToXeGPUBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ConvertVectorToXeGPUBase(const ConvertVectorToXeGPUBase &other) : ::mlir::OperationPass<>(other) {} + ConvertVectorToXeGPUBase& operator=(const ConvertVectorToXeGPUBase &) = delete; + ConvertVectorToXeGPUBase(ConvertVectorToXeGPUBase &&) = delete; + ConvertVectorToXeGPUBase& operator=(ConvertVectorToXeGPUBase &&) = delete; + ~ConvertVectorToXeGPUBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-vector-to-xegpu"); + } + ::llvm::StringRef getArgument() const override { return "convert-vector-to-xegpu"; } + + ::llvm::StringRef getDescription() const override { return "Lower the operations from the vector dialect into the XeGPU dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ConvertVectorToXeGPU"); + } + ::llvm::StringRef getName() const override { return "ConvertVectorToXeGPU"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ConvertVectorToXeGPUBase) + +protected: +}; + +template +class FinalizeMemRefToLLVMConversionPassBase : public ::mlir::OperationPass { +public: + using Base = FinalizeMemRefToLLVMConversionPassBase; + + FinalizeMemRefToLLVMConversionPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + FinalizeMemRefToLLVMConversionPassBase(const FinalizeMemRefToLLVMConversionPassBase &other) : ::mlir::OperationPass(other) {} + FinalizeMemRefToLLVMConversionPassBase& operator=(const FinalizeMemRefToLLVMConversionPassBase &) = delete; + FinalizeMemRefToLLVMConversionPassBase(FinalizeMemRefToLLVMConversionPassBase &&) = delete; + FinalizeMemRefToLLVMConversionPassBase& operator=(FinalizeMemRefToLLVMConversionPassBase &&) = delete; + ~FinalizeMemRefToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("finalize-memref-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "finalize-memref-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Finalize MemRef dialect to LLVM dialect conversion"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("FinalizeMemRefToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "FinalizeMemRefToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(FinalizeMemRefToLLVMConversionPassBase) + +protected: + ::mlir::Pass::Option useAlignedAlloc{*this, "use-aligned-alloc", ::llvm::cl::desc("Use aligned_alloc in place of malloc for heap allocations"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; + ::mlir::Pass::Option useGenericFunctions{*this, "use-generic-functions", ::llvm::cl::desc("Use generic allocation and deallocation functions instead of the classic 'malloc', 'aligned_alloc' and 'free' functions"), ::llvm::cl::init(false)}; +}; + +template +class GpuToLLVMConversionPassBase : public ::mlir::OperationPass { +public: + using Base = GpuToLLVMConversionPassBase; + + GpuToLLVMConversionPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + GpuToLLVMConversionPassBase(const GpuToLLVMConversionPassBase &other) : ::mlir::OperationPass(other) {} + GpuToLLVMConversionPassBase& operator=(const GpuToLLVMConversionPassBase &) = delete; + GpuToLLVMConversionPassBase(GpuToLLVMConversionPassBase &&) = delete; + GpuToLLVMConversionPassBase& operator=(GpuToLLVMConversionPassBase &&) = delete; + ~GpuToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("gpu-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "gpu-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert GPU dialect to LLVM dialect with GPU runtime calls"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("GpuToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "GpuToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(GpuToLLVMConversionPassBase) + +protected: + ::mlir::Pass::Option hostBarePtrCallConv{*this, "use-bare-pointers-for-host", ::llvm::cl::desc("Use bare pointers to pass memref arguments to host functions. All memrefs must have static shape."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option kernelBarePtrCallConv{*this, "use-bare-pointers-for-kernels", ::llvm::cl::desc("Use bare pointers to pass memref arguments to kernels. The kernel must use the same setting for this option."), ::llvm::cl::init(false)}; + ::mlir::Pass::Option kernelIntersperseSizeCallConv{*this, "intersperse-sizes-for-kernels", ::llvm::cl::desc("Inserts a size_t argument following each memref argument, containing the static size in bytes of the buffer. Incompatible arguments are rejected. This is intended for use by the Vulkan runtime with the kernel bare pointer calling convention, to enable dynamic binding of buffers as arguments without static type info."), ::llvm::cl::init(false)}; +}; + +template +class LiftControlFlowToSCFPassBase : public ::mlir::OperationPass<> { +public: + using Base = LiftControlFlowToSCFPassBase; + + LiftControlFlowToSCFPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + LiftControlFlowToSCFPassBase(const LiftControlFlowToSCFPassBase &other) : ::mlir::OperationPass<>(other) {} + LiftControlFlowToSCFPassBase& operator=(const LiftControlFlowToSCFPassBase &) = delete; + LiftControlFlowToSCFPassBase(LiftControlFlowToSCFPassBase &&) = delete; + LiftControlFlowToSCFPassBase& operator=(LiftControlFlowToSCFPassBase &&) = delete; + ~LiftControlFlowToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lift-cf-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "lift-cf-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lift ControlFlow dialect to SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LiftControlFlowToSCFPass"); + } + ::llvm::StringRef getName() const override { return "LiftControlFlowToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LiftControlFlowToSCFPassBase) + +protected: +}; + +template +class LowerAffinePassBase : public ::mlir::OperationPass<> { +public: + using Base = LowerAffinePassBase; + + LowerAffinePassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + LowerAffinePassBase(const LowerAffinePassBase &other) : ::mlir::OperationPass<>(other) {} + LowerAffinePassBase& operator=(const LowerAffinePassBase &) = delete; + LowerAffinePassBase(LowerAffinePassBase &&) = delete; + LowerAffinePassBase& operator=(LowerAffinePassBase &&) = delete; + ~LowerAffinePassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lower-affine"); + } + ::llvm::StringRef getArgument() const override { return "lower-affine"; } + + ::llvm::StringRef getDescription() const override { return "Lower Affine operations to a combination of Arith and SCF operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LowerAffinePass"); + } + ::llvm::StringRef getName() const override { return "LowerAffinePass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LowerAffinePassBase) + +protected: +}; + +template +class LowerHostCodeToLLVMPassBase : public ::mlir::OperationPass { +public: + using Base = LowerHostCodeToLLVMPassBase; + + LowerHostCodeToLLVMPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + LowerHostCodeToLLVMPassBase(const LowerHostCodeToLLVMPassBase &other) : ::mlir::OperationPass(other) {} + LowerHostCodeToLLVMPassBase& operator=(const LowerHostCodeToLLVMPassBase &) = delete; + LowerHostCodeToLLVMPassBase(LowerHostCodeToLLVMPassBase &&) = delete; + LowerHostCodeToLLVMPassBase& operator=(LowerHostCodeToLLVMPassBase &&) = delete; + ~LowerHostCodeToLLVMPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("lower-host-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "lower-host-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Lowers the host module code and `gpu.launch_func` to LLVM"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("LowerHostCodeToLLVMPass"); + } + ::llvm::StringRef getName() const override { return "LowerHostCodeToLLVMPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(LowerHostCodeToLLVMPassBase) + +protected: +}; + +template +class MapMemRefStorageClassBase : public ::mlir::OperationPass<> { +public: + using Base = MapMemRefStorageClassBase; + + MapMemRefStorageClassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + MapMemRefStorageClassBase(const MapMemRefStorageClassBase &other) : ::mlir::OperationPass<>(other) {} + MapMemRefStorageClassBase& operator=(const MapMemRefStorageClassBase &) = delete; + MapMemRefStorageClassBase(MapMemRefStorageClassBase &&) = delete; + MapMemRefStorageClassBase& operator=(MapMemRefStorageClassBase &&) = delete; + ~MapMemRefStorageClassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("map-memref-spirv-storage-class"); + } + ::llvm::StringRef getArgument() const override { return "map-memref-spirv-storage-class"; } + + ::llvm::StringRef getDescription() const override { return "Map numeric MemRef memory spaces to SPIR-V storage classes"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("MapMemRefStorageClass"); + } + ::llvm::StringRef getName() const override { return "MapMemRefStorageClass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(MapMemRefStorageClassBase) + +protected: + ::mlir::Pass::Option clientAPI{*this, "client-api", ::llvm::cl::desc("The client API to use for populating mappings"), ::llvm::cl::init("vulkan")}; +}; + +template +class ReconcileUnrealizedCastsPassBase : public ::mlir::OperationPass<> { +public: + using Base = ReconcileUnrealizedCastsPassBase; + + ReconcileUnrealizedCastsPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + ReconcileUnrealizedCastsPassBase(const ReconcileUnrealizedCastsPassBase &other) : ::mlir::OperationPass<>(other) {} + ReconcileUnrealizedCastsPassBase& operator=(const ReconcileUnrealizedCastsPassBase &) = delete; + ReconcileUnrealizedCastsPassBase(ReconcileUnrealizedCastsPassBase &&) = delete; + ReconcileUnrealizedCastsPassBase& operator=(ReconcileUnrealizedCastsPassBase &&) = delete; + ~ReconcileUnrealizedCastsPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("reconcile-unrealized-casts"); + } + ::llvm::StringRef getArgument() const override { return "reconcile-unrealized-casts"; } + + ::llvm::StringRef getDescription() const override { return "Simplify and eliminate unrealized conversion casts"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("ReconcileUnrealizedCastsPass"); + } + ::llvm::StringRef getName() const override { return "ReconcileUnrealizedCastsPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(ReconcileUnrealizedCastsPassBase) + +protected: +}; + +template +class SCFToControlFlowPassBase : public ::mlir::OperationPass<> { +public: + using Base = SCFToControlFlowPassBase; + + SCFToControlFlowPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + SCFToControlFlowPassBase(const SCFToControlFlowPassBase &other) : ::mlir::OperationPass<>(other) {} + SCFToControlFlowPassBase& operator=(const SCFToControlFlowPassBase &) = delete; + SCFToControlFlowPassBase(SCFToControlFlowPassBase &&) = delete; + SCFToControlFlowPassBase& operator=(SCFToControlFlowPassBase &&) = delete; + ~SCFToControlFlowPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-cf"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-cf"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF dialect to ControlFlow dialect, replacing structured control flow with a CFG"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SCFToControlFlowPass"); + } + ::llvm::StringRef getName() const override { return "SCFToControlFlowPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SCFToControlFlowPassBase) + +protected: +}; + +template +class SCFToEmitCBase : public ::mlir::OperationPass<> { +public: + using Base = SCFToEmitCBase; + + SCFToEmitCBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + SCFToEmitCBase(const SCFToEmitCBase &other) : ::mlir::OperationPass<>(other) {} + SCFToEmitCBase& operator=(const SCFToEmitCBase &) = delete; + SCFToEmitCBase(SCFToEmitCBase &&) = delete; + SCFToEmitCBase& operator=(SCFToEmitCBase &&) = delete; + ~SCFToEmitCBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-emitc"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-emitc"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF dialect to EmitC dialect, maintaining structured control flow"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SCFToEmitC"); + } + ::llvm::StringRef getName() const override { return "SCFToEmitC"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SCFToEmitCBase) + +protected: +}; + +template +class SCFToSPIRVBase : public ::mlir::OperationPass<> { +public: + using Base = SCFToSPIRVBase; + + SCFToSPIRVBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + SCFToSPIRVBase(const SCFToSPIRVBase &other) : ::mlir::OperationPass<>(other) {} + SCFToSPIRVBase& operator=(const SCFToSPIRVBase &) = delete; + SCFToSPIRVBase(SCFToSPIRVBase &&) = delete; + SCFToSPIRVBase& operator=(SCFToSPIRVBase &&) = delete; + ~SCFToSPIRVBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-scf-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-scf-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert SCF dialect to SPIR-V dialect."; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SCFToSPIRV"); + } + ::llvm::StringRef getName() const override { return "SCFToSPIRV"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SCFToSPIRVBase) + +protected: +}; + +template +class SetLLVMModuleDataLayoutPassBase : public ::mlir::OperationPass { +public: + using Base = SetLLVMModuleDataLayoutPassBase; + + SetLLVMModuleDataLayoutPassBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + SetLLVMModuleDataLayoutPassBase(const SetLLVMModuleDataLayoutPassBase &other) : ::mlir::OperationPass(other) {} + SetLLVMModuleDataLayoutPassBase& operator=(const SetLLVMModuleDataLayoutPassBase &) = delete; + SetLLVMModuleDataLayoutPassBase(SetLLVMModuleDataLayoutPassBase &&) = delete; + SetLLVMModuleDataLayoutPassBase& operator=(SetLLVMModuleDataLayoutPassBase &&) = delete; + ~SetLLVMModuleDataLayoutPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("set-llvm-module-datalayout"); + } + ::llvm::StringRef getArgument() const override { return "set-llvm-module-datalayout"; } + + ::llvm::StringRef getDescription() const override { return "Attach a datalayout string as a module attribute"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("SetLLVMModuleDataLayoutPass"); + } + ::llvm::StringRef getName() const override { return "SetLLVMModuleDataLayoutPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(SetLLVMModuleDataLayoutPassBase) + +protected: + ::mlir::Pass::Option dataLayout{*this, "data-layout", ::llvm::cl::desc("String description (LLVM format) of the data layout that is expected on the produced module"), ::llvm::cl::init("")}; +}; + +template +class TosaToArithPassBase : public ::mlir::OperationPass<> { +public: + using Base = TosaToArithPassBase; + + TosaToArithPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + TosaToArithPassBase(const TosaToArithPassBase &other) : ::mlir::OperationPass<>(other) {} + TosaToArithPassBase& operator=(const TosaToArithPassBase &) = delete; + TosaToArithPassBase(TosaToArithPassBase &&) = delete; + TosaToArithPassBase& operator=(TosaToArithPassBase &&) = delete; + ~TosaToArithPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-arith"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-arith"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the Arith dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToArithPass"); + } + ::llvm::StringRef getName() const override { return "TosaToArithPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToArithPassBase) + +protected: + ::mlir::Pass::Option includeApplyRescale{*this, "include-apply-rescale", ::llvm::cl::desc("Whether to include the lowering for tosa.apply_rescale to arith"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option use32Bit{*this, "use-32-bit", ::llvm::cl::desc("Whether to prioritze lowering to 32-bit operations"), ::llvm::cl::init(false)}; +}; + +template +class TosaToLinalgBase : public ::mlir::InterfacePass { +public: + using Base = TosaToLinalgBase; + + TosaToLinalgBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + TosaToLinalgBase(const TosaToLinalgBase &other) : ::mlir::InterfacePass(other) {} + TosaToLinalgBase& operator=(const TosaToLinalgBase &) = delete; + TosaToLinalgBase(TosaToLinalgBase &&) = delete; + TosaToLinalgBase& operator=(TosaToLinalgBase &&) = delete; + ~TosaToLinalgBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-linalg"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-linalg"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to LinAlg on tensors"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToLinalg"); + } + ::llvm::StringRef getName() const override { return "TosaToLinalg"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToLinalgBase) + +protected: + ::mlir::Pass::Option disableTosaDecompositions{*this, "disable-tosa-decompositions", ::llvm::cl::desc("Disable tosa decompositions pass"), ::llvm::cl::init(false)}; + ::mlir::Pass::Option aggressiveReduceConstant{*this, "aggressive-reduce-constant", ::llvm::cl::desc("Always perform the reduce constant optimization"), ::llvm::cl::init(false)}; +}; + +template +class TosaToLinalgNamedBase : public ::mlir::InterfacePass { +public: + using Base = TosaToLinalgNamedBase; + + TosaToLinalgNamedBase() : ::mlir::InterfacePass(::mlir::TypeID::get()) {} + TosaToLinalgNamedBase(const TosaToLinalgNamedBase &other) : ::mlir::InterfacePass(other) {} + TosaToLinalgNamedBase& operator=(const TosaToLinalgNamedBase &) = delete; + TosaToLinalgNamedBase(TosaToLinalgNamedBase &&) = delete; + TosaToLinalgNamedBase& operator=(TosaToLinalgNamedBase &&) = delete; + ~TosaToLinalgNamedBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-linalg-named"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-linalg-named"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to LinAlg named operations"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToLinalgNamed"); + } + ::llvm::StringRef getName() const override { return "TosaToLinalgNamed"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToLinalgNamedBase) + +protected: + ::mlir::Pass::Option preferConv2DKernelLayoutHWCF{*this, "prefer-conv2d-kernel-layout-hwcf", ::llvm::cl::desc("Prefer generating linalg.conv_2d_nhwc_hwcf over linalg.conv_2d_nhwc_fhwc"), ::llvm::cl::init(false)}; +}; + +template +class TosaToMLProgramBase : public ::mlir::OperationPass { +public: + using Base = TosaToMLProgramBase; + + TosaToMLProgramBase() : ::mlir::OperationPass(::mlir::TypeID::get()) {} + TosaToMLProgramBase(const TosaToMLProgramBase &other) : ::mlir::OperationPass(other) {} + TosaToMLProgramBase& operator=(const TosaToMLProgramBase &) = delete; + TosaToMLProgramBase(TosaToMLProgramBase &&) = delete; + TosaToMLProgramBase& operator=(TosaToMLProgramBase &&) = delete; + ~TosaToMLProgramBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-mlprogram"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-mlprogram"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the MLProgram dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToMLProgram"); + } + ::llvm::StringRef getName() const override { return "TosaToMLProgram"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToMLProgramBase) + +protected: +}; + +template +class TosaToSCFPassBase : public ::mlir::OperationPass<> { +public: + using Base = TosaToSCFPassBase; + + TosaToSCFPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + TosaToSCFPassBase(const TosaToSCFPassBase &other) : ::mlir::OperationPass<>(other) {} + TosaToSCFPassBase& operator=(const TosaToSCFPassBase &) = delete; + TosaToSCFPassBase(TosaToSCFPassBase &&) = delete; + TosaToSCFPassBase& operator=(TosaToSCFPassBase &&) = delete; + ~TosaToSCFPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-scf"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-scf"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the SCF dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToSCFPass"); + } + ::llvm::StringRef getName() const override { return "TosaToSCFPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToSCFPassBase) + +protected: +}; + +template +class TosaToTensorPassBase : public ::mlir::OperationPass<> { +public: + using Base = TosaToTensorPassBase; + + TosaToTensorPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + TosaToTensorPassBase(const TosaToTensorPassBase &other) : ::mlir::OperationPass<>(other) {} + TosaToTensorPassBase& operator=(const TosaToTensorPassBase &) = delete; + TosaToTensorPassBase(TosaToTensorPassBase &&) = delete; + TosaToTensorPassBase& operator=(TosaToTensorPassBase &&) = delete; + ~TosaToTensorPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("tosa-to-tensor"); + } + ::llvm::StringRef getArgument() const override { return "tosa-to-tensor"; } + + ::llvm::StringRef getDescription() const override { return "Lower TOSA to the Tensor dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("TosaToTensorPass"); + } + ::llvm::StringRef getName() const override { return "TosaToTensorPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TosaToTensorPassBase) + +protected: +}; + +template +class UBToLLVMConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = UBToLLVMConversionPassBase; + + UBToLLVMConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + UBToLLVMConversionPassBase(const UBToLLVMConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + UBToLLVMConversionPassBase& operator=(const UBToLLVMConversionPassBase &) = delete; + UBToLLVMConversionPassBase(UBToLLVMConversionPassBase &&) = delete; + UBToLLVMConversionPassBase& operator=(UBToLLVMConversionPassBase &&) = delete; + ~UBToLLVMConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-ub-to-llvm"); + } + ::llvm::StringRef getArgument() const override { return "convert-ub-to-llvm"; } + + ::llvm::StringRef getDescription() const override { return "Convert UB dialect to LLVM dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("UBToLLVMConversionPass"); + } + ::llvm::StringRef getName() const override { return "UBToLLVMConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(UBToLLVMConversionPassBase) + +protected: + ::mlir::Pass::Option indexBitwidth{*this, "index-bitwidth", ::llvm::cl::desc("Bitwidth of the index type, 0 to use size of machine word"), ::llvm::cl::init(0)}; +}; + +template +class UBToSPIRVConversionPassBase : public ::mlir::OperationPass<> { +public: + using Base = UBToSPIRVConversionPassBase; + + UBToSPIRVConversionPassBase() : ::mlir::OperationPass<>(::mlir::TypeID::get()) {} + UBToSPIRVConversionPassBase(const UBToSPIRVConversionPassBase &other) : ::mlir::OperationPass<>(other) {} + UBToSPIRVConversionPassBase& operator=(const UBToSPIRVConversionPassBase &) = delete; + UBToSPIRVConversionPassBase(UBToSPIRVConversionPassBase &&) = delete; + UBToSPIRVConversionPassBase& operator=(UBToSPIRVConversionPassBase &&) = delete; + ~UBToSPIRVConversionPassBase() = default; + + /// Returns the command-line argument attached to this pass. + static constexpr ::llvm::StringLiteral getArgumentName() { + return ::llvm::StringLiteral("convert-ub-to-spirv"); + } + ::llvm::StringRef getArgument() const override { return "convert-ub-to-spirv"; } + + ::llvm::StringRef getDescription() const override { return "Convert UB dialect to SPIR-V dialect"; } + + /// Returns the derived pass name. + static constexpr ::llvm::StringLiteral getPassName() { + return ::llvm::StringLiteral("UBToSPIRVConversionPass"); + } + ::llvm::StringRef getName() const override { return "UBToSPIRVConversionPass"; } + + /// Support isa/dyn_cast functionality for the derived pass class. + static bool classof(const ::mlir::Pass *pass) { + return pass->getTypeID() == ::mlir::TypeID::get(); + } + + /// A clone method to create a copy of this pass. + std::unique_ptr<::mlir::Pass> clonePass() const override { + return std::make_unique(*static_cast(this)); + } + + /// Register the dialects that must be loaded in the context before this pass. + void getDependentDialects(::mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + /// Explicitly declare the TypeID for this class. We declare an explicit private + /// instantiation because Pass classes should only be visible by the current + /// library. + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(UBToSPIRVConversionPassBase) + +protected: +}; +#undef GEN_PASS_CLASSES +#endif // GEN_PASS_CLASSES diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h new file mode 100644 index 0000000000000000000000000000000000000000..01a6be8ea957c46be7ee634fd1b3ddb298ce87d8 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h @@ -0,0 +1,23 @@ +//===- ReconcileUnrealizedCasts.h - Pass entrypoint -------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_RECONCILEUNREALIZEDCASTS_RECONCILEUNREALIZEDCASTS_H_ +#define MLIR_CONVERSION_RECONCILEUNREALIZEDCASTS_RECONCILEUNREALIZEDCASTS_H_ + +#include + +namespace mlir { +class Pass; +class RewritePatternSet; + +#define GEN_PASS_DECL_RECONCILEUNREALIZEDCASTSPASS +#include "mlir/Conversion/Passes.h.inc" + +} // namespace mlir + +#endif // MLIR_CONVERSION_RECONCILEUNREALIZEDCASTS_RECONCILEUNREALIZEDCASTS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h new file mode 100644 index 0000000000000000000000000000000000000000..2def01d208f728470946249ec48c23f8ca346fcf --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h @@ -0,0 +1,27 @@ +//===- SCFToControlFlow.h - SCF to ControlFlow Pass entrypoint --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_SCFTOCONTROLFLOW_SCFTOCONTROLFLOW_H_ +#define MLIR_CONVERSION_SCFTOCONTROLFLOW_SCFTOCONTROLFLOW_H_ + +#include + +namespace mlir { +class Pass; +class RewritePatternSet; + +#define GEN_PASS_DECL_SCFTOCONTROLFLOWPASS +#include "mlir/Conversion/Passes.h.inc" + +/// Collect a set of patterns to convert SCF operations to CFG branch-based +/// operations within the ControlFlow dialect. +void populateSCFToControlFlowConversionPatterns(RewritePatternSet &patterns); + +} // namespace mlir + +#endif // MLIR_CONVERSION_SCFTOCONTROLFLOW_SCFTOCONTROLFLOW_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h new file mode 100644 index 0000000000000000000000000000000000000000..f6b09deb4e44c3cc1bee25363bbea9b78974815e --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h @@ -0,0 +1,33 @@ +//===- ConvertVectorToLLVM.h - Utils to convert from the vector dialect ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_VECTORTOLLVM_CONVERTVECTORTOLLVM_H_ +#define MLIR_CONVERSION_VECTORTOLLVM_CONVERTVECTORTOLLVM_H_ + +#include "mlir/Transforms/DialectConversion.h" + +namespace mlir { +class LLVMTypeConverter; + +/// Collect a set of patterns to convert from Vector contractions to LLVM Matrix +/// Intrinsics. To lower to assembly, the LLVM flag -lower-matrix-intrinsics +/// will be needed when invoking LLVM. +void populateVectorToLLVMMatrixConversionPatterns( + const LLVMTypeConverter &converter, RewritePatternSet &patterns); + +/// Collect a set of patterns to convert from the Vector dialect to LLVM. +void populateVectorToLLVMConversionPatterns( + const LLVMTypeConverter &converter, RewritePatternSet &patterns, + bool reassociateFPReductions = false, bool force32BitVectorIndices = false, + bool useVectorAlignment = false); + +namespace vector { +void registerConvertVectorToLLVMInterface(DialectRegistry ®istry); +} +} // namespace mlir + +#endif // MLIR_CONVERSION_VECTORTOLLVM_CONVERTVECTORTOLLVM_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVMPass.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVMPass.h new file mode 100644 index 0000000000000000000000000000000000000000..410b881db79590c0547d57b96d709c4bb8654305 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToLLVM/ConvertVectorToLLVMPass.h @@ -0,0 +1,20 @@ +//===- ConvertVectorToLLVMPass.h - Pass to check Vector->LLVM --- --===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +#ifndef MLIR_CONVERSION_VECTORTOLLVM_CONVERTVECTORTOLLVMPASS_H_ +#define MLIR_CONVERSION_VECTORTOLLVM_CONVERTVECTORTOLLVMPASS_H_ + +#include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" +#include "mlir/Dialect/Vector/Transforms/VectorTransforms.h" + +namespace mlir { +class Pass; + +#define GEN_PASS_DECL_CONVERTVECTORTOLLVMPASS +#include "mlir/Conversion/Passes.h.inc" +} // namespace mlir +#endif // MLIR_CONVERSION_VECTORTOLLVM_CONVERTVECTORTOLLVMPASS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToSCF/VectorToSCF.h b/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToSCF/VectorToSCF.h new file mode 100644 index 0000000000000000000000000000000000000000..e0ef67c39a1013bff0f7be2b3fdf66d3a16d7870 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Conversion/VectorToSCF/VectorToSCF.h @@ -0,0 +1,93 @@ +//===- VectorToSCF.h - Convert vector to SCF dialect ------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_CONVERSION_VECTORTOSCF_VECTORTOSCF_H_ +#define MLIR_CONVERSION_VECTORTOSCF_VECTORTOSCF_H_ + +#include "mlir/IR/PatternMatch.h" + +namespace mlir { +class MLIRContext; +class Pass; +class RewritePatternSet; + +#define GEN_PASS_DECL_CONVERTVECTORTOSCF +#include "mlir/Conversion/Passes.h.inc" + +/// When lowering an N-d vector transfer op to an (N-1)-d vector transfer op, +/// a temporary buffer is created through which individual (N-1)-d vector are +/// staged. This pattern can be applied multiple time, until the transfer op +/// is 1-d. +/// This is consistent with the lack of an LLVM instruction to dynamically +/// index into an aggregate (see the Vector dialect lowering to LLVM deep dive). +/// +/// An instruction such as: +/// ``` +/// vector.transfer_write %vec, %A[%a, %b, %c] : +/// vector<9x17x15xf32>, memref +/// ``` +/// Lowers to pseudo-IR resembling (unpacking one dimension): +/// ``` +/// %0 = alloca() : memref> +/// store %vec, %0[] : memref> +/// %1 = vector.type_cast %0 : +/// memref> to memref<9xvector<17x15xf32>> +/// affine.for %I = 0 to 9 { +/// %dim = dim %A, 0 : memref +/// %add = affine.apply %I + %a +/// %cmp = arith.cmpi "slt", %add, %dim : index +/// scf.if %cmp { +/// %vec_2d = load %1[%I] : memref<9xvector<17x15xf32>> +/// vector.transfer_write %vec_2d, %A[%add, %b, %c] : +/// vector<17x15xf32>, memref +/// ``` +/// +/// When applying the pattern a second time, the existing alloca() operation +/// is reused and only a second vector.type_cast is added. +struct VectorTransferToSCFOptions { + /// Minimal rank to which vector transfer are lowered. + unsigned targetRank = 1; + VectorTransferToSCFOptions &setTargetRank(unsigned r) { + targetRank = r; + return *this; + } + /// Allows vector transfers that operated on tensors to be lowered (this is an + /// uncommon alternative). + bool lowerTensors = false; + VectorTransferToSCFOptions &enableLowerTensors(bool l = true) { + lowerTensors = l; + return *this; + } + /// Triggers full unrolling (vs iterating with a loop) during transfer to scf. + bool unroll = false; + VectorTransferToSCFOptions &enableFullUnroll(bool u = true) { + unroll = u; + return *this; + } + /// Enable scalable vector specific lowerings (which introduce loops). These + /// work alongside fullUnroll (which unrolls until the first scalable + /// dimension). + bool lowerScalable = false; + VectorTransferToSCFOptions enableLowerScalable(bool enable = true) { + lowerScalable = enable; + return *this; + } +}; + +/// Collect a set of patterns to convert from the Vector dialect to SCF + func. +void populateVectorToSCFConversionPatterns( + RewritePatternSet &patterns, + const VectorTransferToSCFOptions &options = VectorTransferToSCFOptions()); + +/// Create a pass to convert a subset of vector ops to SCF. +std::unique_ptr createConvertVectorToSCFPass( + const VectorTransferToSCFOptions &options = VectorTransferToSCFOptions()); + +} // namespace mlir + +#endif // MLIR_CONVERSION_VECTORTOSCF_VECTORTOSCF_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/ScalableValueBoundsConstraintSet.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/ScalableValueBoundsConstraintSet.h new file mode 100644 index 0000000000000000000000000000000000000000..93b3c92533c54f8cd32eeaaf6298c04ab41e48d6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/ScalableValueBoundsConstraintSet.h @@ -0,0 +1,108 @@ +//===- ScalableValueBoundsConstraintSet.h - Scalable Value Bounds ---------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_IR_SCALABLEVALUEBOUNDSCONSTRAINTSET_H +#define MLIR_DIALECT_VECTOR_IR_SCALABLEVALUEBOUNDSCONSTRAINTSET_H + +#include "mlir/Analysis/Presburger/IntegerRelation.h" +#include "mlir/Dialect/Vector/IR/VectorOps.h" +#include "mlir/Interfaces/ValueBoundsOpInterface.h" + +namespace mlir::vector { + +namespace detail { + +/// Parent class for the value bounds RTTIExtends. Uses protected inheritance to +/// hide all ValueBoundsConstraintSet methods by default (as some do not use the +/// ScalableValueBoundsConstraintSet, so may produce unexpected results). +struct ValueBoundsConstraintSet : protected ::mlir::ValueBoundsConstraintSet { + using ::mlir::ValueBoundsConstraintSet::ValueBoundsConstraintSet; +}; +} // namespace detail + +/// A version of `ValueBoundsConstraintSet` that can solve for scalable bounds. +struct ScalableValueBoundsConstraintSet + : public llvm::RTTIExtends { + ScalableValueBoundsConstraintSet( + MLIRContext *context, + ValueBoundsConstraintSet::StopConditionFn stopCondition, + unsigned vscaleMin, unsigned vscaleMax) + : RTTIExtends(context, stopCondition, + /*addConservativeSemiAffineBounds=*/true), + vscaleMin(vscaleMin), vscaleMax(vscaleMax) {}; + + using RTTIExtends::bound; + using RTTIExtends::StopConditionFn; + + /// A thin wrapper over an `AffineMap` which can represent a constant bound, + /// or a scalable bound (in terms of vscale). The `AffineMap` will always + /// take at most one parameter, vscale, and returns a single result, which is + /// the bound of value. + struct ConstantOrScalableBound { + AffineMap map; + + struct BoundSize { + int64_t baseSize{0}; + bool scalable{false}; + }; + + /// Get the (possibly) scalable size of the bound, returns failure if + /// the bound cannot be represented as a single quantity. + FailureOr getSize() const; + }; + + /// Computes a (possibly) scalable bound for a given value. This is + /// similar to `ValueBoundsConstraintSet::computeConstantBound()`, but + /// uses knowledge of the range of vscale to compute either a constant + /// bound, an expression in terms of vscale, or failure if no bound can + /// be computed. + /// + /// The resulting `AffineMap` will always take at most one parameter, + /// vscale, and return a single result, which is the bound of `value`. + /// + /// Note: `vscaleMin` must be `<=` to `vscaleMax`. If `vscaleMin` == + /// `vscaleMax`, the resulting bound (if found), will be constant. + static FailureOr + computeScalableBound(Value value, std::optional dim, + unsigned vscaleMin, unsigned vscaleMax, + presburger::BoundType boundType, bool closedUB = true, + StopConditionFn stopCondition = nullptr); + + /// Get the value of vscale. Returns `nullptr` vscale as not been encountered. + Value getVscaleValue() const { return vscale; } + + /// Sets the value of vscale. Asserts if vscale has already been set. + void setVscale(vector::VectorScaleOp vscaleOp) { + assert(!vscale && "expected vscale to be unset"); + vscale = vscaleOp.getResult(); + } + + /// The minimum possible value of vscale. + unsigned getVscaleMin() const { return vscaleMin; } + + /// The maximum possible value of vscale. + unsigned getVscaleMax() const { return vscaleMax; } + + static char ID; + +private: + const unsigned vscaleMin; + const unsigned vscaleMax; + + // This will be set when the first `vector.vscale` operation is found within + // the `ValueBoundsOpInterface` implementation then reused from there on. + Value vscale = nullptr; +}; + +using ConstantOrScalableBound = + ScalableValueBoundsConstraintSet::ConstantOrScalableBound; + +} // namespace mlir::vector + +#endif // MLIR_DIALECT_VECTOR_IR_SCALABLEVALUEBOUNDSCONSTRAINTSET_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/ValueBoundsOpInterfaceImpl.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/ValueBoundsOpInterfaceImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..4794bc9016c6f949190bea39386a8c3f24b5f2fb --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/ValueBoundsOpInterfaceImpl.h @@ -0,0 +1,20 @@ +//===- ValueBoundsOpInterfaceImpl.h - Impl. of ValueBoundsOpInterface -----===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_IR_VALUEBOUNDSOPINTERFACEIMPL_H +#define MLIR_DIALECT_VECTOR_IR_VALUEBOUNDSOPINTERFACEIMPL_H + +namespace mlir { +class DialectRegistry; + +namespace vector { +void registerValueBoundsOpInterfaceExternalModels(DialectRegistry ®istry); +} // namespace vector +} // namespace mlir + +#endif // MLIR_DIALECT_VECTOR_IR_VALUEBOUNDSOPINTERFACEIMPL_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..530eccb405e370a24c60873fbec7a775302940a0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorAttributes.cpp.inc @@ -0,0 +1,315 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_LIST +#undef GET_ATTRDEF_LIST + +::mlir::vector::CombiningKindAttr, +::mlir::vector::IteratorTypeAttr, +::mlir::vector::PrintPunctuationAttr + +#endif // GET_ATTRDEF_LIST + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + +static ::mlir::OptionalParseResult generatedAttributeParser(::mlir::AsmParser &parser, ::llvm::StringRef *mnemonic, ::mlir::Type type, ::mlir::Attribute &value) { + return ::mlir::AsmParser::KeywordSwitch<::mlir::OptionalParseResult>(parser) + .Case(::mlir::vector::CombiningKindAttr::getMnemonic(), [&](llvm::StringRef, llvm::SMLoc) { + value = ::mlir::vector::CombiningKindAttr::parse(parser, type); + return ::mlir::success(!!value); + }) + .Case(::mlir::vector::IteratorTypeAttr::getMnemonic(), [&](llvm::StringRef, llvm::SMLoc) { + value = ::mlir::vector::IteratorTypeAttr::parse(parser, type); + return ::mlir::success(!!value); + }) + .Case(::mlir::vector::PrintPunctuationAttr::getMnemonic(), [&](llvm::StringRef, llvm::SMLoc) { + value = ::mlir::vector::PrintPunctuationAttr::parse(parser, type); + return ::mlir::success(!!value); + }) + .Default([&](llvm::StringRef keyword, llvm::SMLoc) { + *mnemonic = keyword; + return std::nullopt; + }); +} + +static ::llvm::LogicalResult generatedAttributePrinter(::mlir::Attribute def, ::mlir::AsmPrinter &printer) { + return ::llvm::TypeSwitch<::mlir::Attribute, ::llvm::LogicalResult>(def) .Case<::mlir::vector::CombiningKindAttr>([&](auto t) { + printer << ::mlir::vector::CombiningKindAttr::getMnemonic(); +t.print(printer); + return ::mlir::success(); + }) + .Case<::mlir::vector::IteratorTypeAttr>([&](auto t) { + printer << ::mlir::vector::IteratorTypeAttr::getMnemonic(); +t.print(printer); + return ::mlir::success(); + }) + .Case<::mlir::vector::PrintPunctuationAttr>([&](auto t) { + printer << ::mlir::vector::PrintPunctuationAttr::getMnemonic(); +t.print(printer); + return ::mlir::success(); + }) + .Default([](auto) { return ::mlir::failure(); }); +} + +namespace mlir { +namespace vector { +namespace detail { +struct CombiningKindAttrStorage : public ::mlir::AttributeStorage { + using KeyTy = std::tuple<::mlir::vector::CombiningKind>; + CombiningKindAttrStorage(::mlir::vector::CombiningKind value) : value(std::move(value)) {} + + KeyTy getAsKey() const { + return KeyTy(value); + } + + bool operator==(const KeyTy &tblgenKey) const { + return (value == std::get<0>(tblgenKey)); + } + + static ::llvm::hash_code hashKey(const KeyTy &tblgenKey) { + return ::llvm::hash_combine(std::get<0>(tblgenKey)); + } + + static CombiningKindAttrStorage *construct(::mlir::AttributeStorageAllocator &allocator, KeyTy &&tblgenKey) { + auto value = std::move(std::get<0>(tblgenKey)); + return new (allocator.allocate()) CombiningKindAttrStorage(std::move(value)); + } + + ::mlir::vector::CombiningKind value; +}; +} // namespace detail +CombiningKindAttr CombiningKindAttr::get(::mlir::MLIRContext *context, ::mlir::vector::CombiningKind value) { + return Base::get(context, std::move(value)); +} + +::mlir::Attribute CombiningKindAttr::parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType) { + ::mlir::Builder odsBuilder(odsParser.getContext()); + ::llvm::SMLoc odsLoc = odsParser.getCurrentLocation(); + (void) odsLoc; + ::mlir::FailureOr<::mlir::vector::CombiningKind> _result_value; + // Parse literal '<' + if (odsParser.parseLess()) return {}; + + // Parse variable 'value' + _result_value = [&]() -> ::mlir::FailureOr<::mlir::vector::CombiningKind> { + auto loc = odsParser.getCurrentLocation(); + ::llvm::StringRef enumKeyword; + if (::mlir::failed(odsParser.parseKeyword(&enumKeyword))) + return ::mlir::failure(); + auto maybeEnum = ::mlir::vector::symbolizeCombiningKind(enumKeyword); + if (maybeEnum) + return *maybeEnum; + return {(::llvm::LogicalResult)(odsParser.emitError(loc) << "expected " << "::mlir::vector::CombiningKind" << " to be one of: " << "add" << ", " << "mul" << ", " << "minui" << ", " << "minsi" << ", " << "minnumf" << ", " << "maxui" << ", " << "maxsi" << ", " << "maxnumf" << ", " << "and" << ", " << "or" << ", " << "xor" << ", " << "maximumf" << ", " << "minimumf")}; + }(); + if (::mlir::failed(_result_value)) { + odsParser.emitError(odsParser.getCurrentLocation(), "failed to parse Vector_CombiningKindAttr parameter 'value' which is to be a `::mlir::vector::CombiningKind`"); + return {}; + } + // Parse literal '>' + if (odsParser.parseGreater()) return {}; + assert(::mlir::succeeded(_result_value)); + return CombiningKindAttr::get(odsParser.getContext(), + ::mlir::vector::CombiningKind((*_result_value))); +} + +void CombiningKindAttr::print(::mlir::AsmPrinter &odsPrinter) const { + ::mlir::Builder odsBuilder(getContext()); + odsPrinter << "<"; + odsPrinter << stringifyCombiningKind(getValue()); + odsPrinter << ">"; +} + +::mlir::vector::CombiningKind CombiningKindAttr::getValue() const { + return getImpl()->value; +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::CombiningKindAttr) +namespace mlir { +namespace vector { +namespace detail { +struct IteratorTypeAttrStorage : public ::mlir::AttributeStorage { + using KeyTy = std::tuple<::mlir::vector::IteratorType>; + IteratorTypeAttrStorage(::mlir::vector::IteratorType value) : value(std::move(value)) {} + + KeyTy getAsKey() const { + return KeyTy(value); + } + + bool operator==(const KeyTy &tblgenKey) const { + return (value == std::get<0>(tblgenKey)); + } + + static ::llvm::hash_code hashKey(const KeyTy &tblgenKey) { + return ::llvm::hash_combine(std::get<0>(tblgenKey)); + } + + static IteratorTypeAttrStorage *construct(::mlir::AttributeStorageAllocator &allocator, KeyTy &&tblgenKey) { + auto value = std::move(std::get<0>(tblgenKey)); + return new (allocator.allocate()) IteratorTypeAttrStorage(std::move(value)); + } + + ::mlir::vector::IteratorType value; +}; +} // namespace detail +IteratorTypeAttr IteratorTypeAttr::get(::mlir::MLIRContext *context, ::mlir::vector::IteratorType value) { + return Base::get(context, std::move(value)); +} + +::mlir::Attribute IteratorTypeAttr::parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType) { + ::mlir::Builder odsBuilder(odsParser.getContext()); + ::llvm::SMLoc odsLoc = odsParser.getCurrentLocation(); + (void) odsLoc; + ::mlir::FailureOr<::mlir::vector::IteratorType> _result_value; + // Parse literal '<' + if (odsParser.parseLess()) return {}; + + // Parse variable 'value' + _result_value = [&]() -> ::mlir::FailureOr<::mlir::vector::IteratorType> { + auto loc = odsParser.getCurrentLocation(); + ::llvm::StringRef enumKeyword; + if (::mlir::failed(odsParser.parseKeyword(&enumKeyword))) + return ::mlir::failure(); + auto maybeEnum = ::mlir::vector::symbolizeIteratorType(enumKeyword); + if (maybeEnum) + return *maybeEnum; + return {(::llvm::LogicalResult)(odsParser.emitError(loc) << "expected " << "::mlir::vector::IteratorType" << " to be one of: " << "parallel" << ", " << "reduction")}; + }(); + if (::mlir::failed(_result_value)) { + odsParser.emitError(odsParser.getCurrentLocation(), "failed to parse Vector_IteratorTypeEnum parameter 'value' which is to be a `::mlir::vector::IteratorType`"); + return {}; + } + // Parse literal '>' + if (odsParser.parseGreater()) return {}; + assert(::mlir::succeeded(_result_value)); + return IteratorTypeAttr::get(odsParser.getContext(), + ::mlir::vector::IteratorType((*_result_value))); +} + +void IteratorTypeAttr::print(::mlir::AsmPrinter &odsPrinter) const { + ::mlir::Builder odsBuilder(getContext()); + odsPrinter << "<"; + odsPrinter << stringifyIteratorType(getValue()); + odsPrinter << ">"; +} + +::mlir::vector::IteratorType IteratorTypeAttr::getValue() const { + return getImpl()->value; +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::IteratorTypeAttr) +namespace mlir { +namespace vector { +namespace detail { +struct PrintPunctuationAttrStorage : public ::mlir::AttributeStorage { + using KeyTy = std::tuple<::mlir::vector::PrintPunctuation>; + PrintPunctuationAttrStorage(::mlir::vector::PrintPunctuation value) : value(std::move(value)) {} + + KeyTy getAsKey() const { + return KeyTy(value); + } + + bool operator==(const KeyTy &tblgenKey) const { + return (value == std::get<0>(tblgenKey)); + } + + static ::llvm::hash_code hashKey(const KeyTy &tblgenKey) { + return ::llvm::hash_combine(std::get<0>(tblgenKey)); + } + + static PrintPunctuationAttrStorage *construct(::mlir::AttributeStorageAllocator &allocator, KeyTy &&tblgenKey) { + auto value = std::move(std::get<0>(tblgenKey)); + return new (allocator.allocate()) PrintPunctuationAttrStorage(std::move(value)); + } + + ::mlir::vector::PrintPunctuation value; +}; +} // namespace detail +PrintPunctuationAttr PrintPunctuationAttr::get(::mlir::MLIRContext *context, ::mlir::vector::PrintPunctuation value) { + return Base::get(context, std::move(value)); +} + +::mlir::Attribute PrintPunctuationAttr::parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType) { + ::mlir::Builder odsBuilder(odsParser.getContext()); + ::llvm::SMLoc odsLoc = odsParser.getCurrentLocation(); + (void) odsLoc; + ::mlir::FailureOr<::mlir::vector::PrintPunctuation> _result_value; + // Parse literal '<' + if (odsParser.parseLess()) return {}; + + // Parse variable 'value' + _result_value = [&]() -> ::mlir::FailureOr<::mlir::vector::PrintPunctuation> { + auto loc = odsParser.getCurrentLocation(); + ::llvm::StringRef enumKeyword; + if (::mlir::failed(odsParser.parseKeyword(&enumKeyword))) + return ::mlir::failure(); + auto maybeEnum = ::mlir::vector::symbolizePrintPunctuation(enumKeyword); + if (maybeEnum) + return *maybeEnum; + return {(::llvm::LogicalResult)(odsParser.emitError(loc) << "expected " << "::mlir::vector::PrintPunctuation" << " to be one of: " << "no_punctuation" << ", " << "newline" << ", " << "comma" << ", " << "open" << ", " << "close")}; + }(); + if (::mlir::failed(_result_value)) { + odsParser.emitError(odsParser.getCurrentLocation(), "failed to parse Vector_PrintPunctuation parameter 'value' which is to be a `::mlir::vector::PrintPunctuation`"); + return {}; + } + // Parse literal '>' + if (odsParser.parseGreater()) return {}; + assert(::mlir::succeeded(_result_value)); + return PrintPunctuationAttr::get(odsParser.getContext(), + ::mlir::vector::PrintPunctuation((*_result_value))); +} + +void PrintPunctuationAttr::print(::mlir::AsmPrinter &odsPrinter) const { + ::mlir::Builder odsBuilder(getContext()); + odsPrinter << "<"; + odsPrinter << stringifyPrintPunctuation(getValue()); + odsPrinter << ">"; +} + +::mlir::vector::PrintPunctuation PrintPunctuationAttr::getValue() const { + return getImpl()->value; +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::PrintPunctuationAttr) +namespace mlir { +namespace vector { + +/// Parse an attribute registered to this dialect. +::mlir::Attribute VectorDialect::parseAttribute(::mlir::DialectAsmParser &parser, + ::mlir::Type type) const { + ::llvm::SMLoc typeLoc = parser.getCurrentLocation(); + ::llvm::StringRef attrTag; + { + ::mlir::Attribute attr; + auto parseResult = generatedAttributeParser(parser, &attrTag, type, attr); + if (parseResult.has_value()) + return attr; + } + + parser.emitError(typeLoc) << "unknown attribute `" + << attrTag << "` in dialect `" << getNamespace() << "`"; + return {}; +} +/// Print an attribute registered to this dialect. +void VectorDialect::printAttribute(::mlir::Attribute attr, + ::mlir::DialectAsmPrinter &printer) const { + if (::mlir::succeeded(generatedAttributePrinter(attr, printer))) + return; + +} +} // namespace vector +} // namespace mlir + +#endif // GET_ATTRDEF_CLASSES + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorAttributes.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorAttributes.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..8957dab455ecc863bb09229f53140c13659bc1f6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorAttributes.h.inc @@ -0,0 +1,83 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* AttrDef Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_ATTRDEF_CLASSES +#undef GET_ATTRDEF_CLASSES + + +namespace mlir { +class AsmParser; +class AsmPrinter; +} // namespace mlir +namespace mlir { +namespace vector { +/// Kind of combining function for contractions and reductions +class CombiningKindAttr; +/// Iterator type +class IteratorTypeAttr; +/// Punctuation for separating vectors or vector elements +class PrintPunctuationAttr; +namespace detail { +struct CombiningKindAttrStorage; +} // namespace detail +class CombiningKindAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral name = "vector.kind"; + static constexpr ::llvm::StringLiteral dialectName = "vector"; + static CombiningKindAttr get(::mlir::MLIRContext *context, ::mlir::vector::CombiningKind value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"kind"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::vector::CombiningKind getValue() const; +}; +namespace detail { +struct IteratorTypeAttrStorage; +} // namespace detail +class IteratorTypeAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral name = "vector.iterator_type"; + static constexpr ::llvm::StringLiteral dialectName = "vector"; + static IteratorTypeAttr get(::mlir::MLIRContext *context, ::mlir::vector::IteratorType value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"iterator_type"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::vector::IteratorType getValue() const; +}; +namespace detail { +struct PrintPunctuationAttrStorage; +} // namespace detail +class PrintPunctuationAttr : public ::mlir::Attribute::AttrBase { +public: + using Base::Base; + static constexpr ::llvm::StringLiteral name = "vector.punctuation"; + static constexpr ::llvm::StringLiteral dialectName = "vector"; + static PrintPunctuationAttr get(::mlir::MLIRContext *context, ::mlir::vector::PrintPunctuation value); + static constexpr ::llvm::StringLiteral getMnemonic() { + return {"punctuation"}; + } + + static ::mlir::Attribute parse(::mlir::AsmParser &odsParser, ::mlir::Type odsType); + void print(::mlir::AsmPrinter &odsPrinter) const; + ::mlir::vector::PrintPunctuation getValue() const; +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::CombiningKindAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::IteratorTypeAttr) +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::PrintPunctuationAttr) + +#endif // GET_ATTRDEF_CLASSES + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorDialect.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorDialect.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..5cdc66822aa83dadb251c2ce42ee3208151bde49 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorDialect.cpp.inc @@ -0,0 +1,25 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: Vector.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::VectorDialect) +namespace mlir { +namespace vector { + +VectorDialect::VectorDialect(::mlir::MLIRContext *context) + : ::mlir::Dialect(getDialectNamespace(), context, ::mlir::TypeID::get()) + + { + getContext()->loadDialect(); + initialize(); +} + +VectorDialect::~VectorDialect() = default; + +} // namespace vector +} // namespace mlir diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorDialect.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorDialect.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..76a11bebfc2919873ab8d97a6d0eac42a6c71c8e --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorDialect.h.inc @@ -0,0 +1,42 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Dialect Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: Vector.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { + + +class VectorDialect : public ::mlir::Dialect { + explicit VectorDialect(::mlir::MLIRContext *context); + + void initialize(); + friend class ::mlir::MLIRContext; +public: + ~VectorDialect() override; + static constexpr ::llvm::StringLiteral getDialectNamespace() { + return ::llvm::StringLiteral("vector"); + } + + /// Parse an attribute registered to this dialect. + ::mlir::Attribute parseAttribute(::mlir::DialectAsmParser &parser, + ::mlir::Type type) const override; + + /// Print an attribute registered to this dialect. + void printAttribute(::mlir::Attribute attr, + ::mlir::DialectAsmPrinter &os) const override; + + /// Materialize a single constant operation from a given attribute value with + /// the desired resultant type. + ::mlir::Operation *materializeConstant(::mlir::OpBuilder &builder, + ::mlir::Attribute value, + ::mlir::Type type, + ::mlir::Location loc) override; +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::VectorDialect) diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorEnums.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorEnums.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..89af6d744d5de8369e33e007e787f6a90ab50bab --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorEnums.cpp.inc @@ -0,0 +1,132 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: VectorAttributes.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { +::llvm::StringRef stringifyCombiningKind(CombiningKind val) { + switch (val) { + case CombiningKind::ADD: return "add"; + case CombiningKind::MUL: return "mul"; + case CombiningKind::MINUI: return "minui"; + case CombiningKind::MINSI: return "minsi"; + case CombiningKind::MINNUMF: return "minnumf"; + case CombiningKind::MAXUI: return "maxui"; + case CombiningKind::MAXSI: return "maxsi"; + case CombiningKind::MAXNUMF: return "maxnumf"; + case CombiningKind::AND: return "and"; + case CombiningKind::OR: return "or"; + case CombiningKind::XOR: return "xor"; + case CombiningKind::MAXIMUMF: return "maximumf"; + case CombiningKind::MINIMUMF: return "minimumf"; + } + return ""; +} + +::std::optional symbolizeCombiningKind(::llvm::StringRef str) { + return ::llvm::StringSwitch<::std::optional>(str) + .Case("add", CombiningKind::ADD) + .Case("mul", CombiningKind::MUL) + .Case("minui", CombiningKind::MINUI) + .Case("minsi", CombiningKind::MINSI) + .Case("minnumf", CombiningKind::MINNUMF) + .Case("maxui", CombiningKind::MAXUI) + .Case("maxsi", CombiningKind::MAXSI) + .Case("maxnumf", CombiningKind::MAXNUMF) + .Case("and", CombiningKind::AND) + .Case("or", CombiningKind::OR) + .Case("xor", CombiningKind::XOR) + .Case("maximumf", CombiningKind::MAXIMUMF) + .Case("minimumf", CombiningKind::MINIMUMF) + .Default(::std::nullopt); +} +::std::optional symbolizeCombiningKind(uint32_t value) { + switch (value) { + case 0: return CombiningKind::ADD; + case 1: return CombiningKind::MUL; + case 2: return CombiningKind::MINUI; + case 3: return CombiningKind::MINSI; + case 4: return CombiningKind::MINNUMF; + case 5: return CombiningKind::MAXUI; + case 6: return CombiningKind::MAXSI; + case 7: return CombiningKind::MAXNUMF; + case 8: return CombiningKind::AND; + case 9: return CombiningKind::OR; + case 10: return CombiningKind::XOR; + case 12: return CombiningKind::MAXIMUMF; + case 11: return CombiningKind::MINIMUMF; + default: return ::std::nullopt; + } +} + +} // namespace vector +} // namespace mlir + +namespace mlir { +namespace vector { +::llvm::StringRef stringifyPrintPunctuation(PrintPunctuation val) { + switch (val) { + case PrintPunctuation::NoPunctuation: return "no_punctuation"; + case PrintPunctuation::NewLine: return "newline"; + case PrintPunctuation::Comma: return "comma"; + case PrintPunctuation::Open: return "open"; + case PrintPunctuation::Close: return "close"; + } + return ""; +} + +::std::optional symbolizePrintPunctuation(::llvm::StringRef str) { + return ::llvm::StringSwitch<::std::optional>(str) + .Case("no_punctuation", PrintPunctuation::NoPunctuation) + .Case("newline", PrintPunctuation::NewLine) + .Case("comma", PrintPunctuation::Comma) + .Case("open", PrintPunctuation::Open) + .Case("close", PrintPunctuation::Close) + .Default(::std::nullopt); +} +::std::optional symbolizePrintPunctuation(uint32_t value) { + switch (value) { + case 0: return PrintPunctuation::NoPunctuation; + case 1: return PrintPunctuation::NewLine; + case 2: return PrintPunctuation::Comma; + case 3: return PrintPunctuation::Open; + case 4: return PrintPunctuation::Close; + default: return ::std::nullopt; + } +} + +} // namespace vector +} // namespace mlir + +namespace mlir { +namespace vector { +::llvm::StringRef stringifyIteratorType(IteratorType val) { + switch (val) { + case IteratorType::parallel: return "parallel"; + case IteratorType::reduction: return "reduction"; + } + return ""; +} + +::std::optional symbolizeIteratorType(::llvm::StringRef str) { + return ::llvm::StringSwitch<::std::optional>(str) + .Case("parallel", IteratorType::parallel) + .Case("reduction", IteratorType::reduction) + .Default(::std::nullopt); +} +::std::optional symbolizeIteratorType(uint32_t value) { + switch (value) { + case 0: return IteratorType::parallel; + case 1: return IteratorType::reduction; + default: return ::std::nullopt; + } +} + +} // namespace vector +} // namespace mlir + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorEnums.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorEnums.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..b1e76189f0d78a89833b5f9b5ae820100664e36f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorEnums.h.inc @@ -0,0 +1,329 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: VectorAttributes.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { +// Kind of combining function for contractions and reductions +enum class CombiningKind : uint32_t { + ADD = 0, + MUL = 1, + MINUI = 2, + MINSI = 3, + MINNUMF = 4, + MAXUI = 5, + MAXSI = 6, + MAXNUMF = 7, + AND = 8, + OR = 9, + XOR = 10, + MAXIMUMF = 12, + MINIMUMF = 11, +}; + +::std::optional symbolizeCombiningKind(uint32_t); +::llvm::StringRef stringifyCombiningKind(CombiningKind); +::std::optional symbolizeCombiningKind(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForCombiningKind() { + return 12; +} + + +inline ::llvm::StringRef stringifyEnum(CombiningKind enumValue) { + return stringifyCombiningKind(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeCombiningKind(str); +} +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::CombiningKind, ::mlir::vector::CombiningKind> { + template + static FailureOr<::mlir::vector::CombiningKind> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Kind of combining function for contractions and reductions"); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::CombiningKind> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::CombiningKind>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [add, mul, minui, minsi, minnumf, maxui, maxsi, maxnumf, and, or, xor, maximumf, minimumf] for Kind of combining function for contractions and reductions, got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::CombiningKind>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::CombiningKind>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::CombiningKind> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::CombiningKind>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [add, mul, minui, minsi, minnumf, maxui, maxsi, maxnumf, and, or, xor, maximumf, minimumf] for Kind of combining function for contractions and reductions, got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::CombiningKind value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::CombiningKind> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::CombiningKind getEmptyKey() { + return static_cast<::mlir::vector::CombiningKind>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::CombiningKind getTombstoneKey() { + return static_cast<::mlir::vector::CombiningKind>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::CombiningKind &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::CombiningKind &lhs, const ::mlir::vector::CombiningKind &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace vector { +// Punctuation for separating vectors or vector elements +enum class PrintPunctuation : uint32_t { + NoPunctuation = 0, + NewLine = 1, + Comma = 2, + Open = 3, + Close = 4, +}; + +::std::optional symbolizePrintPunctuation(uint32_t); +::llvm::StringRef stringifyPrintPunctuation(PrintPunctuation); +::std::optional symbolizePrintPunctuation(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForPrintPunctuation() { + return 4; +} + + +inline ::llvm::StringRef stringifyEnum(PrintPunctuation enumValue) { + return stringifyPrintPunctuation(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizePrintPunctuation(str); +} +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::PrintPunctuation, ::mlir::vector::PrintPunctuation> { + template + static FailureOr<::mlir::vector::PrintPunctuation> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Punctuation for separating vectors or vector elements"); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::PrintPunctuation> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::PrintPunctuation>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [no_punctuation, newline, comma, open, close] for Punctuation for separating vectors or vector elements, got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::PrintPunctuation>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::PrintPunctuation>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::PrintPunctuation> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::PrintPunctuation>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [no_punctuation, newline, comma, open, close] for Punctuation for separating vectors or vector elements, got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::PrintPunctuation value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::PrintPunctuation> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::PrintPunctuation getEmptyKey() { + return static_cast<::mlir::vector::PrintPunctuation>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::PrintPunctuation getTombstoneKey() { + return static_cast<::mlir::vector::PrintPunctuation>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::PrintPunctuation &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::PrintPunctuation &lhs, const ::mlir::vector::PrintPunctuation &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace vector { +// Iterator type +enum class IteratorType : uint32_t { + parallel = 0, + reduction = 1, +}; + +::std::optional symbolizeIteratorType(uint32_t); +::llvm::StringRef stringifyIteratorType(IteratorType); +::std::optional symbolizeIteratorType(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForIteratorType() { + return 1; +} + + +inline ::llvm::StringRef stringifyEnum(IteratorType enumValue) { + return stringifyIteratorType(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeIteratorType(str); +} +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::IteratorType, ::mlir::vector::IteratorType> { + template + static FailureOr<::mlir::vector::IteratorType> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for Iterator type"); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::IteratorType> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::IteratorType>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [parallel, reduction] for Iterator type, got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::IteratorType>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::IteratorType>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::IteratorType> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::IteratorType>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [parallel, reduction] for Iterator type, got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::IteratorType value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::IteratorType> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::IteratorType getEmptyKey() { + return static_cast<::mlir::vector::IteratorType>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::IteratorType getTombstoneKey() { + return static_cast<::mlir::vector::IteratorType>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::IteratorType &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::IteratorType &lhs, const ::mlir::vector::IteratorType &rhs) { + return lhs == rhs; + } +}; +} + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..9d60212377ead3a5e24180c4ae8e7ee29017f437 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.cpp.inc @@ -0,0 +1,14679 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: VectorOps.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifdef GET_OP_LIST +#undef GET_OP_LIST + +::mlir::vector::VectorScaleOp, +::mlir::vector::BitCastOp, +::mlir::vector::BroadcastOp, +::mlir::vector::CompressStoreOp, +::mlir::vector::ConstantMaskOp, +::mlir::vector::ContractionOp, +::mlir::vector::CreateMaskOp, +::mlir::vector::DeinterleaveOp, +::mlir::vector::ExpandLoadOp, +::mlir::vector::ExtractElementOp, +::mlir::vector::ExtractOp, +::mlir::vector::ExtractStridedSliceOp, +::mlir::vector::FMAOp, +::mlir::vector::FlatTransposeOp, +::mlir::vector::FromElementsOp, +::mlir::vector::GatherOp, +::mlir::vector::InsertElementOp, +::mlir::vector::InsertOp, +::mlir::vector::InsertStridedSliceOp, +::mlir::vector::InterleaveOp, +::mlir::vector::LoadOp, +::mlir::vector::MaskOp, +::mlir::vector::MaskedLoadOp, +::mlir::vector::MaskedStoreOp, +::mlir::vector::MatmulOp, +::mlir::vector::MultiDimReductionOp, +::mlir::vector::OuterProductOp, +::mlir::vector::PrintOp, +::mlir::vector::ReductionOp, +::mlir::vector::ScalableExtractOp, +::mlir::vector::ScalableInsertOp, +::mlir::vector::ScanOp, +::mlir::vector::ScatterOp, +::mlir::vector::ShapeCastOp, +::mlir::vector::ShuffleOp, +::mlir::vector::SplatOp, +::mlir::vector::StepOp, +::mlir::vector::StoreOp, +::mlir::vector::TransferReadOp, +::mlir::vector::TransferWriteOp, +::mlir::vector::TransposeOp, +::mlir::vector::TypeCastOp, +::mlir::vector::YieldOp +#endif // GET_OP_LIST + +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + + +//===----------------------------------------------------------------------===// +// Local Utility Method Definitions +//===----------------------------------------------------------------------===// + +namespace mlir { +namespace vector { + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps1( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((::llvm::isa<::mlir::IndexType>(type)))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be index, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps2( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps3( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((true))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be any type, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps4( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::MemRefType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be memref of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps5( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((::llvm::isa<::mlir::IndexType>(type)))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be variadic of index, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps6( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::FixedVectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ([](::mlir::Type elementType) { return (elementType.isSignlessInteger(1)); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be fixed-length vector of 1-bit signless integer values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps7( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps8( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (elementType.isSignlessInteger(1)); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of 1-bit signless integer values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps9( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((type.isSignlessIntOrIndex()))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be signless integer or index, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps10( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (::llvm::isa<::mlir::FloatType>(elementType)); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of floating-point values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps11( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::FixedVectorType>(type))) && ([](::mlir::Type elementType) { return ((elementType.isSignlessInteger())) || ((elementType.isSignedInteger())) || ((::llvm::isa<::mlir::IndexType>(elementType))) || ((::llvm::isa<::mlir::FloatType>(elementType))); }(::llvm::cast<::mlir::ShapedType>(type).getElementType()))) && ((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() + == 1))))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be fixed-length vector of signless integer or signed integer or index or floating-point values of ranks 1, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps12( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((true))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be variadic of any type, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps13( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::FixedVectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be fixed-length vector of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps14( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::TensorType>(type))) || ((::llvm::isa<::mlir::MemRefType>(type)))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be Tensor or MemRef of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps15( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ([](::mlir::Type elementType) { return ((::llvm::isa<::mlir::IntegerType>(elementType))) || ((::llvm::isa<::mlir::IndexType>(elementType))); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of integer or index values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps16( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ([](::mlir::Type elementType) { return (elementType.isSignlessInteger(1)); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of 1-bit signless integer values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps17( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType()))) || ((::llvm::isa<::mlir::IntegerType>(type))) || ((::llvm::isa<::mlir::IndexType>(type))) || ((::llvm::isa<::mlir::FloatType>(type))))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be , but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps18( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::ScalableVectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() + == 1)))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be of ranks 1, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps19( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() + == 1)))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be of ranks 1, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps20( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((type.isSignlessInteger())) || ((::llvm::isa<::mlir::IndexType>(type))) || ((::llvm::isa<::mlir::FloatType>(type))))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be integer/index/float type, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps21( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ([](::mlir::Type elementType) { return (::llvm::isa<::mlir::IndexType>(elementType)); }(::llvm::cast<::mlir::ShapedType>(type).getElementType()))) && ((((::llvm::isa<::mlir::VectorType>(type))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() > 0))) && ((::llvm::cast<::mlir::VectorType>(type).getRank() + == 1))))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be vector of index values of ranks 1, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps22( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::ShapedType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be shaped of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps23( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!(((::llvm::isa<::mlir::RankedTensorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be ranked tensor of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_type_constraint_VectorOps24( + ::mlir::Operation *op, ::mlir::Type type, ::llvm::StringRef valueKind, + unsigned valueIndex) { + if (!((((::llvm::isa<::mlir::MemRefType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType()))) && ((::llvm::cast<::mlir::ShapedType>(type).hasStaticShape())))) { + return op->emitOpError(valueKind) << " #" << valueIndex + << " must be statically shaped memref of any type values, but got " << type; + } + return ::mlir::success(); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps1( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: i64 dense array attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps1( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps1(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps2( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::ArrayAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: array attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps2( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps2(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps3( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !(((::llvm::isa<::mlir::ArrayAttr>(attr))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(attr), [&](::mlir::Attribute attr) { return attr && ((::llvm::isa<::mlir::vector::IteratorTypeAttr>(attr))); })))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: Iterator type should be an enum."; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps3( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps3(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps4( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::vector::CombiningKindAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: Kind of combining function for contractions and reductions"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps4( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps4(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps5( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !(((::llvm::isa<::mlir::ArrayAttr>(attr))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(attr), [&](::mlir::Attribute attr) { return attr && (((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64)))); })))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: 64-bit integer array attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps5( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps5(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps6( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !(((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(32))))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: 32-bit signless integer attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps6( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps6(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps7( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::BoolAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: bool attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps7( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps7(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps8( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::vector::PrintPunctuationAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: Punctuation for separating vectors or vector elements"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps8( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps8(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps9( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::StringAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: An Attribute containing a string"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps9( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps9(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps10( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::arith::FastMathFlagsAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: Floating point fast math flags"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps10( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps10(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps11( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !(((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64))))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: 64-bit signless integer attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps11( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps11(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps12( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !((::llvm::isa<::mlir::AffineMapAttr>(attr)))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: AffineMap attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps12( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps12(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps13( + ::mlir::Attribute attr, ::llvm::StringRef attrName, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + if (attr && !(((::llvm::isa<::mlir::ArrayAttr>(attr))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(attr), [&](::mlir::Attribute attr) { return attr && ((::llvm::isa<::mlir::BoolAttr>(attr))); })))) + return emitError() << "attribute '" << attrName + << "' failed to satisfy constraint: 1-bit boolean array attribute"; + return ::mlir::success(); +} +static ::llvm::LogicalResult __mlir_ods_local_attr_constraint_VectorOps13( + ::mlir::Operation *op, ::mlir::Attribute attr, ::llvm::StringRef attrName) { + return __mlir_ods_local_attr_constraint_VectorOps13(attr, attrName, [op]() { + return op->emitOpError(); + }); +} + +static ::llvm::LogicalResult __mlir_ods_local_region_constraint_VectorOps1( + ::mlir::Operation *op, ::mlir::Region ®ion, ::llvm::StringRef regionName, + unsigned regionIndex) { + if (!((::llvm::hasNItems(region, 1)))) { + return op->emitOpError("region #") << regionIndex + << (regionName.empty() ? " " : " ('" + regionName + "') ") + << "failed to verify constraint: region with 1 blocks"; + } + return ::mlir::success(); +} +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::VectorScaleOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +VectorScaleOpGenericAdaptorBase::VectorScaleOpGenericAdaptorBase(VectorScaleOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +VectorScaleOpAdaptor::VectorScaleOpAdaptor(VectorScaleOp op) : VectorScaleOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult VectorScaleOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult VectorScaleOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute VectorScaleOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code VectorScaleOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional VectorScaleOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void VectorScaleOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void VectorScaleOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult VectorScaleOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void VectorScaleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res) { + odsState.addTypes(res); +} + +void VectorScaleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState) { + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(VectorScaleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void VectorScaleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes) { + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void VectorScaleOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void VectorScaleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(VectorScaleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void VectorScaleOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void VectorScaleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(VectorScaleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult VectorScaleOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps1(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult VectorScaleOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::llvm::LogicalResult VectorScaleOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + ::mlir::Type odsInferredType0 = odsBuilder.getIndexType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult VectorScaleOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(odsBuildableType0); + return ::mlir::success(); +} + +void VectorScaleOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); +} + +void VectorScaleOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +void VectorScaleOp::getAsmResultNames( + ::llvm::function_ref setNameFn) { + setNameFn(getResult(), "vscale"); +} +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::VectorScaleOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::BitCastOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +BitCastOpGenericAdaptorBase::BitCastOpGenericAdaptorBase(BitCastOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +BitCastOpAdaptor::BitCastOpAdaptor(BitCastOp op) : BitCastOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult BitCastOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult BitCastOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute BitCastOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code BitCastOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional BitCastOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void BitCastOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void BitCastOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult BitCastOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void BitCastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value source) { + odsState.addOperands(source); + odsState.addTypes(result); +} + +void BitCastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source) { + odsState.addOperands(source); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void BitCastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void BitCastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult BitCastOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!(((::llvm::cast<::mlir::ShapedType>((*this->getODSOperands(0).begin()).getType()).getRank()) == (::llvm::cast<::mlir::ShapedType>((*this->getODSResults(0).begin()).getType()).getRank()) && (::llvm::cast<::mlir::ShapedType>((*this->getODSResults(0).begin()).getType()).getRank()) == (::llvm::cast<::mlir::ShapedType>((*this->getODSOperands(0).begin()).getType()).getRank())))) + return emitOpError("failed to verify that all of {source, result} have same rank"); + return ::mlir::success(); +} + +::llvm::LogicalResult BitCastOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult BitCastOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + result.addTypes(resultTypes); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void BitCastOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getSource(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void BitCastOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::BitCastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::BroadcastOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +BroadcastOpGenericAdaptorBase::BroadcastOpGenericAdaptorBase(BroadcastOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +BroadcastOpAdaptor::BroadcastOpAdaptor(BroadcastOp op) : BroadcastOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult BroadcastOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult BroadcastOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute BroadcastOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code BroadcastOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional BroadcastOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void BroadcastOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void BroadcastOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult BroadcastOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void BroadcastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value source) { + odsState.addOperands(source); + odsState.addTypes(vector); +} + +void BroadcastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source) { + odsState.addOperands(source); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void BroadcastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void BroadcastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult BroadcastOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that source operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult BroadcastOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult BroadcastOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + ::mlir::Type vectorRawType{}; + ::llvm::ArrayRef<::mlir::Type> vectorTypes(&vectorRawType, 1); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::Type type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + vectorRawType = type; + } + result.addTypes(vectorTypes); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void BroadcastOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getSource(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::Type>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + { + auto type = getVector().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void BroadcastOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::BroadcastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::CompressStoreOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +CompressStoreOpGenericAdaptorBase::CompressStoreOpGenericAdaptorBase(CompressStoreOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair CompressStoreOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +CompressStoreOpAdaptor::CompressStoreOpAdaptor(CompressStoreOp op) : CompressStoreOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult CompressStoreOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair CompressStoreOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange CompressStoreOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult CompressStoreOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute CompressStoreOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code CompressStoreOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional CompressStoreOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void CompressStoreOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void CompressStoreOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult CompressStoreOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void CompressStoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(valueToStore); +} + +void CompressStoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(valueToStore); + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void CompressStoreOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void CompressStoreOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult CompressStoreOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps6(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult CompressStoreOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult CompressStoreOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand maskRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> maskOperands(&maskRawOperand, 1); ::llvm::SMLoc maskOperandsLoc; + (void)maskOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type maskRawType{}; + ::llvm::ArrayRef<::mlir::Type> maskTypes(&maskRawType, 1); + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + maskOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(maskRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + maskRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(maskOperands, maskTypes, maskOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void CompressStoreOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getMask(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getMask().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void CompressStoreOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Write::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::CompressStoreOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ConstantMaskOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ConstantMaskOpGenericAdaptorBase::ConstantMaskOpGenericAdaptorBase(ConstantMaskOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::llvm::ArrayRef ConstantMaskOpGenericAdaptorBase::getMaskDimSizes() { + auto attr = getMaskDimSizesAttr(); + return attr; +} + +} // namespace detail +ConstantMaskOpAdaptor::ConstantMaskOpAdaptor(ConstantMaskOp op) : ConstantMaskOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ConstantMaskOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_mask_dim_sizes = getProperties().mask_dim_sizes; (void)tblgen_mask_dim_sizes; + if (!tblgen_mask_dim_sizes) return emitError(loc, "'vector.constant_mask' op ""requires attribute 'mask_dim_sizes'"); + + if (tblgen_mask_dim_sizes && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(tblgen_mask_dim_sizes)))) + return emitError(loc, "'vector.constant_mask' op ""attribute 'mask_dim_sizes' failed to satisfy constraint: i64 dense array attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult ConstantMaskOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.mask_dim_sizes; + auto attr = dict.get("mask_dim_sizes"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `mask_dim_sizes` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ConstantMaskOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.mask_dim_sizes; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("mask_dim_sizes", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ConstantMaskOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.mask_dim_sizes.getAsOpaquePointer())); +} + +std::optional ConstantMaskOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "mask_dim_sizes") + return prop.mask_dim_sizes; + return std::nullopt; +} + +void ConstantMaskOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "mask_dim_sizes") { + prop.mask_dim_sizes = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ConstantMaskOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.mask_dim_sizes) attrs.append("mask_dim_sizes", prop.mask_dim_sizes); +} + +::llvm::LogicalResult ConstantMaskOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getMaskDimSizesAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(attr, "mask_dim_sizes", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ConstantMaskOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.mask_dim_sizes))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ConstantMaskOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.mask_dim_sizes); +} + +::llvm::ArrayRef ConstantMaskOp::getMaskDimSizes() { + auto attr = getMaskDimSizesAttr(); + return attr; +} + +void ConstantMaskOp::setMaskDimSizes(::llvm::ArrayRef attrValue) { + getProperties().mask_dim_sizes = ::mlir::Builder((*this)->getContext()).getDenseI64ArrayAttr(attrValue); +} + +void ConstantMaskOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::DenseI64ArrayAttr mask_dim_sizes) { + odsState.getOrAddProperties().mask_dim_sizes = mask_dim_sizes; + odsState.addTypes(resultType0); +} + +void ConstantMaskOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::DenseI64ArrayAttr mask_dim_sizes) { + odsState.getOrAddProperties().mask_dim_sizes = mask_dim_sizes; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ConstantMaskOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::llvm::ArrayRef mask_dim_sizes) { + odsState.getOrAddProperties().mask_dim_sizes = odsBuilder.getDenseI64ArrayAttr(mask_dim_sizes); + odsState.addTypes(resultType0); +} + +void ConstantMaskOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::llvm::ArrayRef mask_dim_sizes) { + odsState.getOrAddProperties().mask_dim_sizes = odsBuilder.getDenseI64ArrayAttr(mask_dim_sizes); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ConstantMaskOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ConstantMaskOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult ConstantMaskOp::verifyInvariantsImpl() { + auto tblgen_mask_dim_sizes = getProperties().mask_dim_sizes; (void)tblgen_mask_dim_sizes; + if (!tblgen_mask_dim_sizes) return emitOpError("requires attribute 'mask_dim_sizes'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(*this, tblgen_mask_dim_sizes, "mask_dim_sizes"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps8(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult ConstantMaskOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ConstantMaskOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::DenseI64ArrayAttr mask_dim_sizesAttr; + ::llvm::SmallVector<::mlir::Type, 1> allResultTypes; + + if (parser.parseCustomAttributeWithFallback(mask_dim_sizesAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (mask_dim_sizesAttr) result.getOrAddProperties().mask_dim_sizes = mask_dim_sizesAttr; + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + if (parser.parseTypeList(allResultTypes)) + return ::mlir::failure(); + result.addTypes(allResultTypes); + return ::mlir::success(); +} + +void ConstantMaskOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getMaskDimSizesAttr()); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("mask_dim_sizes"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << getOperation()->getResultTypes(); +} + +void ConstantMaskOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ConstantMaskOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ContractionOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ContractionOpGenericAdaptorBase::ContractionOpGenericAdaptorBase(ContractionOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::mlir::ArrayAttr ContractionOpGenericAdaptorBase::getIndexingMaps() { + auto attr = getIndexingMapsAttr(); + return attr; +} + +::mlir::ArrayAttr ContractionOpGenericAdaptorBase::getIteratorTypes() { + auto attr = getIteratorTypesAttr(); + return attr; +} + +::mlir::vector::CombiningKindAttr ContractionOpGenericAdaptorBase::getKindAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::vector::CombiningKindAttr>(getProperties().kind); + return attr; +} + +::mlir::vector::CombiningKind ContractionOpGenericAdaptorBase::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +} // namespace detail +ContractionOpAdaptor::ContractionOpAdaptor(ContractionOp op) : ContractionOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ContractionOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_indexing_maps = getProperties().indexing_maps; (void)tblgen_indexing_maps; + if (!tblgen_indexing_maps) return emitError(loc, "'vector.contract' op ""requires attribute 'indexing_maps'"); + auto tblgen_iterator_types = getProperties().iterator_types; (void)tblgen_iterator_types; + if (!tblgen_iterator_types) return emitError(loc, "'vector.contract' op ""requires attribute 'iterator_types'"); + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + + if (tblgen_indexing_maps && !((::llvm::isa<::mlir::ArrayAttr>(tblgen_indexing_maps)))) + return emitError(loc, "'vector.contract' op ""attribute 'indexing_maps' failed to satisfy constraint: array attribute"); + + if (tblgen_iterator_types && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_iterator_types))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_iterator_types), [&](::mlir::Attribute attr) { return attr && ((::llvm::isa<::mlir::vector::IteratorTypeAttr>(attr))); })))) + return emitError(loc, "'vector.contract' op ""attribute 'iterator_types' failed to satisfy constraint: Iterator type should be an enum."); + + if (tblgen_kind && !((::llvm::isa<::mlir::vector::CombiningKindAttr>(tblgen_kind)))) + return emitError(loc, "'vector.contract' op ""attribute 'kind' failed to satisfy constraint: Kind of combining function for contractions and reductions"); + return ::mlir::success(); +} + +::llvm::LogicalResult ContractionOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.indexing_maps; + auto attr = dict.get("indexing_maps"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `indexing_maps` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.iterator_types; + auto attr = dict.get("iterator_types"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `iterator_types` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.kind; + auto attr = dict.get("kind"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `kind` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ContractionOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.indexing_maps; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("indexing_maps", + propStorage)); + } + + { + const auto &propStorage = prop.iterator_types; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("iterator_types", + propStorage)); + } + + { + const auto &propStorage = prop.kind; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("kind", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ContractionOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.indexing_maps.getAsOpaquePointer()), + llvm::hash_value(prop.iterator_types.getAsOpaquePointer()), + llvm::hash_value(prop.kind.getAsOpaquePointer())); +} + +std::optional ContractionOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "indexing_maps") + return prop.indexing_maps; + + if (name == "iterator_types") + return prop.iterator_types; + + if (name == "kind") + return prop.kind; + return std::nullopt; +} + +void ContractionOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "indexing_maps") { + prop.indexing_maps = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "iterator_types") { + prop.iterator_types = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "kind") { + prop.kind = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ContractionOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.indexing_maps) attrs.append("indexing_maps", prop.indexing_maps); + + if (prop.iterator_types) attrs.append("iterator_types", prop.iterator_types); + + if (prop.kind) attrs.append("kind", prop.kind); +} + +::llvm::LogicalResult ContractionOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getIndexingMapsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps2(attr, "indexing_maps", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getIteratorTypesAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps3(attr, "iterator_types", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getKindAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(attr, "kind", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ContractionOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.indexing_maps))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.iterator_types))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readOptionalAttribute(prop.kind))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ContractionOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.indexing_maps); + writer.writeAttribute(prop.iterator_types); + + writer.writeOptionalAttribute(prop.kind); +} + +::mlir::ArrayAttr ContractionOp::getIndexingMaps() { + auto attr = getIndexingMapsAttr(); + return attr; +} + +::mlir::ArrayAttr ContractionOp::getIteratorTypes() { + auto attr = getIteratorTypesAttr(); + return attr; +} + +::mlir::vector::CombiningKind ContractionOp::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +void ContractionOp::setKind(::mlir::vector::CombiningKind attrValue) { + getProperties().kind = ::mlir::vector::CombiningKindAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void ContractionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKindAttr kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + odsState.getOrAddProperties().indexing_maps = indexing_maps; + odsState.getOrAddProperties().iterator_types = iterator_types; + if (kind) { + odsState.getOrAddProperties().kind = kind; + } + odsState.addTypes(resultType0); +} + +void ContractionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKindAttr kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + odsState.getOrAddProperties().indexing_maps = indexing_maps; + odsState.getOrAddProperties().iterator_types = iterator_types; + if (kind) { + odsState.getOrAddProperties().kind = kind; + } + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ContractionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKind kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + odsState.getOrAddProperties().indexing_maps = indexing_maps; + odsState.getOrAddProperties().iterator_types = iterator_types; + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.addTypes(resultType0); +} + +void ContractionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKind kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + odsState.getOrAddProperties().indexing_maps = indexing_maps; + odsState.getOrAddProperties().iterator_types = iterator_types; + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ContractionOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ContractionOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ContractionOp::populateDefaultProperties(::mlir::OperationName opName, Properties &properties) { + ::mlir::Builder odsBuilder(opName.getContext()); + if (!properties.kind) + properties.kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), CombiningKind::ADD); +} + +::llvm::LogicalResult ContractionOp::verifyInvariantsImpl() { + auto tblgen_indexing_maps = getProperties().indexing_maps; (void)tblgen_indexing_maps; + if (!tblgen_indexing_maps) return emitOpError("requires attribute 'indexing_maps'"); + auto tblgen_iterator_types = getProperties().iterator_types; (void)tblgen_iterator_types; + if (!tblgen_iterator_types) return emitOpError("requires attribute 'iterator_types'"); + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps2(*this, tblgen_indexing_maps, "indexing_maps"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps3(*this, tblgen_iterator_types, "iterator_types"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(*this, tblgen_kind, "kind"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((((*this->getOperation()).getNumOperands() > 1)) && ((::llvm::isa<::mlir::ShapedType>((*this->getOperation()).getOperand(0).getType()))) && ((::llvm::isa<::mlir::ShapedType>((*this->getOperation()).getOperand(1).getType()))) && ((::mlir::getElementTypeOrSelf((*this->getOperation()).getOperand(0)) == ::mlir::getElementTypeOrSelf((*this->getOperation()).getOperand(1)))))) + return emitOpError("failed to verify that lhs and rhs have same element type"); + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(2))))) + return emitOpError("failed to verify that third operand acc and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult ContractionOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +void ContractionOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ContractionOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::CreateMaskOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +CreateMaskOpGenericAdaptorBase::CreateMaskOpGenericAdaptorBase(CreateMaskOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair CreateMaskOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +CreateMaskOpAdaptor::CreateMaskOpAdaptor(CreateMaskOp op) : CreateMaskOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult CreateMaskOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair CreateMaskOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange CreateMaskOp::getOperandsMutable() { + auto range = getODSOperandIndexAndLength(0); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult CreateMaskOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute CreateMaskOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code CreateMaskOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional CreateMaskOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void CreateMaskOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void CreateMaskOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult CreateMaskOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void CreateMaskOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange operands) { + odsState.addOperands(operands); + odsState.addTypes(resultType0); +} + +void CreateMaskOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void CreateMaskOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult CreateMaskOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps8(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult CreateMaskOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult CreateMaskOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> operandsOperands; + ::llvm::SMLoc operandsOperandsLoc; + (void)operandsOperandsLoc; + ::llvm::SmallVector<::mlir::Type, 1> allResultTypes; + + operandsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(operandsOperands)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + if (parser.parseTypeList(allResultTypes)) + return ::mlir::failure(); + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(allResultTypes); + if (parser.resolveOperands(operandsOperands, odsBuildableType0, operandsOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void CreateMaskOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getOperands(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << getOperation()->getResultTypes(); +} + +void CreateMaskOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::CreateMaskOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::DeinterleaveOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +DeinterleaveOpGenericAdaptorBase::DeinterleaveOpGenericAdaptorBase(DeinterleaveOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +DeinterleaveOpAdaptor::DeinterleaveOpAdaptor(DeinterleaveOp op) : DeinterleaveOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult DeinterleaveOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +void DeinterleaveOp::getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn) { + auto resultGroup0 = getODSResults(0); + if (!resultGroup0.empty()) + setNameFn(*resultGroup0.begin(), "res1"); + auto resultGroup1 = getODSResults(1); + if (!resultGroup1.empty()) + setNameFn(*resultGroup1.begin(), "res2"); +} + +::llvm::LogicalResult DeinterleaveOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute DeinterleaveOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code DeinterleaveOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional DeinterleaveOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void DeinterleaveOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void DeinterleaveOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult DeinterleaveOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void DeinterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res1, ::mlir::Type res2, ::mlir::Value source) { + odsState.addOperands(source); + odsState.addTypes(res1); + odsState.addTypes(res2); +} + +void DeinterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source) { + odsState.addOperands(source); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(DeinterleaveOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void DeinterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source) { + odsState.addOperands(source); + assert(resultTypes.size() == 2u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void DeinterleaveOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void DeinterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(DeinterleaveOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void DeinterleaveOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void DeinterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(DeinterleaveOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult DeinterleaveOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSResults(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!(( + [&](){ + auto srcVec = getSourceVectorType(); + return srcVec.getDimSize(srcVec.getRank() - 1) % 2 == 0; + }() + ))) + return emitOpError("failed to verify that the trailing dimension of the source vector has an even number of elements"); + if (!((std::equal_to<>()( + [&]() -> ::mlir::VectorType { + auto vectorType = ::llvm::cast((*this->getODSOperands(0).begin()).getType()); + ::mlir::VectorType::Builder builder(vectorType); + auto lastDim = vectorType.getRank() - 1; + auto newDimSize = vectorType.getDimSize(lastDim) / 2;; + if (newDimSize <= 0) + return vectorType; // (invalid input type) + return builder.setDim(lastDim, newDimSize); + }() + , (*this->getODSResults(0).begin()).getType())))) + return emitOpError("failed to verify that the trailing dimension of the results is half the width of source trailing dimension"); + if (!((((*this->getODSResults(0).begin()).getType()) == ((*this->getODSResults(1).begin()).getType()) && ((*this->getODSResults(1).begin()).getType()) == ((*this->getODSResults(0).begin()).getType())))) + return emitOpError("failed to verify that all of {res1, res2} have same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult DeinterleaveOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::llvm::LogicalResult DeinterleaveOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(2); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 0) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = + [&]() -> ::mlir::VectorType { + auto vectorType = ::llvm::cast(operands[0].getType()); + ::mlir::VectorType::Builder builder(vectorType); + auto lastDim = vectorType.getRank() - 1; + auto newDimSize = vectorType.getDimSize(lastDim) / 2;; + if (newDimSize <= 0) + return vectorType; // (invalid input type) + return builder.setDim(lastDim, newDimSize); + }() + ; + ::mlir::Type odsInferredType1 = odsInferredType0; + inferredReturnTypes[0] = odsInferredType0; + inferredReturnTypes[1] = odsInferredType1; + return ::mlir::success(); +} + +::mlir::ParseResult DeinterleaveOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + ::mlir::Type res1RawType{}; + ::llvm::ArrayRef<::mlir::Type> res1Types(&res1RawType, 1); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + if (parser.parseArrow()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + res1RawType = type; + } + result.addTypes(res1Types); + result.addTypes(res1Types[0]); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void DeinterleaveOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getSource(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "->"; + _odsPrinter << ' '; + { + auto type = getRes1().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void DeinterleaveOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::DeinterleaveOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExpandLoadOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ExpandLoadOpGenericAdaptorBase::ExpandLoadOpGenericAdaptorBase(ExpandLoadOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair ExpandLoadOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +ExpandLoadOpAdaptor::ExpandLoadOpAdaptor(ExpandLoadOp op) : ExpandLoadOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ExpandLoadOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair ExpandLoadOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange ExpandLoadOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult ExpandLoadOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute ExpandLoadOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ExpandLoadOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional ExpandLoadOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void ExpandLoadOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void ExpandLoadOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult ExpandLoadOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void ExpandLoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(pass_thru); + odsState.addTypes(result); +} + +void ExpandLoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(pass_thru); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ExpandLoadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ExpandLoadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult ExpandLoadOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps6(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult ExpandLoadOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ExpandLoadOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand maskRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> maskOperands(&maskRawOperand, 1); ::llvm::SMLoc maskOperandsLoc; + (void)maskOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand pass_thruRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> pass_thruOperands(&pass_thruRawOperand, 1); ::llvm::SMLoc pass_thruOperandsLoc; + (void)pass_thruOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type maskRawType{}; + ::llvm::ArrayRef<::mlir::Type> maskTypes(&maskRawType, 1); + ::mlir::Type pass_thruRawType{}; + ::llvm::ArrayRef<::mlir::Type> pass_thruTypes(&pass_thruRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + maskOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(maskRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + pass_thruOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(pass_thruRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + maskRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + pass_thruRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(resultTypes); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(maskOperands, maskTypes, maskOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(pass_thruOperands, pass_thruTypes, pass_thruOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ExpandLoadOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getMask(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getPassThru(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getMask().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getPassThru().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ExpandLoadOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Read::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ExpandLoadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExtractElementOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ExtractElementOpGenericAdaptorBase::ExtractElementOpGenericAdaptorBase(ExtractElementOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair ExtractElementOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +ExtractElementOpAdaptor::ExtractElementOpAdaptor(ExtractElementOp op) : ExtractElementOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ExtractElementOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair ExtractElementOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange ExtractElementOp::getPositionMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult ExtractElementOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute ExtractElementOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ExtractElementOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional ExtractElementOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void ExtractElementOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void ExtractElementOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult ExtractElementOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void ExtractElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, /*optional*/::mlir::Value position) { + odsState.addOperands(vector); + if (position) + odsState.addOperands(position); + odsState.addTypes(result); +} + +void ExtractElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value vector, /*optional*/::mlir::Value position) { + odsState.addOperands(vector); + if (position) + odsState.addOperands(position); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractElementOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ExtractElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, /*optional*/::mlir::Value position) { + odsState.addOperands(vector); + if (position) + odsState.addOperands(position); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ExtractElementOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ExtractElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractElementOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void ExtractElementOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ExtractElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractElementOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult ExtractElementOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + if (valueGroup1.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup1.size(); + } + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps9(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((std::equal_to<>()(::llvm::cast((*this->getODSOperands(0).begin()).getType()).getElementType(), (*this->getODSResults(0).begin()).getType())))) + return emitOpError("failed to verify that result type matches element type of vector operand"); + return ::mlir::success(); +} + +::llvm::LogicalResult ExtractElementOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::llvm::LogicalResult ExtractElementOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 0) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = ::llvm::cast(operands[0].getType()).getElementType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult ExtractElementOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand vectorRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> vectorOperands(&vectorRawOperand, 1); ::llvm::SMLoc vectorOperandsLoc; + (void)vectorOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> positionOperands; + ::llvm::SMLoc positionOperandsLoc; + (void)positionOperandsLoc; + ::llvm::SmallVector<::mlir::Type, 1> positionTypes; + ::mlir::Type vectorRawType{}; + ::llvm::ArrayRef<::mlir::Type> vectorTypes(&vectorRawType, 1); + + vectorOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(vectorRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + { + positionOperandsLoc = parser.getCurrentLocation(); + ::mlir::OpAsmParser::UnresolvedOperand operand; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalOperand(operand); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + positionOperands.push_back(operand); + } + } + if (!positionOperands.empty()) { + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::Type optionalType; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalType(optionalType); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + positionTypes.push_back(optionalType); + } + } + } + if (parser.parseRSquare()) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + vectorRawType = type; + } + for (::mlir::Type type : vectorTypes) { + (void)type; + if (!(((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return parser.emitError(parser.getNameLoc()) << "'vector' must be vector of any type values, but got " << type; + } + } + result.addTypes(::llvm::cast(vectorTypes[0]).getElementType()); + if (parser.resolveOperands(vectorOperands, vectorTypes, vectorOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(positionOperands, positionTypes, positionOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ExtractElementOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getVector(); + _odsPrinter << "["; + if (getPosition()) { + if (::mlir::Value value = getPosition()) + _odsPrinter << value; + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << (getPosition() ? ::llvm::ArrayRef<::mlir::Type>(getPosition().getType()) : ::llvm::ArrayRef<::mlir::Type>()); + } + _odsPrinter << "]"; + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getVector().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ExtractElementOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ExtractElementOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExtractOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ExtractOpGenericAdaptorBase::ExtractOpGenericAdaptorBase(ExtractOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair ExtractOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::llvm::ArrayRef ExtractOpGenericAdaptorBase::getStaticPosition() { + auto attr = getStaticPositionAttr(); + return attr; +} + +} // namespace detail +ExtractOpAdaptor::ExtractOpAdaptor(ExtractOp op) : ExtractOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ExtractOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_static_position = getProperties().static_position; (void)tblgen_static_position; + if (!tblgen_static_position) return emitError(loc, "'vector.extract' op ""requires attribute 'static_position'"); + + if (tblgen_static_position && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(tblgen_static_position)))) + return emitError(loc, "'vector.extract' op ""attribute 'static_position' failed to satisfy constraint: i64 dense array attribute"); + return ::mlir::success(); +} + +std::pair ExtractOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange ExtractOp::getDynamicPositionMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult ExtractOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.static_position; + auto attr = dict.get("static_position"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `static_position` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ExtractOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.static_position; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("static_position", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ExtractOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.static_position.getAsOpaquePointer())); +} + +std::optional ExtractOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "static_position") + return prop.static_position; + return std::nullopt; +} + +void ExtractOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "static_position") { + prop.static_position = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ExtractOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.static_position) attrs.append("static_position", prop.static_position); +} + +::llvm::LogicalResult ExtractOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getStaticPositionAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(attr, "static_position", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ExtractOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.static_position))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ExtractOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.static_position); +} + +::llvm::ArrayRef ExtractOp::getStaticPosition() { + auto attr = getStaticPositionAttr(); + return attr; +} + +void ExtractOp::setStaticPosition(::llvm::ArrayRef attrValue) { + getProperties().static_position = ::mlir::Builder((*this)->getContext()).getDenseI64ArrayAttr(attrValue); +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position) { + odsState.addOperands(vector); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = static_position; + odsState.addTypes(result); +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position) { + odsState.addOperands(vector); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = static_position; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position) { + odsState.addOperands(vector); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = static_position; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position) { + odsState.addOperands(vector); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = odsBuilder.getDenseI64ArrayAttr(static_position); + odsState.addTypes(result); +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position) { + odsState.addOperands(vector); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = odsBuilder.getDenseI64ArrayAttr(static_position); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position) { + odsState.addOperands(vector); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = odsBuilder.getDenseI64ArrayAttr(static_position); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ExtractOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void ExtractOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ExtractOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult ExtractOp::verifyInvariantsImpl() { + auto tblgen_static_position = getProperties().static_position; (void)tblgen_static_position; + if (!tblgen_static_position) return emitOpError("requires attribute 'static_position'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(*this, tblgen_static_position, "static_position"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult ExtractOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ExtractOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand vectorRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> vectorOperands(&vectorRawOperand, 1); ::llvm::SMLoc vectorOperandsLoc; + (void)vectorOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> dynamic_positionOperands; + ::llvm::SMLoc dynamic_positionOperandsLoc; + (void)dynamic_positionOperandsLoc; + ::mlir::DenseI64ArrayAttr static_positionAttr; + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + ::mlir::Type vectorRawType{}; + ::llvm::ArrayRef<::mlir::Type> vectorTypes(&vectorRawType, 1); + + vectorOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(vectorRawOperand)) + return ::mlir::failure(); + { + dynamic_positionOperandsLoc = parser.getCurrentLocation(); + auto odsResult = parseDynamicIndexList(parser, dynamic_positionOperands, static_positionAttr); + if (odsResult) return ::mlir::failure(); + result.getOrAddProperties().static_position = static_positionAttr; + } + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::Type type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + if (parser.parseKeyword("from")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + vectorRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(resultTypes); + if (parser.resolveOperands(vectorOperands, vectorTypes, vectorOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(dynamic_positionOperands, odsBuildableType0, dynamic_positionOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ExtractOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getVector(); + printDynamicIndexList(_odsPrinter, *this, getDynamicPosition(), getStaticPositionAttr()); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("static_position"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::Type>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "from"; + _odsPrinter << ' '; + { + auto type = getVector().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ExtractOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +::llvm::LogicalResult +ExtractOp::inferReturnTypes(::mlir::MLIRContext *context, + std::optional<::mlir::Location> location, + ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, + ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, + ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes) { + ExtractOp::Adaptor adaptor(operands, attributes, properties, regions); + return ExtractOp::inferReturnTypes(context, + location, adaptor, inferredReturnTypes); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ExtractOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExtractStridedSliceOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ExtractStridedSliceOpGenericAdaptorBase::ExtractStridedSliceOpGenericAdaptorBase(ExtractStridedSliceOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::mlir::ArrayAttr ExtractStridedSliceOpGenericAdaptorBase::getOffsets() { + auto attr = getOffsetsAttr(); + return attr; +} + +::mlir::ArrayAttr ExtractStridedSliceOpGenericAdaptorBase::getSizes() { + auto attr = getSizesAttr(); + return attr; +} + +::mlir::ArrayAttr ExtractStridedSliceOpGenericAdaptorBase::getStrides() { + auto attr = getStridesAttr(); + return attr; +} + +} // namespace detail +ExtractStridedSliceOpAdaptor::ExtractStridedSliceOpAdaptor(ExtractStridedSliceOp op) : ExtractStridedSliceOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ExtractStridedSliceOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_offsets = getProperties().offsets; (void)tblgen_offsets; + if (!tblgen_offsets) return emitError(loc, "'vector.extract_strided_slice' op ""requires attribute 'offsets'"); + auto tblgen_sizes = getProperties().sizes; (void)tblgen_sizes; + if (!tblgen_sizes) return emitError(loc, "'vector.extract_strided_slice' op ""requires attribute 'sizes'"); + auto tblgen_strides = getProperties().strides; (void)tblgen_strides; + if (!tblgen_strides) return emitError(loc, "'vector.extract_strided_slice' op ""requires attribute 'strides'"); + + if (tblgen_offsets && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_offsets))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_offsets), [&](::mlir::Attribute attr) { return attr && (((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64)))); })))) + return emitError(loc, "'vector.extract_strided_slice' op ""attribute 'offsets' failed to satisfy constraint: 64-bit integer array attribute"); + + if (tblgen_sizes && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_sizes))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_sizes), [&](::mlir::Attribute attr) { return attr && (((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64)))); })))) + return emitError(loc, "'vector.extract_strided_slice' op ""attribute 'sizes' failed to satisfy constraint: 64-bit integer array attribute"); + + if (tblgen_strides && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_strides))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_strides), [&](::mlir::Attribute attr) { return attr && (((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64)))); })))) + return emitError(loc, "'vector.extract_strided_slice' op ""attribute 'strides' failed to satisfy constraint: 64-bit integer array attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult ExtractStridedSliceOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.offsets; + auto attr = dict.get("offsets"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `offsets` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.sizes; + auto attr = dict.get("sizes"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `sizes` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.strides; + auto attr = dict.get("strides"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `strides` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ExtractStridedSliceOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.offsets; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("offsets", + propStorage)); + } + + { + const auto &propStorage = prop.sizes; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("sizes", + propStorage)); + } + + { + const auto &propStorage = prop.strides; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("strides", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ExtractStridedSliceOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.offsets.getAsOpaquePointer()), + llvm::hash_value(prop.sizes.getAsOpaquePointer()), + llvm::hash_value(prop.strides.getAsOpaquePointer())); +} + +std::optional ExtractStridedSliceOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "offsets") + return prop.offsets; + + if (name == "sizes") + return prop.sizes; + + if (name == "strides") + return prop.strides; + return std::nullopt; +} + +void ExtractStridedSliceOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "offsets") { + prop.offsets = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "sizes") { + prop.sizes = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "strides") { + prop.strides = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ExtractStridedSliceOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.offsets) attrs.append("offsets", prop.offsets); + + if (prop.sizes) attrs.append("sizes", prop.sizes); + + if (prop.strides) attrs.append("strides", prop.strides); +} + +::llvm::LogicalResult ExtractStridedSliceOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getOffsetsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(attr, "offsets", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getSizesAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(attr, "sizes", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getStridesAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(attr, "strides", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ExtractStridedSliceOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.offsets))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.sizes))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.strides))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ExtractStridedSliceOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.offsets); + writer.writeAttribute(prop.sizes); + writer.writeAttribute(prop.strides); +} + +::mlir::ArrayAttr ExtractStridedSliceOp::getOffsets() { + auto attr = getOffsetsAttr(); + return attr; +} + +::mlir::ArrayAttr ExtractStridedSliceOp::getSizes() { + auto attr = getSizesAttr(); + return attr; +} + +::mlir::ArrayAttr ExtractStridedSliceOp::getStrides() { + auto attr = getStridesAttr(); + return attr; +} + +void ExtractStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value vector, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr sizes, ::mlir::ArrayAttr strides) { + odsState.addOperands(vector); + odsState.getOrAddProperties().offsets = offsets; + odsState.getOrAddProperties().sizes = sizes; + odsState.getOrAddProperties().strides = strides; + odsState.addTypes(resultType0); +} + +void ExtractStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr sizes, ::mlir::ArrayAttr strides) { + odsState.addOperands(vector); + odsState.getOrAddProperties().offsets = offsets; + odsState.getOrAddProperties().sizes = sizes; + odsState.getOrAddProperties().strides = strides; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ExtractStridedSliceOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ExtractStridedSliceOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult ExtractStridedSliceOp::verifyInvariantsImpl() { + auto tblgen_offsets = getProperties().offsets; (void)tblgen_offsets; + if (!tblgen_offsets) return emitOpError("requires attribute 'offsets'"); + auto tblgen_sizes = getProperties().sizes; (void)tblgen_sizes; + if (!tblgen_sizes) return emitOpError("requires attribute 'sizes'"); + auto tblgen_strides = getProperties().strides; (void)tblgen_strides; + if (!tblgen_strides) return emitOpError("requires attribute 'strides'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(*this, tblgen_offsets, "offsets"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(*this, tblgen_sizes, "sizes"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(*this, tblgen_strides, "strides"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult ExtractStridedSliceOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ExtractStridedSliceOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand vectorRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> vectorOperands(&vectorRawOperand, 1); ::llvm::SMLoc vectorOperandsLoc; + (void)vectorOperandsLoc; + ::mlir::Type vectorRawType{}; + ::llvm::ArrayRef<::mlir::Type> vectorTypes(&vectorRawType, 1); + ::llvm::SmallVector<::mlir::Type, 1> allResultTypes; + + vectorOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(vectorRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + vectorRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + if (parser.parseTypeList(allResultTypes)) + return ::mlir::failure(); + result.addTypes(allResultTypes); + if (parser.resolveOperands(vectorOperands, vectorTypes, vectorOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ExtractStridedSliceOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getVector(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getVector().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + _odsPrinter << getOperation()->getResultTypes(); +} + +void ExtractStridedSliceOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ExtractStridedSliceOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::FMAOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +FMAOpGenericAdaptorBase::FMAOpGenericAdaptorBase(FMAOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +FMAOpAdaptor::FMAOpAdaptor(FMAOp op) : FMAOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult FMAOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult FMAOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute FMAOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code FMAOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional FMAOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void FMAOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void FMAOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult FMAOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void FMAOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + odsState.addTypes(result); +} + +void FMAOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(FMAOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void FMAOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addOperands(acc); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void FMAOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void FMAOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(FMAOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void FMAOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void FMAOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(FMAOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult FMAOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps10(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps10(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps10(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps10(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((((*this->getODSOperands(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType()) && ((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSOperands(2).begin()).getType()) && ((*this->getODSOperands(2).begin()).getType()) == ((*this->getODSResults(0).begin()).getType()) && ((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(0).begin()).getType())))) + return emitOpError("failed to verify that all of {lhs, rhs, acc, result} have same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult FMAOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::llvm::LogicalResult FMAOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 2) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[2].getType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult FMAOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand lhsRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> lhsOperands(&lhsRawOperand, 1); ::llvm::SMLoc lhsOperandsLoc; + (void)lhsOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand rhsRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> rhsOperands(&rhsRawOperand, 1); ::llvm::SMLoc rhsOperandsLoc; + (void)rhsOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand accRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> accOperands(&accRawOperand, 1); ::llvm::SMLoc accOperandsLoc; + (void)accOperandsLoc; + ::mlir::Type lhsRawType{}; + ::llvm::ArrayRef<::mlir::Type> lhsTypes(&lhsRawType, 1); + + lhsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(lhsRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + rhsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(rhsRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + accOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(accRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + lhsRawType = type; + } + result.addTypes(lhsTypes[0]); + if (parser.resolveOperands(lhsOperands, lhsTypes, lhsOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(rhsOperands, lhsTypes[0], rhsOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(accOperands, lhsTypes[0], accOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void FMAOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getLhs(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getRhs(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getAcc(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getLhs().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void FMAOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::FMAOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::FlatTransposeOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +FlatTransposeOpGenericAdaptorBase::FlatTransposeOpGenericAdaptorBase(FlatTransposeOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +uint32_t FlatTransposeOpGenericAdaptorBase::getRows() { + auto attr = getRowsAttr(); + return attr.getValue().getZExtValue(); +} + +uint32_t FlatTransposeOpGenericAdaptorBase::getColumns() { + auto attr = getColumnsAttr(); + return attr.getValue().getZExtValue(); +} + +} // namespace detail +FlatTransposeOpAdaptor::FlatTransposeOpAdaptor(FlatTransposeOp op) : FlatTransposeOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult FlatTransposeOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_columns = getProperties().columns; (void)tblgen_columns; + if (!tblgen_columns) return emitError(loc, "'vector.flat_transpose' op ""requires attribute 'columns'"); + auto tblgen_rows = getProperties().rows; (void)tblgen_rows; + if (!tblgen_rows) return emitError(loc, "'vector.flat_transpose' op ""requires attribute 'rows'"); + + if (tblgen_rows && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_rows))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_rows).getType().isSignlessInteger(32))))) + return emitError(loc, "'vector.flat_transpose' op ""attribute 'rows' failed to satisfy constraint: 32-bit signless integer attribute"); + + if (tblgen_columns && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_columns))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_columns).getType().isSignlessInteger(32))))) + return emitError(loc, "'vector.flat_transpose' op ""attribute 'columns' failed to satisfy constraint: 32-bit signless integer attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult FlatTransposeOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.columns; + auto attr = dict.get("columns"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `columns` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.rows; + auto attr = dict.get("rows"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `rows` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute FlatTransposeOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.columns; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("columns", + propStorage)); + } + + { + const auto &propStorage = prop.rows; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("rows", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code FlatTransposeOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.columns.getAsOpaquePointer()), + llvm::hash_value(prop.rows.getAsOpaquePointer())); +} + +std::optional FlatTransposeOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "columns") + return prop.columns; + + if (name == "rows") + return prop.rows; + return std::nullopt; +} + +void FlatTransposeOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "columns") { + prop.columns = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "rows") { + prop.rows = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void FlatTransposeOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.columns) attrs.append("columns", prop.columns); + + if (prop.rows) attrs.append("rows", prop.rows); +} + +::llvm::LogicalResult FlatTransposeOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getColumnsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(attr, "columns", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getRowsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(attr, "rows", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult FlatTransposeOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.columns))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.rows))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void FlatTransposeOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.columns); + writer.writeAttribute(prop.rows); +} + +uint32_t FlatTransposeOp::getRows() { + auto attr = getRowsAttr(); + return attr.getValue().getZExtValue(); +} + +uint32_t FlatTransposeOp::getColumns() { + auto attr = getColumnsAttr(); + return attr.getValue().getZExtValue(); +} + +void FlatTransposeOp::setRows(uint32_t attrValue) { + getProperties().rows = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(32), attrValue); +} + +void FlatTransposeOp::setColumns(uint32_t attrValue) { + getProperties().columns = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(32), attrValue); +} + +void FlatTransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value matrix, ::mlir::IntegerAttr rows, ::mlir::IntegerAttr columns) { + odsState.addOperands(matrix); + odsState.getOrAddProperties().rows = rows; + odsState.getOrAddProperties().columns = columns; + odsState.addTypes(res); +} + +void FlatTransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value matrix, ::mlir::IntegerAttr rows, ::mlir::IntegerAttr columns) { + odsState.addOperands(matrix); + odsState.getOrAddProperties().rows = rows; + odsState.getOrAddProperties().columns = columns; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void FlatTransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value matrix, uint32_t rows, uint32_t columns) { + odsState.addOperands(matrix); + odsState.getOrAddProperties().rows = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), rows); + odsState.getOrAddProperties().columns = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), columns); + odsState.addTypes(res); +} + +void FlatTransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value matrix, uint32_t rows, uint32_t columns) { + odsState.addOperands(matrix); + odsState.getOrAddProperties().rows = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), rows); + odsState.getOrAddProperties().columns = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), columns); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void FlatTransposeOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void FlatTransposeOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult FlatTransposeOp::verifyInvariantsImpl() { + auto tblgen_columns = getProperties().columns; (void)tblgen_columns; + if (!tblgen_columns) return emitOpError("requires attribute 'columns'"); + auto tblgen_rows = getProperties().rows; (void)tblgen_rows; + if (!tblgen_rows) return emitOpError("requires attribute 'rows'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(*this, tblgen_rows, "rows"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(*this, tblgen_columns, "columns"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps11(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps11(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that source operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult FlatTransposeOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult FlatTransposeOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand matrixRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> matrixOperands(&matrixRawOperand, 1); ::llvm::SMLoc matrixOperandsLoc; + (void)matrixOperandsLoc; + ::mlir::Type matrixRawType{}; + ::llvm::ArrayRef<::mlir::Type> matrixTypes(&matrixRawType, 1); + ::mlir::Type resRawType{}; + ::llvm::ArrayRef<::mlir::Type> resTypes(&resRawType, 1); + + matrixOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(matrixRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + matrixRawType = type; + } + if (parser.parseArrow()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resRawType = type; + } + result.addTypes(resTypes); + if (parser.resolveOperands(matrixOperands, matrixTypes, matrixOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void FlatTransposeOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getMatrix(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getMatrix().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "->"; + _odsPrinter << ' '; + { + auto type = getRes().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void FlatTransposeOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::FlatTransposeOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::FromElementsOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +FromElementsOpGenericAdaptorBase::FromElementsOpGenericAdaptorBase(FromElementsOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair FromElementsOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +FromElementsOpAdaptor::FromElementsOpAdaptor(FromElementsOp op) : FromElementsOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult FromElementsOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair FromElementsOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange FromElementsOp::getElementsMutable() { + auto range = getODSOperandIndexAndLength(0); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult FromElementsOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute FromElementsOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code FromElementsOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional FromElementsOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void FromElementsOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void FromElementsOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult FromElementsOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void FromElementsOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::ValueRange elements) { + odsState.addOperands(elements); + odsState.addTypes(result); +} + +void FromElementsOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void FromElementsOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult FromElementsOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps12(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps13(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((std::equal_to<>()(SmallVector(::llvm::cast((*this->getODSResults(0).begin()).getType()).getNumElements(), ::llvm::cast((*this->getODSResults(0).begin()).getType()).getElementType()), this->getODSOperands(0).getType())))) + return emitOpError("failed to verify that operand types match result element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult FromElementsOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult FromElementsOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> elementsOperands; + ::llvm::SMLoc elementsOperandsLoc; + (void)elementsOperandsLoc; + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + elementsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(elementsOperands)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + for (::mlir::Type type : resultTypes) { + (void)type; + if (!(((::llvm::isa<::mlir::FixedVectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return parser.emitError(parser.getNameLoc()) << "'result' must be fixed-length vector of any type values, but got " << type; + } + } + result.addTypes(resultTypes); + if (parser.resolveOperands(elementsOperands, SmallVector(::llvm::cast(resultTypes[0]).getNumElements(), ::llvm::cast(resultTypes[0]).getElementType()), elementsOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void FromElementsOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getElements(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void FromElementsOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::FromElementsOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::GatherOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +GatherOpGenericAdaptorBase::GatherOpGenericAdaptorBase(GatherOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair GatherOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true, false, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 4) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +GatherOpAdaptor::GatherOpAdaptor(GatherOp op) : GatherOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult GatherOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair GatherOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true, false, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 4) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange GatherOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult GatherOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute GatherOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code GatherOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional GatherOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void GatherOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void GatherOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult GatherOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void GatherOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value pass_thru) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(index_vec); + odsState.addOperands(mask); + odsState.addOperands(pass_thru); + odsState.addTypes(result); +} + +void GatherOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value pass_thru) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(index_vec); + odsState.addOperands(mask); + odsState.addOperands(pass_thru); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void GatherOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 4u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void GatherOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 4u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult GatherOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps14(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps15(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup4 = getODSOperands(4); + + for (auto v : valueGroup4) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult GatherOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult GatherOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand index_vecRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> index_vecOperands(&index_vecRawOperand, 1); ::llvm::SMLoc index_vecOperandsLoc; + (void)index_vecOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand maskRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> maskOperands(&maskRawOperand, 1); ::llvm::SMLoc maskOperandsLoc; + (void)maskOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand pass_thruRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> pass_thruOperands(&pass_thruRawOperand, 1); ::llvm::SMLoc pass_thruOperandsLoc; + (void)pass_thruOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type index_vecRawType{}; + ::llvm::ArrayRef<::mlir::Type> index_vecTypes(&index_vecRawType, 1); + ::mlir::Type maskRawType{}; + ::llvm::ArrayRef<::mlir::Type> maskTypes(&maskRawType, 1); + ::mlir::Type pass_thruRawType{}; + ::llvm::ArrayRef<::mlir::Type> pass_thruTypes(&pass_thruRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + index_vecOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(index_vecRawOperand)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + maskOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(maskRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + pass_thruOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(pass_thruRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::ShapedType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + index_vecRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + maskRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + pass_thruRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(resultTypes); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(index_vecOperands, index_vecTypes, index_vecOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(maskOperands, maskTypes, maskOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(pass_thruOperands, pass_thruTypes, pass_thruOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void GatherOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + _odsPrinter << ' ' << "["; + _odsPrinter << getIndexVec(); + _odsPrinter << "]"; + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getMask(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getPassThru(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::ShapedType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getIndexVec().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getMask().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getPassThru().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void GatherOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Read::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::GatherOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InsertElementOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +InsertElementOpGenericAdaptorBase::InsertElementOpGenericAdaptorBase(InsertElementOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair InsertElementOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +InsertElementOpAdaptor::InsertElementOpAdaptor(InsertElementOp op) : InsertElementOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult InsertElementOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair InsertElementOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange InsertElementOp::getPositionMutable() { + auto range = getODSOperandIndexAndLength(2); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult InsertElementOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute InsertElementOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code InsertElementOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional InsertElementOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void InsertElementOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void InsertElementOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult InsertElementOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void InsertElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value source, ::mlir::Value dest, /*optional*/::mlir::Value position) { + odsState.addOperands(source); + odsState.addOperands(dest); + if (position) + odsState.addOperands(position); + odsState.addTypes(result); +} + +void InsertElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source, ::mlir::Value dest, /*optional*/::mlir::Value position) { + odsState.addOperands(source); + odsState.addOperands(dest); + if (position) + odsState.addOperands(position); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertElementOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void InsertElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source, ::mlir::Value dest, /*optional*/::mlir::Value position) { + odsState.addOperands(source); + odsState.addOperands(dest); + if (position) + odsState.addOperands(position); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void InsertElementOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void InsertElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertElementOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void InsertElementOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void InsertElementOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertElementOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult InsertElementOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + if (valueGroup2.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup2.size(); + } + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps9(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((std::equal_to<>()(::llvm::cast((*this->getODSResults(0).begin()).getType()).getElementType(), (*this->getODSOperands(0).begin()).getType())))) + return emitOpError("failed to verify that source operand type matches element type of result"); + if (!((((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSResults(0).begin()).getType()) && ((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType())))) + return emitOpError("failed to verify that all of {dest, result} have same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult InsertElementOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::llvm::LogicalResult InsertElementOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 1) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[1].getType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult InsertElementOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand destRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> destOperands(&destRawOperand, 1); ::llvm::SMLoc destOperandsLoc; + (void)destOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> positionOperands; + ::llvm::SMLoc positionOperandsLoc; + (void)positionOperandsLoc; + ::llvm::SmallVector<::mlir::Type, 1> positionTypes; + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + destOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(destRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + { + positionOperandsLoc = parser.getCurrentLocation(); + ::mlir::OpAsmParser::UnresolvedOperand operand; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalOperand(operand); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + positionOperands.push_back(operand); + } + } + if (!positionOperands.empty()) { + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::Type optionalType; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalType(optionalType); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + positionTypes.push_back(optionalType); + } + } + } + if (parser.parseRSquare()) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + for (::mlir::Type type : resultTypes) { + (void)type; + if (!(((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return parser.emitError(parser.getNameLoc()) << "'result' must be vector of any type values, but got " << type; + } + } + result.addTypes(resultTypes); + if (parser.resolveOperands(sourceOperands, ::llvm::cast(resultTypes[0]).getElementType(), sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(destOperands, resultTypes[0], destOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(positionOperands, positionTypes, positionOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void InsertElementOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getSource(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getDest(); + _odsPrinter << "["; + if (getPosition()) { + if (::mlir::Value value = getPosition()) + _odsPrinter << value; + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << (getPosition() ? ::llvm::ArrayRef<::mlir::Type>(getPosition().getType()) : ::llvm::ArrayRef<::mlir::Type>()); + } + _odsPrinter << "]"; + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void InsertElementOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::InsertElementOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InsertOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +InsertOpGenericAdaptorBase::InsertOpGenericAdaptorBase(InsertOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair InsertOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::llvm::ArrayRef InsertOpGenericAdaptorBase::getStaticPosition() { + auto attr = getStaticPositionAttr(); + return attr; +} + +} // namespace detail +InsertOpAdaptor::InsertOpAdaptor(InsertOp op) : InsertOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult InsertOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_static_position = getProperties().static_position; (void)tblgen_static_position; + if (!tblgen_static_position) return emitError(loc, "'vector.insert' op ""requires attribute 'static_position'"); + + if (tblgen_static_position && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(tblgen_static_position)))) + return emitError(loc, "'vector.insert' op ""attribute 'static_position' failed to satisfy constraint: i64 dense array attribute"); + return ::mlir::success(); +} + +std::pair InsertOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange InsertOp::getDynamicPositionMutable() { + auto range = getODSOperandIndexAndLength(2); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult InsertOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.static_position; + auto attr = dict.get("static_position"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `static_position` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute InsertOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.static_position; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("static_position", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code InsertOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.static_position.getAsOpaquePointer())); +} + +std::optional InsertOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "static_position") + return prop.static_position; + return std::nullopt; +} + +void InsertOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "static_position") { + prop.static_position = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void InsertOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.static_position) attrs.append("static_position", prop.static_position); +} + +::llvm::LogicalResult InsertOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getStaticPositionAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(attr, "static_position", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult InsertOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.static_position))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void InsertOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.static_position); +} + +::llvm::ArrayRef InsertOp::getStaticPosition() { + auto attr = getStaticPositionAttr(); + return attr; +} + +void InsertOp::setStaticPosition(::llvm::ArrayRef attrValue) { + getProperties().static_position = ::mlir::Builder((*this)->getContext()).getDenseI64ArrayAttr(attrValue); +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = static_position; + odsState.addTypes(result); +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = static_position; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = static_position; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = odsBuilder.getDenseI64ArrayAttr(static_position); + odsState.addTypes(result); +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = odsBuilder.getDenseI64ArrayAttr(static_position); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.addOperands(dynamic_position); + odsState.getOrAddProperties().static_position = odsBuilder.getDenseI64ArrayAttr(static_position); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void InsertOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void InsertOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void InsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult InsertOp::verifyInvariantsImpl() { + auto tblgen_static_position = getProperties().static_position; (void)tblgen_static_position; + if (!tblgen_static_position) return emitOpError("requires attribute 'static_position'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(*this, tblgen_static_position, "static_position"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that source operand and result have same element type"); + if (!((((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSResults(0).begin()).getType()) && ((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType())))) + return emitOpError("failed to verify that all of {dest, result} have same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult InsertOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::llvm::LogicalResult InsertOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 1) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[1].getType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult InsertOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand destRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> destOperands(&destRawOperand, 1); ::llvm::SMLoc destOperandsLoc; + (void)destOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> dynamic_positionOperands; + ::llvm::SMLoc dynamic_positionOperandsLoc; + (void)dynamic_positionOperandsLoc; + ::mlir::DenseI64ArrayAttr static_positionAttr; + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + ::mlir::Type destRawType{}; + ::llvm::ArrayRef<::mlir::Type> destTypes(&destRawType, 1); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + destOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(destRawOperand)) + return ::mlir::failure(); + { + dynamic_positionOperandsLoc = parser.getCurrentLocation(); + auto odsResult = parseDynamicIndexList(parser, dynamic_positionOperands, static_positionAttr); + if (odsResult) return ::mlir::failure(); + result.getOrAddProperties().static_position = static_positionAttr; + } + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::Type type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + destRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(destTypes[0]); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(destOperands, destTypes, destOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(dynamic_positionOperands, odsBuildableType0, dynamic_positionOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void InsertOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getDest(); + _odsPrinter << ' '; + printDynamicIndexList(_odsPrinter, *this, getDynamicPosition(), getStaticPositionAttr()); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("static_position"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::Type>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getDest().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void InsertOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::InsertOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InsertStridedSliceOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +InsertStridedSliceOpGenericAdaptorBase::InsertStridedSliceOpGenericAdaptorBase(InsertStridedSliceOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::mlir::ArrayAttr InsertStridedSliceOpGenericAdaptorBase::getOffsets() { + auto attr = getOffsetsAttr(); + return attr; +} + +::mlir::ArrayAttr InsertStridedSliceOpGenericAdaptorBase::getStrides() { + auto attr = getStridesAttr(); + return attr; +} + +} // namespace detail +InsertStridedSliceOpAdaptor::InsertStridedSliceOpAdaptor(InsertStridedSliceOp op) : InsertStridedSliceOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult InsertStridedSliceOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_offsets = getProperties().offsets; (void)tblgen_offsets; + if (!tblgen_offsets) return emitError(loc, "'vector.insert_strided_slice' op ""requires attribute 'offsets'"); + auto tblgen_strides = getProperties().strides; (void)tblgen_strides; + if (!tblgen_strides) return emitError(loc, "'vector.insert_strided_slice' op ""requires attribute 'strides'"); + + if (tblgen_offsets && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_offsets))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_offsets), [&](::mlir::Attribute attr) { return attr && (((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64)))); })))) + return emitError(loc, "'vector.insert_strided_slice' op ""attribute 'offsets' failed to satisfy constraint: 64-bit integer array attribute"); + + if (tblgen_strides && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_strides))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_strides), [&](::mlir::Attribute attr) { return attr && (((::llvm::isa<::mlir::IntegerAttr>(attr))) && ((::llvm::cast<::mlir::IntegerAttr>(attr).getType().isSignlessInteger(64)))); })))) + return emitError(loc, "'vector.insert_strided_slice' op ""attribute 'strides' failed to satisfy constraint: 64-bit integer array attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult InsertStridedSliceOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.offsets; + auto attr = dict.get("offsets"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `offsets` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.strides; + auto attr = dict.get("strides"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `strides` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute InsertStridedSliceOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.offsets; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("offsets", + propStorage)); + } + + { + const auto &propStorage = prop.strides; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("strides", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code InsertStridedSliceOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.offsets.getAsOpaquePointer()), + llvm::hash_value(prop.strides.getAsOpaquePointer())); +} + +std::optional InsertStridedSliceOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "offsets") + return prop.offsets; + + if (name == "strides") + return prop.strides; + return std::nullopt; +} + +void InsertStridedSliceOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "offsets") { + prop.offsets = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "strides") { + prop.strides = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void InsertStridedSliceOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.offsets) attrs.append("offsets", prop.offsets); + + if (prop.strides) attrs.append("strides", prop.strides); +} + +::llvm::LogicalResult InsertStridedSliceOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getOffsetsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(attr, "offsets", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getStridesAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(attr, "strides", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult InsertStridedSliceOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.offsets))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.strides))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void InsertStridedSliceOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.offsets); + writer.writeAttribute(prop.strides); +} + +::mlir::ArrayAttr InsertStridedSliceOp::getOffsets() { + auto attr = getOffsetsAttr(); + return attr; +} + +::mlir::ArrayAttr InsertStridedSliceOp::getStrides() { + auto attr = getStridesAttr(); + return attr; +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr strides) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().offsets = offsets; + odsState.getOrAddProperties().strides = strides; + odsState.addTypes(res); +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr strides) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().offsets = offsets; + odsState.getOrAddProperties().strides = strides; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertStridedSliceOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr strides) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().offsets = offsets; + odsState.getOrAddProperties().strides = strides; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertStridedSliceOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void InsertStridedSliceOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InsertStridedSliceOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult InsertStridedSliceOp::verifyInvariantsImpl() { + auto tblgen_offsets = getProperties().offsets; (void)tblgen_offsets; + if (!tblgen_offsets) return emitOpError("requires attribute 'offsets'"); + auto tblgen_strides = getProperties().strides; (void)tblgen_strides; + if (!tblgen_strides) return emitOpError("requires attribute 'strides'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(*this, tblgen_offsets, "offsets"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps5(*this, tblgen_strides, "strides"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that operand #0 and result have same element type"); + if (!((((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSResults(0).begin()).getType()) && ((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType())))) + return emitOpError("failed to verify that all of {dest, res} have same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult InsertStridedSliceOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::llvm::LogicalResult InsertStridedSliceOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 1) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[1].getType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult InsertStridedSliceOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand destRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> destOperands(&destRawOperand, 1); ::llvm::SMLoc destOperandsLoc; + (void)destOperandsLoc; + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + ::mlir::Type destRawType{}; + ::llvm::ArrayRef<::mlir::Type> destTypes(&destRawType, 1); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + destOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(destRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + destRawType = type; + } + result.addTypes(destTypes[0]); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(destOperands, destTypes, destOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void InsertStridedSliceOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getDest(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getDest().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void InsertStridedSliceOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::InsertStridedSliceOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InterleaveOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +InterleaveOpGenericAdaptorBase::InterleaveOpGenericAdaptorBase(InterleaveOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +InterleaveOpAdaptor::InterleaveOpAdaptor(InterleaveOp op) : InterleaveOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult InterleaveOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult InterleaveOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute InterleaveOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code InterleaveOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional InterleaveOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void InterleaveOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void InterleaveOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult InterleaveOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void InterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.addTypes(result); +} + +void InterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InterleaveOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void InterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void InterleaveOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void InterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InterleaveOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void InterleaveOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void InterleaveOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(InterleaveOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult InterleaveOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((((*this->getODSOperands(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType()) && ((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSOperands(0).begin()).getType())))) + return emitOpError("failed to verify that all of {lhs, rhs} have same type"); + if (!((std::equal_to<>()( + [&]() -> ::mlir::VectorType { + auto vectorType = ::llvm::cast<::mlir::VectorType>((*this->getODSOperands(0).begin()).getType()); + ::mlir::VectorType::Builder builder(vectorType); + if (vectorType.getRank() == 0) { + static constexpr int64_t v2xTyShape[] = {2}; + return builder.setShape(v2xTyShape); + } + auto lastDim = vectorType.getRank() - 1; + return builder.setDim(lastDim, vectorType.getDimSize(lastDim) * 2); + }() + , (*this->getODSResults(0).begin()).getType())))) + return emitOpError("failed to verify that type of 'result' is double the width of the inputs"); + return ::mlir::success(); +} + +::llvm::LogicalResult InterleaveOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::llvm::LogicalResult InterleaveOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 0) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = + [&]() -> ::mlir::VectorType { + auto vectorType = ::llvm::cast<::mlir::VectorType>(operands[0].getType()); + ::mlir::VectorType::Builder builder(vectorType); + if (vectorType.getRank() == 0) { + static constexpr int64_t v2xTyShape[] = {2}; + return builder.setShape(v2xTyShape); + } + auto lastDim = vectorType.getRank() - 1; + return builder.setDim(lastDim, vectorType.getDimSize(lastDim) * 2); + }() + ; + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult InterleaveOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand lhsRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> lhsOperands(&lhsRawOperand, 1); ::llvm::SMLoc lhsOperandsLoc; + (void)lhsOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand rhsRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> rhsOperands(&rhsRawOperand, 1); ::llvm::SMLoc rhsOperandsLoc; + (void)rhsOperandsLoc; + ::mlir::Type lhsRawType{}; + ::llvm::ArrayRef<::mlir::Type> lhsTypes(&lhsRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + lhsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(lhsRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + rhsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(rhsRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + lhsRawType = type; + } + if (parser.parseArrow()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + result.addTypes(resultTypes); + if (parser.resolveOperands(lhsOperands, lhsTypes, lhsOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(rhsOperands, lhsTypes[0], rhsOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void InterleaveOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getLhs(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getRhs(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getLhs().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "->"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void InterleaveOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::InterleaveOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::LoadOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +LoadOpGenericAdaptorBase::LoadOpGenericAdaptorBase(LoadOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair LoadOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::BoolAttr LoadOpGenericAdaptorBase::getNontemporalAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::BoolAttr>(getProperties().nontemporal); + if (!attr) + attr = ::mlir::Builder(odsAttrs.getContext()).getBoolAttr(false); + return attr; +} + +bool LoadOpGenericAdaptorBase::getNontemporal() { + auto attr = getNontemporalAttr(); + if (!attr) + return ::mlir::Builder(odsAttrs.getContext()).getBoolAttr(false).getValue(); + return attr.getValue(); +} + +} // namespace detail +LoadOpAdaptor::LoadOpAdaptor(LoadOp op) : LoadOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult LoadOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_nontemporal = getProperties().nontemporal; (void)tblgen_nontemporal; + + if (tblgen_nontemporal && !((::llvm::isa<::mlir::BoolAttr>(tblgen_nontemporal)))) + return emitError(loc, "'vector.load' op ""attribute 'nontemporal' failed to satisfy constraint: bool attribute"); + return ::mlir::success(); +} + +std::pair LoadOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange LoadOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult LoadOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.nontemporal; + auto attr = dict.get("nontemporal"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `nontemporal` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute LoadOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.nontemporal; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("nontemporal", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code LoadOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.nontemporal.getAsOpaquePointer())); +} + +std::optional LoadOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "nontemporal") + return prop.nontemporal; + return std::nullopt; +} + +void LoadOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "nontemporal") { + prop.nontemporal = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void LoadOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.nontemporal) attrs.append("nontemporal", prop.nontemporal); +} + +::llvm::LogicalResult LoadOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getNontemporalAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps7(attr, "nontemporal", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult LoadOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readOptionalAttribute(prop.nontemporal))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void LoadOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + + writer.writeOptionalAttribute(prop.nontemporal); +} + +bool LoadOp::getNontemporal() { + auto attr = getNontemporalAttr(); + if (!attr) + return ::mlir::Builder((*this)->getContext()).getBoolAttr(false).getValue(); + return attr.getValue(); +} + +void LoadOp::setNontemporal(::std::optional attrValue) { + auto &odsProp = getProperties().nontemporal; + if (attrValue) + odsProp = ::mlir::Builder((*this)->getContext()).getBoolAttr(*attrValue); + else + odsProp = nullptr; +} + +void LoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal) { + odsState.addOperands(base); + odsState.addOperands(indices); + if (nontemporal) { + odsState.getOrAddProperties().nontemporal = nontemporal; + } + odsState.addTypes(result); +} + +void LoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal) { + odsState.addOperands(base); + odsState.addOperands(indices); + if (nontemporal) { + odsState.getOrAddProperties().nontemporal = nontemporal; + } + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void LoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.getOrAddProperties().nontemporal = odsBuilder.getBoolAttr(nontemporal); + odsState.addTypes(result); +} + +void LoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.getOrAddProperties().nontemporal = odsBuilder.getBoolAttr(nontemporal); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void LoadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void LoadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult LoadOp::verifyInvariantsImpl() { + auto tblgen_nontemporal = getProperties().nontemporal; (void)tblgen_nontemporal; + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps7(*this, tblgen_nontemporal, "nontemporal"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult LoadOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult LoadOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(resultTypes); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void LoadOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + { + ::mlir::Builder odsBuilder(getContext()); + ::mlir::Attribute attr = getNontemporalAttr(); + if(attr && (attr == odsBuilder.getBoolAttr(false))) + elidedAttrs.push_back("nontemporal"); + } + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void LoadOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Read::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::LoadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MaskOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +MaskOpGenericAdaptorBase::MaskOpGenericAdaptorBase(MaskOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair MaskOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +MaskOpAdaptor::MaskOpAdaptor(MaskOp op) : MaskOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult MaskOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair MaskOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange MaskOp::getPassthruMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +std::pair MaskOp::getODSResultIndexAndLength(unsigned index) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumResults() - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::llvm::LogicalResult MaskOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute MaskOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code MaskOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional MaskOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void MaskOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void MaskOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult MaskOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +::llvm::LogicalResult MaskOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + if (valueGroup1.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup1.size(); + } + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps12(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + + for (auto ®ion : ::llvm::MutableArrayRef((*this)->getRegion(0))) + if (::mlir::failed(__mlir_ods_local_region_constraint_VectorOps1(*this, region, "maskRegion", index++))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult MaskOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::MaskOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MaskedLoadOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +MaskedLoadOpGenericAdaptorBase::MaskedLoadOpGenericAdaptorBase(MaskedLoadOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair MaskedLoadOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +MaskedLoadOpAdaptor::MaskedLoadOpAdaptor(MaskedLoadOp op) : MaskedLoadOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult MaskedLoadOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair MaskedLoadOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange MaskedLoadOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult MaskedLoadOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute MaskedLoadOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code MaskedLoadOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional MaskedLoadOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void MaskedLoadOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void MaskedLoadOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult MaskedLoadOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void MaskedLoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(pass_thru); + odsState.addTypes(result); +} + +void MaskedLoadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(pass_thru); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void MaskedLoadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void MaskedLoadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult MaskedLoadOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult MaskedLoadOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult MaskedLoadOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand maskRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> maskOperands(&maskRawOperand, 1); ::llvm::SMLoc maskOperandsLoc; + (void)maskOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand pass_thruRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> pass_thruOperands(&pass_thruRawOperand, 1); ::llvm::SMLoc pass_thruOperandsLoc; + (void)pass_thruOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type maskRawType{}; + ::llvm::ArrayRef<::mlir::Type> maskTypes(&maskRawType, 1); + ::mlir::Type pass_thruRawType{}; + ::llvm::ArrayRef<::mlir::Type> pass_thruTypes(&pass_thruRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + maskOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(maskRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + pass_thruOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(pass_thruRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + maskRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + pass_thruRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + result.addTypes(resultTypes); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(maskOperands, maskTypes, maskOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(pass_thruOperands, pass_thruTypes, pass_thruOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void MaskedLoadOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getMask(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getPassThru(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getMask().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getPassThru().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void MaskedLoadOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Read::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::MaskedLoadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MaskedStoreOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +MaskedStoreOpGenericAdaptorBase::MaskedStoreOpGenericAdaptorBase(MaskedStoreOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair MaskedStoreOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +MaskedStoreOpAdaptor::MaskedStoreOpAdaptor(MaskedStoreOp op) : MaskedStoreOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult MaskedStoreOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair MaskedStoreOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 3) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange MaskedStoreOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult MaskedStoreOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute MaskedStoreOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code MaskedStoreOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional MaskedStoreOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void MaskedStoreOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void MaskedStoreOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult MaskedStoreOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void MaskedStoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(valueToStore); +} + +void MaskedStoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(mask); + odsState.addOperands(valueToStore); + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void MaskedStoreOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void MaskedStoreOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 3u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult MaskedStoreOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult MaskedStoreOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult MaskedStoreOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand maskRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> maskOperands(&maskRawOperand, 1); ::llvm::SMLoc maskOperandsLoc; + (void)maskOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type maskRawType{}; + ::llvm::ArrayRef<::mlir::Type> maskTypes(&maskRawType, 1); + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + maskOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(maskRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + maskRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(maskOperands, maskTypes, maskOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void MaskedStoreOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getMask(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getMask().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void MaskedStoreOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Write::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::MaskedStoreOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MatmulOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +MatmulOpGenericAdaptorBase::MatmulOpGenericAdaptorBase(MatmulOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +uint32_t MatmulOpGenericAdaptorBase::getLhsRows() { + auto attr = getLhsRowsAttr(); + return attr.getValue().getZExtValue(); +} + +uint32_t MatmulOpGenericAdaptorBase::getLhsColumns() { + auto attr = getLhsColumnsAttr(); + return attr.getValue().getZExtValue(); +} + +uint32_t MatmulOpGenericAdaptorBase::getRhsColumns() { + auto attr = getRhsColumnsAttr(); + return attr.getValue().getZExtValue(); +} + +} // namespace detail +MatmulOpAdaptor::MatmulOpAdaptor(MatmulOp op) : MatmulOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult MatmulOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_lhs_columns = getProperties().lhs_columns; (void)tblgen_lhs_columns; + if (!tblgen_lhs_columns) return emitError(loc, "'vector.matrix_multiply' op ""requires attribute 'lhs_columns'"); + auto tblgen_lhs_rows = getProperties().lhs_rows; (void)tblgen_lhs_rows; + if (!tblgen_lhs_rows) return emitError(loc, "'vector.matrix_multiply' op ""requires attribute 'lhs_rows'"); + auto tblgen_rhs_columns = getProperties().rhs_columns; (void)tblgen_rhs_columns; + if (!tblgen_rhs_columns) return emitError(loc, "'vector.matrix_multiply' op ""requires attribute 'rhs_columns'"); + + if (tblgen_lhs_rows && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_lhs_rows))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_lhs_rows).getType().isSignlessInteger(32))))) + return emitError(loc, "'vector.matrix_multiply' op ""attribute 'lhs_rows' failed to satisfy constraint: 32-bit signless integer attribute"); + + if (tblgen_lhs_columns && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_lhs_columns))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_lhs_columns).getType().isSignlessInteger(32))))) + return emitError(loc, "'vector.matrix_multiply' op ""attribute 'lhs_columns' failed to satisfy constraint: 32-bit signless integer attribute"); + + if (tblgen_rhs_columns && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_rhs_columns))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_rhs_columns).getType().isSignlessInteger(32))))) + return emitError(loc, "'vector.matrix_multiply' op ""attribute 'rhs_columns' failed to satisfy constraint: 32-bit signless integer attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult MatmulOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.lhs_columns; + auto attr = dict.get("lhs_columns"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `lhs_columns` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.lhs_rows; + auto attr = dict.get("lhs_rows"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `lhs_rows` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.rhs_columns; + auto attr = dict.get("rhs_columns"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `rhs_columns` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute MatmulOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.lhs_columns; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("lhs_columns", + propStorage)); + } + + { + const auto &propStorage = prop.lhs_rows; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("lhs_rows", + propStorage)); + } + + { + const auto &propStorage = prop.rhs_columns; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("rhs_columns", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code MatmulOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.lhs_columns.getAsOpaquePointer()), + llvm::hash_value(prop.lhs_rows.getAsOpaquePointer()), + llvm::hash_value(prop.rhs_columns.getAsOpaquePointer())); +} + +std::optional MatmulOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "lhs_columns") + return prop.lhs_columns; + + if (name == "lhs_rows") + return prop.lhs_rows; + + if (name == "rhs_columns") + return prop.rhs_columns; + return std::nullopt; +} + +void MatmulOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "lhs_columns") { + prop.lhs_columns = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "lhs_rows") { + prop.lhs_rows = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "rhs_columns") { + prop.rhs_columns = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void MatmulOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.lhs_columns) attrs.append("lhs_columns", prop.lhs_columns); + + if (prop.lhs_rows) attrs.append("lhs_rows", prop.lhs_rows); + + if (prop.rhs_columns) attrs.append("rhs_columns", prop.rhs_columns); +} + +::llvm::LogicalResult MatmulOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getLhsColumnsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(attr, "lhs_columns", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getLhsRowsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(attr, "lhs_rows", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getRhsColumnsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(attr, "rhs_columns", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult MatmulOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.lhs_columns))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.lhs_rows))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.rhs_columns))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void MatmulOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.lhs_columns); + writer.writeAttribute(prop.lhs_rows); + writer.writeAttribute(prop.rhs_columns); +} + +uint32_t MatmulOp::getLhsRows() { + auto attr = getLhsRowsAttr(); + return attr.getValue().getZExtValue(); +} + +uint32_t MatmulOp::getLhsColumns() { + auto attr = getLhsColumnsAttr(); + return attr.getValue().getZExtValue(); +} + +uint32_t MatmulOp::getRhsColumns() { + auto attr = getRhsColumnsAttr(); + return attr.getValue().getZExtValue(); +} + +void MatmulOp::setLhsRows(uint32_t attrValue) { + getProperties().lhs_rows = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(32), attrValue); +} + +void MatmulOp::setLhsColumns(uint32_t attrValue) { + getProperties().lhs_columns = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(32), attrValue); +} + +void MatmulOp::setRhsColumns(uint32_t attrValue) { + getProperties().rhs_columns = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(32), attrValue); +} + +void MatmulOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, unsigned lhsRows, unsigned lhsColumns, unsigned rhsColumns) { + odsState.addOperands({lhs, rhs}); + odsState.addAttribute("lhs_rows",odsBuilder.getI32IntegerAttr(lhsRows)); + odsState.addAttribute("lhs_columns",odsBuilder.getI32IntegerAttr(lhsColumns)); + odsState.addAttribute("rhs_columns",odsBuilder.getI32IntegerAttr(rhsColumns)); + odsState.addTypes(VectorType::get(lhsRows * rhsColumns, + ::llvm::cast(lhs.getType()).getElementType())); + +} + +void MatmulOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::IntegerAttr lhs_rows, ::mlir::IntegerAttr lhs_columns, ::mlir::IntegerAttr rhs_columns) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.getOrAddProperties().lhs_rows = lhs_rows; + odsState.getOrAddProperties().lhs_columns = lhs_columns; + odsState.getOrAddProperties().rhs_columns = rhs_columns; + odsState.addTypes(res); +} + +void MatmulOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::IntegerAttr lhs_rows, ::mlir::IntegerAttr lhs_columns, ::mlir::IntegerAttr rhs_columns) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.getOrAddProperties().lhs_rows = lhs_rows; + odsState.getOrAddProperties().lhs_columns = lhs_columns; + odsState.getOrAddProperties().rhs_columns = rhs_columns; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void MatmulOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value lhs, ::mlir::Value rhs, uint32_t lhs_rows, uint32_t lhs_columns, uint32_t rhs_columns) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.getOrAddProperties().lhs_rows = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), lhs_rows); + odsState.getOrAddProperties().lhs_columns = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), lhs_columns); + odsState.getOrAddProperties().rhs_columns = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), rhs_columns); + odsState.addTypes(res); +} + +void MatmulOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, uint32_t lhs_rows, uint32_t lhs_columns, uint32_t rhs_columns) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + odsState.getOrAddProperties().lhs_rows = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), lhs_rows); + odsState.getOrAddProperties().lhs_columns = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), lhs_columns); + odsState.getOrAddProperties().rhs_columns = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(32), rhs_columns); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void MatmulOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void MatmulOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult MatmulOp::verifyInvariantsImpl() { + auto tblgen_lhs_columns = getProperties().lhs_columns; (void)tblgen_lhs_columns; + if (!tblgen_lhs_columns) return emitOpError("requires attribute 'lhs_columns'"); + auto tblgen_lhs_rows = getProperties().lhs_rows; (void)tblgen_lhs_rows; + if (!tblgen_lhs_rows) return emitOpError("requires attribute 'lhs_rows'"); + auto tblgen_rhs_columns = getProperties().rhs_columns; (void)tblgen_rhs_columns; + if (!tblgen_rhs_columns) return emitOpError("requires attribute 'rhs_columns'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(*this, tblgen_lhs_rows, "lhs_rows"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(*this, tblgen_lhs_columns, "lhs_columns"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps6(*this, tblgen_rhs_columns, "rhs_columns"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps11(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps11(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps11(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that lhs operand and result have same element type"); + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(1))))) + return emitOpError("failed to verify that rhs operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult MatmulOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult MatmulOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand lhsRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> lhsOperands(&lhsRawOperand, 1); ::llvm::SMLoc lhsOperandsLoc; + (void)lhsOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand rhsRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> rhsOperands(&rhsRawOperand, 1); ::llvm::SMLoc rhsOperandsLoc; + (void)rhsOperandsLoc; + ::mlir::Type lhsRawType{}; + ::llvm::ArrayRef<::mlir::Type> lhsTypes(&lhsRawType, 1); + ::mlir::Type rhsRawType{}; + ::llvm::ArrayRef<::mlir::Type> rhsTypes(&rhsRawType, 1); + ::mlir::Type resRawType{}; + ::llvm::ArrayRef<::mlir::Type> resTypes(&resRawType, 1); + + lhsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(lhsRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + rhsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(rhsRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + if (parser.parseLParen()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + lhsRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + rhsRawType = type; + } + if (parser.parseRParen()) + return ::mlir::failure(); + if (parser.parseArrow()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resRawType = type; + } + result.addTypes(resTypes); + if (parser.resolveOperands(lhsOperands, lhsTypes, lhsOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(rhsOperands, rhsTypes, rhsOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void MatmulOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getLhs(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getRhs(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' ' << "("; + { + auto type = getLhs().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getRhs().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ")"; + _odsPrinter << ' ' << "->"; + _odsPrinter << ' '; + { + auto type = getRes().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void MatmulOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::MatmulOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MultiDimReductionOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +MultiDimReductionOpGenericAdaptorBase::MultiDimReductionOpGenericAdaptorBase(MultiDimReductionOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::mlir::vector::CombiningKind MultiDimReductionOpGenericAdaptorBase::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +::llvm::ArrayRef MultiDimReductionOpGenericAdaptorBase::getReductionDims() { + auto attr = getReductionDimsAttr(); + return attr; +} + +} // namespace detail +MultiDimReductionOpAdaptor::MultiDimReductionOpAdaptor(MultiDimReductionOp op) : MultiDimReductionOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult MultiDimReductionOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + if (!tblgen_kind) return emitError(loc, "'vector.multi_reduction' op ""requires attribute 'kind'"); + auto tblgen_reduction_dims = getProperties().reduction_dims; (void)tblgen_reduction_dims; + if (!tblgen_reduction_dims) return emitError(loc, "'vector.multi_reduction' op ""requires attribute 'reduction_dims'"); + + if (tblgen_kind && !((::llvm::isa<::mlir::vector::CombiningKindAttr>(tblgen_kind)))) + return emitError(loc, "'vector.multi_reduction' op ""attribute 'kind' failed to satisfy constraint: Kind of combining function for contractions and reductions"); + + if (tblgen_reduction_dims && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(tblgen_reduction_dims)))) + return emitError(loc, "'vector.multi_reduction' op ""attribute 'reduction_dims' failed to satisfy constraint: i64 dense array attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult MultiDimReductionOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.kind; + auto attr = dict.get("kind"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `kind` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.reduction_dims; + auto attr = dict.get("reduction_dims"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `reduction_dims` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute MultiDimReductionOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.kind; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("kind", + propStorage)); + } + + { + const auto &propStorage = prop.reduction_dims; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("reduction_dims", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code MultiDimReductionOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.kind.getAsOpaquePointer()), + llvm::hash_value(prop.reduction_dims.getAsOpaquePointer())); +} + +std::optional MultiDimReductionOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "kind") + return prop.kind; + + if (name == "reduction_dims") + return prop.reduction_dims; + return std::nullopt; +} + +void MultiDimReductionOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "kind") { + prop.kind = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "reduction_dims") { + prop.reduction_dims = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void MultiDimReductionOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.kind) attrs.append("kind", prop.kind); + + if (prop.reduction_dims) attrs.append("reduction_dims", prop.reduction_dims); +} + +::llvm::LogicalResult MultiDimReductionOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getKindAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(attr, "kind", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getReductionDimsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(attr, "reduction_dims", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult MultiDimReductionOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.kind))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.reduction_dims))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void MultiDimReductionOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.kind); + writer.writeAttribute(prop.reduction_dims); +} + +::mlir::vector::CombiningKind MultiDimReductionOp::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +::llvm::ArrayRef MultiDimReductionOp::getReductionDims() { + auto attr = getReductionDimsAttr(); + return attr; +} + +void MultiDimReductionOp::setKind(::mlir::vector::CombiningKind attrValue) { + getProperties().kind = ::mlir::vector::CombiningKindAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void MultiDimReductionOp::setReductionDims(::llvm::ArrayRef attrValue) { + getProperties().reduction_dims = ::mlir::Builder((*this)->getContext()).getDenseI64ArrayAttr(attrValue); +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value acc, ::mlir::DenseI64ArrayAttr reduction_dims) { + odsState.addOperands(source); + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = kind; + odsState.getOrAddProperties().reduction_dims = reduction_dims; + odsState.addTypes(dest); +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value acc, ::mlir::DenseI64ArrayAttr reduction_dims) { + odsState.addOperands(source); + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = kind; + odsState.getOrAddProperties().reduction_dims = reduction_dims; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(MultiDimReductionOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value acc, ::mlir::DenseI64ArrayAttr reduction_dims) { + odsState.addOperands(source); + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = kind; + odsState.getOrAddProperties().reduction_dims = reduction_dims; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value acc, ::llvm::ArrayRef reduction_dims) { + odsState.addOperands(source); + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().reduction_dims = odsBuilder.getDenseI64ArrayAttr(reduction_dims); + odsState.addTypes(dest); +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value acc, ::llvm::ArrayRef reduction_dims) { + odsState.addOperands(source); + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().reduction_dims = odsBuilder.getDenseI64ArrayAttr(reduction_dims); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(MultiDimReductionOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value acc, ::llvm::ArrayRef reduction_dims) { + odsState.addOperands(source); + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().reduction_dims = odsBuilder.getDenseI64ArrayAttr(reduction_dims); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(MultiDimReductionOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void MultiDimReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(MultiDimReductionOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult MultiDimReductionOp::verifyInvariantsImpl() { + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + if (!tblgen_kind) return emitOpError("requires attribute 'kind'"); + auto tblgen_reduction_dims = getProperties().reduction_dims; (void)tblgen_reduction_dims; + if (!tblgen_reduction_dims) return emitOpError("requires attribute 'reduction_dims'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(*this, tblgen_kind, "kind"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(*this, tblgen_reduction_dims, "reduction_dims"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType()) && ((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSResults(0).begin()).getType())))) + return emitOpError("failed to verify that all of {dest, acc} have same type"); + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that source operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult MultiDimReductionOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::llvm::LogicalResult MultiDimReductionOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 1) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[1].getType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult MultiDimReductionOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::vector::CombiningKindAttr kindAttr; + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand accRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> accOperands(&accRawOperand, 1); ::llvm::SMLoc accOperandsLoc; + (void)accOperandsLoc; + ::mlir::DenseI64ArrayAttr reduction_dimsAttr; + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + ::mlir::Type destRawType{}; + ::llvm::ArrayRef<::mlir::Type> destTypes(&destRawType, 1); + + if (parser.parseCustomAttributeWithFallback(kindAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (kindAttr) result.getOrAddProperties().kind = kindAttr; + if (parser.parseComma()) + return ::mlir::failure(); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + accOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(accRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + + if (parser.parseCustomAttributeWithFallback(reduction_dimsAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (reduction_dimsAttr) result.getOrAddProperties().reduction_dims = reduction_dimsAttr; + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + { + ::mlir::Type type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + destRawType = type; + } + result.addTypes(destTypes); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(accOperands, destTypes[0], accOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void MultiDimReductionOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getKindAttr()); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getSource(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getAcc(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("kind"); + elidedAttrs.push_back("reduction_dims"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getReductionDimsAttr()); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + { + auto type = getDest().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::Type>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void MultiDimReductionOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::MultiDimReductionOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::OuterProductOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +OuterProductOpGenericAdaptorBase::OuterProductOpGenericAdaptorBase(OuterProductOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair OuterProductOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::vector::CombiningKindAttr OuterProductOpGenericAdaptorBase::getKindAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::vector::CombiningKindAttr>(getProperties().kind); + return attr; +} + +::mlir::vector::CombiningKind OuterProductOpGenericAdaptorBase::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +} // namespace detail +OuterProductOpAdaptor::OuterProductOpAdaptor(OuterProductOp op) : OuterProductOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult OuterProductOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + + if (tblgen_kind && !((::llvm::isa<::mlir::vector::CombiningKindAttr>(tblgen_kind)))) + return emitError(loc, "'vector.outerproduct' op ""attribute 'kind' failed to satisfy constraint: Kind of combining function for contractions and reductions"); + return ::mlir::success(); +} + +std::pair OuterProductOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange OuterProductOp::getAccMutable() { + auto range = getODSOperandIndexAndLength(2); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult OuterProductOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.kind; + auto attr = dict.get("kind"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `kind` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute OuterProductOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.kind; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("kind", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code OuterProductOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.kind.getAsOpaquePointer())); +} + +std::optional OuterProductOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "kind") + return prop.kind; + return std::nullopt; +} + +void OuterProductOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "kind") { + prop.kind = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void OuterProductOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.kind) attrs.append("kind", prop.kind); +} + +::llvm::LogicalResult OuterProductOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getKindAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(attr, "kind", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult OuterProductOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readOptionalAttribute(prop.kind))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void OuterProductOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + + writer.writeOptionalAttribute(prop.kind); +} + +::mlir::vector::CombiningKind OuterProductOp::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +void OuterProductOp::setKind(::mlir::vector::CombiningKind attrValue) { + getProperties().kind = ::mlir::vector::CombiningKindAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void OuterProductOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKindAttr kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + if (acc) + odsState.addOperands(acc); + if (kind) { + odsState.getOrAddProperties().kind = kind; + } + odsState.addTypes(resultType0); +} + +void OuterProductOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKindAttr kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + if (acc) + odsState.addOperands(acc); + if (kind) { + odsState.getOrAddProperties().kind = kind; + } + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void OuterProductOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKind kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + if (acc) + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.addTypes(resultType0); +} + +void OuterProductOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKind kind) { + odsState.addOperands(lhs); + odsState.addOperands(rhs); + if (acc) + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void OuterProductOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void OuterProductOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void OuterProductOp::populateDefaultProperties(::mlir::OperationName opName, Properties &properties) { + ::mlir::Builder odsBuilder(opName.getContext()); + if (!properties.kind) + properties.kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), CombiningKind::ADD); +} + +::llvm::LogicalResult OuterProductOp::verifyInvariantsImpl() { + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(*this, tblgen_kind, "kind"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + if (valueGroup2.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup2.size(); + } + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that lhs operand and result have same element type"); + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(1))))) + return emitOpError("failed to verify that rhs operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult OuterProductOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +void OuterProductOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::OuterProductOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::PrintOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +PrintOpGenericAdaptorBase::PrintOpGenericAdaptorBase(PrintOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair PrintOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::vector::PrintPunctuationAttr PrintOpGenericAdaptorBase::getPunctuationAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::vector::PrintPunctuationAttr>(getProperties().punctuation); + return attr; +} + +::mlir::vector::PrintPunctuation PrintOpGenericAdaptorBase::getPunctuation() { + auto attr = getPunctuationAttr(); + return attr.getValue(); +} + +::std::optional<::mlir::StringAttr> PrintOpGenericAdaptorBase::getStringLiteral() { + auto attr = getStringLiteralAttr(); + return attr ? ::std::optional<::mlir::StringAttr>(::llvm::cast<::mlir::StringAttr>(attr)) : (::std::nullopt); +} + +} // namespace detail +PrintOpAdaptor::PrintOpAdaptor(PrintOp op) : PrintOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult PrintOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_punctuation = getProperties().punctuation; (void)tblgen_punctuation; + auto tblgen_stringLiteral = getProperties().stringLiteral; (void)tblgen_stringLiteral; + + if (tblgen_punctuation && !((::llvm::isa<::mlir::vector::PrintPunctuationAttr>(tblgen_punctuation)))) + return emitError(loc, "'vector.print' op ""attribute 'punctuation' failed to satisfy constraint: Punctuation for separating vectors or vector elements"); + + if (tblgen_stringLiteral && !((::llvm::isa<::mlir::StringAttr>(tblgen_stringLiteral)))) + return emitError(loc, "'vector.print' op ""attribute 'stringLiteral' failed to satisfy constraint: An Attribute containing a string"); + return ::mlir::success(); +} + +std::pair PrintOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange PrintOp::getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult PrintOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.punctuation; + auto attr = dict.get("punctuation"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `punctuation` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.stringLiteral; + auto attr = dict.get("stringLiteral"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `stringLiteral` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute PrintOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.punctuation; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("punctuation", + propStorage)); + } + + { + const auto &propStorage = prop.stringLiteral; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("stringLiteral", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code PrintOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.punctuation.getAsOpaquePointer()), + llvm::hash_value(prop.stringLiteral.getAsOpaquePointer())); +} + +std::optional PrintOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "punctuation") + return prop.punctuation; + + if (name == "stringLiteral") + return prop.stringLiteral; + return std::nullopt; +} + +void PrintOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "punctuation") { + prop.punctuation = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "stringLiteral") { + prop.stringLiteral = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void PrintOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.punctuation) attrs.append("punctuation", prop.punctuation); + + if (prop.stringLiteral) attrs.append("stringLiteral", prop.stringLiteral); +} + +::llvm::LogicalResult PrintOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getPunctuationAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps8(attr, "punctuation", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getStringLiteralAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps9(attr, "stringLiteral", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult PrintOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readOptionalAttribute(prop.punctuation))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readOptionalAttribute(prop.stringLiteral))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void PrintOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + + writer.writeOptionalAttribute(prop.punctuation); + + writer.writeOptionalAttribute(prop.stringLiteral); +} + +::mlir::vector::PrintPunctuation PrintOp::getPunctuation() { + auto attr = getPunctuationAttr(); + return attr.getValue(); +} + +::std::optional<::mlir::StringAttr> PrintOp::getStringLiteral() { + auto attr = getStringLiteralAttr(); + return attr ? ::std::optional<::mlir::StringAttr>(::llvm::cast<::mlir::StringAttr>(attr)) : (::std::nullopt); +} + +void PrintOp::setPunctuation(::mlir::vector::PrintPunctuation attrValue) { + getProperties().punctuation = ::mlir::vector::PrintPunctuationAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, PrintPunctuation punctuation) { + build(odsBuilder, odsState, {}, punctuation, {}); + +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source) { + build(odsBuilder, odsState, source, PrintPunctuation::NewLine); + +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source, PrintPunctuation punctuation) { + build(odsBuilder, odsState, source, punctuation, {}); + +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::llvm::StringRef string) { + build(odsBuilder, odsState, {}, PrintPunctuation::NewLine, odsBuilder.getStringAttr(string)); + +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuationAttr punctuation, /*optional*/::mlir::StringAttr stringLiteral) { + if (source) + odsState.addOperands(source); + if (punctuation) { + odsState.getOrAddProperties().punctuation = punctuation; + } + if (stringLiteral) { + odsState.getOrAddProperties().stringLiteral = stringLiteral; + } +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuationAttr punctuation, /*optional*/::mlir::StringAttr stringLiteral) { + if (source) + odsState.addOperands(source); + if (punctuation) { + odsState.getOrAddProperties().punctuation = punctuation; + } + if (stringLiteral) { + odsState.getOrAddProperties().stringLiteral = stringLiteral; + } + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuation punctuation, /*optional*/::mlir::StringAttr stringLiteral) { + if (source) + odsState.addOperands(source); + odsState.getOrAddProperties().punctuation = ::mlir::vector::PrintPunctuationAttr::get(odsBuilder.getContext(), punctuation); + if (stringLiteral) { + odsState.getOrAddProperties().stringLiteral = stringLiteral; + } +} + +void PrintOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuation punctuation, /*optional*/::mlir::StringAttr stringLiteral) { + if (source) + odsState.addOperands(source); + odsState.getOrAddProperties().punctuation = ::mlir::vector::PrintPunctuationAttr::get(odsBuilder.getContext(), punctuation); + if (stringLiteral) { + odsState.getOrAddProperties().stringLiteral = stringLiteral; + } + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void PrintOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void PrintOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void PrintOp::populateDefaultProperties(::mlir::OperationName opName, Properties &properties) { + ::mlir::Builder odsBuilder(opName.getContext()); + if (!properties.punctuation) + properties.punctuation = ::mlir::vector::PrintPunctuationAttr::get(odsBuilder.getContext(), ::mlir::vector::PrintPunctuation::NewLine); +} + +::llvm::LogicalResult PrintOp::verifyInvariantsImpl() { + auto tblgen_punctuation = getProperties().punctuation; (void)tblgen_punctuation; + auto tblgen_stringLiteral = getProperties().stringLiteral; (void)tblgen_stringLiteral; + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps8(*this, tblgen_punctuation, "punctuation"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps9(*this, tblgen_stringLiteral, "stringLiteral"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + if (valueGroup0.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup0.size(); + } + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps17(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + if (!((!getStringLiteral() || (!getSource() && getPunctuation() == PrintPunctuation::NewLine)))) + return emitOpError("failed to verify that `source` or `punctuation` are not set when printing strings"); + return ::mlir::success(); +} + +::llvm::LogicalResult PrintOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult PrintOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> sourceOperands; + ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::llvm::SmallVector<::mlir::Type, 1> sourceTypes; + ::mlir::StringAttr stringLiteralAttr; + ::mlir::vector::PrintPunctuationAttr punctuationAttr; + + { + sourceOperandsLoc = parser.getCurrentLocation(); + ::mlir::OpAsmParser::UnresolvedOperand operand; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalOperand(operand); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + sourceOperands.push_back(operand); + } + } + if (!sourceOperands.empty()) { + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::Type optionalType; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalType(optionalType); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + sourceTypes.push_back(optionalType); + } + } + } + bool strClause = false; + bool punctuationClause = false; + while(true) { +if (succeeded(parser.parseOptionalKeyword("str"))) { + + if (strClause) { + return parser.emitError(parser.getNameLoc()) + << "`str` clause can appear at most once in the expansion of the " + "oilist directive"; + } + strClause = true; + + ::mlir::OptionalParseResult parseResultstringLiteralAttr = + parser.parseOptionalAttribute(stringLiteralAttr, ::mlir::Type{}); + if (parseResultstringLiteralAttr.has_value() && failed(*parseResultstringLiteralAttr)) + return ::mlir::failure(); + if (parseResultstringLiteralAttr.has_value() && succeeded(*parseResultstringLiteralAttr)) + if (stringLiteralAttr) result.getOrAddProperties().stringLiteral = stringLiteralAttr; + } else if (succeeded(parser.parseOptionalKeyword("punctuation"))) { + + if (punctuationClause) { + return parser.emitError(parser.getNameLoc()) + << "`punctuation` clause can appear at most once in the expansion of the " + "oilist directive"; + } + punctuationClause = true; + + if (parser.parseCustomAttributeWithFallback(punctuationAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (punctuationAttr) result.getOrAddProperties().punctuation = punctuationAttr; + } else { + break; + } +} + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void PrintOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + if (getSource()) { + _odsPrinter << ' '; + if (::mlir::Value value = getSource()) + _odsPrinter << value; + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << (getSource() ? ::llvm::ArrayRef<::mlir::Type>(getSource().getType()) : ::llvm::ArrayRef<::mlir::Type>()); + } + if (false || (getStringLiteralAttr())) { + _odsPrinter << ' ' << "str"; + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getStringLiteralAttr()); + } + if (false || (getPunctuationAttr() != ::mlir::vector::PrintPunctuationAttr::get(::mlir::OpBuilder((*this)->getContext()).getContext(), ::mlir::vector::PrintPunctuation::NewLine))) { + _odsPrinter << ' ' << "punctuation"; + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getPunctuationAttr()); + } + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("stringLiteral"); + elidedAttrs.push_back("punctuation"); + { + ::mlir::Builder odsBuilder(getContext()); + ::mlir::Attribute attr = getPunctuationAttr(); + if(attr && (attr == ::mlir::vector::PrintPunctuationAttr::get(odsBuilder.getContext(), ::mlir::vector::PrintPunctuation::NewLine))) + elidedAttrs.push_back("punctuation"); + } + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); +} + +void PrintOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + effects.emplace_back(::mlir::MemoryEffects::Write::get(), 0, false, ::mlir::SideEffects::DefaultResource::get()); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::PrintOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ReductionOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ReductionOpGenericAdaptorBase::ReductionOpGenericAdaptorBase(ReductionOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair ReductionOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::vector::CombiningKind ReductionOpGenericAdaptorBase::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +::mlir::arith::FastMathFlagsAttr ReductionOpGenericAdaptorBase::getFastmathAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::arith::FastMathFlagsAttr>(getProperties().fastmath); + return attr; +} + +::mlir::arith::FastMathFlags ReductionOpGenericAdaptorBase::getFastmath() { + auto attr = getFastmathAttr(); + return attr.getValue(); +} + +} // namespace detail +ReductionOpAdaptor::ReductionOpAdaptor(ReductionOp op) : ReductionOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ReductionOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_fastmath = getProperties().fastmath; (void)tblgen_fastmath; + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + if (!tblgen_kind) return emitError(loc, "'vector.reduction' op ""requires attribute 'kind'"); + + if (tblgen_kind && !((::llvm::isa<::mlir::vector::CombiningKindAttr>(tblgen_kind)))) + return emitError(loc, "'vector.reduction' op ""attribute 'kind' failed to satisfy constraint: Kind of combining function for contractions and reductions"); + + if (tblgen_fastmath && !((::llvm::isa<::mlir::arith::FastMathFlagsAttr>(tblgen_fastmath)))) + return emitError(loc, "'vector.reduction' op ""attribute 'fastmath' failed to satisfy constraint: Floating point fast math flags"); + return ::mlir::success(); +} + +std::pair ReductionOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 1) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange ReductionOp::getAccMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult ReductionOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.fastmath; + auto attr = dict.get("fastmath"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `fastmath` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.kind; + auto attr = dict.get("kind"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `kind` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ReductionOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.fastmath; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("fastmath", + propStorage)); + } + + { + const auto &propStorage = prop.kind; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("kind", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ReductionOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.fastmath.getAsOpaquePointer()), + llvm::hash_value(prop.kind.getAsOpaquePointer())); +} + +std::optional ReductionOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "fastmath") + return prop.fastmath; + + if (name == "kind") + return prop.kind; + return std::nullopt; +} + +void ReductionOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "fastmath") { + prop.fastmath = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "kind") { + prop.kind = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ReductionOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.fastmath) attrs.append("fastmath", prop.fastmath); + + if (prop.kind) attrs.append("kind", prop.kind); +} + +::llvm::LogicalResult ReductionOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getFastmathAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps10(attr, "fastmath", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getKindAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(attr, "kind", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ReductionOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readOptionalAttribute(prop.fastmath))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.kind))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ReductionOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + + writer.writeOptionalAttribute(prop.fastmath); + writer.writeAttribute(prop.kind); +} + +::mlir::vector::CombiningKind ReductionOp::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +::mlir::arith::FastMathFlags ReductionOp::getFastmath() { + auto attr = getFastmathAttr(); + return attr.getValue(); +} + +void ReductionOp::setKind(::mlir::vector::CombiningKind attrValue) { + getProperties().kind = ::mlir::vector::CombiningKindAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void ReductionOp::setFastmath(::mlir::arith::FastMathFlags attrValue) { + getProperties().fastmath = ::mlir::arith::FastMathFlagsAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void ReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlagsAttr fastmath) { + odsState.addOperands(vector); + if (acc) + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = kind; + if (fastmath) { + odsState.getOrAddProperties().fastmath = fastmath; + } + odsState.addTypes(dest); +} + +void ReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlagsAttr fastmath) { + odsState.addOperands(vector); + if (acc) + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = kind; + if (fastmath) { + odsState.getOrAddProperties().fastmath = fastmath; + } + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKind kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlags fastmath) { + odsState.addOperands(vector); + if (acc) + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().fastmath = ::mlir::arith::FastMathFlagsAttr::get(odsBuilder.getContext(), fastmath); + odsState.addTypes(dest); +} + +void ReductionOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKind kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlags fastmath) { + odsState.addOperands(vector); + if (acc) + odsState.addOperands(acc); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().fastmath = ::mlir::arith::FastMathFlagsAttr::get(odsBuilder.getContext(), fastmath); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ReductionOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ReductionOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ReductionOp::populateDefaultProperties(::mlir::OperationName opName, Properties &properties) { + ::mlir::Builder odsBuilder(opName.getContext()); + if (!properties.fastmath) + properties.fastmath = ::mlir::arith::FastMathFlagsAttr::get(odsBuilder.getContext(), ::mlir::arith::FastMathFlags::none); +} + +::llvm::LogicalResult ReductionOp::verifyInvariantsImpl() { + auto tblgen_fastmath = getProperties().fastmath; (void)tblgen_fastmath; + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + if (!tblgen_kind) return emitOpError("requires attribute 'kind'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(*this, tblgen_kind, "kind"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps10(*this, tblgen_fastmath, "fastmath"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + if (valueGroup1.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup1.size(); + } + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that source operand and result have same element type"); + if (!((!getDest() || !getAcc() || std::equal_to<>()(::llvm::cast((*this->getODSResults(0).begin()).getType()), (*this->getODSOperands(1).begin()).getType())))) + return emitOpError("failed to verify that dest and acc have the same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult ReductionOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ReductionOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::vector::CombiningKindAttr kindAttr; + ::mlir::OpAsmParser::UnresolvedOperand vectorRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> vectorOperands(&vectorRawOperand, 1); ::llvm::SMLoc vectorOperandsLoc; + (void)vectorOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> accOperands; + ::llvm::SMLoc accOperandsLoc; + (void)accOperandsLoc; + ::mlir::arith::FastMathFlagsAttr fastmathAttr; + ::mlir::Type vectorRawType{}; + ::llvm::ArrayRef<::mlir::Type> vectorTypes(&vectorRawType, 1); + ::mlir::Type destRawType{}; + ::llvm::ArrayRef<::mlir::Type> destTypes(&destRawType, 1); + + if (parser.parseCustomAttributeWithFallback(kindAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (kindAttr) result.getOrAddProperties().kind = kindAttr; + if (parser.parseComma()) + return ::mlir::failure(); + + vectorOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(vectorRawOperand)) + return ::mlir::failure(); + if (::mlir::succeeded(parser.parseOptionalComma())) { + + { + accOperandsLoc = parser.getCurrentLocation(); + ::mlir::OpAsmParser::UnresolvedOperand operand; + ::mlir::OptionalParseResult parseResult = + parser.parseOptionalOperand(operand); + if (parseResult.has_value()) { + if (failed(*parseResult)) + return ::mlir::failure(); + accOperands.push_back(operand); + } + } + } + if (::mlir::succeeded(parser.parseOptionalKeyword("fastmath"))) { + + if (parser.parseCustomAttributeWithFallback(fastmathAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (fastmathAttr) result.getOrAddProperties().fastmath = fastmathAttr; + } + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + vectorRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::Type type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + destRawType = type; + } + for (::mlir::Type type : destTypes) { + (void)type; + if (!((true))) { + return parser.emitError(parser.getNameLoc()) << "'dest' must be any type, but got " << type; + } + } + result.addTypes(destTypes); + if (parser.resolveOperands(vectorOperands, vectorTypes, vectorOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(accOperands, ::llvm::cast(destTypes[0]), accOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ReductionOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getKindAttr()); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getVector(); + if (getAcc()) { + _odsPrinter << ","; + _odsPrinter << ' '; + if (::mlir::Value value = getAcc()) + _odsPrinter << value; + } + if (getFastmathAttr() != ::mlir::arith::FastMathFlagsAttr::get(::mlir::OpBuilder((*this)->getContext()).getContext(), ::mlir::arith::FastMathFlags::none)) { + _odsPrinter << ' ' << "fastmath"; + _odsPrinter.printStrippedAttrOrType(getFastmathAttr()); + } + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("kind"); + elidedAttrs.push_back("fastmath"); + { + ::mlir::Builder odsBuilder(getContext()); + ::mlir::Attribute attr = getFastmathAttr(); + if(attr && (attr == ::mlir::arith::FastMathFlagsAttr::get(odsBuilder.getContext(), ::mlir::arith::FastMathFlags::none))) + elidedAttrs.push_back("fastmath"); + } + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getVector().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getDest().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::Type>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ReductionOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ReductionOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScalableExtractOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ScalableExtractOpGenericAdaptorBase::ScalableExtractOpGenericAdaptorBase(ScalableExtractOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +uint64_t ScalableExtractOpGenericAdaptorBase::getPos() { + auto attr = getPosAttr(); + return attr.getValue().getZExtValue(); +} + +} // namespace detail +ScalableExtractOpAdaptor::ScalableExtractOpAdaptor(ScalableExtractOp op) : ScalableExtractOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ScalableExtractOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_pos = getProperties().pos; (void)tblgen_pos; + if (!tblgen_pos) return emitError(loc, "'vector.scalable.extract' op ""requires attribute 'pos'"); + + if (tblgen_pos && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_pos))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_pos).getType().isSignlessInteger(64))))) + return emitError(loc, "'vector.scalable.extract' op ""attribute 'pos' failed to satisfy constraint: 64-bit signless integer attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult ScalableExtractOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.pos; + auto attr = dict.get("pos"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `pos` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ScalableExtractOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.pos; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("pos", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ScalableExtractOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.pos.getAsOpaquePointer())); +} + +std::optional ScalableExtractOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "pos") + return prop.pos; + return std::nullopt; +} + +void ScalableExtractOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "pos") { + prop.pos = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ScalableExtractOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.pos) attrs.append("pos", prop.pos); +} + +::llvm::LogicalResult ScalableExtractOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getPosAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps11(attr, "pos", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ScalableExtractOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.pos))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScalableExtractOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.pos); +} + +uint64_t ScalableExtractOp::getPos() { + auto attr = getPosAttr(); + return attr.getValue().getZExtValue(); +} + +void ScalableExtractOp::setPos(uint64_t attrValue) { + getProperties().pos = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(64), attrValue); +} + +void ScalableExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value source, ::mlir::IntegerAttr pos) { + odsState.addOperands(source); + odsState.getOrAddProperties().pos = pos; + odsState.addTypes(res); +} + +void ScalableExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source, ::mlir::IntegerAttr pos) { + odsState.addOperands(source); + odsState.getOrAddProperties().pos = pos; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScalableExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value source, uint64_t pos) { + odsState.addOperands(source); + odsState.getOrAddProperties().pos = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), pos); + odsState.addTypes(res); +} + +void ScalableExtractOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source, uint64_t pos) { + odsState.addOperands(source); + odsState.getOrAddProperties().pos = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), pos); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScalableExtractOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ScalableExtractOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult ScalableExtractOp::verifyInvariantsImpl() { + auto tblgen_pos = getProperties().pos; (void)tblgen_pos; + if (!tblgen_pos) return emitOpError("requires attribute 'pos'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps11(*this, tblgen_pos, "pos"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps18(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps19(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!(((getElementTypeOrSelf((*this->getODSOperands(0).begin()))) == (getElementTypeOrSelf((*this->getODSResults(0).begin()))) && (getElementTypeOrSelf((*this->getODSResults(0).begin()))) == (getElementTypeOrSelf((*this->getODSOperands(0).begin())))))) + return emitOpError("failed to verify that all of {source, res} have same element type"); + if (!(((getPos() % getResultVectorType().getNumElements()) == 0))) + return emitOpError("failed to verify that position is a multiple of the result length."); + return ::mlir::success(); +} + +::llvm::LogicalResult ScalableExtractOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult ScalableExtractOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::IntegerAttr posAttr; + ::mlir::Type resRawType{}; + ::llvm::ArrayRef<::mlir::Type> resTypes(&resRawType, 1); + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + if (parser.parseCustomAttributeWithFallback(posAttr, parser.getBuilder().getIntegerType(64))) { + return ::mlir::failure(); + } + if (posAttr) result.getOrAddProperties().pos = posAttr; + if (parser.parseRSquare()) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resRawType = type; + } + if (parser.parseKeyword("from")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + result.addTypes(resTypes); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScalableExtractOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getSource(); + _odsPrinter << "["; + _odsPrinter.printAttributeWithoutType(getPosAttr()); + _odsPrinter << "]"; + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("pos"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getRes().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "from"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ScalableExtractOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ScalableExtractOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScalableInsertOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ScalableInsertOpGenericAdaptorBase::ScalableInsertOpGenericAdaptorBase(ScalableInsertOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +uint64_t ScalableInsertOpGenericAdaptorBase::getPos() { + auto attr = getPosAttr(); + return attr.getValue().getZExtValue(); +} + +} // namespace detail +ScalableInsertOpAdaptor::ScalableInsertOpAdaptor(ScalableInsertOp op) : ScalableInsertOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ScalableInsertOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_pos = getProperties().pos; (void)tblgen_pos; + if (!tblgen_pos) return emitError(loc, "'vector.scalable.insert' op ""requires attribute 'pos'"); + + if (tblgen_pos && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_pos))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_pos).getType().isSignlessInteger(64))))) + return emitError(loc, "'vector.scalable.insert' op ""attribute 'pos' failed to satisfy constraint: 64-bit signless integer attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult ScalableInsertOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.pos; + auto attr = dict.get("pos"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `pos` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ScalableInsertOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.pos; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("pos", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ScalableInsertOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.pos.getAsOpaquePointer())); +} + +std::optional ScalableInsertOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "pos") + return prop.pos; + return std::nullopt; +} + +void ScalableInsertOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "pos") { + prop.pos = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ScalableInsertOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.pos) attrs.append("pos", prop.pos); +} + +::llvm::LogicalResult ScalableInsertOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getPosAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps11(attr, "pos", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ScalableInsertOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.pos))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScalableInsertOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.pos); +} + +uint64_t ScalableInsertOp::getPos() { + auto attr = getPosAttr(); + return attr.getValue().getZExtValue(); +} + +void ScalableInsertOp::setPos(uint64_t attrValue) { + getProperties().pos = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(64), attrValue); +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::IntegerAttr pos) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().pos = pos; + odsState.addTypes(res); +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::IntegerAttr pos) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().pos = pos; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScalableInsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::IntegerAttr pos) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().pos = pos; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value valueToStore, ::mlir::Value dest, uint64_t pos) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().pos = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), pos); + odsState.addTypes(res); +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, uint64_t pos) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().pos = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), pos); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScalableInsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, uint64_t pos) { + odsState.addOperands(valueToStore); + odsState.addOperands(dest); + odsState.getOrAddProperties().pos = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), pos); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScalableInsertOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScalableInsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void ScalableInsertOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ScalableInsertOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScalableInsertOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult ScalableInsertOp::verifyInvariantsImpl() { + auto tblgen_pos = getProperties().pos; (void)tblgen_pos; + if (!tblgen_pos) return emitOpError("requires attribute 'pos'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps11(*this, tblgen_pos, "pos"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps19(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps18(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps18(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!(((getElementTypeOrSelf((*this->getODSOperands(0).begin()))) == (getElementTypeOrSelf((*this->getODSOperands(1).begin()))) && (getElementTypeOrSelf((*this->getODSOperands(1).begin()))) == (getElementTypeOrSelf((*this->getODSOperands(0).begin())))))) + return emitOpError("failed to verify that all of {valueToStore, dest} have same element type"); + if (!((((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSResults(0).begin()).getType()) && ((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType())))) + return emitOpError("failed to verify that all of {dest, res} have same type"); + if (!(((getPos() % getSourceVectorType().getNumElements()) == 0))) + return emitOpError("failed to verify that position is a multiple of the source length."); + return ::mlir::success(); +} + +::llvm::LogicalResult ScalableInsertOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::llvm::LogicalResult ScalableInsertOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(1); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 1) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[1].getType(); + inferredReturnTypes[0] = odsInferredType0; + return ::mlir::success(); +} + +::mlir::ParseResult ScalableInsertOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand destRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> destOperands(&destRawOperand, 1); ::llvm::SMLoc destOperandsLoc; + (void)destOperandsLoc; + ::mlir::IntegerAttr posAttr; + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + ::mlir::Type destRawType{}; + ::llvm::ArrayRef<::mlir::Type> destTypes(&destRawType, 1); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + destOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(destRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + if (parser.parseCustomAttributeWithFallback(posAttr, parser.getBuilder().getIntegerType(64))) { + return ::mlir::failure(); + } + if (posAttr) result.getOrAddProperties().pos = posAttr; + if (parser.parseRSquare()) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + if (parser.parseKeyword("into")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + destRawType = type; + } + result.addTypes(destTypes[0]); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(destOperands, destTypes, destOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScalableInsertOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getDest(); + _odsPrinter << "["; + _odsPrinter.printAttributeWithoutType(getPosAttr()); + _odsPrinter << "]"; + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("pos"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "into"; + _odsPrinter << ' '; + { + auto type = getDest().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ScalableInsertOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ScalableInsertOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScanOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ScanOpGenericAdaptorBase::ScanOpGenericAdaptorBase(ScanOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::mlir::vector::CombiningKind ScanOpGenericAdaptorBase::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +uint64_t ScanOpGenericAdaptorBase::getReductionDim() { + auto attr = getReductionDimAttr(); + return attr.getValue().getZExtValue(); +} + +bool ScanOpGenericAdaptorBase::getInclusive() { + auto attr = getInclusiveAttr(); + return attr.getValue(); +} + +} // namespace detail +ScanOpAdaptor::ScanOpAdaptor(ScanOp op) : ScanOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ScanOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_inclusive = getProperties().inclusive; (void)tblgen_inclusive; + if (!tblgen_inclusive) return emitError(loc, "'vector.scan' op ""requires attribute 'inclusive'"); + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + if (!tblgen_kind) return emitError(loc, "'vector.scan' op ""requires attribute 'kind'"); + auto tblgen_reduction_dim = getProperties().reduction_dim; (void)tblgen_reduction_dim; + if (!tblgen_reduction_dim) return emitError(loc, "'vector.scan' op ""requires attribute 'reduction_dim'"); + + if (tblgen_kind && !((::llvm::isa<::mlir::vector::CombiningKindAttr>(tblgen_kind)))) + return emitError(loc, "'vector.scan' op ""attribute 'kind' failed to satisfy constraint: Kind of combining function for contractions and reductions"); + + if (tblgen_reduction_dim && !(((::llvm::isa<::mlir::IntegerAttr>(tblgen_reduction_dim))) && ((::llvm::cast<::mlir::IntegerAttr>(tblgen_reduction_dim).getType().isSignlessInteger(64))))) + return emitError(loc, "'vector.scan' op ""attribute 'reduction_dim' failed to satisfy constraint: 64-bit signless integer attribute"); + + if (tblgen_inclusive && !((::llvm::isa<::mlir::BoolAttr>(tblgen_inclusive)))) + return emitError(loc, "'vector.scan' op ""attribute 'inclusive' failed to satisfy constraint: bool attribute"); + return ::mlir::success(); +} + +void ScanOp::getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn) { + auto resultGroup0 = getODSResults(0); + if (!resultGroup0.empty()) + setNameFn(*resultGroup0.begin(), "dest"); + auto resultGroup1 = getODSResults(1); + if (!resultGroup1.empty()) + setNameFn(*resultGroup1.begin(), "accumulated_value"); +} + +::llvm::LogicalResult ScanOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.inclusive; + auto attr = dict.get("inclusive"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `inclusive` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.kind; + auto attr = dict.get("kind"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `kind` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.reduction_dim; + auto attr = dict.get("reduction_dim"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `reduction_dim` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ScanOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.inclusive; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("inclusive", + propStorage)); + } + + { + const auto &propStorage = prop.kind; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("kind", + propStorage)); + } + + { + const auto &propStorage = prop.reduction_dim; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("reduction_dim", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ScanOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.inclusive.getAsOpaquePointer()), + llvm::hash_value(prop.kind.getAsOpaquePointer()), + llvm::hash_value(prop.reduction_dim.getAsOpaquePointer())); +} + +std::optional ScanOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "inclusive") + return prop.inclusive; + + if (name == "kind") + return prop.kind; + + if (name == "reduction_dim") + return prop.reduction_dim; + return std::nullopt; +} + +void ScanOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "inclusive") { + prop.inclusive = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "kind") { + prop.kind = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "reduction_dim") { + prop.reduction_dim = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ScanOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.inclusive) attrs.append("inclusive", prop.inclusive); + + if (prop.kind) attrs.append("kind", prop.kind); + + if (prop.reduction_dim) attrs.append("reduction_dim", prop.reduction_dim); +} + +::llvm::LogicalResult ScanOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getInclusiveAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps7(attr, "inclusive", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getKindAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(attr, "kind", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getReductionDimAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps11(attr, "reduction_dim", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ScanOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.inclusive))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.kind))) + return ::mlir::failure(); + + if (::mlir::failed(reader.readAttribute(prop.reduction_dim))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScanOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.inclusive); + writer.writeAttribute(prop.kind); + writer.writeAttribute(prop.reduction_dim); +} + +::mlir::vector::CombiningKind ScanOp::getKind() { + auto attr = getKindAttr(); + return attr.getValue(); +} + +uint64_t ScanOp::getReductionDim() { + auto attr = getReductionDimAttr(); + return attr.getValue().getZExtValue(); +} + +bool ScanOp::getInclusive() { + auto attr = getInclusiveAttr(); + return attr.getValue(); +} + +void ScanOp::setKind(::mlir::vector::CombiningKind attrValue) { + getProperties().kind = ::mlir::vector::CombiningKindAttr::get(::mlir::Builder((*this)->getContext()).getContext(), attrValue); +} + +void ScanOp::setReductionDim(uint64_t attrValue) { + getProperties().reduction_dim = ::mlir::Builder((*this)->getContext()).getIntegerAttr(::mlir::Builder((*this)->getContext()).getIntegerType(64), attrValue); +} + +void ScanOp::setInclusive(bool attrValue) { + getProperties().inclusive = ::mlir::Builder((*this)->getContext()).getBoolAttr(attrValue); +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::Type accumulated_value, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value initial_value, ::mlir::IntegerAttr reduction_dim, ::mlir::BoolAttr inclusive) { + odsState.addOperands(source); + odsState.addOperands(initial_value); + odsState.getOrAddProperties().kind = kind; + odsState.getOrAddProperties().reduction_dim = reduction_dim; + odsState.getOrAddProperties().inclusive = inclusive; + odsState.addTypes(dest); + odsState.addTypes(accumulated_value); +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value initial_value, ::mlir::IntegerAttr reduction_dim, ::mlir::BoolAttr inclusive) { + odsState.addOperands(source); + odsState.addOperands(initial_value); + odsState.getOrAddProperties().kind = kind; + odsState.getOrAddProperties().reduction_dim = reduction_dim; + odsState.getOrAddProperties().inclusive = inclusive; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScanOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value initial_value, ::mlir::IntegerAttr reduction_dim, ::mlir::BoolAttr inclusive) { + odsState.addOperands(source); + odsState.addOperands(initial_value); + odsState.getOrAddProperties().kind = kind; + odsState.getOrAddProperties().reduction_dim = reduction_dim; + odsState.getOrAddProperties().inclusive = inclusive; + assert(resultTypes.size() == 2u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::Type accumulated_value, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value initial_value, uint64_t reduction_dim, bool inclusive) { + odsState.addOperands(source); + odsState.addOperands(initial_value); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().reduction_dim = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), reduction_dim); + odsState.getOrAddProperties().inclusive = odsBuilder.getBoolAttr(inclusive); + odsState.addTypes(dest); + odsState.addTypes(accumulated_value); +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value initial_value, uint64_t reduction_dim, bool inclusive) { + odsState.addOperands(source); + odsState.addOperands(initial_value); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().reduction_dim = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), reduction_dim); + odsState.getOrAddProperties().inclusive = odsBuilder.getBoolAttr(inclusive); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScanOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value initial_value, uint64_t reduction_dim, bool inclusive) { + odsState.addOperands(source); + odsState.addOperands(initial_value); + odsState.getOrAddProperties().kind = ::mlir::vector::CombiningKindAttr::get(odsBuilder.getContext(), kind); + odsState.getOrAddProperties().reduction_dim = odsBuilder.getIntegerAttr(odsBuilder.getIntegerType(64), reduction_dim); + odsState.getOrAddProperties().inclusive = odsBuilder.getBoolAttr(inclusive); + assert(resultTypes.size() == 2u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScanOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScanOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void ScanOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ScanOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ScanOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 2u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult ScanOp::verifyInvariantsImpl() { + auto tblgen_inclusive = getProperties().inclusive; (void)tblgen_inclusive; + if (!tblgen_inclusive) return emitOpError("requires attribute 'inclusive'"); + auto tblgen_kind = getProperties().kind; (void)tblgen_kind; + if (!tblgen_kind) return emitOpError("requires attribute 'kind'"); + auto tblgen_reduction_dim = getProperties().reduction_dim; (void)tblgen_reduction_dim; + if (!tblgen_reduction_dim) return emitOpError("requires attribute 'reduction_dim'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps4(*this, tblgen_kind, "kind"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps11(*this, tblgen_reduction_dim, "reduction_dim"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps7(*this, tblgen_inclusive, "inclusive"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSResults(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((((*this->getODSOperands(0).begin()).getType()) == ((*this->getODSResults(0).begin()).getType()) && ((*this->getODSResults(0).begin()).getType()) == ((*this->getODSOperands(0).begin()).getType())))) + return emitOpError("failed to verify that all of {source, dest} have same type"); + if (!((((*this->getODSOperands(1).begin()).getType()) == ((*this->getODSResults(1).begin()).getType()) && ((*this->getODSResults(1).begin()).getType()) == ((*this->getODSOperands(1).begin()).getType())))) + return emitOpError("failed to verify that all of {initial_value, accumulated_value} have same type"); + return ::mlir::success(); +} + +::llvm::LogicalResult ScanOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::llvm::LogicalResult ScanOp::inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes) { + inferredReturnTypes.resize(2); + ::mlir::Builder odsBuilder(context); + if (operands.size() <= 1) + return ::mlir::failure(); + ::mlir::Type odsInferredType0 = operands[0].getType(); + ::mlir::Type odsInferredType1 = operands[1].getType(); + inferredReturnTypes[0] = odsInferredType0; + inferredReturnTypes[1] = odsInferredType1; + return ::mlir::success(); +} + +::mlir::ParseResult ScanOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::vector::CombiningKindAttr kindAttr; + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand initial_valueRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> initial_valueOperands(&initial_valueRawOperand, 1); ::llvm::SMLoc initial_valueOperandsLoc; + (void)initial_valueOperandsLoc; + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + ::mlir::Type initial_valueRawType{}; + ::llvm::ArrayRef<::mlir::Type> initial_valueTypes(&initial_valueRawType, 1); + + if (parser.parseCustomAttributeWithFallback(kindAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (kindAttr) result.getOrAddProperties().kind = kindAttr; + if (parser.parseComma()) + return ::mlir::failure(); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + initial_valueOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(initial_valueRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + initial_valueRawType = type; + } + result.addTypes(sourceTypes[0]); + result.addTypes(initial_valueTypes[0]); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(initial_valueOperands, initial_valueTypes, initial_valueOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScanOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getKindAttr()); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getSource(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getInitialValue(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("kind"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getInitialValue().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ScanOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ScanOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScatterOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ScatterOpGenericAdaptorBase::ScatterOpGenericAdaptorBase(ScatterOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair ScatterOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, true, false, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 4) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +ScatterOpAdaptor::ScatterOpAdaptor(ScatterOp op) : ScatterOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ScatterOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair ScatterOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, true, false, false, false}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 4) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange ScatterOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult ScatterOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute ScatterOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ScatterOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional ScatterOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void ScatterOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void ScatterOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult ScatterOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void ScatterOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value valueToStore) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(index_vec); + odsState.addOperands(mask); + odsState.addOperands(valueToStore); +} + +void ScatterOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value valueToStore) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(index_vec); + odsState.addOperands(mask); + odsState.addOperands(valueToStore); + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ScatterOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 4u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ScatterOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 4u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult ScatterOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps15(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup4 = getODSOperands(4); + + for (auto v : valueGroup4) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult ScatterOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ScatterOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand index_vecRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> index_vecOperands(&index_vecRawOperand, 1); ::llvm::SMLoc index_vecOperandsLoc; + (void)index_vecOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand maskRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> maskOperands(&maskRawOperand, 1); ::llvm::SMLoc maskOperandsLoc; + (void)maskOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type index_vecRawType{}; + ::llvm::ArrayRef<::mlir::Type> index_vecTypes(&index_vecRawType, 1); + ::mlir::Type maskRawType{}; + ::llvm::ArrayRef<::mlir::Type> maskTypes(&maskRawType, 1); + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + index_vecOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(index_vecRawOperand)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + maskOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(maskRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + index_vecRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + maskRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(index_vecOperands, index_vecTypes, index_vecOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(maskOperands, maskTypes, maskOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ScatterOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + _odsPrinter << ' ' << "["; + _odsPrinter << getIndexVec(); + _odsPrinter << "]"; + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getMask(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getIndexVec().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getMask().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ScatterOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(0); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Write::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ScatterOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ShapeCastOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ShapeCastOpGenericAdaptorBase::ShapeCastOpGenericAdaptorBase(ShapeCastOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +ShapeCastOpAdaptor::ShapeCastOpAdaptor(ShapeCastOp op) : ShapeCastOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ShapeCastOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult ShapeCastOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute ShapeCastOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ShapeCastOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional ShapeCastOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void ShapeCastOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void ShapeCastOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult ShapeCastOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void ShapeCastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value source) { + odsState.addOperands(source); + odsState.addTypes(result); +} + +void ShapeCastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source) { + odsState.addOperands(source); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ShapeCastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ShapeCastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult ShapeCastOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult ShapeCastOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ShapeCastOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand sourceRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> sourceOperands(&sourceRawOperand, 1); ::llvm::SMLoc sourceOperandsLoc; + (void)sourceOperandsLoc; + ::mlir::Type sourceRawType{}; + ::llvm::ArrayRef<::mlir::Type> sourceTypes(&sourceRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + sourceOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(sourceRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + sourceRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + result.addTypes(resultTypes); + if (parser.resolveOperands(sourceOperands, sourceTypes, sourceOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ShapeCastOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getSource(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getSource().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void ShapeCastOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ShapeCastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ShuffleOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +ShuffleOpGenericAdaptorBase::ShuffleOpGenericAdaptorBase(ShuffleOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::llvm::ArrayRef ShuffleOpGenericAdaptorBase::getMask() { + auto attr = getMaskAttr(); + return attr; +} + +} // namespace detail +ShuffleOpAdaptor::ShuffleOpAdaptor(ShuffleOp op) : ShuffleOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult ShuffleOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_mask = getProperties().mask; (void)tblgen_mask; + if (!tblgen_mask) return emitError(loc, "'vector.shuffle' op ""requires attribute 'mask'"); + + if (tblgen_mask && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(tblgen_mask)))) + return emitError(loc, "'vector.shuffle' op ""attribute 'mask' failed to satisfy constraint: i64 dense array attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult ShuffleOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.mask; + auto attr = dict.get("mask"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `mask` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute ShuffleOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.mask; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("mask", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code ShuffleOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.mask.getAsOpaquePointer())); +} + +std::optional ShuffleOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "mask") + return prop.mask; + return std::nullopt; +} + +void ShuffleOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "mask") { + prop.mask = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void ShuffleOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.mask) attrs.append("mask", prop.mask); +} + +::llvm::LogicalResult ShuffleOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getMaskAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(attr, "mask", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult ShuffleOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.mask))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void ShuffleOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.mask); +} + +::llvm::ArrayRef ShuffleOp::getMask() { + auto attr = getMaskAttr(); + return attr; +} + +void ShuffleOp::setMask(::llvm::ArrayRef attrValue) { + getProperties().mask = ::mlir::Builder((*this)->getContext()).getDenseI64ArrayAttr(attrValue); +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value v1, ::mlir::Value v2, ::mlir::DenseI64ArrayAttr mask) { + odsState.addOperands(v1); + odsState.addOperands(v2); + odsState.getOrAddProperties().mask = mask; + odsState.addTypes(vector); +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value v1, ::mlir::Value v2, ::mlir::DenseI64ArrayAttr mask) { + odsState.addOperands(v1); + odsState.addOperands(v2); + odsState.getOrAddProperties().mask = mask; + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ShuffleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value v1, ::mlir::Value v2, ::mlir::DenseI64ArrayAttr mask) { + odsState.addOperands(v1); + odsState.addOperands(v2); + odsState.getOrAddProperties().mask = mask; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value v1, ::mlir::Value v2, ::llvm::ArrayRef mask) { + odsState.addOperands(v1); + odsState.addOperands(v2); + odsState.getOrAddProperties().mask = odsBuilder.getDenseI64ArrayAttr(mask); + odsState.addTypes(vector); +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value v1, ::mlir::Value v2, ::llvm::ArrayRef mask) { + odsState.addOperands(v1); + odsState.addOperands(v2); + odsState.getOrAddProperties().mask = odsBuilder.getDenseI64ArrayAttr(mask); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ShuffleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, odsState.operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) + odsState.addTypes(inferredReturnTypes); + else + ::mlir::detail::reportFatalInferReturnTypesError(odsState); + +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value v1, ::mlir::Value v2, ::llvm::ArrayRef mask) { + odsState.addOperands(v1); + odsState.addOperands(v2); + odsState.getOrAddProperties().mask = odsBuilder.getDenseI64ArrayAttr(mask); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void ShuffleOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ShuffleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +void ShuffleOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void ShuffleOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + + ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes; + if (::mlir::succeeded(ShuffleOp::inferReturnTypes(odsBuilder.getContext(), + odsState.location, operands, + odsState.attributes.getDictionary(odsState.getContext()), + odsState.getRawProperties(), + odsState.regions, inferredReturnTypes))) { + assert(inferredReturnTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(inferredReturnTypes); + } else { + ::llvm::report_fatal_error("Failed to infer result type(s)."); + } +} + +::llvm::LogicalResult ShuffleOp::verifyInvariantsImpl() { + auto tblgen_mask = getProperties().mask; (void)tblgen_mask; + if (!tblgen_mask) return emitOpError("requires attribute 'mask'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(*this, tblgen_mask, "mask"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps13(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps13(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps7(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that first operand v1 and result have same element type"); + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(1))))) + return emitOpError("failed to verify that second operand v2 and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult ShuffleOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult ShuffleOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> allOperands; + ::mlir::DenseI64ArrayAttr maskAttr; + ::llvm::SmallVector<::mlir::Type, 1> allOperandTypes; + [[maybe_unused]] ::llvm::SMLoc allOperandLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(allOperands)) + return ::mlir::failure(); + + if (parser.parseCustomAttributeWithFallback(maskAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (maskAttr) result.getOrAddProperties().mask = maskAttr; + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + if (parser.parseTypeList(allOperandTypes)) + return ::mlir::failure(); + if (parser.resolveOperands(allOperands, allOperandTypes, allOperandLoc, result.operands)) + return ::mlir::failure(); + + ::llvm::SmallVector<::mlir::Type> inferredReturnTypes; + if (::mlir::failed(ShuffleOp::inferReturnTypes(parser.getContext(), + result.location, result.operands, + result.attributes.getDictionary(parser.getContext()), + result.getRawProperties(), + result.regions, inferredReturnTypes))) + return ::mlir::failure(); + result.addTypes(inferredReturnTypes); + return ::mlir::success(); +} + +void ShuffleOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getOperation()->getOperands(); + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getMaskAttr()); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("mask"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << getOperation()->getOperandTypes(); +} + +void ShuffleOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +::llvm::LogicalResult +ShuffleOp::inferReturnTypes(::mlir::MLIRContext *context, + std::optional<::mlir::Location> location, + ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, + ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, + ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes) { + ShuffleOp::Adaptor adaptor(operands, attributes, properties, regions); + return ShuffleOp::inferReturnTypes(context, + location, adaptor, inferredReturnTypes); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::ShuffleOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::SplatOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +SplatOpGenericAdaptorBase::SplatOpGenericAdaptorBase(SplatOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +SplatOpAdaptor::SplatOpAdaptor(SplatOp op) : SplatOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult SplatOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult SplatOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute SplatOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code SplatOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional SplatOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void SplatOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void SplatOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult SplatOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void SplatOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value element, Type aggregateType) { + build(odsBuilder, odsState, aggregateType, element); +} + +void SplatOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type aggregate, ::mlir::Value input) { + odsState.addOperands(input); + odsState.addTypes(aggregate); +} + +void SplatOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input) { + odsState.addOperands(input); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void SplatOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void SplatOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult SplatOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps20(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((std::equal_to<>()(::llvm::cast((*this->getODSResults(0).begin()).getType()).getElementType(), (*this->getODSOperands(0).begin()).getType())))) + return emitOpError("failed to verify that operand type matches element type of result"); + return ::mlir::success(); +} + +::llvm::LogicalResult SplatOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult SplatOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand inputRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> inputOperands(&inputRawOperand, 1); ::llvm::SMLoc inputOperandsLoc; + (void)inputOperandsLoc; + ::mlir::Type aggregateRawType{}; + ::llvm::ArrayRef<::mlir::Type> aggregateTypes(&aggregateRawType, 1); + + inputOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(inputRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + aggregateRawType = type; + } + for (::mlir::Type type : aggregateTypes) { + (void)type; + if (!(((::llvm::isa<::mlir::VectorType>(type))) && ([](::mlir::Type elementType) { return (true); }(::llvm::cast<::mlir::ShapedType>(type).getElementType())))) { + return parser.emitError(parser.getNameLoc()) << "'aggregate' must be vector of any type values, but got " << type; + } + } + result.addTypes(aggregateTypes); + if (parser.resolveOperands(inputOperands, ::llvm::cast(aggregateTypes[0]).getElementType(), inputOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void SplatOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getInput(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getAggregate().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void SplatOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::SplatOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::StepOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +StepOpGenericAdaptorBase::StepOpGenericAdaptorBase(StepOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +StepOpAdaptor::StepOpAdaptor(StepOp op) : StepOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult StepOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult StepOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute StepOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code StepOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional StepOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void StepOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void StepOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult StepOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void StepOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result) { + odsState.addTypes(result); +} + +void StepOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes) { + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void StepOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void StepOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 0u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult StepOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps21(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult StepOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult StepOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + result.addTypes(resultTypes); + return ::mlir::success(); +} + +void StepOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void StepOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::StepOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::StoreOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +StoreOpGenericAdaptorBase::StoreOpGenericAdaptorBase(StoreOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair StoreOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::BoolAttr StoreOpGenericAdaptorBase::getNontemporalAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::BoolAttr>(getProperties().nontemporal); + if (!attr) + attr = ::mlir::Builder(odsAttrs.getContext()).getBoolAttr(false); + return attr; +} + +bool StoreOpGenericAdaptorBase::getNontemporal() { + auto attr = getNontemporalAttr(); + if (!attr) + return ::mlir::Builder(odsAttrs.getContext()).getBoolAttr(false).getValue(); + return attr.getValue(); +} + +} // namespace detail +StoreOpAdaptor::StoreOpAdaptor(StoreOp op) : StoreOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult StoreOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_nontemporal = getProperties().nontemporal; (void)tblgen_nontemporal; + + if (tblgen_nontemporal && !((::llvm::isa<::mlir::BoolAttr>(tblgen_nontemporal)))) + return emitError(loc, "'vector.store' op ""attribute 'nontemporal' failed to satisfy constraint: bool attribute"); + return ::mlir::success(); +} + +std::pair StoreOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {false, false, true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 2) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange StoreOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(2); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult StoreOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.nontemporal; + auto attr = dict.get("nontemporal"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `nontemporal` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute StoreOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.nontemporal; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("nontemporal", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code StoreOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.nontemporal.getAsOpaquePointer())); +} + +std::optional StoreOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "nontemporal") + return prop.nontemporal; + return std::nullopt; +} + +void StoreOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "nontemporal") { + prop.nontemporal = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void StoreOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.nontemporal) attrs.append("nontemporal", prop.nontemporal); +} + +::llvm::LogicalResult StoreOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getNontemporalAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps7(attr, "nontemporal", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult StoreOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readOptionalAttribute(prop.nontemporal))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void StoreOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + + writer.writeOptionalAttribute(prop.nontemporal); +} + +bool StoreOp::getNontemporal() { + auto attr = getNontemporalAttr(); + if (!attr) + return ::mlir::Builder((*this)->getContext()).getBoolAttr(false).getValue(); + return attr.getValue(); +} + +void StoreOp::setNontemporal(::std::optional attrValue) { + auto &odsProp = getProperties().nontemporal; + if (attrValue) + odsProp = ::mlir::Builder((*this)->getContext()).getBoolAttr(*attrValue); + else + odsProp = nullptr; +} + +void StoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + if (nontemporal) { + odsState.getOrAddProperties().nontemporal = nontemporal; + } +} + +void StoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + if (nontemporal) { + odsState.getOrAddProperties().nontemporal = nontemporal; + } + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void StoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.getOrAddProperties().nontemporal = odsBuilder.getBoolAttr(nontemporal); +} + +void StoreOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.getOrAddProperties().nontemporal = odsBuilder.getBoolAttr(nontemporal); + assert(resultTypes.size() == 0u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void StoreOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void StoreOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult StoreOp::verifyInvariantsImpl() { + auto tblgen_nontemporal = getProperties().nontemporal; (void)tblgen_nontemporal; + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps7(*this, tblgen_nontemporal, "nontemporal"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult StoreOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult StoreOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand valueToStoreRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> valueToStoreOperands(&valueToStoreRawOperand, 1); ::llvm::SMLoc valueToStoreOperandsLoc; + (void)valueToStoreOperandsLoc; + ::mlir::OpAsmParser::UnresolvedOperand baseRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> baseOperands(&baseRawOperand, 1); ::llvm::SMLoc baseOperandsLoc; + (void)baseOperandsLoc; + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> indicesOperands; + ::llvm::SMLoc indicesOperandsLoc; + (void)indicesOperandsLoc; + ::mlir::Type baseRawType{}; + ::llvm::ArrayRef<::mlir::Type> baseTypes(&baseRawType, 1); + ::mlir::Type valueToStoreRawType{}; + ::llvm::ArrayRef<::mlir::Type> valueToStoreTypes(&valueToStoreRawType, 1); + + valueToStoreOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(valueToStoreRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + baseOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(baseRawOperand)) + return ::mlir::failure(); + if (parser.parseLSquare()) + return ::mlir::failure(); + + indicesOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(indicesOperands)) + return ::mlir::failure(); + if (parser.parseRSquare()) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + baseRawType = type; + } + if (parser.parseComma()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + valueToStoreRawType = type; + } + ::mlir::Type odsBuildableType0 = parser.getBuilder().getIndexType(); + if (parser.resolveOperands(valueToStoreOperands, valueToStoreTypes, valueToStoreOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(baseOperands, baseTypes, baseOperandsLoc, result.operands)) + return ::mlir::failure(); + if (parser.resolveOperands(indicesOperands, odsBuildableType0, indicesOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void StoreOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getValueToStore(); + _odsPrinter << ","; + _odsPrinter << ' '; + _odsPrinter << getBase(); + _odsPrinter << "["; + _odsPrinter << getIndices(); + _odsPrinter << "]"; + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + { + ::mlir::Builder odsBuilder(getContext()); + ::mlir::Attribute attr = getNontemporalAttr(); + if(attr && (attr == odsBuilder.getBoolAttr(false))) + elidedAttrs.push_back("nontemporal"); + } + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getBase().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ","; + _odsPrinter << ' '; + { + auto type = getValueToStore().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void StoreOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { + { + auto valueRange = getODSOperandIndexAndLength(1); + for (unsigned idx = valueRange.first; idx < valueRange.first + valueRange.second; idx++) { + effects.emplace_back(::mlir::MemoryEffects::Write::get(), &getOperation()->getOpOperand(idx), 0, false, ::mlir::SideEffects::DefaultResource::get()); + } + } +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::StoreOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TransferReadOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +TransferReadOpGenericAdaptorBase::TransferReadOpGenericAdaptorBase(TransferReadOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair TransferReadOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + ::llvm::ArrayRef sizeAttr = getProperties().operandSegmentSizes; + + unsigned start = 0; + for (unsigned i = 0; i < index; ++i) + start += sizeAttr[i]; + return {start, sizeAttr[index]}; +} + +::mlir::AffineMap TransferReadOpGenericAdaptorBase::getPermutationMap() { + auto attr = getPermutationMapAttr(); + return attr.getValue(); +} + +::mlir::ArrayAttr TransferReadOpGenericAdaptorBase::getInBounds() { + auto attr = getInBoundsAttr(); + return attr; +} + +} // namespace detail +TransferReadOpAdaptor::TransferReadOpAdaptor(TransferReadOp op) : TransferReadOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult TransferReadOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_in_bounds = getProperties().in_bounds; (void)tblgen_in_bounds; + if (!tblgen_in_bounds) return emitError(loc, "'vector.transfer_read' op ""requires attribute 'in_bounds'"); + auto tblgen_permutation_map = getProperties().permutation_map; (void)tblgen_permutation_map; + if (!tblgen_permutation_map) return emitError(loc, "'vector.transfer_read' op ""requires attribute 'permutation_map'"); + + if (tblgen_permutation_map && !((::llvm::isa<::mlir::AffineMapAttr>(tblgen_permutation_map)))) + return emitError(loc, "'vector.transfer_read' op ""attribute 'permutation_map' failed to satisfy constraint: AffineMap attribute"); + + if (tblgen_in_bounds && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_in_bounds))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_in_bounds), [&](::mlir::Attribute attr) { return attr && ((::llvm::isa<::mlir::BoolAttr>(attr))); })))) + return emitError(loc, "'vector.transfer_read' op ""attribute 'in_bounds' failed to satisfy constraint: 1-bit boolean array attribute"); + return ::mlir::success(); +} + +std::pair TransferReadOp::getODSOperandIndexAndLength(unsigned index) { + ::llvm::ArrayRef sizeAttr = getProperties().operandSegmentSizes; + + unsigned start = 0; + for (unsigned i = 0; i < index; ++i) + start += sizeAttr[i]; + return {start, sizeAttr[index]}; +} + +::mlir::MutableOperandRange TransferReadOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(1); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second, ::mlir::MutableOperandRange::OperandSegment(1u, {getOperandSegmentSizesAttrName(), ::mlir::DenseI32ArrayAttr::get(getContext(), getProperties().operandSegmentSizes)})); + return mutableRange; +} + +::mlir::MutableOperandRange TransferReadOp::getMaskMutable() { + auto range = getODSOperandIndexAndLength(3); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second, ::mlir::MutableOperandRange::OperandSegment(3u, {getOperandSegmentSizesAttrName(), ::mlir::DenseI32ArrayAttr::get(getContext(), getProperties().operandSegmentSizes)})); + return mutableRange; +} + +::llvm::LogicalResult TransferReadOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.in_bounds; + auto attr = dict.get("in_bounds"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `in_bounds` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.permutation_map; + auto attr = dict.get("permutation_map"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `permutation_map` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } +{ + + auto setFromAttr = [] (auto &propStorage, ::mlir::Attribute propAttr, + ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) -> ::mlir::LogicalResult { + return convertFromAttribute(propStorage, propAttr, emitError); + }; + auto attr = dict.get("operandSegmentSizes"); if (!attr) attr = dict.get("operand_segment_sizes");; +; + if (attr && ::mlir::failed(setFromAttr(prop.operandSegmentSizes, attr, emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute TransferReadOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.in_bounds; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("in_bounds", + propStorage)); + } + + { + const auto &propStorage = prop.permutation_map; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("permutation_map", + propStorage)); + } + + { + const auto &propStorage = prop.operandSegmentSizes; + auto attr = [&]() -> ::mlir::Attribute { + return ::mlir::DenseI32ArrayAttr::get(ctx, propStorage); + }(); + attrs.push_back(odsBuilder.getNamedAttr("operandSegmentSizes", attr)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code TransferReadOp::computePropertiesHash(const Properties &prop) { + auto hash_operandSegmentSizes = [] (const auto &propStorage) -> llvm::hash_code { + using ::llvm::hash_value; + return ::llvm::hash_combine_range(std::begin(propStorage), std::end(propStorage));; + }; + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.in_bounds.getAsOpaquePointer()), + llvm::hash_value(prop.permutation_map.getAsOpaquePointer()), + hash_operandSegmentSizes(prop.operandSegmentSizes)); +} + +std::optional TransferReadOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "in_bounds") + return prop.in_bounds; + + if (name == "permutation_map") + return prop.permutation_map; + if (name == "operand_segment_sizes" || name == "operandSegmentSizes") return [&]() -> ::mlir::Attribute { return ::mlir::DenseI32ArrayAttr::get(ctx, prop.operandSegmentSizes); }(); + return std::nullopt; +} + +void TransferReadOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "in_bounds") { + prop.in_bounds = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "permutation_map") { + prop.permutation_map = ::llvm::dyn_cast_or_null>(value); + return; + } + if (name == "operand_segment_sizes" || name == "operandSegmentSizes") { + auto arrAttr = ::llvm::dyn_cast_or_null<::mlir::DenseI32ArrayAttr>(value); + if (!arrAttr) return; + if (arrAttr.size() != sizeof(prop.operandSegmentSizes) / sizeof(int32_t)) + return; + llvm::copy(arrAttr.asArrayRef(), prop.operandSegmentSizes.begin()); + return; + } +} + +void TransferReadOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.in_bounds) attrs.append("in_bounds", prop.in_bounds); + + if (prop.permutation_map) attrs.append("permutation_map", prop.permutation_map); + attrs.append("operandSegmentSizes", [&]() -> ::mlir::Attribute { return ::mlir::DenseI32ArrayAttr::get(ctx, prop.operandSegmentSizes); }()); +} + +::llvm::LogicalResult TransferReadOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getInBoundsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps13(attr, "in_bounds", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getPermutationMapAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps12(attr, "permutation_map", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult TransferReadOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.in_bounds))) + return ::mlir::failure(); + + if (reader.getBytecodeVersion() < /*kNativePropertiesODSSegmentSize=*/6) { + auto &propStorage = prop.operandSegmentSizes; + ::mlir::DenseI32ArrayAttr attr; + if (::mlir::failed(reader.readAttribute(attr))) return ::mlir::failure(); + if (attr.size() > static_cast(sizeof(propStorage) / sizeof(int32_t))) { + reader.emitError("size mismatch for operand/result_segment_size"); + return ::mlir::failure(); + } + ::llvm::copy(::llvm::ArrayRef(attr), propStorage.begin()); + } + + if (::mlir::failed(reader.readAttribute(prop.permutation_map))) + return ::mlir::failure(); + + { + auto &propStorage = prop.operandSegmentSizes; + auto readProp = [&]() { + + if (reader.getBytecodeVersion() >= /*kNativePropertiesODSSegmentSize=*/6) + return reader.readSparseArray(::llvm::MutableArrayRef(propStorage)); +; + return ::mlir::success(); + }; + if (::mlir::failed(readProp())) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +void TransferReadOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.in_bounds); + +if (writer.getBytecodeVersion() < /*kNativePropertiesODSSegmentSize=*/6) { + auto &propStorage = prop.operandSegmentSizes; + writer.writeAttribute(::mlir::DenseI32ArrayAttr::get(this->getContext(), propStorage)); +} + writer.writeAttribute(prop.permutation_map); + + { + auto &propStorage = prop.operandSegmentSizes; + + if (writer.getBytecodeVersion() >= /*kNativePropertiesODSSegmentSize=*/6) + writer.writeSparseArray(::llvm::ArrayRef(propStorage)); +; + } +} + +::mlir::AffineMap TransferReadOp::getPermutationMap() { + auto attr = getPermutationMapAttr(); + return attr.getValue(); +} + +::mlir::ArrayAttr TransferReadOp::getInBounds() { + auto attr = getInBoundsAttr(); + return attr; +} + +void TransferReadOp::setPermutationMap(::mlir::AffineMap attrValue) { + getProperties().permutation_map = ::mlir::AffineMapAttr::get(attrValue); +} + +void TransferReadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(padding); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, static_cast(indices.size()), 1, (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = permutation_map; + odsState.getOrAddProperties().in_bounds = in_bounds; + odsState.addTypes(vector); +} + +void TransferReadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(padding); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, static_cast(indices.size()), 1, (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = permutation_map; + odsState.getOrAddProperties().in_bounds = in_bounds; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void TransferReadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(padding); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, static_cast(indices.size()), 1, (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = ::mlir::AffineMapAttr::get(permutation_map); + odsState.getOrAddProperties().in_bounds = in_bounds; + odsState.addTypes(vector); +} + +void TransferReadOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(base); + odsState.addOperands(indices); + odsState.addOperands(padding); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, static_cast(indices.size()), 1, (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = ::mlir::AffineMapAttr::get(permutation_map); + odsState.getOrAddProperties().in_bounds = in_bounds; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void TransferReadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void TransferReadOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult TransferReadOp::verifyInvariantsImpl() { + auto tblgen_in_bounds = getProperties().in_bounds; (void)tblgen_in_bounds; + if (!tblgen_in_bounds) return emitOpError("requires attribute 'in_bounds'"); + auto tblgen_permutation_map = getProperties().permutation_map; (void)tblgen_permutation_map; + if (!tblgen_permutation_map) return emitOpError("requires attribute 'permutation_map'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps12(*this, tblgen_permutation_map, "permutation_map"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps13(*this, tblgen_in_bounds, "in_bounds"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps22(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps3(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + if (valueGroup3.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup3.size(); + } + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult TransferReadOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::TransferReadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TransferWriteOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +TransferWriteOpGenericAdaptorBase::TransferWriteOpGenericAdaptorBase(TransferWriteOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair TransferWriteOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + ::llvm::ArrayRef sizeAttr = getProperties().operandSegmentSizes; + + unsigned start = 0; + for (unsigned i = 0; i < index; ++i) + start += sizeAttr[i]; + return {start, sizeAttr[index]}; +} + +::mlir::AffineMap TransferWriteOpGenericAdaptorBase::getPermutationMap() { + auto attr = getPermutationMapAttr(); + return attr.getValue(); +} + +::mlir::ArrayAttr TransferWriteOpGenericAdaptorBase::getInBounds() { + auto attr = getInBoundsAttr(); + return attr; +} + +} // namespace detail +TransferWriteOpAdaptor::TransferWriteOpAdaptor(TransferWriteOp op) : TransferWriteOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult TransferWriteOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_in_bounds = getProperties().in_bounds; (void)tblgen_in_bounds; + if (!tblgen_in_bounds) return emitError(loc, "'vector.transfer_write' op ""requires attribute 'in_bounds'"); + auto tblgen_permutation_map = getProperties().permutation_map; (void)tblgen_permutation_map; + if (!tblgen_permutation_map) return emitError(loc, "'vector.transfer_write' op ""requires attribute 'permutation_map'"); + + if (tblgen_permutation_map && !((::llvm::isa<::mlir::AffineMapAttr>(tblgen_permutation_map)))) + return emitError(loc, "'vector.transfer_write' op ""attribute 'permutation_map' failed to satisfy constraint: AffineMap attribute"); + + if (tblgen_in_bounds && !(((::llvm::isa<::mlir::ArrayAttr>(tblgen_in_bounds))) && (::llvm::all_of(::llvm::cast<::mlir::ArrayAttr>(tblgen_in_bounds), [&](::mlir::Attribute attr) { return attr && ((::llvm::isa<::mlir::BoolAttr>(attr))); })))) + return emitError(loc, "'vector.transfer_write' op ""attribute 'in_bounds' failed to satisfy constraint: 1-bit boolean array attribute"); + return ::mlir::success(); +} + +std::pair TransferWriteOp::getODSOperandIndexAndLength(unsigned index) { + ::llvm::ArrayRef sizeAttr = getProperties().operandSegmentSizes; + + unsigned start = 0; + for (unsigned i = 0; i < index; ++i) + start += sizeAttr[i]; + return {start, sizeAttr[index]}; +} + +::mlir::MutableOperandRange TransferWriteOp::getIndicesMutable() { + auto range = getODSOperandIndexAndLength(2); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second, ::mlir::MutableOperandRange::OperandSegment(2u, {getOperandSegmentSizesAttrName(), ::mlir::DenseI32ArrayAttr::get(getContext(), getProperties().operandSegmentSizes)})); + return mutableRange; +} + +::mlir::MutableOperandRange TransferWriteOp::getMaskMutable() { + auto range = getODSOperandIndexAndLength(3); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second, ::mlir::MutableOperandRange::OperandSegment(3u, {getOperandSegmentSizesAttrName(), ::mlir::DenseI32ArrayAttr::get(getContext(), getProperties().operandSegmentSizes)})); + return mutableRange; +} + +std::pair TransferWriteOp::getODSResultIndexAndLength(unsigned index) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumResults() - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::llvm::LogicalResult TransferWriteOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.in_bounds; + auto attr = dict.get("in_bounds"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `in_bounds` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + + { + auto &propStorage = prop.permutation_map; + auto attr = dict.get("permutation_map"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `permutation_map` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } +{ + + auto setFromAttr = [] (auto &propStorage, ::mlir::Attribute propAttr, + ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) -> ::mlir::LogicalResult { + return convertFromAttribute(propStorage, propAttr, emitError); + }; + auto attr = dict.get("operandSegmentSizes"); if (!attr) attr = dict.get("operand_segment_sizes");; +; + if (attr && ::mlir::failed(setFromAttr(prop.operandSegmentSizes, attr, emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute TransferWriteOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.in_bounds; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("in_bounds", + propStorage)); + } + + { + const auto &propStorage = prop.permutation_map; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("permutation_map", + propStorage)); + } + + { + const auto &propStorage = prop.operandSegmentSizes; + auto attr = [&]() -> ::mlir::Attribute { + return ::mlir::DenseI32ArrayAttr::get(ctx, propStorage); + }(); + attrs.push_back(odsBuilder.getNamedAttr("operandSegmentSizes", attr)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code TransferWriteOp::computePropertiesHash(const Properties &prop) { + auto hash_operandSegmentSizes = [] (const auto &propStorage) -> llvm::hash_code { + using ::llvm::hash_value; + return ::llvm::hash_combine_range(std::begin(propStorage), std::end(propStorage));; + }; + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.in_bounds.getAsOpaquePointer()), + llvm::hash_value(prop.permutation_map.getAsOpaquePointer()), + hash_operandSegmentSizes(prop.operandSegmentSizes)); +} + +std::optional TransferWriteOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "in_bounds") + return prop.in_bounds; + + if (name == "permutation_map") + return prop.permutation_map; + if (name == "operand_segment_sizes" || name == "operandSegmentSizes") return [&]() -> ::mlir::Attribute { return ::mlir::DenseI32ArrayAttr::get(ctx, prop.operandSegmentSizes); }(); + return std::nullopt; +} + +void TransferWriteOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "in_bounds") { + prop.in_bounds = ::llvm::dyn_cast_or_null>(value); + return; + } + + if (name == "permutation_map") { + prop.permutation_map = ::llvm::dyn_cast_or_null>(value); + return; + } + if (name == "operand_segment_sizes" || name == "operandSegmentSizes") { + auto arrAttr = ::llvm::dyn_cast_or_null<::mlir::DenseI32ArrayAttr>(value); + if (!arrAttr) return; + if (arrAttr.size() != sizeof(prop.operandSegmentSizes) / sizeof(int32_t)) + return; + llvm::copy(arrAttr.asArrayRef(), prop.operandSegmentSizes.begin()); + return; + } +} + +void TransferWriteOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.in_bounds) attrs.append("in_bounds", prop.in_bounds); + + if (prop.permutation_map) attrs.append("permutation_map", prop.permutation_map); + attrs.append("operandSegmentSizes", [&]() -> ::mlir::Attribute { return ::mlir::DenseI32ArrayAttr::get(ctx, prop.operandSegmentSizes); }()); +} + +::llvm::LogicalResult TransferWriteOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getInBoundsAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps13(attr, "in_bounds", emitError))) + return ::mlir::failure(); + } + + { + ::mlir::Attribute attr = attrs.get(getPermutationMapAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps12(attr, "permutation_map", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult TransferWriteOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.in_bounds))) + return ::mlir::failure(); + + if (reader.getBytecodeVersion() < /*kNativePropertiesODSSegmentSize=*/6) { + auto &propStorage = prop.operandSegmentSizes; + ::mlir::DenseI32ArrayAttr attr; + if (::mlir::failed(reader.readAttribute(attr))) return ::mlir::failure(); + if (attr.size() > static_cast(sizeof(propStorage) / sizeof(int32_t))) { + reader.emitError("size mismatch for operand/result_segment_size"); + return ::mlir::failure(); + } + ::llvm::copy(::llvm::ArrayRef(attr), propStorage.begin()); + } + + if (::mlir::failed(reader.readAttribute(prop.permutation_map))) + return ::mlir::failure(); + + { + auto &propStorage = prop.operandSegmentSizes; + auto readProp = [&]() { + + if (reader.getBytecodeVersion() >= /*kNativePropertiesODSSegmentSize=*/6) + return reader.readSparseArray(::llvm::MutableArrayRef(propStorage)); +; + return ::mlir::success(); + }; + if (::mlir::failed(readProp())) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +void TransferWriteOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.in_bounds); + +if (writer.getBytecodeVersion() < /*kNativePropertiesODSSegmentSize=*/6) { + auto &propStorage = prop.operandSegmentSizes; + writer.writeAttribute(::mlir::DenseI32ArrayAttr::get(this->getContext(), propStorage)); +} + writer.writeAttribute(prop.permutation_map); + + { + auto &propStorage = prop.operandSegmentSizes; + + if (writer.getBytecodeVersion() >= /*kNativePropertiesODSSegmentSize=*/6) + writer.writeSparseArray(::llvm::ArrayRef(propStorage)); +; + } +} + +::mlir::AffineMap TransferWriteOp::getPermutationMap() { + auto attr = getPermutationMapAttr(); + return attr.getValue(); +} + +::mlir::ArrayAttr TransferWriteOp::getInBounds() { + auto attr = getInBoundsAttr(); + return attr; +} + +void TransferWriteOp::setPermutationMap(::mlir::AffineMap attrValue) { + getProperties().permutation_map = ::mlir::AffineMapAttr::get(attrValue); +} + +void TransferWriteOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, 1, static_cast(indices.size()), (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = permutation_map; + odsState.getOrAddProperties().in_bounds = in_bounds; + if (result) + odsState.addTypes(result); +} + +void TransferWriteOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, 1, static_cast(indices.size()), (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = permutation_map; + odsState.getOrAddProperties().in_bounds = in_bounds; + odsState.addTypes(resultTypes); +} + +void TransferWriteOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, 1, static_cast(indices.size()), (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = ::mlir::AffineMapAttr::get(permutation_map); + odsState.getOrAddProperties().in_bounds = in_bounds; + if (result) + odsState.addTypes(result); +} + +void TransferWriteOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds) { + odsState.addOperands(valueToStore); + odsState.addOperands(base); + odsState.addOperands(indices); + if (mask) + odsState.addOperands(mask); + ::llvm::copy(::llvm::ArrayRef({1, 1, static_cast(indices.size()), (mask ? 1 : 0)}), odsState.getOrAddProperties().operandSegmentSizes.begin()); + odsState.getOrAddProperties().permutation_map = ::mlir::AffineMapAttr::get(permutation_map); + odsState.getOrAddProperties().in_bounds = in_bounds; + odsState.addTypes(resultTypes); +} + +void TransferWriteOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void TransferWriteOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() >= 2u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult TransferWriteOp::verifyInvariantsImpl() { + auto tblgen_in_bounds = getProperties().in_bounds; (void)tblgen_in_bounds; + if (!tblgen_in_bounds) return emitOpError("requires attribute 'in_bounds'"); + auto tblgen_permutation_map = getProperties().permutation_map; (void)tblgen_permutation_map; + if (!tblgen_permutation_map) return emitOpError("requires attribute 'permutation_map'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps12(*this, tblgen_permutation_map, "permutation_map"))) + return ::mlir::failure(); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps13(*this, tblgen_in_bounds, "in_bounds"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup1 = getODSOperands(1); + + for (auto v : valueGroup1) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps22(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup2 = getODSOperands(2); + + for (auto v : valueGroup2) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps5(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + auto valueGroup3 = getODSOperands(3); + + if (valueGroup3.size() > 1) { + return emitOpError("operand group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup3.size(); + } + + for (auto v : valueGroup3) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps16(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + if (valueGroup0.size() > 1) { + return emitOpError("result group starting at #") << index + << " requires 0 or 1 element, but found " << valueGroup0.size(); + } + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps23(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult TransferWriteOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::TransferWriteOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TransposeOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +TransposeOpGenericAdaptorBase::TransposeOpGenericAdaptorBase(TransposeOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +::llvm::ArrayRef TransposeOpGenericAdaptorBase::getPermutation() { + auto attr = getPermutationAttr(); + return attr; +} + +} // namespace detail +TransposeOpAdaptor::TransposeOpAdaptor(TransposeOp op) : TransposeOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult TransposeOpAdaptor::verify(::mlir::Location loc) { + auto tblgen_permutation = getProperties().permutation; (void)tblgen_permutation; + if (!tblgen_permutation) return emitError(loc, "'vector.transpose' op ""requires attribute 'permutation'"); + + if (tblgen_permutation && !((::llvm::isa<::mlir::DenseI64ArrayAttr>(tblgen_permutation)))) + return emitError(loc, "'vector.transpose' op ""attribute 'permutation' failed to satisfy constraint: i64 dense array attribute"); + return ::mlir::success(); +} + +::llvm::LogicalResult TransposeOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + + { + auto &propStorage = prop.permutation; + auto attr = dict.get("permutation"); + if (attr) { + auto convertedAttr = ::llvm::dyn_cast>(attr); + if (convertedAttr) { + propStorage = convertedAttr; + } else { + emitError() << "Invalid attribute `permutation` in property conversion: " << attr; + return ::mlir::failure(); + } + } + } + return ::mlir::success(); +} + +::mlir::Attribute TransposeOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + { + const auto &propStorage = prop.permutation; + if (propStorage) + attrs.push_back(odsBuilder.getNamedAttr("permutation", + propStorage)); + } + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code TransposeOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine( + llvm::hash_value(prop.permutation.getAsOpaquePointer())); +} + +std::optional TransposeOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + if (name == "permutation") + return prop.permutation; + return std::nullopt; +} + +void TransposeOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { + if (name == "permutation") { + prop.permutation = ::llvm::dyn_cast_or_null>(value); + return; + } +} + +void TransposeOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { + if (prop.permutation) attrs.append("permutation", prop.permutation); +} + +::llvm::LogicalResult TransposeOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + { + ::mlir::Attribute attr = attrs.get(getPermutationAttrName(opName)); + if (attr && ::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(attr, "permutation", emitError))) + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::llvm::LogicalResult TransposeOp::readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state) { + auto &prop = state.getOrAddProperties(); (void)prop; + if (::mlir::failed(reader.readAttribute(prop.permutation))) + return ::mlir::failure(); + return ::mlir::success(); +} + +void TransposeOp::writeProperties(::mlir::DialectBytecodeWriter &writer) { + auto &prop = getProperties(); (void)prop; + writer.writeAttribute(prop.permutation); +} + +::llvm::ArrayRef TransposeOp::getPermutation() { + auto attr = getPermutationAttr(); + return attr; +} + +void TransposeOp::setPermutation(::llvm::ArrayRef attrValue) { + getProperties().permutation = ::mlir::Builder((*this)->getContext()).getDenseI64ArrayAttr(attrValue); +} + +void TransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::mlir::DenseI64ArrayAttr permutation) { + odsState.addOperands(vector); + odsState.getOrAddProperties().permutation = permutation; + odsState.addTypes(result); +} + +void TransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::DenseI64ArrayAttr permutation) { + odsState.addOperands(vector); + odsState.getOrAddProperties().permutation = permutation; + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void TransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::llvm::ArrayRef permutation) { + odsState.addOperands(vector); + odsState.getOrAddProperties().permutation = odsBuilder.getDenseI64ArrayAttr(permutation); + odsState.addTypes(result); +} + +void TransposeOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::llvm::ArrayRef permutation) { + odsState.addOperands(vector); + odsState.getOrAddProperties().permutation = odsBuilder.getDenseI64ArrayAttr(permutation); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void TransposeOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); + + if (!attributes.empty()) { + ::mlir::OpaqueProperties properties = + &odsState.getOrAddProperties(); + std::optional<::mlir::RegisteredOperationName> info = + odsState.name.getRegisteredInfo(); + if (failed(info->setOpPropertiesFromAttribute(odsState.name, properties, + odsState.attributes.getDictionary(odsState.getContext()), nullptr))) + ::llvm::report_fatal_error("Property conversion failed."); + } +} + +void TransposeOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult TransposeOp::verifyInvariantsImpl() { + auto tblgen_permutation = getProperties().permutation; (void)tblgen_permutation; + if (!tblgen_permutation) return emitOpError("requires attribute 'permutation'"); + + if (::mlir::failed(__mlir_ods_local_attr_constraint_VectorOps1(*this, tblgen_permutation, "permutation"))) + return ::mlir::failure(); + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps2(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + if (!((getElementTypeOrSelf((*this->getOperation()).getResult(0)) == getElementTypeOrSelf((*this->getOperation()).getOperand(0))))) + return emitOpError("failed to verify that operand and result have same element type"); + return ::mlir::success(); +} + +::llvm::LogicalResult TransposeOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult TransposeOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand vectorRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> vectorOperands(&vectorRawOperand, 1); ::llvm::SMLoc vectorOperandsLoc; + (void)vectorOperandsLoc; + ::mlir::DenseI64ArrayAttr permutationAttr; + ::mlir::Type vectorRawType{}; + ::llvm::ArrayRef<::mlir::Type> vectorTypes(&vectorRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + vectorOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(vectorRawOperand)) + return ::mlir::failure(); + if (parser.parseComma()) + return ::mlir::failure(); + + if (parser.parseCustomAttributeWithFallback(permutationAttr, ::mlir::Type{})) { + return ::mlir::failure(); + } + if (permutationAttr) result.getOrAddProperties().permutation = permutationAttr; + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + vectorRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + { + ::mlir::VectorType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + result.addTypes(resultTypes); + if (parser.resolveOperands(vectorOperands, vectorTypes, vectorOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void TransposeOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getVector(); + _odsPrinter << ","; + _odsPrinter << ' '; +_odsPrinter.printStrippedAttrOrType(getPermutationAttr()); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + elidedAttrs.push_back("permutation"); + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getVector().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::VectorType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void TransposeOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::TransposeOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TypeCastOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +TypeCastOpGenericAdaptorBase::TypeCastOpGenericAdaptorBase(TypeCastOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +} // namespace detail +TypeCastOpAdaptor::TypeCastOpAdaptor(TypeCastOp op) : TypeCastOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult TypeCastOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +::llvm::LogicalResult TypeCastOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute TypeCastOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code TypeCastOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional TypeCastOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void TypeCastOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void TypeCastOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult TypeCastOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void TypeCastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value memref) { + odsState.addOperands(memref); + odsState.addTypes(result); +} + +void TypeCastOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value memref) { + odsState.addOperands(memref); + assert(resultTypes.size() == 1u && "mismatched number of results"); + odsState.addTypes(resultTypes); +} + +void TypeCastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void TypeCastOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + assert(operands.size() == 1u && "mismatched number of parameters"); + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 1u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult TypeCastOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps24(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSResults(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps4(*this, v.getType(), "result", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult TypeCastOp::verifyInvariants() { + if(::mlir::succeeded(verifyInvariantsImpl()) && ::mlir::succeeded(verify())) + return ::mlir::success(); + return ::mlir::failure(); +} + +::mlir::ParseResult TypeCastOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::mlir::OpAsmParser::UnresolvedOperand memrefRawOperand{}; + ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> memrefOperands(&memrefRawOperand, 1); ::llvm::SMLoc memrefOperandsLoc; + (void)memrefOperandsLoc; + ::mlir::Type memrefRawType{}; + ::llvm::ArrayRef<::mlir::Type> memrefTypes(&memrefRawType, 1); + ::mlir::Type resultRawType{}; + ::llvm::ArrayRef<::mlir::Type> resultTypes(&resultRawType, 1); + + memrefOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperand(memrefRawOperand)) + return ::mlir::failure(); + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + if (parser.parseColon()) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + memrefRawType = type; + } + if (parser.parseKeyword("to")) + return ::mlir::failure(); + + { + ::mlir::MemRefType type; + if (parser.parseCustomTypeWithFallback(type)) + return ::mlir::failure(); + resultRawType = type; + } + result.addTypes(resultTypes); + if (parser.resolveOperands(memrefOperands, memrefTypes, memrefOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void TypeCastOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + _odsPrinter << ' '; + _odsPrinter << getMemref(); + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + { + auto type = getMemref().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } + _odsPrinter << ' ' << "to"; + _odsPrinter << ' '; + { + auto type = getResult().getType(); + if (auto validType = ::llvm::dyn_cast<::mlir::MemRefType>(type)) + _odsPrinter.printStrippedAttrOrType(validType); + else + _odsPrinter << type; + } +} + +void TypeCastOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::TypeCastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::YieldOp definitions +//===----------------------------------------------------------------------===// + +namespace detail { +YieldOpGenericAdaptorBase::YieldOpGenericAdaptorBase(YieldOp op) : odsAttrs(op->getRawDictionaryAttrs()), odsOpName(op->getName()), properties(op.getProperties()), odsRegions(op->getRegions()) {} + +std::pair YieldOpGenericAdaptorBase::getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (odsOperandsSize - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +} // namespace detail +YieldOpAdaptor::YieldOpAdaptor(YieldOp op) : YieldOpGenericAdaptor(op->getOperands(), op) {} + +::llvm::LogicalResult YieldOpAdaptor::verify(::mlir::Location loc) { + return ::mlir::success(); +} + +std::pair YieldOp::getODSOperandIndexAndLength(unsigned index) { + bool isVariadic[] = {true}; + int prevVariadicCount = 0; + for (unsigned i = 0; i < index; ++i) + if (isVariadic[i]) ++prevVariadicCount; + + // Calculate how many dynamic values a static variadic operand corresponds to. + // This assumes all static variadic operands have the same dynamic value count. + int variadicSize = (getOperation()->getNumOperands() - 0) / 1; + // `index` passed in as the parameter is the static index which counts each + // operand (variadic or not) as size 1. So here for each previous static variadic + // operand, we need to offset by (variadicSize - 1) to get where the dynamic + // value pack for this static operand starts. + int start = index + (variadicSize - 1) * prevVariadicCount; + int size = isVariadic[index] ? variadicSize : 1; + return {start, size}; +} + +::mlir::MutableOperandRange YieldOp::getOperandsMutable() { + auto range = getODSOperandIndexAndLength(0); + auto mutableRange = ::mlir::MutableOperandRange(getOperation(), range.first, range.second); + return mutableRange; +} + +::llvm::LogicalResult YieldOp::setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr); + if (!dict) { + emitError() << "expected DictionaryAttr to set properties"; + return ::mlir::failure(); + } + return ::mlir::success(); +} + +::mlir::Attribute YieldOp::getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop) { + ::mlir::SmallVector<::mlir::NamedAttribute> attrs; + ::mlir::Builder odsBuilder{ctx}; + + if (!attrs.empty()) + return odsBuilder.getDictionaryAttr(attrs); + return {}; +} + +llvm::hash_code YieldOp::computePropertiesHash(const Properties &prop) { + using llvm::hash_value; + return llvm::hash_combine(); +} + +std::optional YieldOp::getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name) { + return std::nullopt; +} + +void YieldOp::setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value) { +} + +void YieldOp::populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs) { +} + +::llvm::LogicalResult YieldOp::verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) { + return ::mlir::success(); +} + +void YieldOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState) { + /* nothing to do */ +} + +void YieldOp::build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands) { + odsState.addOperands(operands); +} + +void YieldOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes) { + odsState.addOperands(operands); + odsState.addAttributes(attributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +void YieldOp::build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes) { + odsState.addOperands(operands); + odsState.useProperties(const_cast(properties)); + odsState.addAttributes(discardableAttributes); + assert(resultTypes.size() == 0u && "mismatched number of return types"); + odsState.addTypes(resultTypes); +} + +::llvm::LogicalResult YieldOp::verifyInvariantsImpl() { + { + unsigned index = 0; (void)index; + auto valueGroup0 = getODSOperands(0); + + for (auto v : valueGroup0) { + if (::mlir::failed(__mlir_ods_local_type_constraint_VectorOps12(*this, v.getType(), "operand", index++))) + return ::mlir::failure(); + } + } + return ::mlir::success(); +} + +::llvm::LogicalResult YieldOp::verifyInvariants() { + return verifyInvariantsImpl(); +} + +::mlir::ParseResult YieldOp::parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result) { + ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> operandsOperands; + ::llvm::SMLoc operandsOperandsLoc; + (void)operandsOperandsLoc; + ::llvm::SmallVector<::mlir::Type, 1> operandsTypes; + { + auto loc = parser.getCurrentLocation();(void)loc; + if (parser.parseOptionalAttrDict(result.attributes)) + return ::mlir::failure(); + if (failed(verifyInherentAttrs(result.name, result.attributes, [&]() { + return parser.emitError(loc) << "'" << result.name.getStringRef() << "' op "; + }))) + return ::mlir::failure(); + } + + operandsOperandsLoc = parser.getCurrentLocation(); + if (parser.parseOperandList(operandsOperands)) + return ::mlir::failure(); + if (!operandsOperands.empty()) { + if (parser.parseColon()) + return ::mlir::failure(); + + if (parser.parseTypeList(operandsTypes)) + return ::mlir::failure(); + } + if (parser.resolveOperands(operandsOperands, operandsTypes, operandsOperandsLoc, result.operands)) + return ::mlir::failure(); + return ::mlir::success(); +} + +void YieldOp::print(::mlir::OpAsmPrinter &_odsPrinter) { + ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs; + _odsPrinter.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs); + if (!getOperands().empty()) { + _odsPrinter << ' '; + _odsPrinter << getOperands(); + _odsPrinter << ' ' << ":"; + _odsPrinter << ' '; + _odsPrinter << getOperands().getTypes(); + } +} + +void YieldOp::getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects) { +} + +::mlir::MutableOperandRange YieldOp::getMutableSuccessorOperands( + ::mlir::RegionBranchPoint point) { + return ::mlir::MutableOperandRange(*this); +} + +} // namespace vector +} // namespace mlir +MLIR_DEFINE_EXPLICIT_TYPE_ID(::mlir::vector::YieldOp) + + +#endif // GET_OP_CLASSES + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.h new file mode 100644 index 0000000000000000000000000000000000000000..98fb6075cbf329934e442bd6459a8fa73ece649a --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.h @@ -0,0 +1,216 @@ +//===- VectorOps.h - MLIR Vector Dialect Operations -------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the Vector dialect. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_IR_VECTOROPS_H +#define MLIR_DIALECT_VECTOR_IR_VECTOROPS_H + +#include "mlir/Bytecode/BytecodeOpInterface.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h" +#include "mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h" +#include "mlir/IR/AffineMap.h" +#include "mlir/IR/Attributes.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Dialect.h" +#include "mlir/IR/OpDefinition.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Interfaces/ControlFlowInterfaces.h" +#include "mlir/Interfaces/DestinationStyleOpInterface.h" +#include "mlir/Interfaces/InferTypeOpInterface.h" +#include "mlir/Interfaces/SideEffectInterfaces.h" +#include "mlir/Interfaces/VectorInterfaces.h" +#include "mlir/Interfaces/ViewLikeInterface.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/StringExtras.h" + +// Pull in all enum type definitions and utility function declarations. +#include "mlir/Dialect/Vector/IR/VectorEnums.h.inc" + +#define GET_ATTRDEF_CLASSES +#include "mlir/Dialect/Vector/IR/VectorAttributes.h.inc" + +namespace mlir { +class MLIRContext; +class RewritePatternSet; + +namespace arith { +enum class AtomicRMWKind : uint64_t; +} // namespace arith + +namespace vector { +class ContractionOp; +class TransferReadOp; +class TransferWriteOp; +class VectorDialect; + +namespace detail { +struct BitmaskEnumStorage; +} // namespace detail + +/// Predefined constant_mask kinds. +enum class ConstantMaskKind { AllFalse = 0, AllTrue }; + +/// Default callback to build a region with a 'vector.yield' terminator with no +/// arguments. +void buildTerminatedBody(OpBuilder &builder, Location loc); + +/// Return whether `srcType` can be broadcast to `dstVectorType` under the +/// semantics of the `vector.broadcast` op. +enum class BroadcastableToResult { + Success = 0, + SourceRankHigher = 1, + DimensionMismatch = 2, + SourceTypeNotAVector = 3 +}; + +struct VectorDim { + int64_t dim; + bool isScalable; +}; +BroadcastableToResult +isBroadcastableTo(Type srcType, VectorType dstVectorType, + std::pair *mismatchingDims = nullptr); + +/// Collect a set of vector-to-vector canonicalization patterns. +void populateVectorToVectorCanonicalizationPatterns(RewritePatternSet &patterns, + PatternBenefit benefit = 1); + +/// Collect a set of patterns that fold arithmetic extension on floating point +/// into vector contract for the backends with native support. +void populateFoldArithExtensionPatterns(RewritePatternSet &patterns); + +/// Collect a set of patterns that fold elementwise op on vectors to the vector +/// dialect. +void populateElementwiseToVectorOpsPatterns(RewritePatternSet &patterns); + +/// Returns the integer type required for subscripts in the vector dialect. +IntegerType getVectorSubscriptType(Builder &builder); + +/// Returns an integer array attribute containing the given values using +/// the integer type required for subscripts in the vector dialect. +ArrayAttr getVectorSubscriptAttr(Builder &b, ArrayRef values); + +/// Returns the value obtained by reducing the vector into a scalar using the +/// operation kind associated with a binary AtomicRMWKind op. +Value getVectorReductionOp(arith::AtomicRMWKind op, OpBuilder &builder, + Location loc, Value vector); + +/// Build the default minor identity map suitable for a vector transfer. This +/// also handles the case memref<... x vector<...>> -> vector<...> in which the +/// rank of the identity map must take the vector element type into account. +AffineMap getTransferMinorIdentityMap(ShapedType shapedType, + VectorType vectorType); + +/// Return true if the transfer_write fully writes the data accessed by the +/// transfer_read. +bool checkSameValueRAW(TransferWriteOp defWrite, TransferReadOp read); + +/// Return true if the write op fully over-write the priorWrite transfer_write +/// op. +bool checkSameValueWAW(TransferWriteOp write, TransferWriteOp priorWrite); + +/// Return true if we can prove that the transfer operations access disjoint +/// memory, without requring the accessed tensor/memref to be the same. +/// +/// If `testDynamicValueUsingBounds` is true, tries to test dynamic values +/// via ValueBoundsOpInterface. +bool isDisjointTransferIndices(VectorTransferOpInterface transferA, + VectorTransferOpInterface transferB, + bool testDynamicValueUsingBounds = false); + +/// Return true if we can prove that the transfer operations access disjoint +/// memory, requiring the operations to access the same tensor/memref. +/// +/// If `testDynamicValueUsingBounds` is true, tries to test dynamic values +/// via ValueBoundsOpInterface. +bool isDisjointTransferSet(VectorTransferOpInterface transferA, + VectorTransferOpInterface transferB, + bool testDynamicValueUsingBounds = false); + +/// Returns the result value of reducing two scalar/vector values with the +/// corresponding arith operation. +Value makeArithReduction(OpBuilder &b, Location loc, CombiningKind kind, + Value v1, Value acc, + arith::FastMathFlagsAttr fastmath = nullptr, + Value mask = nullptr); + +/// Returns true if `attr` has "parallel" iterator type semantics. +inline bool isParallelIterator(Attribute attr) { + return cast(attr).getValue() == IteratorType::parallel; +} + +/// Returns true if `attr` has "reduction" iterator type semantics. +inline bool isReductionIterator(Attribute attr) { + return cast(attr).getValue() == IteratorType::reduction; +} + +/// Returns the integer numbers in `values`. `values` are expected to be +/// constant operations. +SmallVector getAsIntegers(ArrayRef values); + +/// Returns the integer numbers in `foldResults`. `foldResults` are expected to +/// be constant operations. +SmallVector getAsIntegers(ArrayRef foldResults); + +/// Convert `foldResults` into Values. Integer attributes are converted to +/// constant op. +SmallVector getAsValues(OpBuilder &builder, Location loc, + ArrayRef foldResults); + +/// If `value` is a constant multiple of `vector.vscale` (e.g. `%cst * +/// vector.vscale`), return the multiplier (`%cst`). Otherwise, return +/// `std::nullopt`. +std::optional getConstantVscaleMultiplier(Value value); + +//===----------------------------------------------------------------------===// +// Vector Masking Utilities +//===----------------------------------------------------------------------===// + +/// Infers the mask type for a transfer op given its vector type and +/// permutation map. The mask in a transfer op operation applies to the +/// tensor/buffer part of it and its type should match the vector shape +/// *before* any permutation or broadcasting. For example, +/// +/// vecType = vector<1x2x3xf32>, permMap = affine_map<(d0, d1, d2) -> (d1, d0)> +/// +/// Has inferred mask type: +/// +/// maskType = vector<2x1xi1> +VectorType inferTransferOpMaskType(VectorType vecType, AffineMap permMap); + +/// Create the vector.yield-ended region of a vector.mask op with `maskableOp` +/// as masked operation. +void createMaskOpRegion(OpBuilder &builder, Operation *maskableOp); + +/// Creates a vector.mask operation around a maskable operation. Returns the +/// vector.mask operation if the mask provided is valid. Otherwise, returns the +/// maskable operation itself. +Operation *maskOperation(OpBuilder &builder, Operation *maskableOp, Value mask, + Value passthru = Value()); + +/// Creates a vector select operation that picks values from `newValue` or +/// `passthru` for each result vector lane based on `mask`. This utility is used +/// to propagate the pass-thru value for masked-out or expeculatively executed +/// lanes. VP intrinsics do not support pass-thru values and every mask-out lane +/// is set to poison. LLVM backends are usually able to match op + select +/// patterns and fold them into a native target instructions. +Value selectPassthru(OpBuilder &builder, Value mask, Value newValue, + Value passthru); + +} // namespace vector +} // namespace mlir + +#define GET_OP_CLASSES +#include "mlir/Dialect/Vector/IR/VectorDialect.h.inc" +#include "mlir/Dialect/Vector/IR/VectorOps.h.inc" + +#endif // MLIR_DIALECT_VECTOR_IR_VECTOROPS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..31485ab37650b86168706113851a97b78783bf16 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/IR/VectorOps.h.inc @@ -0,0 +1,11050 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Op Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: VectorOps.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { +/// Load vector scale size +/// The `vscale` op returns the scale of the scalable vectors, a positive +/// integer value that is constant at runtime but unknown at compile-time. +/// The scale of the vector indicates the multiplicity of the vectors and +/// vector operations. For example, a `vector<[4]xi32>` is equivalent to +/// `vscale` consecutive `vector<4xi32>`; and an operation on a +/// `vector<[4]xi32>` is equivalent to performing that operation `vscale` +/// times, once on each `<4xi32>` segment of the scalable vector. The `vscale` +/// op can be used to calculate the step in vector-length agnostic (VLA) loops. +/// Right now we only support one contiguous set of scalable dimensions, all of +/// them grouped and scaled with the value returned by 'vscale'. +class VectorScaleOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// bitcast casts between vectors +/// The bitcast operation casts between vectors of the same rank, the minor 1-D +/// vector size is casted to a vector with a different element type but same +/// bitwidth. In case of 0-D vectors, the bitwidth of element types must be +/// equal. +/// +/// Example: +/// +/// ```mlir +/// // Example casting to a smaller element type. +/// %1 = vector.bitcast %0 : vector<5x1x4x3xf32> to vector<5x1x4x6xi16> +/// +/// // Example casting to a bigger element type. +/// %3 = vector.bitcast %2 : vector<10x12x8xi8> to vector<10x12x2xi32> +/// +/// // Example casting to an element type of the same size. +/// %5 = vector.bitcast %4 : vector<5x1x4x3xf32> to vector<5x1x4x3xi32> +/// +/// // Example casting of 0-D vectors. +/// %7 = vector.bitcast %6 : vector to vector +/// ``` +class BitCastOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// broadcast operation +/// Broadcasts the scalar or k-D vector value in the source operand +/// to a n-D result vector such that the broadcast makes sense, i.e., +/// the source operand is duplicated to match the given rank and sizes +/// in the result vector. The legality rules are: +/// * the source operand must have the same element type as the result type +/// * a k-D vector can be broadcast to +/// a n-D vector if +/// * k <= n, and +/// * the sizes in the trailing dimensions n-k < i <= n with j=i+k-n +/// match exactly as s_j = t_i or s_j = 1: +/// ``` +/// t_1 x .. t_n-k x t_n-k+1 x .. x t_i x .. x t_n +/// s_1 x .. x s_j x .. x s_k +/// +/// ``` +/// * in addition, any scalable unit dimension, `[1]`, must match exactly. +/// +/// The source operand is duplicated over all the missing leading dimensions +/// and stretched over the trailing dimensions where the source has a non-equal +/// dimension of 1 (stretching a trailing dimension is also referred to as +/// "dim-1" broadcasting). These rules imply that any scalar broadcast (k=0) to +/// any shaped vector with the same element type is always legal. +/// +/// Example: +/// +/// ```mlir +/// %0 = arith.constant 0.0 : f32 +/// %1 = vector.broadcast %0 : f32 to vector<16xf32> +/// %2 = vector.broadcast %1 : vector<16xf32> to vector<4x16xf32> +/// ``` +class BroadcastOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// writes elements selectively from a vector as defined by a mask +/// The compress store operation writes elements from a vector into memory as +/// defined by a base with indices and a mask vector. Compression only applies +/// to the innermost dimension. When the mask is set, the corresponding element +/// from the vector is written next to memory. Otherwise, no action is taken +/// for the element. Informally the semantics are: +/// +/// ``` +/// index = i +/// if (mask[0]) base[index++] = value[0] +/// if (mask[1]) base[index++] = value[1] +/// etc. +/// ``` +/// +/// Note that the index increment is done conditionally. +/// +/// If a mask bit is set and the corresponding index is out-of-bounds for the +/// given base, the behavior is undefined. If a mask bit is not set, no value +/// is stored regardless of the index, and the index is allowed to be +/// out-of-bounds. +/// +/// The compress store can be used directly where applicable, or can be used +/// during progressively lowering to bring other memory operations closer to +/// hardware ISA support for a compress. The semantics of the operation closely +/// correspond to those of the `llvm.masked.compressstore` +/// [intrinsic](https://llvm.org/docs/LangRef.html#llvm-masked-compressstore-intrinsics). +/// +/// Note, at the moment this Op is only available for fixed-width vectors. +/// +/// Examples: +/// +/// ```mlir +/// vector.compressstore %base[%i], %mask, %value +/// : memref, vector<8xi1>, vector<8xf32> +/// +/// vector.compressstore %base[%i, %j], %mask, %value +/// : memref, vector<16xi1>, vector<16xf32> +/// ``` +class CompressStoreOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// creates a constant vector mask +/// Creates and returns a vector mask where elements of the result vector +/// are set to '0' or '1', based on whether the element indices are contained +/// within a hyper-rectangular region specified by the 'mask_dim_sizes' +/// array attribute argument. Each element of the 'mask_dim_sizes' array, +/// specifies an exclusive upper bound [0, mask-dim-size-element-value) +/// for a unique dimension in the vector result. The conjunction of the ranges +/// define a hyper-rectangular region within which elements values are set to 1 +/// (otherwise element values are set to 0). Each value of 'mask_dim_sizes' must +/// be non-negative and not greater than the size of the corresponding vector +/// dimension (as opposed to vector.create_mask which allows this). Sizes that +/// correspond to scalable dimensions are implicitly multiplied by vscale, +/// though currently only zero (none set) or the size of the dim/vscale +/// (all set) are supported. +/// +/// Example: +/// +/// ```mlir +/// // create a constant vector mask of size 4x3xi1 with elements in range +/// // 0 <= row <= 2 and 0 <= col <= 1 are set to 1 (others to 0). +/// %1 = vector.constant_mask [3, 2] : vector<4x3xi1> +/// +/// print %1 +/// columns +/// 0 1 2 +/// |------------ +/// 0 | 1 1 0 +/// rows 1 | 1 1 0 +/// 2 | 1 1 0 +/// 3 | 0 0 0 +/// ``` +class ConstantMaskOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// vector contraction operation +/// Computes the sum of products of vector elements along contracting +/// dimension pairs from 2 vectors of rank M and N respectively, adds this +/// intermediate result to the accumulator argument of rank K, and returns a +/// vector result of rank K (where K = num_lhs_free_dims + num_rhs_free_dims + +/// num_batch_dims (see dimension type descriptions below)). For K = 0 (no +/// free or batch dimensions), the accumulator and output are a scalar. +/// +/// If operands and the result have types of different bitwidths, operands are +/// promoted to have the same bitwidth as the result before performing the +/// contraction. For integer types, only signless integer types are supported, +/// and the promotion happens via sign extension. +/// +/// An iterator type attribute list must be specified, where each element of +/// the list represents an iterator with one of the following types: +/// +/// * "reduction": reduction dimensions are present in the lhs and rhs +/// arguments but not in the output (and accumulator +/// argument). These are the dimensions along which the vector +/// contraction op computes the sum of products, and +/// contracting dimension pair dimension sizes must match +/// between lhs/rhs. +/// +/// * "parallel": Batch dimensions are iterator type "parallel", and +/// are non-contracting dimensions present in the lhs, rhs and +/// output. The lhs/rhs co-iterate along the batch dimensions, +/// which should be expressed in their indexing maps. +/// +/// Free dimensions are iterator type "parallel", and are +/// non-contraction, non-batch dimensions accessed by either the +/// lhs or rhs (but not both). The lhs and rhs free dimensions +/// are unrelated to each other and do not co-iterate, which +/// should be expressed in their indexing maps. +/// +/// An indexing map attribute list must be specified with an entry for lhs, rhs +/// and acc arguments. An indexing map attribute specifies a mapping from each +/// iterator in the iterator type list, to each dimension of an N-D vector. +/// +/// An optional kind attribute may be used to specify the combining function +/// between the intermediate result and accumulator argument of rank K. This +/// attribute can take the values `add`/`mul`/`minsi`/`minui`/`maxsi`/`maxui` +/// /`and`/`or`/`xor` for integers, and `add`/`mul`/`minnumf`/`maxnumf` +/// /`minimumf`/`maximumf` for floats. The default is `add`. +/// +/// Example: +/// +/// ```mlir +/// // Simple DOT product (K = 0). +/// #contraction_accesses = [ +/// affine_map<(i) -> (i)>, +/// affine_map<(i) -> (i)>, +/// affine_map<(i) -> ()> +/// ] +/// #contraction_trait = { +/// indexing_maps = #contraction_accesses, +/// iterator_types = ["reduction"] +/// } +/// %3 = vector.contract #contraction_trait %0, %1, %2 +/// : vector<10xf32>, vector<10xf32> into f32 +/// +/// // 2D vector contraction with one contracting dimension (matmul, K = 2). +/// #contraction_accesses = [ +/// affine_map<(i, j, k) -> (i, k)>, +/// affine_map<(i, j, k) -> (k, j)>, +/// affine_map<(i, j, k) -> (i, j)> +/// ] +/// #contraction_trait = { +/// indexing_maps = #contraction_accesses, +/// iterator_types = ["parallel", "parallel", "reduction"] +/// } +/// +/// %3 = vector.contract #contraction_trait %0, %1, %2 +/// : vector<4x3xf32>, vector<3x7xf32> into vector<4x7xf32> +/// +/// // 4D to 3D vector contraction with two contracting dimensions and +/// // one batch dimension (K = 3). +/// #contraction_accesses = [ +/// affine_map<(b0, f0, f1, c0, c1) -> (c0, b0, c1, f0)>, +/// affine_map<(b0, f0, f1, c0, c1) -> (b0, c1, c0, f1)>, +/// affine_map<(b0, f0, f1, c0, c1) -> (b0, f0, f1)> +/// ] +/// #contraction_trait = { +/// indexing_maps = #contraction_accesses, +/// iterator_types = ["parallel", "parallel", "parallel", +/// "reduction", "reduction"] +/// } +/// +/// %4 = vector.contract #contraction_trait %0, %1, %2 +/// : vector<7x8x16x15xf32>, vector<8x16x7x5xf32> into vector<8x15x5xf32> +/// +/// // Vector contraction with mixed typed. lhs/rhs have different element +/// // types than accumulator/result. +/// %5 = vector.contract #contraction_trait %0, %1, %2 +/// : vector<10xf16>, vector<10xf16> into f32 +/// +/// // Contract with max (K = 0). +/// #contraction_accesses = [ +/// affine_map<(i) -> (i)>, +/// affine_map<(i) -> (i)>, +/// affine_map<(i) -> ()> +/// ] +/// #contraction_trait = { +/// indexing_maps = #contraction_accesses, +/// iterator_types = ["reduction"], +/// kind = #vector.kind +/// } +/// %6 = vector.contract #contraction_trait %0, %1, %2 +/// : vector<10xf32>, vector<10xf32> into f32 +/// ``` +class ContractionOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// creates a vector mask +/// Creates and returns a vector mask where elements of the result vector +/// are set to '0' or '1', based on whether the element indices are contained +/// within a hyper-rectangular region specified by the operands. Specifically, +/// each operand specifies a range [0, operand-value) for a unique dimension in +/// the vector result. The conjunction of the operand ranges define a +/// hyper-rectangular region within which elements values are set to 1 +/// (otherwise element values are set to 0). If operand-value is negative, it is +/// treated as if it were zero, and if it is greater than the corresponding +/// dimension size, it is treated as if it were equal to the dimension size. +/// +/// Example: +/// +/// ```mlir +/// // create a vector mask of size 4x3xi1 where elements in range +/// // 0 <= row <= 2 and 0 <= col <= 1 are set to 1 (others to 0). +/// %1 = vector.create_mask %c3, %c2 : vector<4x3xi1> +/// +/// print %1 +/// columns +/// 0 1 2 +/// |------------ +/// 0 | 1 1 0 +/// rows 1 | 1 1 0 +/// 2 | 1 1 0 +/// 3 | 0 0 0 +/// ``` +class CreateMaskOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// constructs two vectors by deinterleaving an input vector +/// The deinterleave operation constructs two vectors from a single input +/// vector. The first result vector contains the elements from even indexes +/// of the input, and the second contains elements from odd indexes. This is +/// the inverse of a `vector.interleave` operation. +/// +/// Each output's trailing dimension is half of the size of the input +/// vector's trailing dimension. This operation requires the input vector +/// to have a rank > 0 and an even number of elements in its trailing +/// dimension. +/// +/// The operation supports scalable vectors. +/// +/// Example: +/// ```mlir +/// %0, %1 = vector.deinterleave %a +/// : vector<8xi8> -> vector<4xi8> +/// %2, %3 = vector.deinterleave %b +/// : vector<2x8xi8> -> vector<2x4xi8> +/// %4, %5 = vector.deinterleave %c +/// : vector<2x8x4xi8> -> vector<2x8x2xi8> +/// %6, %7 = vector.deinterleave %d +/// : vector<[8]xf32> -> vector<[4]xf32> +/// %8, %9 = vector.deinterleave %e +/// : vector<2x[6]xf64> -> vector<2x[3]xf64> +/// %10, %11 = vector.deinterleave %f +/// : vector<2x4x[6]xf64> -> vector<2x4x[3]xf64> +/// ``` +class DeinterleaveOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// reads elements from memory and spreads them into a vector as defined by a mask +/// The expand load reads elements from memory into a vector as defined by a +/// base with indices and a mask vector. Expansion only applies to the innermost +/// dimension. When the mask is set, the next element is read from memory. +/// Otherwise, the corresponding element is taken from a pass-through vector. +/// Informally the semantics are: +/// +/// ``` +/// index = i +/// result[0] := if mask[0] then base[index++] else pass_thru[0] +/// result[1] := if mask[1] then base[index++] else pass_thru[1] +/// etc. +/// ``` +/// +/// Note that the index increment is done conditionally. +/// +/// If a mask bit is set and the corresponding index is out-of-bounds for the +/// given base, the behavior is undefined. If a mask bit is not set, the value +/// comes from the pass-through vector regardless of the index, and the index is +/// allowed to be out-of-bounds. +/// +/// The expand load can be used directly where applicable, or can be used +/// during progressively lowering to bring other memory operations closer to +/// hardware ISA support for an expand. The semantics of the operation closely +/// correspond to those of the `llvm.masked.expandload` +/// [intrinsic](https://llvm.org/docs/LangRef.html#llvm-masked-expandload-intrinsics). +/// +/// Note, at the moment this Op is only available for fixed-width vectors. +/// +/// Examples: +/// +/// ```mlir +/// %0 = vector.expandload %base[%i], %mask, %pass_thru +/// : memref, vector<8xi1>, vector<8xf32> into vector<8xf32> +/// +/// %1 = vector.expandload %base[%i, %j], %mask, %pass_thru +/// : memref, vector<16xi1>, vector<16xf32> into vector<16xf32> +/// ``` +class ExpandLoadOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// extractelement operation +/// Note: This operation is deprecated. Please use vector.extract insert. +/// +/// Takes a 0-D or 1-D vector and a optional dynamic index position and +/// extracts the scalar at that position. +/// +/// Note that this instruction resembles vector.extract, but is restricted to +/// 0-D and 1-D vectors. +/// If the vector is 0-D, the position must be std::nullopt. +/// +/// +/// It is meant to be closer to LLVM's version: +/// https://llvm.org/docs/LangRef.html#extractelement-instruction +/// +/// Example: +/// +/// ```mlir +/// %c = arith.constant 15 : i32 +/// %1 = vector.extractelement %0[%c : i32]: vector<16xf32> +/// %2 = vector.extractelement %z[]: vector +/// ``` +class ExtractElementOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// extract operation +/// Takes an n-D vector and a k-D position and extracts the (n-k)-D vector at +/// the proper position. Degenerates to an element type if n-k is zero. +/// +/// Static and dynamic indices must be greater or equal to zero and less than +/// the size of the corresponding dimension. The result is undefined if any +/// index is out-of-bounds. The value `-1` represents a poison index, which +/// specifies that the extracted element is poison. +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.extract %0[3]: vector<8x16xf32> from vector<4x8x16xf32> +/// %2 = vector.extract %0[2, 1, 3]: f32 from vector<4x8x16xf32> +/// %3 = vector.extract %1[]: vector from vector +/// %4 = vector.extract %0[%a, %b, %c]: f32 from vector<4x8x16xf32> +/// %5 = vector.extract %0[2, %b]: vector<16xf32> from vector<4x8x16xf32> +/// %6 = vector.extract %10[-1, %c]: f32 from vector<4x16xf32> +/// ``` +class ExtractOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// extract_strided_slice operation +/// Takes an n-D vector, k-D `offsets` integer array attribute, a k-sized +/// `sizes` integer array attribute, a k-sized `strides` integer array +/// attribute and extracts the n-D subvector at the proper offset. +/// +/// At the moment strides must contain only 1s. +/// +/// Returns an n-D vector where the first k-D dimensions match the `sizes` +/// attribute. The returned subvector contains the elements starting at offset +/// `offsets` and ending at `offsets + sizes`. +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.extract_strided_slice %0 +/// {offsets = [0, 2], sizes = [2, 4], strides = [1, 1]}: +/// vector<4x8x16xf32> to vector<2x4x16xf32> +/// +/// // TODO: Evolve to a range form syntax similar to: +/// %1 = vector.extract_strided_slice %0[0:2:1][2:4:1] +/// vector<4x8x16xf32> to vector<2x4x16xf32> +/// ``` +/// +/// TODO: Implement support for poison indices. +class ExtractStridedSliceOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// vector fused multiply-add +/// Multiply-add expressions operate on n-D vectors and compute a fused +/// pointwise multiply-and-accumulate: `$result = $lhs * $rhs + $acc`. +/// All operands and result have the same vector type. The semantics +/// of the operation correspond to those of the `llvm.fma` +/// [intrinsic](https://llvm.org/docs/LangRef.html#int-fma). In the +/// particular case of lowering to LLVM, this is guaranteed to lower +/// to the `llvm.fma.*` intrinsic. +/// +/// Example: +/// +/// ```mlir +/// %3 = vector.fma %0, %1, %2: vector<8x16xf32> +/// ``` +class FMAOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Vector matrix transposition on flattened 1-D MLIR vectors +/// This is the counterpart of llvm.matrix.transpose in MLIR. It serves +/// the purposes of more progressive lowering and localized type conversion. +/// Higher levels typically lower matrix transpositions into 'vector.transpose' +/// operations. Subsequent rewriting rule progressively lower these operations +/// into 'vector.flat_transpose' operations to bring the operations closer +/// to the hardware ISA. +/// +/// The `vector.flat_transpose` op treats the 1-D input `matrix` as +/// a 2-D matrix with rows and columns, and returns the +/// transposed matrix in flattened form in 'res'. +/// +/// Note, the corresponding LLVM intrinsic, `@llvm.matrix.transpose.*`, does not +/// support scalable vectors. Hence, this Op is only available for fixed-width +/// vectors. Also see: +/// +/// http://llvm.org/docs/LangRef.html#llvm-matrix-transpose-intrinsic +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.flat_transpose %0 {columns = 4 : i32, rows = 4 : i32} +/// : vector<16xf32> -> vector<16xf32> +/// ``` +class FlatTransposeOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// operation that defines a vector from scalar elements +/// This operation defines a vector from one or multiple scalar elements. The +/// number of elements must match the number of elements in the result type. +/// All elements must have the same type, which must match the element type of +/// the result vector type. +/// +/// `elements` are a flattened version of the result vector in row-major order. +/// +/// Example: +/// +/// ```mlir +/// // %f1 +/// %0 = vector.from_elements %f1 : vector +/// // [%f1, %f2] +/// %1 = vector.from_elements %f1, %f2 : vector<2xf32> +/// // [[%f1, %f2, %f3], [%f4, %f5, %f6]] +/// %2 = vector.from_elements %f1, %f2, %f3, %f4, %f5, %f6 : vector<2x3xf32> +/// // [[[%f1, %f2]], [[%f3, %f4]], [[%f5, %f6]]] +/// %3 = vector.from_elements %f1, %f2, %f3, %f4, %f5, %f6 : vector<3x1x2xf32> +/// ``` +/// +/// Note, scalable vectors are not supported. +class FromElementsOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// gathers elements from memory or ranked tensor into a vector as defined by an +/// index vector and a mask vector +/// The gather operation returns an n-D vector whose elements are either loaded +/// from memory or ranked tensor, or taken from a pass-through vector, depending +/// on the values of an n-D mask vector. +/// If a mask bit is set, the corresponding result element is defined by the base +/// with indices and the n-D index vector (each index is a 1-D offset on the base). +/// Otherwise, the corresponding element is taken from the n-D pass-through vector. +/// Informally the semantics are: +/// ``` +/// result[0] := if mask[0] then base[index[0]] else pass_thru[0] +/// result[1] := if mask[1] then base[index[1]] else pass_thru[1] +/// etc. +/// ``` +/// +/// If a mask bit is set and the corresponding index is out-of-bounds for the +/// given base, the behavior is undefined. If a mask bit is not set, the value +/// comes from the pass-through vector regardless of the index, and the index is +/// allowed to be out-of-bounds. +/// +/// The gather operation can be used directly where applicable, or can be used +/// during progressively lowering to bring other memory operations closer to +/// hardware ISA support for a gather. +/// +/// Examples: +/// +/// ```mlir +/// %0 = vector.gather %base[%c0][%v], %mask, %pass_thru +/// : memref, vector<2x16xi32>, vector<2x16xi1>, vector<2x16xf32> into vector<2x16xf32> +/// +/// %1 = vector.gather %base[%i, %j][%v], %mask, %pass_thru +/// : memref<16x16xf32>, vector<16xi32>, vector<16xi1>, vector<16xf32> into vector<16xf32> +/// ``` +class GatherOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// insertelement operation +/// Note: This operation is deprecated. Please use vector.insert instead. +/// +/// Takes a scalar source, a 0-D or 1-D destination vector and a dynamic index +/// position and inserts the source into the destination at the proper position. +/// +/// Note that this instruction resembles vector.insert, but is restricted to 0-D +/// and 1-D vectors. +/// +/// It is meant to be closer to LLVM's version: +/// https://llvm.org/docs/LangRef.html#insertelement-instruction +/// +/// Example: +/// +/// ```mlir +/// %c = arith.constant 15 : i32 +/// %f = arith.constant 0.0f : f32 +/// %1 = vector.insertelement %f, %0[%c : i32]: vector<16xf32> +/// %2 = vector.insertelement %f, %z[]: vector +/// ``` +class InsertElementOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// insert operation +/// Takes an n-D source vector, an (n+k)-D destination vector and a k-D position +/// and inserts the n-D source into the (n+k)-D destination at the proper +/// position. Degenerates to a scalar or a 0-d vector source type when n = 0. +/// +/// Static and dynamic indices must be greater or equal to zero and less than +/// the size of the corresponding dimension. The result is undefined if any +/// index is out-of-bounds. The value `-1` represents a poison index, which +/// specifies that the resulting vector is poison. +/// +/// Example: +/// +/// ```mlir +/// %2 = vector.insert %0, %1[3] : vector<8x16xf32> into vector<4x8x16xf32> +/// %5 = vector.insert %3, %4[2, 1, 3] : f32 into vector<4x8x16xf32> +/// %8 = vector.insert %6, %7[] : f32 into vector +/// %11 = vector.insert %9, %10[%a, %b, %c] : vector into vector<4x8x16xf32> +/// %12 = vector.insert %4, %10[2, %b] : vector<16xf32> into vector<4x8x16xf32> +/// %13 = vector.insert %20, %1[-1, %c] : f32 into vector<4x16xf32> +/// ``` +class InsertOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// strided_slice operation +/// Takes a k-D valueToStore vector, an n-D destination vector (n >= k), n-sized +/// `offsets` integer array attribute, a k-sized `strides` integer array attribute +/// and inserts the k-D valueToStore vector as a strided subvector at the proper offset +/// into the n-D destination vector. +/// +/// At the moment strides must contain only 1s. +/// +/// Returns an n-D vector that is a copy of the n-D destination vector in which +/// the last k-D dimensions contain the k-D valueToStore vector elements strided at +/// the proper location as specified by the offsets. +/// +/// Example: +/// +/// ```mlir +/// %2 = vector.insert_strided_slice %0, %1 +/// {offsets = [0, 0, 2], strides = [1, 1]}: +/// vector<2x4xf32> into vector<16x4x8xf32> +/// ``` +class InsertStridedSliceOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// constructs a vector by interleaving two input vectors +/// The interleave operation constructs a new vector by interleaving the +/// elements from the trailing (or final) dimension of two input vectors, +/// returning a new vector where the trailing dimension is twice the size. +/// +/// Note that for the n-D case this differs from the interleaving possible with +/// `vector.shuffle`, which would only operate on the leading dimension. +/// +/// Another key difference is this operation supports scalable vectors, though +/// currently a general LLVM lowering is limited to the case where only the +/// trailing dimension is scalable. +/// +/// Example: +/// ```mlir +/// %a = arith.constant dense<[0, 1]> : vector<2xi32> +/// %b = arith.constant dense<[2, 3]> : vector<2xi32> +/// // The value of `%0` is `[0, 2, 1, 3]`. +/// %0 = vector.interleave %a, %b : vector<2xi32> -> vector<4xi32> +/// +/// // Examples showing allowed input and result types. +/// %1 = vector.interleave %c, %d : vector -> vector<2xf16> +/// %2 = vector.interleave %e, %f : vector<6x3xf32> -> vector<6x6xf32> +/// %3 = vector.interleave %g, %h : vector<[4]xi32> -> vector<[8]xi32> +/// %4 = vector.interleave %i, %j : vector<2x4x[2]xf64> -> vector<2x4x[4]xf64> +/// ``` +class InterleaveOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// reads an n-D slice of memory into an n-D vector +/// The 'vector.load' operation reads an n-D slice of memory into an n-D +/// vector. It takes a 'base' memref, an index for each memref dimension and a +/// result vector type as arguments. It returns a value of the result vector +/// type. The 'base' memref and indices determine the start memory address from +/// which to read. Each index provides an offset for each memref dimension +/// based on the element type of the memref. The shape of the result vector +/// type determines the shape of the slice read from the start memory address. +/// The elements along each dimension of the slice are strided by the memref +/// strides. When loading more than 1 element, only unit strides are allowed +/// along the most minor memref dimension. These constraints guarantee that +/// elements read along the first dimension of the slice are contiguous in +/// memory. +/// +/// The memref element type can be a scalar or a vector type. If the memref +/// element type is a scalar, it should match the element type of the result +/// vector. If the memref element type is vector, it should match the result +/// vector type. +/// +/// Example: 0-D vector load on a scalar memref. +/// ```mlir +/// %result = vector.load %base[%i, %j] : memref<100x100xf32>, vector +/// ``` +/// +/// Example: 1-D vector load on a scalar memref. +/// ```mlir +/// %result = vector.load %base[%i, %j] : memref<100x100xf32>, vector<8xf32> +/// ``` +/// +/// Example: 1-D vector load on a vector memref. +/// ```mlir +/// %result = vector.load %memref[%i, %j] : memref<200x100xvector<8xf32>>, vector<8xf32> +/// ``` +/// +/// Example: 2-D vector load on a scalar memref. +/// ```mlir +/// %result = vector.load %memref[%i, %j] : memref<200x100xf32>, vector<4x8xf32> +/// ``` +/// +/// Example: 2-D vector load on a vector memref. +/// ```mlir +/// %result = vector.load %memref[%i, %j] : memref<200x100xvector<4x8xf32>>, vector<4x8xf32> +/// ``` +/// +/// Representation-wise, the 'vector.load' operation permits out-of-bounds +/// reads. Support and implementation of out-of-bounds vector loads is +/// target-specific. No assumptions should be made on the value of elements +/// loaded out of bounds. Not all targets may support out-of-bounds vector +/// loads. +/// +/// Example: Potential out-of-bound vector load. +/// ```mlir +/// %result = vector.load %memref[%index] : memref, vector<8xf32> +/// ``` +/// +/// Example: Explicit out-of-bound vector load. +/// ```mlir +/// %result = vector.load %memref[%c0] : memref<7xf32>, vector<8xf32> +/// ``` +class LoadOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Predicates a maskable vector operation +/// The `vector.mask` is a `MaskingOpInterface` operation that predicates the +/// execution of another operation. It takes an `i1` vector mask and an +/// optional passthru vector as arguments. +/// +/// A implicitly `vector.yield`-terminated region encloses the operation to be +/// masked. Values used within the region are captured from above. Only one +/// *maskable* operation can be masked with a `vector.mask` operation at a time. +/// An operation is *maskable* if it implements the `MaskableOpInterface`. The +/// terminator yields all results from the maskable operation to the result of +/// this operation. No other values are allowed to be yielded. +/// +/// An empty `vector.mask` operation is currently legal to enable optimizations +/// across the `vector.mask` region. However, this might change in the future +/// once vector transformations gain better support for `vector.mask`. +/// TODO: Consider making empty `vector.mask` illegal. +/// +/// The vector mask argument holds a bit for each vector lane and determines +/// which vector lanes should execute the maskable operation and which ones +/// should not. The `vector.mask` operation returns the value produced by the +/// masked execution of the nested operation, if any. The masked-off lanes in +/// the result vector are taken from the corresponding lanes of the pass-thru +/// argument, if provided, or left unmodified, otherwise. At this point, 0-D +/// vectors are not supported by `vector.mask`. They may be supported in the +/// future. +/// +/// The `vector.mask` operation does not prescribe how a maskable operation +/// should be masked or how a masked operation should be lowered. Masking +/// constraints and some semantic details are provided by each maskable +/// operation through the `MaskableOpInterface`. Lowering of masked operations +/// is implementation defined. For instance, scalarizing the masked operation +/// or executing the operation for the masked-off lanes are valid lowerings as +/// long as the execution of masked-off lanes does not change the observable +/// behavior of the program. +/// +/// Examples: +/// +/// ``` +/// %0 = vector.mask %mask { vector.reduction , %a : vector<8xi32> into i32 } : vector<8xi1> -> i32 +/// ``` +/// +/// ``` +/// %0 = vector.mask %mask, %passthru { arith.divsi %a, %b : vector<8xi32> } : vector<8xi1> -> vector<8xi32> +/// ``` +/// +/// ``` +/// vector.mask %mask { vector.transfer_write %val, %t0[%idx] : vector<16xf32>, memref } : vector<16xi1> +/// ``` +/// +/// ``` +/// vector.mask %mask { vector.transfer_write %val, %t0[%idx] : vector<16xf32>, tensor } : vector<16xi1> -> tensor +/// ``` +class MaskOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// loads elements from memory into a vector as defined by a mask vector +/// The masked load reads elements from memory into a vector as defined +/// by a base with indices and a mask vector. When the mask is set, the +/// element is read from memory. Otherwise, the corresponding element is taken +/// from a pass-through vector. Informally the semantics are: +/// ``` +/// result[0] := if mask[0] then base[i + 0] else pass_thru[0] +/// result[1] := if mask[1] then base[i + 1] else pass_thru[1] +/// etc. +/// ``` +/// +/// If a mask bit is set and the corresponding index is out-of-bounds for the +/// given base, the behavior is undefined. If a mask bit is not set, the value +/// comes from the pass-through vector regardless of the index, and the index is +/// allowed to be out-of-bounds. +/// +/// The masked load can be used directly where applicable, or can be used +/// during progressively lowering to bring other memory operations closer to +/// hardware ISA support for a masked load. The semantics of the operation +/// closely correspond to those of the `llvm.masked.load` +/// [intrinsic](https://llvm.org/docs/LangRef.html#llvm-masked-load-intrinsics). +/// +/// Examples: +/// +/// ```mlir +/// %0 = vector.maskedload %base[%i], %mask, %pass_thru +/// : memref, vector<8xi1>, vector<8xf32> into vector<8xf32> +/// +/// %1 = vector.maskedload %base[%i, %j], %mask, %pass_thru +/// : memref, vector<16xi1>, vector<16xf32> into vector<16xf32> +/// ``` +class MaskedLoadOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// stores elements from a vector into memory as defined by a mask vector +/// The masked store operation writes elements from a vector into memory +/// as defined by a base with indices and a mask vector. When the mask is +/// set, the corresponding element from the vector is written to memory. Otherwise, +/// no action is taken for the element. Informally the semantics are: +/// ``` +/// if (mask[0]) base[i+0] = value[0] +/// if (mask[1]) base[i+1] = value[1] +/// etc. +/// ``` +/// +/// If a mask bit is set and the corresponding index is out-of-bounds for the +/// given base, the behavior is undefined. If a mask bit is not set, no value +/// is stored regardless of the index, and the index is allowed to be +/// out-of-bounds. +/// +/// The masked store can be used directly where applicable, or can be used +/// during progressively lowering to bring other memory operations closer to +/// hardware ISA support for a masked store. The semantics of the operation +/// closely correspond to those of the `llvm.masked.store` +/// [intrinsic](https://llvm.org/docs/LangRef.html#llvm-masked-store-intrinsics). +/// +/// Examples: +/// +/// ```mlir +/// vector.maskedstore %base[%i], %mask, %value +/// : memref, vector<8xi1>, vector<8xf32> +/// +/// vector.maskedstore %base[%i, %j], %mask, %value +/// : memref, vector<16xi1>, vector<16xf32> +/// ``` +class MaskedStoreOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Vector matrix multiplication op that operates on flattened 1-D MLIR vectors +/// This is the counterpart of llvm.matrix.multiply in MLIR. It serves the +/// purposes of more progressive lowering and localized type conversion. +/// Higher levels typically lower matrix multiplications into 'vector.contract' +/// operations. Subsequent rewriting rule progressively lower these operations +/// into 'vector.matrix_multiply' operations to bring the operations closer +/// to the hardware ISA. +/// +/// The ‘vector.matrix_multiply’ op treats `lhs` as matrix with rows +/// and columns, `rhs` as matrix with rows and +/// and multiplies them. The result matrix is returned embedded in +/// the result vector. +/// +/// Note, the corresponding LLVM intrinsic, `@llvm.matrix.multiply.*`, does not +/// support scalable vectors. Hence, this Op is only available for fixed-width +/// vectors. Also see: +/// +/// http://llvm.org/docs/LangRef.html#llvm-matrix-multiply-intrinsic +/// +/// Example: +/// +/// ```mlir +/// %C = vector.matrix_multiply %A, %B +/// { lhs_rows = 4: i32, lhs_columns = 16: i32 , rhs_columns = 3: i32 } : +/// (vector<64xf64>, vector<48xf64>) -> vector<12xf64> +/// ``` +class MatmulOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Multi-dimensional reduction operation +/// Reduces an n-D vector into an (n-k)-D vector (or a scalar when k == n) +/// using the given operation: `add`/`mul`/`minsi`/`minui`/`maxsi`/`maxui` +/// /`and`/`or`/`xor` for integers, and `add`/`mul`/`minnumf`/`maxnumf`/`minimumf` +/// /`maximumf` for floats. +/// Takes an initial accumulator operand. +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.multi_reduction , %0, %acc0 [1, 3] : +/// vector<4x8x16x32xf32> to vector<4x16xf32> +/// %2 = vector.multi_reduction , %1, %acc1 [0, 1] : +/// vector<4x16xf32> to f32 +/// ``` +class MultiDimReductionOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// vector outerproduct with optional fused add +/// Takes 2 1-D vectors and returns the 2-D vector containing the outer-product, +/// as illustrated below: +/// ``` +/// outer | [c, d] +/// ------+------------ +/// [a, | [ [a*c, a*d], +/// b] | [b*c, b*d] ] +/// ``` +/// This operation also accepts a 1-D vector lhs and a scalar rhs. In this +/// case a simple AXPY operation is performed, which returns a 1-D vector. +/// ``` +/// [a, b] * c = [a*c, b*c] +/// ``` +/// +/// An optional extra vector argument with the same shape as the output +/// vector may be specified in which case the operation returns the sum of +/// the outer-product and the extra vector. In this multiply-accumulate +/// scenario for floating-point arguments, the rounding mode is enforced +/// by guaranteeing that a fused-multiply add operation is emitted. When +/// lowered to the LLVMIR dialect, this form emits `llvm.intr.fma`, which +/// is guaranteed to lower to actual `fma` instructions on x86. +/// +/// An optional kind attribute may be specified to be: `add`/`mul`/`minsi` +/// /`minui`/`maxsi`/`maxui`/`and`/`or`/`xor` for integers, and `add`/`mul` +/// /`minnumf`/`maxnumf`/`minimumf`/`maximumf` for floats. The default is +/// `add`. +/// +/// Example: +/// +/// ``` +/// %2 = vector.outerproduct %0, %1: vector<4xf32>, vector<8xf32> +/// return %2: vector<4x8xf32> +/// +/// %3 = vector.outerproduct %0, %1, %2: +/// vector<4xf32>, vector<8xf32>, vector<4x8xf32> +/// return %3: vector<4x8xf32> +/// +/// %4 = vector.outerproduct %0, %1, %2 {kind = #vector.kind}: +/// vector<4xf32>, vector<8xf32>, vector<4x8xf32> +/// return %3: vector<4x8xf32> +/// +/// %6 = vector.outerproduct %4, %5: vector<10xf32>, f32 +/// return %6: vector<10xf32> +/// +/// ``` +class OuterProductOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// print operation (for testing and debugging) +/// Prints the source vector (or scalar) to stdout in a human-readable format +/// (for testing and debugging). No return value. +/// +/// Example: +/// +/// ```mlir +/// %v = arith.constant dense<0.0> : vector<4xf32> +/// vector.print %v : vector<4xf32> +/// ``` +/// +/// When lowered to LLVM, the vector print is decomposed into elementary +/// printing method calls that at runtime will yield: +/// +/// ``` +/// ( 0.0, 0.0, 0.0, 0.0 ) +/// ``` +/// +/// This is printed to stdout via a small runtime support library, which only +/// needs to provide a few printing methods (single value for all data +/// types, opening/closing bracket, comma, newline). +/// +/// By default `vector.print` adds a newline after the vector, but this can be +/// controlled by the `punctuation` attribute. For example, to print a comma +/// after instead do: +/// +/// ```mlir +/// vector.print %v : vector<4xf32> punctuation +/// ``` +/// +/// Note that it is possible to use the punctuation attribute alone. The +/// following will print a single newline: +/// +/// ```mlir +/// vector.print punctuation +/// ``` +/// +/// Additionally, to aid with debugging and testing `vector.print` can also +/// print constant strings: +/// +/// ```mlir +/// vector.print str "Hello, World!" +/// ``` +class PrintOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// reduction operation +/// Reduces an 1-D vector "horizontally" into a scalar using the given +/// operation: `add`/`mul`/`minsi`/`minui`/`maxsi`/`maxui`/`and`/`or`/`xor` for +/// integers, and `add`/`mul`/`minnumf`/`maxnumf`/`minimumf`/`maximumf` for +/// floats. Reductions also allow an optional fused accumulator. +/// +/// Note that these operations are restricted to 1-D vectors to remain +/// close to the corresponding LLVM intrinsics: +/// +/// http://llvm.org/docs/LangRef.html#vector-reduction-intrinsics +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.reduction , %0 : vector<16xf32> into f32 +/// +/// %3 = vector.reduction , %2 : vector<4xi32> into i32 +/// +/// %4 = vector.reduction , %0, %1 : vector<16xf32> into f32 +/// ``` +class ReductionOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// extract subvector from scalable vector operation +/// Takes rank-1 source vector and a position `pos` within the source +/// vector, and extracts a subvector starting from that position. +/// +/// The extraction position must be a multiple of the minimum size of the result +/// vector. For the operation to be well defined, the destination vector must +/// fit within the source vector from the specified position. Since the source +/// vector is scalable and its runtime length is unknown, the validity of the +/// operation can't be verified nor guaranteed at compile time. +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.scalable.extract %0[8] : vector<4xf32> from vector<[8]xf32> +/// %3 = vector.scalable.extract %2[0] : vector<[4]xf32> from vector<[8]xf32> +/// ``` +/// +/// Invalid example: +/// ```mlir +/// %1 = vector.scalable.extract %0[5] : vector<4xf32> from vector<[16]xf32> +/// ``` +class ScalableExtractOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// insert subvector into scalable vector operation +/// This operations takes a rank-1 fixed-length or scalable subvector and +/// inserts it within the destination scalable vector starting from the +/// position specificed by `pos`. If the source vector is scalable, the +/// insertion position will be scaled by the runtime scaling factor of the +/// source subvector. +/// +/// The insertion position must be a multiple of the minimum size of the source +/// vector. For the operation to be well defined, the source vector must fit in +/// the destination vector from the specified position. Since the destination +/// vector is scalable and its runtime length is unknown, the validity of the +/// operation can't be verified nor guaranteed at compile time. +/// +/// Example: +/// +/// ```mlir +/// %2 = vector.scalable.insert %0, %1[8] : vector<4xf32> into vector<[16]xf32> +/// %5 = vector.scalable.insert %3, %4[0] : vector<8xf32> into vector<[4]xf32> +/// %8 = vector.scalable.insert %6, %7[0] : vector<[4]xf32> into vector<[8]xf32> +/// ``` +/// +/// Invalid example: +/// ```mlir +/// %2 = vector.scalable.insert %0, %1[5] : vector<4xf32> into vector<[16]xf32> +/// ``` +class ScalableInsertOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Scan operation +/// Performs an inclusive/exclusive scan on an n-D vector along a single +/// dimension returning an n-D result vector using the given +/// operation (`add`/`mul`/`minsi`/`minui`/`maxsi`/`maxui`/`and`/`or`/`xor` for +/// integers, and `add`/`mul`/`minnumf`/`maxnumf`/`minimumf`/`maximumf` for +/// floats), and a specified value for the initial value. The operator returns +/// the result of scan as well as the result of the last reduction in the scan. +/// +/// Example: +/// +/// ```mlir +/// %1:2 = vector.scan , %0, %acc {inclusive = false, reduction_dim = 1 : i64} : +/// vector<4x8x16x32xf32>, vector<4x16x32xf32> +/// ``` +class ScanOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// scatters elements from a vector into memory as defined by an index vector +/// and a mask vector +/// The scatter operation stores elements from a n-D vector into memory as +/// defined by a base with indices and an additional n-D index vector, but +/// only if the corresponding bit in a n-D mask vector is set. Otherwise, no +/// action is taken for that element. Informally the semantics are: +/// ``` +/// if (mask[0]) base[index[0]] = value[0] +/// if (mask[1]) base[index[1]] = value[1] +/// etc. +/// ``` +/// +/// If a mask bit is set and the corresponding index is out-of-bounds for the +/// given base, the behavior is undefined. If a mask bit is not set, no value +/// is stored regardless of the index, and the index is allowed to be +/// out-of-bounds. +/// +/// If the index vector contains two or more duplicate indices, the behavior is +/// undefined. Underlying implementation may enforce strict sequential +/// semantics. +/// TODO: always enforce strict sequential semantics? +/// +/// The scatter operation can be used directly where applicable, or can be used +/// during progressively lowering to bring other memory operations closer to +/// hardware ISA support for a scatter. The semantics of the operation closely +/// correspond to those of the `llvm.masked.scatter` +/// [intrinsic](https://llvm.org/docs/LangRef.html#llvm-masked-scatter-intrinsics). +/// +/// Examples: +/// +/// ```mlir +/// vector.scatter %base[%c0][%v], %mask, %value +/// : memref, vector<16xi32>, vector<16xi1>, vector<16xf32> +/// +/// vector.scatter %base[%i, %j][%v], %mask, %value +/// : memref<16x16xf32>, vector<16xi32>, vector<16xi1>, vector<16xf32> +/// ``` +class ScatterOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// shape_cast casts between vector shapes +/// Casts to a vector with the same number of elements, element type, and +/// number of scalable dimensions. +/// +/// It is currently assumed that this operation does not require moving data, +/// and that it will be folded away before lowering vector operations. +/// +/// There is an exception to the folding expectation when targeting +/// llvm.intr.matrix operations. We need a type conversion back and forth from a +/// 2-D MLIR vector to a 1-D flattened LLVM vector.shape_cast lowering to LLVM +/// is supported in that particular case, for now. +/// +/// Examples: +/// +/// ```mlir +/// %1 = vector.shape_cast %0 : vector<4x3xf32> to vector<3x2x2xf32> +/// +/// // with 2 scalable dimensions (number of which must be preserved). +/// %3 = vector.shape_cast %2 : vector<[2]x3x[4]xi8> to vector<3x[1]x[8]xi8> +/// ``` +class ShapeCastOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// shuffle operation +/// The shuffle operation constructs a permutation (or duplication) of elements +/// from two input vectors, returning a vector with the same element type as +/// the input and a length that is the same as the shuffle mask. The two input +/// vectors must have the same element type, same rank, and trailing dimension +/// sizes and shuffles their values in the leading dimension (which may differ +/// in size) according to the given mask. The legality rules are: +/// * the two operands must have the same element type as the result +/// - Either, the two operands and the result must have the same +/// rank and trailing dimension sizes, viz. given two k-D operands +/// v1 : and +/// v2 : +/// we have s_i = t_i for all 1 < i <= k +/// - Or, the two operands must be 0-D vectors and the result is a 1-D vector. +/// * the mask length equals the leading dimension size of the result +/// * numbering the input vector indices left to right across the operands, all +/// mask values must be within range, viz. given two k-D operands v1 and v2 +/// above, all mask values are in the range [0,s_1+t_1). The value `-1` +/// represents a poison mask value, which specifies that the selected element +/// is poison. +/// +/// Note, scalable vectors are not supported. +/// +/// Example: +/// +/// ```mlir +/// %0 = vector.shuffle %a, %b[0, 3] +/// : vector<2xf32>, vector<2xf32> ; yields vector<2xf32> +/// %1 = vector.shuffle %c, %b[0, 1, 2] +/// : vector<2x16xf32>, vector<1x16xf32> ; yields vector<3x16xf32> +/// %2 = vector.shuffle %a, %b[3, 2, 1, 0] +/// : vector<2xf32>, vector<2xf32> ; yields vector<4xf32> +/// %3 = vector.shuffle %a, %b[0, 1] +/// : vector, vector ; yields vector<2xf32> +/// %4 = vector.shuffle %a, %b[0, 4, -1, -1, -1, -1] +/// : vector<4xf32>, vector<4xf32> ; yields vector<6xf32> +/// ``` +class ShuffleOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// vector splat or broadcast operation +/// Broadcast the operand to all elements of the result vector. The operand is +/// required to be of integer/index/float type. +/// +/// Example: +/// +/// ```mlir +/// %s = arith.constant 10.1 : f32 +/// %t = vector.splat %s : vector<8x16xf32> +/// ``` +class SplatOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// A linear sequence of values from 0 to N +/// A `step` operation produces an index vector, i.e. a 1-D vector of values of +/// index type that represents a linear sequence from 0 to N-1, where N is the +/// number of elements in the `result` vector. +/// +/// Supports fixed-width and scalable vectors. +/// +/// Examples: +/// +/// ```mlir +/// %0 = vector.step : vector<4xindex> ; [0, 1, 2, 3] +/// %1 = vector.step : vector<[4]xindex> ; [0, 1, .., ] +/// ``` +class StepOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// writes an n-D vector to an n-D slice of memory +/// The 'vector.store' operation writes an n-D vector to an n-D slice of memory. +/// It takes the vector value to be stored, a 'base' memref and an index for +/// each memref dimension. The 'base' memref and indices determine the start +/// memory address from which to write. Each index provides an offset for each +/// memref dimension based on the element type of the memref. The shape of the +/// vector value to store determines the shape of the slice written from the +/// start memory address. The elements along each dimension of the slice are +/// strided by the memref strides. When storing more than 1 element, only unit +/// strides are allowed along the most minor memref dimension. These constraints +/// guarantee that elements written along the first dimension of the slice are +/// contiguous in memory. +/// +/// The memref element type can be a scalar or a vector type. If the memref +/// element type is a scalar, it should match the element type of the value +/// to store. If the memref element type is vector, it should match the type +/// of the value to store. +/// +/// Example: 0-D vector store on a scalar memref. +/// ```mlir +/// vector.store %valueToStore, %memref[%i, %j] : memref<200x100xf32>, vector +/// ``` +/// +/// Example: 1-D vector store on a scalar memref. +/// ```mlir +/// vector.store %valueToStore, %memref[%i, %j] : memref<200x100xf32>, vector<8xf32> +/// ``` +/// +/// Example: 1-D vector store on a vector memref. +/// ```mlir +/// vector.store %valueToStore, %memref[%i, %j] : memref<200x100xvector<8xf32>>, vector<8xf32> +/// ``` +/// +/// Example: 2-D vector store on a scalar memref. +/// ```mlir +/// vector.store %valueToStore, %memref[%i, %j] : memref<200x100xf32>, vector<4x8xf32> +/// ``` +/// +/// Example: 2-D vector store on a vector memref. +/// ```mlir +/// vector.store %valueToStore, %memref[%i, %j] : memref<200x100xvector<4x8xf32>>, vector<4x8xf32> +/// ``` +/// +/// Representation-wise, the 'vector.store' operation permits out-of-bounds +/// writes. Support and implementation of out-of-bounds vector stores are +/// target-specific. No assumptions should be made on the memory written out of +/// bounds. Not all targets may support out-of-bounds vector stores. +/// +/// Example: Potential out-of-bounds vector store. +/// ```mlir +/// vector.store %valueToStore, %memref[%index] : memref, vector<8xf32> +/// ``` +/// +/// Example: Explicit out-of-bounds vector store. +/// ```mlir +/// vector.store %valueToStore, %memref[%c0] : memref<7xf32>, vector<8xf32> +/// ``` +class StoreOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Reads a supervector from memory into an SSA vector value. +/// The `vector.transfer_read` op performs a read from a slice within a +/// [MemRef](../LangRef.md#memref-type) or a Ranked +/// [Tensor](../LangRef.md#tensor-type) supplied as its first operand +/// into a [vector](../LangRef.md#vector-type) of the same base elemental type. +/// +/// A memref/tensor operand with vector element type, must have its vector +/// element type match a suffix (shape and element type) of the vector (e.g. +/// memref<3x2x6x4x3xf32>, vector<1x1x4x3xf32>). +/// +/// The slice is further defined by a full-rank index within the MemRef/Tensor, +/// supplied as the operands `[1 .. 1 + rank(memref/tensor))` that defines the +/// starting point of the transfer (e.g. `%A[%i0, %i1, %i2]`). +/// +/// The permutation_map [attribute](../LangRef.md#attributes) is an +/// [affine-map](Affine.md#affine-maps) which specifies the transposition on the +/// slice to match the vector shape. The permutation map may be implicit and +/// omitted from parsing and printing if it is the canonical minor identity map +/// (i.e. if it does not permute or broadcast any dimension). +/// +/// The size of the slice is specified by the size of the vector, given as the +/// return type. +/// +/// An SSA value `padding` of the same elemental type as the MemRef/Tensor is +/// provided to specify a fallback value in the case of out-of-bounds accesses +/// and/or masking. +/// +/// An optional SSA value `mask` may be specified to mask out elements read from +/// the MemRef/Tensor. The `mask` type is an `i1` vector with a shape that +/// matches how elements are read from the MemRef/Tensor, *before* any +/// permutation or broadcasting. Elements whose corresponding mask element is +/// `0` are masked out and replaced with `padding`. +/// +/// For every vector dimension, the boolean array attribute `in_bounds` +/// specifies if the transfer is guaranteed to be within the source bounds. If +/// set to "false", accesses (including the starting point) may run +/// out-of-bounds along the respective vector dimension as the index increases. +/// Non-vector dimensions *must* always be in-bounds. The `in_bounds` array +/// length has to be equal to the vector rank. This attribute has a default +/// value: `false` (i.e. "out-of-bounds"). When skipped in the textual IR, the +/// default value is assumed. Similarly, the OP printer will omit this +/// attribute when all dimensions are out-of-bounds (i.e. the default value is +/// used). +/// +/// A `vector.transfer_read` can be lowered to a simple load if all dimensions +/// are specified to be within bounds and no `mask` was specified. +/// +/// This operation is called 'read' by opposition to 'load' because the +/// super-vector granularity is generally not representable with a single +/// hardware register. A `vector.transfer_read` is thus a mid-level abstraction +/// that supports super-vectorization with non-effecting padding for full-tile +/// only operations. +/// +/// More precisely, let's dive deeper into the permutation_map for the following +/// MLIR: +/// +/// ```mlir +/// vector.transfer_read %A[%expr1, %expr2, %expr3, %expr4] +/// { permutation_map : (d0,d1,d2,d3) -> (d2,0,d0) } : +/// memref, vector<3x4x5xf32> +/// ``` +/// +/// This operation always reads a slice starting at `%A[%expr1, %expr2, %expr3, +/// %expr4]`. The size of the slice can be inferred from the resulting vector +/// shape and walking back through the permutation map: 3 along d2 and 5 along +/// d0, so the slice is: `%A[%expr1 : %expr1 + 5, %expr2, %expr3:%expr3 + 3, %expr4]` +/// +/// That slice needs to be read into a `vector<3x4x5xf32>`. Since the +/// permutation map is not full rank, there must be a broadcast along vector +/// dimension `1`. +/// +/// A notional lowering of vector.transfer_read could generate code resembling: +/// +/// ```mlir +/// // %expr1, %expr2, %expr3, %expr4 defined before this point +/// // alloc a temporary buffer for performing the "gather" of the slice. +/// %tmp = memref.alloc() : memref> +/// for %i = 0 to 3 { +/// affine.for %j = 0 to 4 { +/// affine.for %k = 0 to 5 { +/// // Note that this load does not involve %j. +/// %a = load %A[%expr1 + %k, %expr2, %expr3 + %i, %expr4] : memref +/// // Update the temporary gathered slice with the individual element +/// %slice = memref.load %tmp : memref> -> vector<3x4x5xf32> +/// %updated = vector.insert %a, %slice[%i, %j, %k] : f32 into vector<3x4x5xf32> +/// memref.store %updated, %tmp : memref> +/// }}} +/// // At this point we gathered the elements from the original +/// // memref into the desired vector layout, stored in the `%tmp` allocation. +/// %vec = memref.load %tmp : memref> -> vector<3x4x5xf32> +/// ``` +/// +/// On a GPU one could then map `i`, `j`, `k` to blocks and threads. Notice that +/// the temporary storage footprint could conceptually be only `3 * 5` values but +/// `3 * 4 * 5` values are actually transferred between `%A` and `%tmp`. +/// +/// Alternatively, if a notional vector broadcast operation were available, we +/// could avoid the loop on `%j` and the lowered code would resemble: +/// +/// ```mlir +/// // %expr1, %expr2, %expr3, %expr4 defined before this point +/// %tmp = memref.alloc() : memref> +/// for %i = 0 to 3 { +/// affine.for %k = 0 to 5 { +/// %a = load %A[%expr1 + %k, %expr2, %expr3 + %i, %expr4] : memref +/// %slice = memref.load %tmp : memref> -> vector<3x4x5xf32> +/// // Here we only store to the first element in dimension one +/// %updated = vector.insert %a, %slice[%i, 0, %k] : f32 into vector<3x4x5xf32> +/// memref.store %updated, %tmp : memref> +/// }} +/// // At this point we gathered the elements from the original +/// // memref into the desired vector layout, stored in the `%tmp` allocation. +/// // However we haven't replicated them alongside the first dimension, we need +/// // to broadcast now. +/// %partialVec = load %tmp : memref> -> vector<3x4x5xf32> +/// %vec = broadcast %tmpvec, 1 : vector<3x4x5xf32> +/// ``` +/// +/// where `broadcast` broadcasts from element 0 to all others along the +/// specified dimension. This time, the number of loaded element is `3 * 5` +/// values. +/// An additional `1` broadcast is required. On a GPU this broadcast could be +/// implemented using a warp-shuffle if loop `j` were mapped to `threadIdx.x`. +/// +/// Syntax +/// ``` +/// operation ::= ssa-id `=` `vector.transfer_read` ssa-use-list +/// `{` attribute-entry `} :` memref-type `,` vector-type +/// ``` +/// +/// Example: +/// +/// ```mlir +/// // Read the slice `%A[%i0, %i1:%i1+256, %i2:%i2+32]` into vector<32x256xf32> +/// // and pad with %f0 to handle the boundary case: +/// %f0 = arith.constant 0.0f : f32 +/// affine.for %i0 = 0 to %0 { +/// affine.for %i1 = 0 to %1 step 256 { +/// affine.for %i2 = 0 to %2 step 32 { +/// %v = vector.transfer_read %A[%i0, %i1, %i2], (%f0) +/// {permutation_map: (d0, d1, d2) -> (d2, d1)} : +/// memref, vector<32x256xf32> +/// }}} +/// +/// // or equivalently (rewrite with vector.transpose) +/// %f0 = arith.constant 0.0f : f32 +/// affine.for %i0 = 0 to %0 { +/// affine.for %i1 = 0 to %1 step 256 { +/// affine.for %i2 = 0 to %2 step 32 { +/// %v0 = vector.transfer_read %A[%i0, %i1, %i2], (%f0) +/// {permutation_map: (d0, d1, d2) -> (d1, d2)} : +/// memref, vector<256x32xf32> +/// %v = vector.transpose %v0, [1, 0] : +/// vector<256x32xf32> to vector<32x256f32> +/// }}} +/// +/// // Read the slice `%A[%i0, %i1]` (i.e. the element `%A[%i0, %i1]`) into +/// // vector<128xf32>. The underlying implementation will require a 1-D vector +/// // broadcast: +/// affine.for %i0 = 0 to %0 { +/// affine.for %i1 = 0 to %1 { +/// %3 = vector.transfer_read %A[%i0, %i1] +/// {permutation_map: (d0, d1) -> (0)} : +/// memref, vector<128xf32> +/// } +/// } +/// +/// // Read from a memref with vector element type. +/// %4 = vector.transfer_read %arg1[%c3, %c3], %vf0 +/// {permutation_map = (d0, d1)->(d0, d1)} +/// : memref>, vector<1x1x4x3xf32> +/// +/// // Read from a tensor with vector element type. +/// %4 = vector.transfer_read %arg1[%c3, %c3], %vf0 +/// {permutation_map = (d0, d1)->(d0, d1)} +/// : tensor>, vector<1x1x4x3xf32> +/// +/// // Special encoding for 0-d transfer with 0-d tensor/memref, vector shape +/// // {1} and permutation_map () -> (0). +/// %0 = vector.transfer_read %arg0[], %f0 {permutation_map = affine_map<()->(0)>} : +/// tensor, vector<1xf32> +/// ``` +class TransferReadOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// The vector.transfer_write op writes a supervector to memory. +/// The `vector.transfer_write` op performs a write from a +/// [vector](../LangRef.md#vector-type), supplied as its first operand, into a +/// slice within a [MemRef](../LangRef.md#memref-type) or a Ranked +/// [Tensor](../LangRef.md#tensor-type) of the same base elemental type, +/// supplied as its second operand. +/// +/// A vector memref/tensor operand must have its vector element type match a +/// suffix (shape and element type) of the vector (e.g. memref<3x2x6x4x3xf32>, +/// vector<1x1x4x3xf32>). If the operand is a tensor, the operation returns a +/// new tensor of the same type. +/// +/// The slice is further defined by a full-rank index within the MemRef/Tensor, +/// supplied as the operands `[2 .. 2 + rank(memref/tensor))` that defines the +/// starting point of the transfer (e.g. `%A[%i0, %i1, %i2, %i3]`). +/// +/// The permutation_map [attribute](../LangRef.md#attributes) is an +/// [affine-map](Affine.md#affine-maps) which specifies the transposition on the +/// slice to match the vector shape. The permutation map may be implicit and +/// omitted from parsing and printing if it is the canonical minor identity map +/// (i.e. if it does not permute any dimension). In contrast to `transfer_read`, +/// write ops cannot have broadcast dimensions. +/// +/// The size of the slice is specified by the size of the vector. +/// +/// An optional SSA value `mask` may be specified to mask out elements written +/// to the MemRef/Tensor. The `mask` type is an `i1` vector with a shape that +/// matches how elements are written into the MemRef/Tensor, *after* applying +/// any permutation. Elements whose corresponding mask element is `0` are +/// masked out. +/// +/// For every vector dimension, the boolean array attribute `in_bounds` +/// specifies if the transfer is guaranteed to be within the source bounds. If +/// set to "false", accesses (including the starting point) may run +/// out-of-bounds along the respective vector dimension as the index increases. +/// Non-vector dimensions *must* always be in-bounds. The `in_bounds` array +/// length has to be equal to the vector rank. This attribute has a default +/// value: `false` (i.e. "out-of-bounds"). When skipped in the textual IR, the +/// default value is assumed. Similarly, the OP printer will omit this +/// attribute when all dimensions are out-of-bounds (i.e. the default value is +/// used). +/// +/// A `vector.transfer_write` can be lowered to a simple store if all +/// dimensions are specified to be within bounds and no `mask` was specified. +/// +/// This operation is called 'write' by opposition to 'store' because the +/// super-vector granularity is generally not representable with a single +/// hardware register. A `vector.transfer_write` is thus a +/// mid-level abstraction that supports super-vectorization with non-effecting +/// padding for full-tile-only code. It is the responsibility of +/// `vector.transfer_write`'s implementation to ensure the memory writes are +/// valid. Different lowerings may be pertinent depending on the hardware +/// support. +/// +/// Example: +/// +/// ```mlir +/// // write vector<16x32x64xf32> into the slice +/// // `%A[%i0, %i1:%i1+32, %i2:%i2+64, %i3:%i3+16]`: +/// for %i0 = 0 to %0 { +/// affine.for %i1 = 0 to %1 step 32 { +/// affine.for %i2 = 0 to %2 step 64 { +/// affine.for %i3 = 0 to %3 step 16 { +/// %val = `ssa-value` : vector<16x32x64xf32> +/// vector.transfer_write %val, %A[%i0, %i1, %i2, %i3] +/// {permutation_map: (d0, d1, d2, d3) -> (d3, d1, d2)} : +/// vector<16x32x64xf32>, memref +/// }}}} +/// +/// // or equivalently (rewrite with vector.transpose) +/// for %i0 = 0 to %0 { +/// affine.for %i1 = 0 to %1 step 32 { +/// affine.for %i2 = 0 to %2 step 64 { +/// affine.for %i3 = 0 to %3 step 16 { +/// %val = `ssa-value` : vector<16x32x64xf32> +/// %valt = vector.transpose %val, [1, 2, 0] : +/// vector<16x32x64xf32> -> vector<32x64x16xf32> +/// vector.transfer_write %valt, %A[%i0, %i1, %i2, %i3] +/// {permutation_map: (d0, d1, d2, d3) -> (d1, d2, d3)} : +/// vector<32x64x16xf32>, memref +/// }}}} +/// +/// // write to a memref with vector element type. +/// vector.transfer_write %4, %arg1[%c3, %c3] +/// {permutation_map = (d0, d1)->(d0, d1)} +/// : vector<1x1x4x3xf32>, memref> +/// +/// // return a tensor where the vector is inserted into the source tensor. +/// %5 = vector.transfer_write %4, %arg1[%c3, %c3] +/// {permutation_map = (d0, d1)->(d0, d1)} +/// : vector<1x1x4x3xf32>, tensor> +/// +/// // Special encoding for 0-d transfer with 0-d tensor/memref, vector shape +/// // {1} and permutation_map () -> (0). +/// %1 = vector.transfer_write %0, %arg0[] {permutation_map = affine_map<()->(0)>} : +/// vector<1xf32>, tensor +/// ``` +class TransferWriteOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// vector transpose operation +/// Takes a n-D vector and returns the transposed n-D vector defined by +/// the permutation of ranks in the n-sized integer array attribute (in case +/// of 0-D vectors the array attribute must be empty). +/// +/// In the operation +/// +/// ```mlir +/// %1 = vector.transpose %0, [i_1, .., i_n] +/// : vector +/// to vector +/// ``` +/// +/// the `permutation` array [i_1, .., i_n] must be a permutation of [0, .., n-1]. +/// +/// Example: +/// +/// ```mlir +/// %1 = vector.transpose %0, [1, 0] : vector<2x3xf32> to vector<3x2xf32> +/// +/// [ [a, b, c], [ [a, d], +/// [d, e, f] ] -> [b, e], +/// [c, f] ] +/// ``` +class TransposeOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// type_cast op converts a scalar memref to a vector memref +/// Performs a conversion from a memref with scalar element to a memref with a +/// *single* vector element, copying the shape of the memref to the vector. This +/// is the minimal viable operation that is required to makeke +/// super-vectorization operational. It can be seen as a special case of the +/// `view` operation but scoped in the super-vectorization context. +/// +/// Example: +/// +/// ```mlir +/// %A = memref.alloc() : memref<5x4x3xf32> +/// %VA = vector.type_cast %A : memref<5x4x3xf32> to memref> +/// ``` +class TypeCastOp; +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +/// Terminates and yields values from vector regions. +/// "vector.yield" yields an SSA value from the Vector dialect op region and +/// terminates the regions. The semantics of how the values are yielded is +/// defined by the parent operation. +/// If "vector.yield" has any operands, the operands must correspond to the +/// parent operation's results. +/// If the parent operation defines no value the vector.yield may be omitted +/// when printing the region. +class YieldOp; +} // namespace vector +} // namespace mlir +#ifdef GET_OP_CLASSES +#undef GET_OP_CLASSES + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::VectorScaleOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class VectorScaleOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + VectorScaleOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.vscale", odsAttrs.getContext()); + } + + VectorScaleOpGenericAdaptorBase(VectorScaleOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class VectorScaleOpGenericAdaptor : public detail::VectorScaleOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::VectorScaleOpGenericAdaptorBase; +public: + VectorScaleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + VectorScaleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : VectorScaleOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + VectorScaleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : VectorScaleOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + VectorScaleOpGenericAdaptor(RangeT values, const VectorScaleOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + VectorScaleOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class VectorScaleOpAdaptor : public VectorScaleOpGenericAdaptor<::mlir::ValueRange> { +public: + using VectorScaleOpGenericAdaptor::VectorScaleOpGenericAdaptor; + VectorScaleOpAdaptor(VectorScaleOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class VectorScaleOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::OpAsmOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = VectorScaleOpAdaptor; + template + using GenericAdaptor = VectorScaleOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.vscale"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::IndexType> getRes() { + return ::llvm::cast<::mlir::TypedValue<::mlir::IndexType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::VectorScaleOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::BitCastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BitCastOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + BitCastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.bitcast", odsAttrs.getContext()); + } + + BitCastOpGenericAdaptorBase(BitCastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class BitCastOpGenericAdaptor : public detail::BitCastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BitCastOpGenericAdaptorBase; +public: + BitCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BitCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BitCastOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + BitCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : BitCastOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + BitCastOpGenericAdaptor(RangeT values, const BitCastOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + BitCastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BitCastOpAdaptor : public BitCastOpGenericAdaptor<::mlir::ValueRange> { +public: + using BitCastOpGenericAdaptor::BitCastOpGenericAdaptor; + BitCastOpAdaptor(BitCastOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class BitCastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BitCastOpAdaptor; + template + using GenericAdaptor = BitCastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.bitcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getSource().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::BitCastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::BroadcastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class BroadcastOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + BroadcastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.broadcast", odsAttrs.getContext()); + } + + BroadcastOpGenericAdaptorBase(BroadcastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class BroadcastOpGenericAdaptor : public detail::BroadcastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::BroadcastOpGenericAdaptorBase; +public: + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : BroadcastOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + BroadcastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : BroadcastOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + BroadcastOpGenericAdaptor(RangeT values, const BroadcastOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + BroadcastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class BroadcastOpAdaptor : public BroadcastOpGenericAdaptor<::mlir::ValueRange> { +public: + using BroadcastOpGenericAdaptor::BroadcastOpGenericAdaptor; + BroadcastOpAdaptor(BroadcastOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class BroadcastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = BroadcastOpAdaptor; + template + using GenericAdaptor = BroadcastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.broadcast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + Type getSourceType() { return getSource().getType(); } + VectorType getResultVectorType() { + return ::llvm::cast(getVector().getType()); + } + + /// Return the dimensions of the result vector that were formerly ones in the + /// source tensor and thus correspond to "dim-1" broadcasting. + llvm::SetVector computeBroadcastedUnitDims(); + + /// Broadcast `value` to a vector of `dstShape`, knowing that exactly the + /// `broadcastedDims` dimensions in the dstShape are broadcasted. + /// This requires (and asserts) that the broadcast is free of "dim-1" + /// broadcasting. + /// Since vector.broadcast only allows expanding leading dimensions, an extra + /// vector.transpose may be inserted to make the broadcast possible. + /// `value`, `dstShape` and `broadcastedDims` must be properly specified or + /// the helper will assert. This means: + /// 1. `dstShape` must not be empty. + /// 2. `broadcastedDims` must be confined to [0 .. rank(value.getResultVectorType)] + /// 2. `dstShape` trimmed of the dimensions specified in `broadcastedDims` + // must match the `value` shape. + static Value createOrFoldBroadcastOp( + OpBuilder &b, Value value, + ArrayRef dstShape, + const llvm::SetVector &broadcastedDims); +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::BroadcastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::CompressStoreOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CompressStoreOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + CompressStoreOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.compressstore", odsAttrs.getContext()); + } + + CompressStoreOpGenericAdaptorBase(CompressStoreOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class CompressStoreOpGenericAdaptor : public detail::CompressStoreOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CompressStoreOpGenericAdaptorBase; +public: + CompressStoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CompressStoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CompressStoreOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + CompressStoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : CompressStoreOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + CompressStoreOpGenericAdaptor(RangeT values, const CompressStoreOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + CompressStoreOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getMask() { + return (*getODSOperands(2).begin()); + } + + ValueT getValueToStore() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class CompressStoreOpAdaptor : public CompressStoreOpGenericAdaptor<::mlir::ValueRange> { +public: + using CompressStoreOpGenericAdaptor::CompressStoreOpGenericAdaptor; + CompressStoreOpAdaptor(CompressStoreOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class CompressStoreOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CompressStoreOpAdaptor; + template + using GenericAdaptor = CompressStoreOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.compressstore"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(3).begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(3); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + MemRefType getMemRefType() { + return ::llvm::cast(getBase().getType()); + } + VectorType getMaskVectorType() { + return ::llvm::cast(getMask().getType()); + } + VectorType getVectorType() { + return ::llvm::cast(getValueToStore().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::CompressStoreOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ConstantMaskOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ConstantMaskOpGenericAdaptorBase { +public: + struct Properties { + using mask_dim_sizesTy = ::mlir::DenseI64ArrayAttr; + mask_dim_sizesTy mask_dim_sizes; + + auto getMaskDimSizes() const { + auto &propStorage = this->mask_dim_sizes; + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(propStorage); + } + void setMaskDimSizes(const ::mlir::DenseI64ArrayAttr &propValue) { + this->mask_dim_sizes = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.mask_dim_sizes == this->mask_dim_sizes && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ConstantMaskOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.constant_mask", odsAttrs.getContext()); + } + + ConstantMaskOpGenericAdaptorBase(ConstantMaskOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::DenseI64ArrayAttr getMaskDimSizesAttr() { + auto attr = ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().mask_dim_sizes); + return attr; + } + + ::llvm::ArrayRef getMaskDimSizes(); +}; +} // namespace detail +template +class ConstantMaskOpGenericAdaptor : public detail::ConstantMaskOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ConstantMaskOpGenericAdaptorBase; +public: + ConstantMaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ConstantMaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ConstantMaskOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ConstantMaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ConstantMaskOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ConstantMaskOpGenericAdaptor(RangeT values, const ConstantMaskOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ConstantMaskOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ConstantMaskOpAdaptor : public ConstantMaskOpGenericAdaptor<::mlir::ValueRange> { +public: + using ConstantMaskOpGenericAdaptor::ConstantMaskOpGenericAdaptor; + ConstantMaskOpAdaptor(ConstantMaskOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ConstantMaskOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ConstantMaskOpAdaptor; + template + using GenericAdaptor = ConstantMaskOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("mask_dim_sizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getMaskDimSizesAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getMaskDimSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.constant_mask"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::DenseI64ArrayAttr getMaskDimSizesAttr() { + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().mask_dim_sizes); + } + + ::llvm::ArrayRef getMaskDimSizes(); + void setMaskDimSizesAttr(::mlir::DenseI64ArrayAttr attr) { + getProperties().mask_dim_sizes = attr; + } + + void setMaskDimSizes(::llvm::ArrayRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, VectorType type, ConstantMaskKind kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::DenseI64ArrayAttr mask_dim_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::DenseI64ArrayAttr mask_dim_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::llvm::ArrayRef mask_dim_sizes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::llvm::ArrayRef mask_dim_sizes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + /// Return the result type of this op. + VectorType getVectorType() { + return cast(getOperation()->getResultTypes()[0]); + } + + /// Return whether the mask is a uniform vector of `1`s. + bool isAllOnesMask(); +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ConstantMaskOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ContractionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ContractionOpGenericAdaptorBase { +public: + struct Properties { + using indexing_mapsTy = ::mlir::ArrayAttr; + indexing_mapsTy indexing_maps; + + auto getIndexingMaps() const { + auto &propStorage = this->indexing_maps; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setIndexingMaps(const ::mlir::ArrayAttr &propValue) { + this->indexing_maps = propValue; + } + using iterator_typesTy = ::mlir::ArrayAttr; + iterator_typesTy iterator_types; + + auto getIteratorTypes() const { + auto &propStorage = this->iterator_types; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setIteratorTypes(const ::mlir::ArrayAttr &propValue) { + this->iterator_types = propValue; + } + using kindTy = ::mlir::vector::CombiningKindAttr; + kindTy kind; + + auto getKind() const { + auto &propStorage = this->kind; + return ::llvm::dyn_cast_or_null<::mlir::vector::CombiningKindAttr>(propStorage); + } + void setKind(const ::mlir::vector::CombiningKindAttr &propValue) { + this->kind = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.indexing_maps == this->indexing_maps && + rhs.iterator_types == this->iterator_types && + rhs.kind == this->kind && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ContractionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.contract", odsAttrs.getContext()); + } + + ContractionOpGenericAdaptorBase(ContractionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::ArrayAttr getIndexingMapsAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().indexing_maps); + return attr; + } + + ::mlir::ArrayAttr getIndexingMaps(); + ::mlir::ArrayAttr getIteratorTypesAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().iterator_types); + return attr; + } + + ::mlir::ArrayAttr getIteratorTypes(); + ::mlir::vector::CombiningKindAttr getKindAttr(); + ::mlir::vector::CombiningKind getKind(); +}; +} // namespace detail +template +class ContractionOpGenericAdaptor : public detail::ContractionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ContractionOpGenericAdaptorBase; +public: + ContractionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ContractionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ContractionOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ContractionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ContractionOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ContractionOpGenericAdaptor(RangeT values, const ContractionOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ContractionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getAcc() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ContractionOpAdaptor : public ContractionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ContractionOpGenericAdaptor::ContractionOpGenericAdaptor; + ContractionOpAdaptor(ContractionOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ContractionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::vector::MaskableOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ContractionOpAdaptor; + template + using GenericAdaptor = ContractionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("indexing_maps"), ::llvm::StringRef("iterator_types"), ::llvm::StringRef("kind")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getIndexingMapsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getIndexingMapsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getIteratorTypesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getIteratorTypesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getKindAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.contract"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getLhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getRhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getAcc() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(2).begin()); + } + + ::mlir::OpOperand &getLhsMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getRhsMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getAccMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::ArrayAttr getIndexingMapsAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().indexing_maps); + } + + ::mlir::ArrayAttr getIndexingMaps(); + ::mlir::ArrayAttr getIteratorTypesAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().iterator_types); + } + + ::mlir::ArrayAttr getIteratorTypes(); + ::mlir::vector::CombiningKindAttr getKindAttr() { + return ::llvm::dyn_cast_or_null<::mlir::vector::CombiningKindAttr>(getProperties().kind); + } + + ::mlir::vector::CombiningKind getKind(); + void setIndexingMapsAttr(::mlir::ArrayAttr attr) { + getProperties().indexing_maps = attr; + } + + void setIteratorTypesAttr(::mlir::ArrayAttr attr) { + getProperties().iterator_types = attr; + } + + void setKindAttr(::mlir::vector::CombiningKindAttr attr) { + getProperties().kind = attr; + } + + void setKind(::mlir::vector::CombiningKind attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, Value acc, ArrayAttr indexingMaps, ArrayAttr iteratorTypes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, Value acc, ArrayRef> indexingExprs, ArrayRef iteratorTypes); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, Value acc, ArrayAttr indexingMaps, ArrayAttr iteratorTypes, CombiningKind kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKindAttr kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKindAttr kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKind kind = CombiningKind::ADD); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc, ::mlir::ArrayAttr indexing_maps, ::mlir::ArrayAttr iterator_types, ::mlir::vector::CombiningKind kind = CombiningKind::ADD); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void populateDefaultProperties(::mlir::OperationName opName, Properties &properties); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + mlir::Type getExpectedMaskType(); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getLhsType() { + return ::llvm::cast(getLhs().getType()); + } + VectorType getRhsType() { + return ::llvm::cast(getRhs().getType()); + } + Type getAccType() { return getAcc().getType(); } + Type getResultType() { return getResult().getType(); } + SmallVector getTraitAttrNames(); + static unsigned getAccOperandIndex() { return 2; } + + llvm::SmallVector<::mlir::AffineMap, 4> getIndexingMapsArray() { + return llvm::to_vector<4>(getIndexingMaps().getAsValueRange<::mlir::AffineMapAttr>()); + } + + // Returns the bounds of each dimension in the iteration space spanned + // by the iterator types of this operation. + void getIterationBounds(SmallVectorImpl &iterationBounds); + + // Returns a list of index maps, where there is a list entry for each + // op indexing map attribute (i.e. one for each input and output, with + // the output listed last). Each index map, maps from this operations + // iteration space, to vector dimensions of the maps input/output. + void getIterationIndexMap( + std::vector> &iterationIndexMap); + + std::vector> getContractingDimMap(); + std::vector> getBatchDimMap(); + + static CombiningKind getDefaultKind() { + return CombiningKind::ADD; + } + + SmallVector getIteratorTypesArray() { + auto range = + getIteratorTypes() + .template getAsValueRange(); + return {range.begin(), range.end()}; + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ContractionOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::CreateMaskOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class CreateMaskOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + CreateMaskOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.create_mask", odsAttrs.getContext()); + } + + CreateMaskOpGenericAdaptorBase(CreateMaskOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class CreateMaskOpGenericAdaptor : public detail::CreateMaskOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::CreateMaskOpGenericAdaptorBase; +public: + CreateMaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + CreateMaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : CreateMaskOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + CreateMaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : CreateMaskOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + CreateMaskOpGenericAdaptor(RangeT values, const CreateMaskOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + CreateMaskOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return getODSOperands(0); + } + +private: + RangeT odsOperands; +}; +class CreateMaskOpAdaptor : public CreateMaskOpGenericAdaptor<::mlir::ValueRange> { +public: + using CreateMaskOpGenericAdaptor::CreateMaskOpGenericAdaptor; + CreateMaskOpAdaptor(CreateMaskOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class CreateMaskOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = CreateMaskOpAdaptor; + template + using GenericAdaptor = CreateMaskOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.create_mask"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::Operation::operand_range getOperands() { + return getODSOperands(0); + } + + ::mlir::MutableOperandRange getOperandsMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, VectorType type, ArrayRef mixedOperands); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::ValueRange operands); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + /// Return the result type of this op. + VectorType getVectorType() { + return cast(getOperation()->getResultTypes()[0]); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::CreateMaskOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::DeinterleaveOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class DeinterleaveOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + DeinterleaveOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.deinterleave", odsAttrs.getContext()); + } + + DeinterleaveOpGenericAdaptorBase(DeinterleaveOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class DeinterleaveOpGenericAdaptor : public detail::DeinterleaveOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::DeinterleaveOpGenericAdaptorBase; +public: + DeinterleaveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + DeinterleaveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : DeinterleaveOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + DeinterleaveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : DeinterleaveOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + DeinterleaveOpGenericAdaptor(RangeT values, const DeinterleaveOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + DeinterleaveOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class DeinterleaveOpAdaptor : public DeinterleaveOpGenericAdaptor<::mlir::ValueRange> { +public: + using DeinterleaveOpGenericAdaptor::DeinterleaveOpGenericAdaptor; + DeinterleaveOpAdaptor(DeinterleaveOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class DeinterleaveOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = DeinterleaveOpAdaptor; + template + using GenericAdaptor = DeinterleaveOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.deinterleave"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getRes1() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getRes2() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(1).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res1, ::mlir::Type res2, ::mlir::Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getSource().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getRes1().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::DeinterleaveOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExpandLoadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExpandLoadOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ExpandLoadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.expandload", odsAttrs.getContext()); + } + + ExpandLoadOpGenericAdaptorBase(ExpandLoadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class ExpandLoadOpGenericAdaptor : public detail::ExpandLoadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExpandLoadOpGenericAdaptorBase; +public: + ExpandLoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExpandLoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExpandLoadOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ExpandLoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ExpandLoadOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ExpandLoadOpGenericAdaptor(RangeT values, const ExpandLoadOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ExpandLoadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getMask() { + return (*getODSOperands(2).begin()); + } + + ValueT getPassThru() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExpandLoadOpAdaptor : public ExpandLoadOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExpandLoadOpGenericAdaptor::ExpandLoadOpGenericAdaptor; + ExpandLoadOpAdaptor(ExpandLoadOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ExpandLoadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExpandLoadOpAdaptor; + template + using GenericAdaptor = ExpandLoadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.expandload"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getPassThru() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(3).begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getPassThruMutable() { + auto range = getODSOperandIndexAndLength(3); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + MemRefType getMemRefType() { + return ::llvm::cast(getBase().getType()); + } + VectorType getMaskVectorType() { + return ::llvm::cast(getMask().getType()); + } + VectorType getPassThruVectorType() { + return ::llvm::cast(getPassThru().getType()); + } + VectorType getVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ExpandLoadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExtractElementOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExtractElementOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ExtractElementOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.extractelement", odsAttrs.getContext()); + } + + ExtractElementOpGenericAdaptorBase(ExtractElementOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class ExtractElementOpGenericAdaptor : public detail::ExtractElementOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExtractElementOpGenericAdaptorBase; +public: + ExtractElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExtractElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExtractElementOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ExtractElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ExtractElementOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ExtractElementOpGenericAdaptor(RangeT values, const ExtractElementOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ExtractElementOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getVector() { + return (*getODSOperands(0).begin()); + } + + ValueT getPosition() { + auto operands = getODSOperands(1); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExtractElementOpAdaptor : public ExtractElementOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExtractElementOpGenericAdaptor::ExtractElementOpGenericAdaptor; + ExtractElementOpAdaptor(ExtractElementOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ExtractElementOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExtractElementOpAdaptor; + template + using GenericAdaptor = ExtractElementOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.extractelement"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getPosition() { + auto operands = getODSOperands(1); + return operands.empty() ? ::mlir::TypedValue<::mlir::Type>{} : ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*operands.begin()); + } + + ::mlir::OpOperand &getVectorMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getPositionMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, /*optional*/::mlir::Value position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value vector, /*optional*/::mlir::Value position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, /*optional*/::mlir::Value position); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getVector().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ExtractElementOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExtractOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExtractOpGenericAdaptorBase { +public: + struct Properties { + using static_positionTy = ::mlir::DenseI64ArrayAttr; + static_positionTy static_position; + + auto getStaticPosition() const { + auto &propStorage = this->static_position; + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(propStorage); + } + void setStaticPosition(const ::mlir::DenseI64ArrayAttr &propValue) { + this->static_position = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.static_position == this->static_position && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ExtractOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.extract", odsAttrs.getContext()); + } + + ExtractOpGenericAdaptorBase(ExtractOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::DenseI64ArrayAttr getStaticPositionAttr() { + auto attr = ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().static_position); + return attr; + } + + ::llvm::ArrayRef getStaticPosition(); +}; +} // namespace detail +template +class ExtractOpGenericAdaptor : public detail::ExtractOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExtractOpGenericAdaptorBase; +public: + ExtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExtractOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ExtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ExtractOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ExtractOpGenericAdaptor(RangeT values, const ExtractOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ExtractOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getVector() { + return (*getODSOperands(0).begin()); + } + + RangeT getDynamicPosition() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExtractOpAdaptor : public ExtractOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExtractOpGenericAdaptor::ExtractOpGenericAdaptor; + ExtractOpAdaptor(ExtractOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ExtractOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpTrait::InferTypeOpAdaptor> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExtractOpAdaptor; + template + using GenericAdaptor = ExtractOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("static_position")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getStaticPositionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getStaticPositionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.extract"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getDynamicPosition() { + return getODSOperands(1); + } + + ::mlir::OpOperand &getVectorMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getDynamicPositionMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::DenseI64ArrayAttr getStaticPositionAttr() { + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().static_position); + } + + ::llvm::ArrayRef getStaticPosition(); + void setStaticPositionAttr(::mlir::DenseI64ArrayAttr attr) { + getProperties().static_position = attr; + } + + void setStaticPosition(::llvm::ArrayRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, int64_t position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, OpFoldResult position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, ArrayRef position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, ArrayRef position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + static ::llvm::LogicalResult + inferReturnTypes(::mlir::MLIRContext *context, + std::optional<::mlir::Location> location, + Adaptor adaptor, + ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes); + + static bool isCompatibleReturnTypes(::mlir::TypeRange l, ::mlir::TypeRange r); + + + // Integer to represent a poison index within a static and positive integer + // range. + static constexpr int64_t kPoisonIndex = -1; + + VectorType getSourceVectorType() { + return ::llvm::cast(getVector().getType()); + } + + /// Return a vector with all the static and dynamic position indices. + SmallVector getMixedPosition() { + OpBuilder builder(getContext()); + return getMixedValues(getStaticPosition(), getDynamicPosition(), builder); + } + + unsigned getNumIndices() { + return getStaticPosition().size(); + } + + /// Return "true" if the op has at least one dynamic position. + bool hasDynamicPosition() { + return !getDynamicPosition().empty(); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ExtractOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ExtractStridedSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ExtractStridedSliceOpGenericAdaptorBase { +public: + struct Properties { + using offsetsTy = ::mlir::ArrayAttr; + offsetsTy offsets; + + auto getOffsets() const { + auto &propStorage = this->offsets; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setOffsets(const ::mlir::ArrayAttr &propValue) { + this->offsets = propValue; + } + using sizesTy = ::mlir::ArrayAttr; + sizesTy sizes; + + auto getSizes() const { + auto &propStorage = this->sizes; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setSizes(const ::mlir::ArrayAttr &propValue) { + this->sizes = propValue; + } + using stridesTy = ::mlir::ArrayAttr; + stridesTy strides; + + auto getStrides() const { + auto &propStorage = this->strides; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setStrides(const ::mlir::ArrayAttr &propValue) { + this->strides = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.offsets == this->offsets && + rhs.sizes == this->sizes && + rhs.strides == this->strides && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ExtractStridedSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.extract_strided_slice", odsAttrs.getContext()); + } + + ExtractStridedSliceOpGenericAdaptorBase(ExtractStridedSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::ArrayAttr getOffsetsAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().offsets); + return attr; + } + + ::mlir::ArrayAttr getOffsets(); + ::mlir::ArrayAttr getSizesAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().sizes); + return attr; + } + + ::mlir::ArrayAttr getSizes(); + ::mlir::ArrayAttr getStridesAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().strides); + return attr; + } + + ::mlir::ArrayAttr getStrides(); +}; +} // namespace detail +template +class ExtractStridedSliceOpGenericAdaptor : public detail::ExtractStridedSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ExtractStridedSliceOpGenericAdaptorBase; +public: + ExtractStridedSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ExtractStridedSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ExtractStridedSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ExtractStridedSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ExtractStridedSliceOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ExtractStridedSliceOpGenericAdaptor(RangeT values, const ExtractStridedSliceOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ExtractStridedSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getVector() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ExtractStridedSliceOpAdaptor : public ExtractStridedSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using ExtractStridedSliceOpGenericAdaptor::ExtractStridedSliceOpGenericAdaptor; + ExtractStridedSliceOpAdaptor(ExtractStridedSliceOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ExtractStridedSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ExtractStridedSliceOpAdaptor; + template + using GenericAdaptor = ExtractStridedSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("offsets"), ::llvm::StringRef("sizes"), ::llvm::StringRef("strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getOffsetsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getOffsetsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getSizesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getSizesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getStridesAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.extract_strided_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getVectorMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::ArrayAttr getOffsetsAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().offsets); + } + + ::mlir::ArrayAttr getOffsets(); + ::mlir::ArrayAttr getSizesAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().sizes); + } + + ::mlir::ArrayAttr getSizes(); + ::mlir::ArrayAttr getStridesAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().strides); + } + + ::mlir::ArrayAttr getStrides(); + void setOffsetsAttr(::mlir::ArrayAttr attr) { + getProperties().offsets = attr; + } + + void setSizesAttr(::mlir::ArrayAttr attr) { + getProperties().sizes = attr; + } + + void setStridesAttr(::mlir::ArrayAttr attr) { + getProperties().strides = attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, ArrayRef offsets, ArrayRef sizes, ArrayRef strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value vector, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr sizes, ::mlir::ArrayAttr strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr sizes, ::mlir::ArrayAttr strides); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getVector().getType()); + } + void getOffsets(SmallVectorImpl &results); + bool hasNonUnitStrides() { + return llvm::any_of(getStrides(), [](Attribute attr) { + return ::llvm::cast(attr).getInt() != 1; + }); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ExtractStridedSliceOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::FMAOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FMAOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + FMAOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.fma", odsAttrs.getContext()); + } + + FMAOpGenericAdaptorBase(FMAOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class FMAOpGenericAdaptor : public detail::FMAOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FMAOpGenericAdaptorBase; +public: + FMAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FMAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FMAOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + FMAOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : FMAOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + FMAOpGenericAdaptor(RangeT values, const FMAOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + FMAOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getAcc() { + return (*getODSOperands(2).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FMAOpAdaptor : public FMAOpGenericAdaptor<::mlir::ValueRange> { +public: + using FMAOpGenericAdaptor::FMAOpGenericAdaptor; + FMAOpAdaptor(FMAOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class FMAOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait, ::mlir::OpTrait::Elementwise, ::mlir::OpTrait::Scalarizable, ::mlir::OpTrait::Vectorizable, ::mlir::OpTrait::Tensorizable, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FMAOpAdaptor; + template + using GenericAdaptor = FMAOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.fma"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getLhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getRhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getAcc() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::OpOperand &getLhsMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getRhsMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getAccMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::Value acc); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + VectorType getVectorType() { return ::llvm::cast(getLhs().getType()); } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::FMAOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::FlatTransposeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FlatTransposeOpGenericAdaptorBase { +public: + struct Properties { + using columnsTy = ::mlir::IntegerAttr; + columnsTy columns; + + auto getColumns() const { + auto &propStorage = this->columns; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setColumns(const ::mlir::IntegerAttr &propValue) { + this->columns = propValue; + } + using rowsTy = ::mlir::IntegerAttr; + rowsTy rows; + + auto getRows() const { + auto &propStorage = this->rows; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setRows(const ::mlir::IntegerAttr &propValue) { + this->rows = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.columns == this->columns && + rhs.rows == this->rows && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + FlatTransposeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.flat_transpose", odsAttrs.getContext()); + } + + FlatTransposeOpGenericAdaptorBase(FlatTransposeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::IntegerAttr getRowsAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().rows); + return attr; + } + + uint32_t getRows(); + ::mlir::IntegerAttr getColumnsAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().columns); + return attr; + } + + uint32_t getColumns(); +}; +} // namespace detail +template +class FlatTransposeOpGenericAdaptor : public detail::FlatTransposeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FlatTransposeOpGenericAdaptorBase; +public: + FlatTransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FlatTransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FlatTransposeOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + FlatTransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : FlatTransposeOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + FlatTransposeOpGenericAdaptor(RangeT values, const FlatTransposeOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + FlatTransposeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMatrix() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FlatTransposeOpAdaptor : public FlatTransposeOpGenericAdaptor<::mlir::ValueRange> { +public: + using FlatTransposeOpGenericAdaptor::FlatTransposeOpGenericAdaptor; + FlatTransposeOpAdaptor(FlatTransposeOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class FlatTransposeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FlatTransposeOpAdaptor; + template + using GenericAdaptor = FlatTransposeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("columns"), ::llvm::StringRef("rows")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getColumnsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getColumnsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getRowsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getRowsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.flat_transpose"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getMatrix() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getMatrixMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getRes() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::IntegerAttr getRowsAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().rows); + } + + uint32_t getRows(); + ::mlir::IntegerAttr getColumnsAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().columns); + } + + uint32_t getColumns(); + void setRowsAttr(::mlir::IntegerAttr attr) { + getProperties().rows = attr; + } + + void setRows(uint32_t attrValue); + void setColumnsAttr(::mlir::IntegerAttr attr) { + getProperties().columns = attr; + } + + void setColumns(uint32_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value matrix, ::mlir::IntegerAttr rows, ::mlir::IntegerAttr columns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value matrix, ::mlir::IntegerAttr rows, ::mlir::IntegerAttr columns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value matrix, uint32_t rows, uint32_t columns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value matrix, uint32_t rows, uint32_t columns); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::FlatTransposeOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::FromElementsOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class FromElementsOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + FromElementsOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.from_elements", odsAttrs.getContext()); + } + + FromElementsOpGenericAdaptorBase(FromElementsOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class FromElementsOpGenericAdaptor : public detail::FromElementsOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::FromElementsOpGenericAdaptorBase; +public: + FromElementsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + FromElementsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : FromElementsOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + FromElementsOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : FromElementsOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + FromElementsOpGenericAdaptor(RangeT values, const FromElementsOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + FromElementsOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getElements() { + return getODSOperands(0); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class FromElementsOpAdaptor : public FromElementsOpGenericAdaptor<::mlir::ValueRange> { +public: + using FromElementsOpGenericAdaptor::FromElementsOpGenericAdaptor; + FromElementsOpAdaptor(FromElementsOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class FromElementsOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::VariadicOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = FromElementsOpAdaptor; + template + using GenericAdaptor = FromElementsOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.from_elements"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::Operation::operand_range getElements() { + return getODSOperands(0); + } + + ::mlir::MutableOperandRange getElementsMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::ValueRange elements); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::FromElementsOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::GatherOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class GatherOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + GatherOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.gather", odsAttrs.getContext()); + } + + GatherOpGenericAdaptorBase(GatherOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class GatherOpGenericAdaptor : public detail::GatherOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::GatherOpGenericAdaptorBase; +public: + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : GatherOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + GatherOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : GatherOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + GatherOpGenericAdaptor(RangeT values, const GatherOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + GatherOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getIndexVec() { + return (*getODSOperands(2).begin()); + } + + ValueT getMask() { + return (*getODSOperands(3).begin()); + } + + ValueT getPassThru() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class GatherOpAdaptor : public GatherOpGenericAdaptor<::mlir::ValueRange> { +public: + using GatherOpGenericAdaptor::GatherOpGenericAdaptor; + GatherOpAdaptor(GatherOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class GatherOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<4>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::vector::MaskableOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = GatherOpAdaptor; + template + using GenericAdaptor = GatherOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.gather"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::ShapedType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::ShapedType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::VectorType> getIndexVec() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(3).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getPassThru() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(4).begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getIndexVecMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(3); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getPassThruMutable() { + auto range = getODSOperandIndexAndLength(4); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value pass_thru); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value pass_thru); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + mlir::Type getExpectedMaskType(); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + ShapedType getBaseType() { return getBase().getType(); } + VectorType getIndexVectorType() { return getIndexVec().getType(); } + VectorType getMaskVectorType() { return getMask().getType(); } + VectorType getPassThruVectorType() { return getPassThru().getType(); } + VectorType getVectorType() { return getResult().getType(); } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::GatherOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InsertElementOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InsertElementOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + InsertElementOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.insertelement", odsAttrs.getContext()); + } + + InsertElementOpGenericAdaptorBase(InsertElementOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class InsertElementOpGenericAdaptor : public detail::InsertElementOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InsertElementOpGenericAdaptorBase; +public: + InsertElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InsertElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InsertElementOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + InsertElementOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : InsertElementOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + InsertElementOpGenericAdaptor(RangeT values, const InsertElementOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + InsertElementOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + ValueT getDest() { + return (*getODSOperands(1).begin()); + } + + ValueT getPosition() { + auto operands = getODSOperands(2); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InsertElementOpAdaptor : public InsertElementOpGenericAdaptor<::mlir::ValueRange> { +public: + using InsertElementOpGenericAdaptor::InsertElementOpGenericAdaptor; + InsertElementOpAdaptor(InsertElementOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class InsertElementOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = InsertElementOpAdaptor; + template + using GenericAdaptor = InsertElementOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.insertelement"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getPosition() { + auto operands = getODSOperands(2); + return operands.empty() ? ::mlir::TypedValue<::mlir::Type>{} : ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*operands.begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getDestMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getPositionMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, Value dest); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value source, ::mlir::Value dest, /*optional*/::mlir::Value position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source, ::mlir::Value dest, /*optional*/::mlir::Value position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source, ::mlir::Value dest, /*optional*/::mlir::Value position); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + Type getSourceType() { return getSource().getType(); } + VectorType getDestVectorType() { + return ::llvm::cast(getDest().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::InsertElementOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InsertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InsertOpGenericAdaptorBase { +public: + struct Properties { + using static_positionTy = ::mlir::DenseI64ArrayAttr; + static_positionTy static_position; + + auto getStaticPosition() const { + auto &propStorage = this->static_position; + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(propStorage); + } + void setStaticPosition(const ::mlir::DenseI64ArrayAttr &propValue) { + this->static_position = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.static_position == this->static_position && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + InsertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.insert", odsAttrs.getContext()); + } + + InsertOpGenericAdaptorBase(InsertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::DenseI64ArrayAttr getStaticPositionAttr() { + auto attr = ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().static_position); + return attr; + } + + ::llvm::ArrayRef getStaticPosition(); +}; +} // namespace detail +template +class InsertOpGenericAdaptor : public detail::InsertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InsertOpGenericAdaptorBase; +public: + InsertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InsertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InsertOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + InsertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : InsertOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + InsertOpGenericAdaptor(RangeT values, const InsertOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + InsertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getValueToStore() { + return (*getODSOperands(0).begin()); + } + + ValueT getDest() { + return (*getODSOperands(1).begin()); + } + + RangeT getDynamicPosition() { + return getODSOperands(2); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InsertOpAdaptor : public InsertOpGenericAdaptor<::mlir::ValueRange> { +public: + using InsertOpGenericAdaptor::InsertOpGenericAdaptor; + InsertOpAdaptor(InsertOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class InsertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = InsertOpAdaptor; + template + using GenericAdaptor = InsertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("static_position")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getStaticPositionAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getStaticPositionAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.insert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::Operation::operand_range getDynamicPosition() { + return getODSOperands(2); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getDestMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getDynamicPositionMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::DenseI64ArrayAttr getStaticPositionAttr() { + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().static_position); + } + + ::llvm::ArrayRef getStaticPosition(); + void setStaticPositionAttr(::mlir::DenseI64ArrayAttr attr) { + getProperties().static_position = attr; + } + + void setStaticPosition(::llvm::ArrayRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value valueToStore, Value dest); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value valueToStore, Value dest, int64_t position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value valueToStore, Value dest, OpFoldResult position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value valueToStore, Value dest, ArrayRef position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value valueToStore, Value dest, ArrayRef position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::mlir::DenseI64ArrayAttr static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ValueRange dynamic_position, ::llvm::ArrayRef static_position); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + // Integer to represent a poison index within a static and positive integer + // range. + static constexpr int64_t kPoisonIndex = -1; + + Type getValueToStoreType() { return getValueToStore().getType(); } + VectorType getDestVectorType() { + return ::llvm::cast(getDest().getType()); + } + + /// Return a vector with all the static and dynamic position indices. + SmallVector getMixedPosition() { + OpBuilder builder(getContext()); + return getMixedValues(getStaticPosition(), getDynamicPosition(), builder); + } + + unsigned getNumIndices() { + return getStaticPosition().size(); + } + + bool hasDynamicPosition() { + return llvm::any_of(getDynamicPosition(), + [](Value operand) { return operand != nullptr; }); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::InsertOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InsertStridedSliceOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InsertStridedSliceOpGenericAdaptorBase { +public: + struct Properties { + using offsetsTy = ::mlir::ArrayAttr; + offsetsTy offsets; + + auto getOffsets() const { + auto &propStorage = this->offsets; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setOffsets(const ::mlir::ArrayAttr &propValue) { + this->offsets = propValue; + } + using stridesTy = ::mlir::ArrayAttr; + stridesTy strides; + + auto getStrides() const { + auto &propStorage = this->strides; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setStrides(const ::mlir::ArrayAttr &propValue) { + this->strides = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.offsets == this->offsets && + rhs.strides == this->strides && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + InsertStridedSliceOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.insert_strided_slice", odsAttrs.getContext()); + } + + InsertStridedSliceOpGenericAdaptorBase(InsertStridedSliceOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::ArrayAttr getOffsetsAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().offsets); + return attr; + } + + ::mlir::ArrayAttr getOffsets(); + ::mlir::ArrayAttr getStridesAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().strides); + return attr; + } + + ::mlir::ArrayAttr getStrides(); +}; +} // namespace detail +template +class InsertStridedSliceOpGenericAdaptor : public detail::InsertStridedSliceOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InsertStridedSliceOpGenericAdaptorBase; +public: + InsertStridedSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InsertStridedSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InsertStridedSliceOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + InsertStridedSliceOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : InsertStridedSliceOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + InsertStridedSliceOpGenericAdaptor(RangeT values, const InsertStridedSliceOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + InsertStridedSliceOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getValueToStore() { + return (*getODSOperands(0).begin()); + } + + ValueT getDest() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InsertStridedSliceOpAdaptor : public InsertStridedSliceOpGenericAdaptor<::mlir::ValueRange> { +public: + using InsertStridedSliceOpGenericAdaptor::InsertStridedSliceOpGenericAdaptor; + InsertStridedSliceOpAdaptor(InsertStridedSliceOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class InsertStridedSliceOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = InsertStridedSliceOpAdaptor; + template + using GenericAdaptor = InsertStridedSliceOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("offsets"), ::llvm::StringRef("strides")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getOffsetsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getOffsetsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getStridesAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getStridesAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.insert_strided_slice"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getDestMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getRes() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::ArrayAttr getOffsetsAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().offsets); + } + + ::mlir::ArrayAttr getOffsets(); + ::mlir::ArrayAttr getStridesAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().strides); + } + + ::mlir::ArrayAttr getStrides(); + void setOffsetsAttr(::mlir::ArrayAttr attr) { + getProperties().offsets = attr; + } + + void setStridesAttr(::mlir::ArrayAttr attr) { + getProperties().strides = attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value valueToStore, Value dest, ArrayRef offsets, ArrayRef strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr strides); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::ArrayAttr offsets, ::mlir::ArrayAttr strides); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + // TODO: Rename + VectorType getSourceVectorType() { + return ::llvm::cast(getValueToStore().getType()); + } + VectorType getDestVectorType() { + return ::llvm::cast(getDest().getType()); + } + bool hasNonUnitStrides() { + return llvm::any_of(getStrides(), [](Attribute attr) { + return ::llvm::cast(attr).getInt() != 1; + }); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::InsertStridedSliceOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::InterleaveOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class InterleaveOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + InterleaveOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.interleave", odsAttrs.getContext()); + } + + InterleaveOpGenericAdaptorBase(InterleaveOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class InterleaveOpGenericAdaptor : public detail::InterleaveOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::InterleaveOpGenericAdaptorBase; +public: + InterleaveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + InterleaveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : InterleaveOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + InterleaveOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : InterleaveOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + InterleaveOpGenericAdaptor(RangeT values, const InterleaveOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + InterleaveOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class InterleaveOpAdaptor : public InterleaveOpGenericAdaptor<::mlir::ValueRange> { +public: + using InterleaveOpGenericAdaptor::InterleaveOpGenericAdaptor; + InterleaveOpAdaptor(InterleaveOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class InterleaveOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = InterleaveOpAdaptor; + template + using GenericAdaptor = InterleaveOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.interleave"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getLhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getRhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getLhsMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getRhsMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getLhs().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::InterleaveOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::LoadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class LoadOpGenericAdaptorBase { +public: + struct Properties { + using nontemporalTy = ::mlir::BoolAttr; + nontemporalTy nontemporal; + + auto getNontemporal() const { + auto &propStorage = this->nontemporal; + return ::llvm::dyn_cast_or_null<::mlir::BoolAttr>(propStorage); + } + void setNontemporal(const ::mlir::BoolAttr &propValue) { + this->nontemporal = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.nontemporal == this->nontemporal && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + LoadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.load", odsAttrs.getContext()); + } + + LoadOpGenericAdaptorBase(LoadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::BoolAttr getNontemporalAttr(); + bool getNontemporal(); +}; +} // namespace detail +template +class LoadOpGenericAdaptor : public detail::LoadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::LoadOpGenericAdaptorBase; +public: + LoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + LoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : LoadOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + LoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : LoadOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + LoadOpGenericAdaptor(RangeT values, const LoadOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + LoadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class LoadOpAdaptor : public LoadOpGenericAdaptor<::mlir::ValueRange> { +public: + using LoadOpGenericAdaptor::LoadOpGenericAdaptor; + LoadOpAdaptor(LoadOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class LoadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = LoadOpAdaptor; + template + using GenericAdaptor = LoadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("nontemporal")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getNontemporalAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getNontemporalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.load"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::BoolAttr getNontemporalAttr() { + return ::llvm::dyn_cast_or_null<::mlir::BoolAttr>(getProperties().nontemporal); + } + + bool getNontemporal(); + void setNontemporalAttr(::mlir::BoolAttr attr) { + getProperties().nontemporal = attr; + } + + void setNontemporal(::std::optional attrValue); + ::mlir::Attribute removeNontemporalAttr() { + auto attr = getProperties().nontemporal; + getProperties().nontemporal = {}; + return attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + MemRefType getMemRefType() { + return ::llvm::cast(getBase().getType()); + } + + VectorType getVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::LoadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MaskOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MaskOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + MaskOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.mask", odsAttrs.getContext()); + } + + MaskOpGenericAdaptorBase(MaskOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::Region &getMaskRegion() { + return *odsRegions[0]; + } + + ::mlir::RegionRange getRegions() { + return odsRegions; + } + +}; +} // namespace detail +template +class MaskOpGenericAdaptor : public detail::MaskOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MaskOpGenericAdaptorBase; +public: + MaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MaskOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + MaskOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : MaskOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + MaskOpGenericAdaptor(RangeT values, const MaskOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + MaskOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMask() { + return (*getODSOperands(0).begin()); + } + + ValueT getPassthru() { + auto operands = getODSOperands(1); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MaskOpAdaptor : public MaskOpGenericAdaptor<::mlir::ValueRange> { +public: + using MaskOpGenericAdaptor::MaskOpGenericAdaptor; + MaskOpAdaptor(MaskOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class MaskOp : public ::mlir::Op::Impl, ::mlir::OpTrait::SingleBlock, ::mlir::OpTrait::SingleBlockImplicitTerminator::Impl, ::mlir::OpTrait::NoRegionArguments, ::mlir::OpTrait::OpInvariants, ::mlir::vector::MaskingOpInterface::Trait, ::mlir::OpTrait::HasRecursiveMemoryEffects> { +public: + using Op::Op; + using Op::print; + using Adaptor = MaskOpAdaptor; + template + using GenericAdaptor = MaskOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.mask"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getPassthru() { + auto operands = getODSOperands(1); + return operands.empty() ? ::mlir::TypedValue<::mlir::Type>{} : ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*operands.begin()); + } + + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getPassthruMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::Operation::result_range getResults() { + return getODSResults(0); + } + + ::mlir::Region &getMaskRegion() { + return (*this)->getRegion(0); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value mask, Operation *maskableOp, function_ref maskRegion); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, TypeRange resultTypes, Value mask, Operation *maskableOp, function_ref maskRegion); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, TypeRange resultTypes, Value mask, Value passthru, Operation *maskableOp, function_ref maskRegion); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::llvm::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + Operation *getMaskableOp(); + bool hasPassthru(); +public: + Block *getMaskBlock() { return &getMaskRegion().front(); } + + /// Returns true if mask op is not masking any operation. + bool isEmpty() { + Block *block = getMaskBlock(); + if (block->getOperations().size() > 1) + return false; + return true; + } + + static void ensureTerminator(Region ®ion, Builder &builder, + Location loc); +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::MaskOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MaskedLoadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MaskedLoadOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + MaskedLoadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.maskedload", odsAttrs.getContext()); + } + + MaskedLoadOpGenericAdaptorBase(MaskedLoadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class MaskedLoadOpGenericAdaptor : public detail::MaskedLoadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MaskedLoadOpGenericAdaptorBase; +public: + MaskedLoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MaskedLoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MaskedLoadOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + MaskedLoadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : MaskedLoadOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + MaskedLoadOpGenericAdaptor(RangeT values, const MaskedLoadOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + MaskedLoadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getMask() { + return (*getODSOperands(2).begin()); + } + + ValueT getPassThru() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MaskedLoadOpAdaptor : public MaskedLoadOpGenericAdaptor<::mlir::ValueRange> { +public: + using MaskedLoadOpGenericAdaptor::MaskedLoadOpGenericAdaptor; + MaskedLoadOpAdaptor(MaskedLoadOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class MaskedLoadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<3>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = MaskedLoadOpAdaptor; + template + using GenericAdaptor = MaskedLoadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.maskedload"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getPassThru() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(3).begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getPassThruMutable() { + auto range = getODSOperandIndexAndLength(3); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value pass_thru); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + MemRefType getMemRefType() { + return ::llvm::cast(getBase().getType()); + } + VectorType getMaskVectorType() { + return ::llvm::cast(getMask().getType()); + } + VectorType getPassThruVectorType() { + return ::llvm::cast(getPassThru().getType()); + } + VectorType getVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::MaskedLoadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MaskedStoreOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MaskedStoreOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + MaskedStoreOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.maskedstore", odsAttrs.getContext()); + } + + MaskedStoreOpGenericAdaptorBase(MaskedStoreOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class MaskedStoreOpGenericAdaptor : public detail::MaskedStoreOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MaskedStoreOpGenericAdaptorBase; +public: + MaskedStoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MaskedStoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MaskedStoreOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + MaskedStoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : MaskedStoreOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + MaskedStoreOpGenericAdaptor(RangeT values, const MaskedStoreOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + MaskedStoreOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getMask() { + return (*getODSOperands(2).begin()); + } + + ValueT getValueToStore() { + return (*getODSOperands(3).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MaskedStoreOpAdaptor : public MaskedStoreOpGenericAdaptor<::mlir::ValueRange> { +public: + using MaskedStoreOpGenericAdaptor::MaskedStoreOpGenericAdaptor; + MaskedStoreOpAdaptor(MaskedStoreOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class MaskedStoreOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = MaskedStoreOpAdaptor; + template + using GenericAdaptor = MaskedStoreOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.maskedstore"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(3).begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(3); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value mask, ::mlir::Value valueToStore); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::llvm::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + MemRefType getMemRefType() { + return ::llvm::cast(getBase().getType()); + } + VectorType getMaskVectorType() { + return ::llvm::cast(getMask().getType()); + } + VectorType getVectorType() { + return ::llvm::cast(getValueToStore().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::MaskedStoreOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MatmulOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MatmulOpGenericAdaptorBase { +public: + struct Properties { + using lhs_columnsTy = ::mlir::IntegerAttr; + lhs_columnsTy lhs_columns; + + auto getLhsColumns() const { + auto &propStorage = this->lhs_columns; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setLhsColumns(const ::mlir::IntegerAttr &propValue) { + this->lhs_columns = propValue; + } + using lhs_rowsTy = ::mlir::IntegerAttr; + lhs_rowsTy lhs_rows; + + auto getLhsRows() const { + auto &propStorage = this->lhs_rows; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setLhsRows(const ::mlir::IntegerAttr &propValue) { + this->lhs_rows = propValue; + } + using rhs_columnsTy = ::mlir::IntegerAttr; + rhs_columnsTy rhs_columns; + + auto getRhsColumns() const { + auto &propStorage = this->rhs_columns; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setRhsColumns(const ::mlir::IntegerAttr &propValue) { + this->rhs_columns = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.lhs_columns == this->lhs_columns && + rhs.lhs_rows == this->lhs_rows && + rhs.rhs_columns == this->rhs_columns && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + MatmulOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.matrix_multiply", odsAttrs.getContext()); + } + + MatmulOpGenericAdaptorBase(MatmulOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::IntegerAttr getLhsRowsAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().lhs_rows); + return attr; + } + + uint32_t getLhsRows(); + ::mlir::IntegerAttr getLhsColumnsAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().lhs_columns); + return attr; + } + + uint32_t getLhsColumns(); + ::mlir::IntegerAttr getRhsColumnsAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().rhs_columns); + return attr; + } + + uint32_t getRhsColumns(); +}; +} // namespace detail +template +class MatmulOpGenericAdaptor : public detail::MatmulOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MatmulOpGenericAdaptorBase; +public: + MatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MatmulOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + MatmulOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : MatmulOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + MatmulOpGenericAdaptor(RangeT values, const MatmulOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + MatmulOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MatmulOpAdaptor : public MatmulOpGenericAdaptor<::mlir::ValueRange> { +public: + using MatmulOpGenericAdaptor::MatmulOpGenericAdaptor; + MatmulOpAdaptor(MatmulOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class MatmulOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = MatmulOpAdaptor; + template + using GenericAdaptor = MatmulOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("lhs_columns"), ::llvm::StringRef("lhs_rows"), ::llvm::StringRef("rhs_columns")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getLhsColumnsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getLhsColumnsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getLhsRowsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getLhsRowsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getRhsColumnsAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getRhsColumnsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.matrix_multiply"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getLhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getRhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getLhsMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getRhsMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getRes() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::IntegerAttr getLhsRowsAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().lhs_rows); + } + + uint32_t getLhsRows(); + ::mlir::IntegerAttr getLhsColumnsAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().lhs_columns); + } + + uint32_t getLhsColumns(); + ::mlir::IntegerAttr getRhsColumnsAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().rhs_columns); + } + + uint32_t getRhsColumns(); + void setLhsRowsAttr(::mlir::IntegerAttr attr) { + getProperties().lhs_rows = attr; + } + + void setLhsRows(uint32_t attrValue); + void setLhsColumnsAttr(::mlir::IntegerAttr attr) { + getProperties().lhs_columns = attr; + } + + void setLhsColumns(uint32_t attrValue); + void setRhsColumnsAttr(::mlir::IntegerAttr attr) { + getProperties().rhs_columns = attr; + } + + void setRhsColumns(uint32_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, unsigned lhsRows, unsigned lhsColumns, unsigned rhsColumns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::IntegerAttr lhs_rows, ::mlir::IntegerAttr lhs_columns, ::mlir::IntegerAttr rhs_columns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, ::mlir::IntegerAttr lhs_rows, ::mlir::IntegerAttr lhs_columns, ::mlir::IntegerAttr rhs_columns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value lhs, ::mlir::Value rhs, uint32_t lhs_rows, uint32_t lhs_columns, uint32_t rhs_columns); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, uint32_t lhs_rows, uint32_t lhs_columns, uint32_t rhs_columns); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::MatmulOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::MultiDimReductionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class MultiDimReductionOpGenericAdaptorBase { +public: + struct Properties { + using kindTy = ::mlir::vector::CombiningKindAttr; + kindTy kind; + + auto getKind() const { + auto &propStorage = this->kind; + return ::llvm::cast<::mlir::vector::CombiningKindAttr>(propStorage); + } + void setKind(const ::mlir::vector::CombiningKindAttr &propValue) { + this->kind = propValue; + } + using reduction_dimsTy = ::mlir::DenseI64ArrayAttr; + reduction_dimsTy reduction_dims; + + auto getReductionDims() const { + auto &propStorage = this->reduction_dims; + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(propStorage); + } + void setReductionDims(const ::mlir::DenseI64ArrayAttr &propValue) { + this->reduction_dims = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.kind == this->kind && + rhs.reduction_dims == this->reduction_dims && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + MultiDimReductionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.multi_reduction", odsAttrs.getContext()); + } + + MultiDimReductionOpGenericAdaptorBase(MultiDimReductionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::vector::CombiningKindAttr getKindAttr() { + auto attr = ::llvm::cast<::mlir::vector::CombiningKindAttr>(getProperties().kind); + return attr; + } + + ::mlir::vector::CombiningKind getKind(); + ::mlir::DenseI64ArrayAttr getReductionDimsAttr() { + auto attr = ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().reduction_dims); + return attr; + } + + ::llvm::ArrayRef getReductionDims(); +}; +} // namespace detail +template +class MultiDimReductionOpGenericAdaptor : public detail::MultiDimReductionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::MultiDimReductionOpGenericAdaptorBase; +public: + MultiDimReductionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + MultiDimReductionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : MultiDimReductionOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + MultiDimReductionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : MultiDimReductionOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + MultiDimReductionOpGenericAdaptor(RangeT values, const MultiDimReductionOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + MultiDimReductionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + ValueT getAcc() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class MultiDimReductionOpAdaptor : public MultiDimReductionOpGenericAdaptor<::mlir::ValueRange> { +public: + using MultiDimReductionOpGenericAdaptor::MultiDimReductionOpGenericAdaptor; + MultiDimReductionOpAdaptor(MultiDimReductionOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class MultiDimReductionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::vector::MaskableOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = MultiDimReductionOpAdaptor; + template + using GenericAdaptor = MultiDimReductionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("kind"), ::llvm::StringRef("reduction_dims")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getKindAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getReductionDimsAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getReductionDimsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.multi_reduction"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getAcc() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getAccMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::vector::CombiningKindAttr getKindAttr() { + return ::llvm::cast<::mlir::vector::CombiningKindAttr>(getProperties().kind); + } + + ::mlir::vector::CombiningKind getKind(); + ::mlir::DenseI64ArrayAttr getReductionDimsAttr() { + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().reduction_dims); + } + + ::llvm::ArrayRef getReductionDims(); + void setKindAttr(::mlir::vector::CombiningKindAttr attr) { + getProperties().kind = attr; + } + + void setKind(::mlir::vector::CombiningKind attrValue); + void setReductionDimsAttr(::mlir::DenseI64ArrayAttr attr) { + getProperties().reduction_dims = attr; + } + + void setReductionDims(::llvm::ArrayRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, Value acc, ArrayRef reductionMask, CombiningKind kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value acc, ::mlir::DenseI64ArrayAttr reduction_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value acc, ::mlir::DenseI64ArrayAttr reduction_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value acc, ::mlir::DenseI64ArrayAttr reduction_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value acc, ::llvm::ArrayRef reduction_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value acc, ::llvm::ArrayRef reduction_dims); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value acc, ::llvm::ArrayRef reduction_dims); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + mlir::Type getExpectedMaskType(); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getSource().getType()); + } + Type getDestType() { + return getDest().getType(); + } + + bool isReducedDim(int64_t d) { + assert(d >= 0 && d < static_cast(getReductionMask().size()) && + "d overflows the number of dims"); + return getReductionMask()[d]; + } + + SmallVector getReductionMask() { + SmallVector res(getSourceVectorType().getRank(), false); + for (int64_t dim : getReductionDims()) + res[dim] = true; + return res; + } + static SmallVector getReductionMask( + ArrayRef reductionDims, unsigned sourceRank) { + SmallVector res(sourceRank, false); + for (auto idx : reductionDims) + res[idx] = true; + return res; + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::MultiDimReductionOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::OuterProductOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class OuterProductOpGenericAdaptorBase { +public: + struct Properties { + using kindTy = ::mlir::vector::CombiningKindAttr; + kindTy kind; + + auto getKind() const { + auto &propStorage = this->kind; + return ::llvm::dyn_cast_or_null<::mlir::vector::CombiningKindAttr>(propStorage); + } + void setKind(const ::mlir::vector::CombiningKindAttr &propValue) { + this->kind = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.kind == this->kind && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + OuterProductOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.outerproduct", odsAttrs.getContext()); + } + + OuterProductOpGenericAdaptorBase(OuterProductOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::vector::CombiningKindAttr getKindAttr(); + ::mlir::vector::CombiningKind getKind(); +}; +} // namespace detail +template +class OuterProductOpGenericAdaptor : public detail::OuterProductOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::OuterProductOpGenericAdaptorBase; +public: + OuterProductOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + OuterProductOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : OuterProductOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + OuterProductOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : OuterProductOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + OuterProductOpGenericAdaptor(RangeT values, const OuterProductOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + OuterProductOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getLhs() { + return (*getODSOperands(0).begin()); + } + + ValueT getRhs() { + return (*getODSOperands(1).begin()); + } + + ValueT getAcc() { + auto operands = getODSOperands(2); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class OuterProductOpAdaptor : public OuterProductOpGenericAdaptor<::mlir::ValueRange> { +public: + using OuterProductOpGenericAdaptor::OuterProductOpGenericAdaptor; + OuterProductOpAdaptor(OuterProductOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class OuterProductOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::vector::MaskableOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = OuterProductOpAdaptor; + template + using GenericAdaptor = OuterProductOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("kind")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getKindAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.outerproduct"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getLhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getRhs() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(1).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getAcc() { + auto operands = getODSOperands(2); + return operands.empty() ? ::mlir::TypedValue<::mlir::VectorType>{} : ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*operands.begin()); + } + + ::mlir::OpOperand &getLhsMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getRhsMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getAccMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::vector::CombiningKindAttr getKindAttr() { + return ::llvm::dyn_cast_or_null<::mlir::vector::CombiningKindAttr>(getProperties().kind); + } + + ::mlir::vector::CombiningKind getKind(); + void setKindAttr(::mlir::vector::CombiningKindAttr attr) { + getProperties().kind = attr; + } + + void setKind(::mlir::vector::CombiningKind attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value lhs, Value rhs, Value acc); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKindAttr kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKindAttr kind); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type resultType0, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKind kind = CombiningKind::ADD); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value lhs, ::mlir::Value rhs, /*optional*/::mlir::Value acc, ::mlir::vector::CombiningKind kind = CombiningKind::ADD); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void populateDefaultProperties(::mlir::OperationName opName, Properties &properties); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + mlir::Type getExpectedMaskType(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getOperandVectorTypeLHS() { + return ::llvm::cast(getLhs().getType()); + } + Type getOperandTypeRHS() { + return getRhs().getType(); + } + VectorType getOperandVectorTypeACC() { + return getAcc() + ? ::llvm::cast(getAcc().getType()) + : VectorType(); + } + VectorType getResultVectorType() { + return ::llvm::cast(getResult().getType()); + } + static CombiningKind getDefaultKind() { + return CombiningKind::ADD; + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::OuterProductOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::PrintOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class PrintOpGenericAdaptorBase { +public: + struct Properties { + using punctuationTy = ::mlir::vector::PrintPunctuationAttr; + punctuationTy punctuation; + + auto getPunctuation() const { + auto &propStorage = this->punctuation; + return ::llvm::dyn_cast_or_null<::mlir::vector::PrintPunctuationAttr>(propStorage); + } + void setPunctuation(const ::mlir::vector::PrintPunctuationAttr &propValue) { + this->punctuation = propValue; + } + using stringLiteralTy = ::mlir::StringAttr; + stringLiteralTy stringLiteral; + + auto getStringLiteral() const { + auto &propStorage = this->stringLiteral; + return ::llvm::dyn_cast_or_null<::mlir::StringAttr>(propStorage); + } + void setStringLiteral(const ::mlir::StringAttr &propValue) { + this->stringLiteral = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.punctuation == this->punctuation && + rhs.stringLiteral == this->stringLiteral && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + PrintOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.print", odsAttrs.getContext()); + } + + PrintOpGenericAdaptorBase(PrintOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::vector::PrintPunctuationAttr getPunctuationAttr(); + ::mlir::vector::PrintPunctuation getPunctuation(); + ::mlir::StringAttr getStringLiteralAttr() { + auto attr = ::llvm::dyn_cast_or_null<::mlir::StringAttr>(getProperties().stringLiteral); + return attr; + } + + ::std::optional<::mlir::StringAttr> getStringLiteral(); +}; +} // namespace detail +template +class PrintOpGenericAdaptor : public detail::PrintOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::PrintOpGenericAdaptorBase; +public: + PrintOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + PrintOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : PrintOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + PrintOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : PrintOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + PrintOpGenericAdaptor(RangeT values, const PrintOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + PrintOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + auto operands = getODSOperands(0); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class PrintOpAdaptor : public PrintOpGenericAdaptor<::mlir::ValueRange> { +public: + using PrintOpGenericAdaptor::PrintOpGenericAdaptor; + PrintOpAdaptor(PrintOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class PrintOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = PrintOpAdaptor; + template + using GenericAdaptor = PrintOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("punctuation"), ::llvm::StringRef("stringLiteral")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPunctuationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPunctuationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getStringLiteralAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getStringLiteralAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.print"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getSource() { + auto operands = getODSOperands(0); + return operands.empty() ? ::mlir::TypedValue<::mlir::Type>{} : ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*operands.begin()); + } + + ::mlir::MutableOperandRange getSourceMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::vector::PrintPunctuationAttr getPunctuationAttr() { + return ::llvm::dyn_cast_or_null<::mlir::vector::PrintPunctuationAttr>(getProperties().punctuation); + } + + ::mlir::vector::PrintPunctuation getPunctuation(); + ::mlir::StringAttr getStringLiteralAttr() { + return ::llvm::dyn_cast_or_null<::mlir::StringAttr>(getProperties().stringLiteral); + } + + ::std::optional<::mlir::StringAttr> getStringLiteral(); + void setPunctuationAttr(::mlir::vector::PrintPunctuationAttr attr) { + getProperties().punctuation = attr; + } + + void setPunctuation(::mlir::vector::PrintPunctuation attrValue); + void setStringLiteralAttr(::mlir::StringAttr attr) { + getProperties().stringLiteral = attr; + } + + ::mlir::Attribute removeStringLiteralAttr() { + auto attr = getProperties().stringLiteral; + getProperties().stringLiteral = {}; + return attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, PrintPunctuation punctuation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value source, PrintPunctuation punctuation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::llvm::StringRef string); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuationAttr punctuation, /*optional*/::mlir::StringAttr stringLiteral); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuationAttr punctuation, /*optional*/::mlir::StringAttr stringLiteral); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuation punctuation, /*optional*/::mlir::StringAttr stringLiteral); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, /*optional*/::mlir::Value source, ::mlir::vector::PrintPunctuation punctuation, /*optional*/::mlir::StringAttr stringLiteral); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void populateDefaultProperties(::mlir::OperationName opName, Properties &properties); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + Type getPrintType() { + return getSource().getType(); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::PrintOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ReductionOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ReductionOpGenericAdaptorBase { +public: + struct Properties { + using fastmathTy = ::mlir::arith::FastMathFlagsAttr; + fastmathTy fastmath; + + auto getFastmath() const { + auto &propStorage = this->fastmath; + return ::llvm::dyn_cast_or_null<::mlir::arith::FastMathFlagsAttr>(propStorage); + } + void setFastmath(const ::mlir::arith::FastMathFlagsAttr &propValue) { + this->fastmath = propValue; + } + using kindTy = ::mlir::vector::CombiningKindAttr; + kindTy kind; + + auto getKind() const { + auto &propStorage = this->kind; + return ::llvm::cast<::mlir::vector::CombiningKindAttr>(propStorage); + } + void setKind(const ::mlir::vector::CombiningKindAttr &propValue) { + this->kind = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.fastmath == this->fastmath && + rhs.kind == this->kind && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ReductionOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.reduction", odsAttrs.getContext()); + } + + ReductionOpGenericAdaptorBase(ReductionOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::vector::CombiningKindAttr getKindAttr() { + auto attr = ::llvm::cast<::mlir::vector::CombiningKindAttr>(getProperties().kind); + return attr; + } + + ::mlir::vector::CombiningKind getKind(); + ::mlir::arith::FastMathFlagsAttr getFastmathAttr(); + ::mlir::arith::FastMathFlags getFastmath(); +}; +} // namespace detail +template +class ReductionOpGenericAdaptor : public detail::ReductionOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ReductionOpGenericAdaptorBase; +public: + ReductionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ReductionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ReductionOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ReductionOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ReductionOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ReductionOpGenericAdaptor(RangeT values, const ReductionOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ReductionOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getVector() { + return (*getODSOperands(0).begin()); + } + + ValueT getAcc() { + auto operands = getODSOperands(1); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ReductionOpAdaptor : public ReductionOpGenericAdaptor<::mlir::ValueRange> { +public: + using ReductionOpGenericAdaptor::ReductionOpGenericAdaptor; + ReductionOpAdaptor(ReductionOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ReductionOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<1>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::arith::ArithFastMathInterface::Trait, ::mlir::vector::MaskableOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ReductionOpAdaptor; + template + using GenericAdaptor = ReductionOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("fastmath"), ::llvm::StringRef("kind")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getFastmathAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getFastmathAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getKindAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.reduction"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::Type> getAcc() { + auto operands = getODSOperands(1); + return operands.empty() ? ::mlir::TypedValue<::mlir::Type>{} : ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*operands.begin()); + } + + ::mlir::OpOperand &getVectorMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getAccMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::vector::CombiningKindAttr getKindAttr() { + return ::llvm::cast<::mlir::vector::CombiningKindAttr>(getProperties().kind); + } + + ::mlir::vector::CombiningKind getKind(); + ::mlir::arith::FastMathFlagsAttr getFastmathAttr() { + return ::llvm::dyn_cast_or_null<::mlir::arith::FastMathFlagsAttr>(getProperties().fastmath); + } + + ::mlir::arith::FastMathFlags getFastmath(); + void setKindAttr(::mlir::vector::CombiningKindAttr attr) { + getProperties().kind = attr; + } + + void setKind(::mlir::vector::CombiningKind attrValue); + void setFastmathAttr(::mlir::arith::FastMathFlagsAttr attr) { + getProperties().fastmath = attr; + } + + void setFastmath(::mlir::arith::FastMathFlags attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, CombiningKind kind, Value vector, Value acc, ::mlir::arith::FastMathFlags fastMathFlags = ::mlir::arith::FastMathFlags::none); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, CombiningKind kind, Value vector, ::mlir::arith::FastMathFlags fastMathFlags = ::mlir::arith::FastMathFlags::none); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlagsAttr fastmath = nullptr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlagsAttr fastmath = nullptr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::vector::CombiningKind kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlags fastmath = ::mlir::arith::FastMathFlags::none); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKind kind, ::mlir::Value vector, /*optional*/::mlir::Value acc, ::mlir::arith::FastMathFlags fastmath = ::mlir::arith::FastMathFlags::none); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void populateDefaultProperties(::mlir::OperationName opName, Properties &properties); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + mlir::Type getExpectedMaskType(); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getVector().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ReductionOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScalableExtractOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ScalableExtractOpGenericAdaptorBase { +public: + struct Properties { + using posTy = ::mlir::IntegerAttr; + posTy pos; + + auto getPos() const { + auto &propStorage = this->pos; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setPos(const ::mlir::IntegerAttr &propValue) { + this->pos = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.pos == this->pos && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ScalableExtractOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.scalable.extract", odsAttrs.getContext()); + } + + ScalableExtractOpGenericAdaptorBase(ScalableExtractOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::IntegerAttr getPosAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().pos); + return attr; + } + + uint64_t getPos(); +}; +} // namespace detail +template +class ScalableExtractOpGenericAdaptor : public detail::ScalableExtractOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ScalableExtractOpGenericAdaptorBase; +public: + ScalableExtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ScalableExtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ScalableExtractOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ScalableExtractOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ScalableExtractOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ScalableExtractOpGenericAdaptor(RangeT values, const ScalableExtractOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ScalableExtractOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ScalableExtractOpAdaptor : public ScalableExtractOpGenericAdaptor<::mlir::ValueRange> { +public: + using ScalableExtractOpGenericAdaptor::ScalableExtractOpGenericAdaptor; + ScalableExtractOpAdaptor(ScalableExtractOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ScalableExtractOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ScalableExtractOpAdaptor; + template + using GenericAdaptor = ScalableExtractOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("pos")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPosAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPosAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.scalable.extract"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getRes() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::IntegerAttr getPosAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().pos); + } + + uint64_t getPos(); + void setPosAttr(::mlir::IntegerAttr attr) { + getProperties().pos = attr; + } + + void setPos(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value source, ::mlir::IntegerAttr pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source, ::mlir::IntegerAttr pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value source, uint64_t pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source, uint64_t pos); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + // Integer to represent a poison index within a static and positive integer + // range. + static constexpr int64_t kPoisonIndex = -1; + + VectorType getSourceVectorType() { + return ::llvm::cast(getSource().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getRes().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ScalableExtractOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScalableInsertOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ScalableInsertOpGenericAdaptorBase { +public: + struct Properties { + using posTy = ::mlir::IntegerAttr; + posTy pos; + + auto getPos() const { + auto &propStorage = this->pos; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setPos(const ::mlir::IntegerAttr &propValue) { + this->pos = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.pos == this->pos && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ScalableInsertOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.scalable.insert", odsAttrs.getContext()); + } + + ScalableInsertOpGenericAdaptorBase(ScalableInsertOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::IntegerAttr getPosAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().pos); + return attr; + } + + uint64_t getPos(); +}; +} // namespace detail +template +class ScalableInsertOpGenericAdaptor : public detail::ScalableInsertOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ScalableInsertOpGenericAdaptorBase; +public: + ScalableInsertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ScalableInsertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ScalableInsertOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ScalableInsertOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ScalableInsertOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ScalableInsertOpGenericAdaptor(RangeT values, const ScalableInsertOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ScalableInsertOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getValueToStore() { + return (*getODSOperands(0).begin()); + } + + ValueT getDest() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ScalableInsertOpAdaptor : public ScalableInsertOpGenericAdaptor<::mlir::ValueRange> { +public: + using ScalableInsertOpGenericAdaptor::ScalableInsertOpGenericAdaptor; + ScalableInsertOpAdaptor(ScalableInsertOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ScalableInsertOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ScalableInsertOpAdaptor; + template + using GenericAdaptor = ScalableInsertOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("pos")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPosAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPosAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.scalable.insert"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getDestMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getRes() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::IntegerAttr getPosAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().pos); + } + + uint64_t getPos(); + void setPosAttr(::mlir::IntegerAttr attr) { + getProperties().pos = attr; + } + + void setPos(uint64_t attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::IntegerAttr pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::IntegerAttr pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, ::mlir::IntegerAttr pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type res, ::mlir::Value valueToStore, ::mlir::Value dest, uint64_t pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value dest, uint64_t pos); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value dest, uint64_t pos); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + // Integer to represent a poison index within a static and positive integer + // range. + static constexpr int64_t kPoisonIndex = -1; + + VectorType getSourceVectorType() { + return ::llvm::cast(getValueToStore().getType()); + } + VectorType getDestVectorType() { + return ::llvm::cast(getDest().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ScalableInsertOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScanOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ScanOpGenericAdaptorBase { +public: + struct Properties { + using inclusiveTy = ::mlir::BoolAttr; + inclusiveTy inclusive; + + auto getInclusive() const { + auto &propStorage = this->inclusive; + return ::llvm::cast<::mlir::BoolAttr>(propStorage); + } + void setInclusive(const ::mlir::BoolAttr &propValue) { + this->inclusive = propValue; + } + using kindTy = ::mlir::vector::CombiningKindAttr; + kindTy kind; + + auto getKind() const { + auto &propStorage = this->kind; + return ::llvm::cast<::mlir::vector::CombiningKindAttr>(propStorage); + } + void setKind(const ::mlir::vector::CombiningKindAttr &propValue) { + this->kind = propValue; + } + using reduction_dimTy = ::mlir::IntegerAttr; + reduction_dimTy reduction_dim; + + auto getReductionDim() const { + auto &propStorage = this->reduction_dim; + return ::llvm::cast<::mlir::IntegerAttr>(propStorage); + } + void setReductionDim(const ::mlir::IntegerAttr &propValue) { + this->reduction_dim = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.inclusive == this->inclusive && + rhs.kind == this->kind && + rhs.reduction_dim == this->reduction_dim && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ScanOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.scan", odsAttrs.getContext()); + } + + ScanOpGenericAdaptorBase(ScanOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::vector::CombiningKindAttr getKindAttr() { + auto attr = ::llvm::cast<::mlir::vector::CombiningKindAttr>(getProperties().kind); + return attr; + } + + ::mlir::vector::CombiningKind getKind(); + ::mlir::IntegerAttr getReductionDimAttr() { + auto attr = ::llvm::cast<::mlir::IntegerAttr>(getProperties().reduction_dim); + return attr; + } + + uint64_t getReductionDim(); + ::mlir::BoolAttr getInclusiveAttr() { + auto attr = ::llvm::cast<::mlir::BoolAttr>(getProperties().inclusive); + return attr; + } + + bool getInclusive(); +}; +} // namespace detail +template +class ScanOpGenericAdaptor : public detail::ScanOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ScanOpGenericAdaptorBase; +public: + ScanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ScanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ScanOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ScanOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ScanOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ScanOpGenericAdaptor(RangeT values, const ScanOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ScanOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + ValueT getInitialValue() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ScanOpAdaptor : public ScanOpGenericAdaptor<::mlir::ValueRange> { +public: + using ScanOpGenericAdaptor::ScanOpGenericAdaptor; + ScanOpAdaptor(ScanOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ScanOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpAsmOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ScanOpAdaptor; + template + using GenericAdaptor = ScanOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("inclusive"), ::llvm::StringRef("kind"), ::llvm::StringRef("reduction_dim")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getInclusiveAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getInclusiveAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getKindAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getKindAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getReductionDimAttrName() { + return getAttributeNameForIndex(2); + } + + static ::mlir::StringAttr getReductionDimAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 2); + } + + void getAsmResultNames(::mlir::OpAsmSetValueNameFn setNameFn); + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.scan"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getInitialValue() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getInitialValueMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getDest() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getAccumulatedValue() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(1).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::vector::CombiningKindAttr getKindAttr() { + return ::llvm::cast<::mlir::vector::CombiningKindAttr>(getProperties().kind); + } + + ::mlir::vector::CombiningKind getKind(); + ::mlir::IntegerAttr getReductionDimAttr() { + return ::llvm::cast<::mlir::IntegerAttr>(getProperties().reduction_dim); + } + + uint64_t getReductionDim(); + ::mlir::BoolAttr getInclusiveAttr() { + return ::llvm::cast<::mlir::BoolAttr>(getProperties().inclusive); + } + + bool getInclusive(); + void setKindAttr(::mlir::vector::CombiningKindAttr attr) { + getProperties().kind = attr; + } + + void setKind(::mlir::vector::CombiningKind attrValue); + void setReductionDimAttr(::mlir::IntegerAttr attr) { + getProperties().reduction_dim = attr; + } + + void setReductionDim(uint64_t attrValue); + void setInclusiveAttr(::mlir::BoolAttr attr) { + getProperties().inclusive = attr; + } + + void setInclusive(bool attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source, Value initial_value, CombiningKind kind, int64_t reduction_dim = 0, bool inclusive = true); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::Type accumulated_value, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value initial_value, ::mlir::IntegerAttr reduction_dim, ::mlir::BoolAttr inclusive); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value initial_value, ::mlir::IntegerAttr reduction_dim, ::mlir::BoolAttr inclusive); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKindAttr kind, ::mlir::Value source, ::mlir::Value initial_value, ::mlir::IntegerAttr reduction_dim, ::mlir::BoolAttr inclusive); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type dest, ::mlir::Type accumulated_value, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value initial_value, uint64_t reduction_dim, bool inclusive); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value initial_value, uint64_t reduction_dim, bool inclusive); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::vector::CombiningKind kind, ::mlir::Value source, ::mlir::Value initial_value, uint64_t reduction_dim, bool inclusive); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 3 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getSourceType() { + return ::llvm::cast(getSource().getType()); + } + VectorType getDestType() { + return ::llvm::cast(getDest().getType()); + } + VectorType getAccumulatorType() { + return ::llvm::cast(getAccumulatedValue().getType()); + } + VectorType getInitialValueType() { + return ::llvm::cast(getInitialValue().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ScanOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ScatterOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ScatterOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ScatterOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.scatter", odsAttrs.getContext()); + } + + ScatterOpGenericAdaptorBase(ScatterOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class ScatterOpGenericAdaptor : public detail::ScatterOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ScatterOpGenericAdaptorBase; +public: + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ScatterOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ScatterOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ScatterOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ScatterOpGenericAdaptor(RangeT values, const ScatterOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ScatterOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getIndexVec() { + return (*getODSOperands(2).begin()); + } + + ValueT getMask() { + return (*getODSOperands(3).begin()); + } + + ValueT getValueToStore() { + return (*getODSOperands(4).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ScatterOpAdaptor : public ScatterOpGenericAdaptor<::mlir::ValueRange> { +public: + using ScatterOpGenericAdaptor::ScatterOpGenericAdaptor; + ScatterOpAdaptor(ScatterOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ScatterOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ScatterOpAdaptor; + template + using GenericAdaptor = ScatterOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.scatter"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::VectorType> getIndexVec() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(3).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(4).begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getIndexVecMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getMaskMutable() { + auto range = getODSOperandIndexAndLength(3); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(4); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value valueToStore); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::Value index_vec, ::mlir::Value mask, ::mlir::Value valueToStore); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + MemRefType getMemRefType() { return getBase().getType(); } + VectorType getIndexVectorType() { return getIndexVec().getType(); } + VectorType getMaskVectorType() { return getMask().getType(); } + VectorType getVectorType() { return getValueToStore().getType(); } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ScatterOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ShapeCastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShapeCastOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ShapeCastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.shape_cast", odsAttrs.getContext()); + } + + ShapeCastOpGenericAdaptorBase(ShapeCastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class ShapeCastOpGenericAdaptor : public detail::ShapeCastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShapeCastOpGenericAdaptorBase; +public: + ShapeCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShapeCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShapeCastOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ShapeCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ShapeCastOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ShapeCastOpGenericAdaptor(RangeT values, const ShapeCastOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ShapeCastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getSource() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShapeCastOpAdaptor : public ShapeCastOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShapeCastOpGenericAdaptor::ShapeCastOpGenericAdaptor; + ShapeCastOpAdaptor(ShapeCastOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ShapeCastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShapeCastOpAdaptor; + template + using GenericAdaptor = ShapeCastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.shape_cast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getSource() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getSourceMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value source); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getSource().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ShapeCastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::ShuffleOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class ShuffleOpGenericAdaptorBase { +public: + struct Properties { + using maskTy = ::mlir::DenseI64ArrayAttr; + maskTy mask; + + auto getMask() const { + auto &propStorage = this->mask; + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(propStorage); + } + void setMask(const ::mlir::DenseI64ArrayAttr &propValue) { + this->mask = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.mask == this->mask && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + ShuffleOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.shuffle", odsAttrs.getContext()); + } + + ShuffleOpGenericAdaptorBase(ShuffleOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::DenseI64ArrayAttr getMaskAttr() { + auto attr = ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().mask); + return attr; + } + + ::llvm::ArrayRef getMask(); +}; +} // namespace detail +template +class ShuffleOpGenericAdaptor : public detail::ShuffleOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::ShuffleOpGenericAdaptorBase; +public: + ShuffleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + ShuffleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : ShuffleOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + ShuffleOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : ShuffleOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + ShuffleOpGenericAdaptor(RangeT values, const ShuffleOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + ShuffleOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getV1() { + return (*getODSOperands(0).begin()); + } + + ValueT getV2() { + return (*getODSOperands(1).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class ShuffleOpAdaptor : public ShuffleOpGenericAdaptor<::mlir::ValueRange> { +public: + using ShuffleOpGenericAdaptor::ShuffleOpGenericAdaptor; + ShuffleOpAdaptor(ShuffleOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class ShuffleOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::NOperands<2>::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferTypeOpInterface::Trait, ::mlir::OpTrait::InferTypeOpAdaptor> { +public: + using Op::Op; + using Op::print; + using Adaptor = ShuffleOpAdaptor; + template + using GenericAdaptor = ShuffleOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("mask")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getMaskAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getMaskAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.shuffle"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getV1() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getV2() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(1).begin()); + } + + ::mlir::OpOperand &getV1Mutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getV2Mutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::DenseI64ArrayAttr getMaskAttr() { + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().mask); + } + + ::llvm::ArrayRef getMask(); + void setMaskAttr(::mlir::DenseI64ArrayAttr attr) { + getProperties().mask = attr; + } + + void setMask(::llvm::ArrayRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value v1, ::mlir::Value v2, ::mlir::DenseI64ArrayAttr mask); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value v1, ::mlir::Value v2, ::mlir::DenseI64ArrayAttr mask); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value v1, ::mlir::Value v2, ::mlir::DenseI64ArrayAttr mask); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value v1, ::mlir::Value v2, ::llvm::ArrayRef mask); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value v1, ::mlir::Value v2, ::llvm::ArrayRef mask); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value v1, ::mlir::Value v2, ::llvm::ArrayRef mask); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + static ::llvm::LogicalResult inferReturnTypes(::mlir::MLIRContext *context, ::std::optional<::mlir::Location> location, ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions, ::llvm::SmallVectorImpl<::mlir::Type>&inferredReturnTypes); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + static ::llvm::LogicalResult + inferReturnTypes(::mlir::MLIRContext *context, + std::optional<::mlir::Location> location, + Adaptor adaptor, + ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes); + + + // Integer to represent a poison index within a static and positive integer + // range. + static constexpr int64_t kPoisonIndex = -1; + + VectorType getV1VectorType() { + return ::llvm::cast(getV1().getType()); + } + VectorType getV2VectorType() { + return ::llvm::cast(getV2().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getVector().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::ShuffleOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::SplatOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class SplatOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + SplatOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.splat", odsAttrs.getContext()); + } + + SplatOpGenericAdaptorBase(SplatOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class SplatOpGenericAdaptor : public detail::SplatOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::SplatOpGenericAdaptorBase; +public: + SplatOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + SplatOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : SplatOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + SplatOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : SplatOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + SplatOpGenericAdaptor(RangeT values, const SplatOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + SplatOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getInput() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class SplatOpAdaptor : public SplatOpGenericAdaptor<::mlir::ValueRange> { +public: + using SplatOpGenericAdaptor::SplatOpGenericAdaptor; + SplatOpAdaptor(SplatOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class SplatOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::InferIntRangeInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = SplatOpAdaptor; + template + using GenericAdaptor = SplatOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.splat"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::Type> getInput() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getInputMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getAggregate() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value element, Type aggregateType); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type aggregate, ::mlir::Value input); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value input); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + void inferResultRanges(::llvm::ArrayRef<::mlir::ConstantIntRanges> argRanges, ::mlir::SetIntRangeFn setResultRanges); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::SplatOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::StepOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class StepOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + StepOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.step", odsAttrs.getContext()); + } + + StepOpGenericAdaptorBase(StepOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class StepOpGenericAdaptor : public detail::StepOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::StepOpGenericAdaptorBase; +public: + StepOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + StepOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : StepOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + StepOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : StepOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + StepOpGenericAdaptor(RangeT values, const StepOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + StepOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class StepOpAdaptor : public StepOpGenericAdaptor<::mlir::ValueRange> { +public: + using StepOpGenericAdaptor::StepOpGenericAdaptor; + StepOpAdaptor(StepOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class StepOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::ZeroOperands, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = StepOpAdaptor; + template + using GenericAdaptor = StepOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.step"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::StepOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::StoreOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class StoreOpGenericAdaptorBase { +public: + struct Properties { + using nontemporalTy = ::mlir::BoolAttr; + nontemporalTy nontemporal; + + auto getNontemporal() const { + auto &propStorage = this->nontemporal; + return ::llvm::dyn_cast_or_null<::mlir::BoolAttr>(propStorage); + } + void setNontemporal(const ::mlir::BoolAttr &propValue) { + this->nontemporal = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.nontemporal == this->nontemporal && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + StoreOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.store", odsAttrs.getContext()); + } + + StoreOpGenericAdaptorBase(StoreOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::BoolAttr getNontemporalAttr(); + bool getNontemporal(); +}; +} // namespace detail +template +class StoreOpGenericAdaptor : public detail::StoreOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::StoreOpGenericAdaptorBase; +public: + StoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + StoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : StoreOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + StoreOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : StoreOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + StoreOpGenericAdaptor(RangeT values, const StoreOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + StoreOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getValueToStore() { + return (*getODSOperands(0).begin()); + } + + ValueT getBase() { + return (*getODSOperands(1).begin()); + } + + RangeT getIndices() { + return getODSOperands(2); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class StoreOpAdaptor : public StoreOpGenericAdaptor<::mlir::ValueRange> { +public: + using StoreOpGenericAdaptor::StoreOpGenericAdaptor; + StoreOpAdaptor(StoreOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class StoreOp : public ::mlir::Op::Impl, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::MemoryEffectOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = StoreOpAdaptor; + template + using GenericAdaptor = StoreOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("nontemporal")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getNontemporalAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getNontemporalAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.store"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::MemRefType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(1).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(2); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::BoolAttr getNontemporalAttr() { + return ::llvm::dyn_cast_or_null<::mlir::BoolAttr>(getProperties().nontemporal); + } + + bool getNontemporal(); + void setNontemporalAttr(::mlir::BoolAttr attr) { + getProperties().nontemporal = attr; + } + + void setNontemporal(::std::optional attrValue); + ::mlir::Attribute removeNontemporalAttr() { + auto attr = getProperties().nontemporal; + getProperties().nontemporal = {}; + return attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/::mlir::BoolAttr nontemporal); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal = false); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, /*optional*/bool nontemporal = false); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + ::llvm::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + MemRefType getMemRefType() { + return ::llvm::cast(getBase().getType()); + } + + VectorType getVectorType() { + return ::llvm::cast(getValueToStore().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::StoreOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TransferReadOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TransferReadOpGenericAdaptorBase { +public: + struct Properties { + using in_boundsTy = ::mlir::ArrayAttr; + in_boundsTy in_bounds; + + auto getInBounds() const { + auto &propStorage = this->in_bounds; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setInBounds(const ::mlir::ArrayAttr &propValue) { + this->in_bounds = propValue; + } + using permutation_mapTy = ::mlir::AffineMapAttr; + permutation_mapTy permutation_map; + + auto getPermutationMap() const { + auto &propStorage = this->permutation_map; + return ::llvm::cast<::mlir::AffineMapAttr>(propStorage); + } + void setPermutationMap(const ::mlir::AffineMapAttr &propValue) { + this->permutation_map = propValue; + } + using operandSegmentSizesTy = std::array; + operandSegmentSizesTy operandSegmentSizes; + ::llvm::ArrayRef getOperandSegmentSizes() const { + auto &propStorage = this->operandSegmentSizes; + return propStorage; + } + void setOperandSegmentSizes(::llvm::ArrayRef propValue) { + auto &propStorage = this->operandSegmentSizes; + ::llvm::copy(propValue, propStorage.begin()); + } + bool operator==(const Properties &rhs) const { + return + rhs.in_bounds == this->in_bounds && + rhs.permutation_map == this->permutation_map && + rhs.operandSegmentSizes == this->operandSegmentSizes && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + TransferReadOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.transfer_read", odsAttrs.getContext()); + } + + TransferReadOpGenericAdaptorBase(TransferReadOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::AffineMapAttr getPermutationMapAttr() { + auto attr = ::llvm::cast<::mlir::AffineMapAttr>(getProperties().permutation_map); + return attr; + } + + ::mlir::AffineMap getPermutationMap(); + ::mlir::ArrayAttr getInBoundsAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().in_bounds); + return attr; + } + + ::mlir::ArrayAttr getInBounds(); +}; +} // namespace detail +template +class TransferReadOpGenericAdaptor : public detail::TransferReadOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TransferReadOpGenericAdaptorBase; +public: + TransferReadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TransferReadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TransferReadOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + TransferReadOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs) : TransferReadOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + TransferReadOpGenericAdaptor(RangeT values, const TransferReadOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + TransferReadOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getBase() { + return (*getODSOperands(0).begin()); + } + + RangeT getIndices() { + return getODSOperands(1); + } + + ValueT getPadding() { + return (*getODSOperands(2).begin()); + } + + ValueT getMask() { + auto operands = getODSOperands(3); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TransferReadOpAdaptor : public TransferReadOpGenericAdaptor<::mlir::ValueRange> { +public: + using TransferReadOpGenericAdaptor::TransferReadOpGenericAdaptor; + TransferReadOpAdaptor(TransferReadOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class TransferReadOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::AtLeastNOperands<2>::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::VectorTransferOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait, ::mlir::vector::MaskableOpInterface::Trait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::DestinationStyleOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TransferReadOpAdaptor; + template + using GenericAdaptor = TransferReadOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("in_bounds"), ::llvm::StringRef("permutation_map"), ::llvm::StringRef("operandSegmentSizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getInBoundsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getInBoundsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPermutationMapAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPermutationMapAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return (*this)->getName().getAttributeNames().back(); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return name.getAttributeNames().back(); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.transfer_read"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::ShapedType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::ShapedType>>(*getODSOperands(0).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(1); + } + + ::mlir::TypedValue<::mlir::Type> getPadding() { + return ::llvm::cast<::mlir::TypedValue<::mlir::Type>>(*getODSOperands(2).begin()); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + auto operands = getODSOperands(3); + return operands.empty() ? ::mlir::TypedValue<::mlir::VectorType>{} : ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*operands.begin()); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::OpOperand &getPaddingMutable() { + auto range = getODSOperandIndexAndLength(2); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getMaskMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::AffineMapAttr getPermutationMapAttr() { + return ::llvm::cast<::mlir::AffineMapAttr>(getProperties().permutation_map); + } + + ::mlir::AffineMap getPermutationMap(); + ::mlir::ArrayAttr getInBoundsAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().in_bounds); + } + + ::mlir::ArrayAttr getInBounds(); + void setPermutationMapAttr(::mlir::AffineMapAttr attr) { + getProperties().permutation_map = attr; + } + + void setPermutationMap(::mlir::AffineMap attrValue); + void setInBoundsAttr(::mlir::ArrayAttr attr) { + getProperties().in_bounds = attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, VectorType vectorType, Value source, ValueRange indices, AffineMapAttr permutationMapAttr, ArrayAttr inBoundsAttr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, VectorType vectorType, Value source, ValueRange indices, AffineMap permutationMap, std::optional> inBounds = ::std::nullopt); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, VectorType vectorType, Value source, ValueRange indices, Value padding, std::optional> inBounds = ::std::nullopt); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, VectorType vectorType, Value source, ValueRange indices, std::optional> inBounds = ::std::nullopt); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type vector, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, ::mlir::Value padding, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + ::mlir::VectorType getVectorType(); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + mlir::Type getExpectedMaskType(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); + ::mlir::Speculation::Speculatability getSpeculatability(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + // MaskableOpInterface methods. + bool supportsPassthru() { return true; } + + MutableOperandRange getDpsInitsMutable() { + return MutableOperandRange(getOperation(), /*start=*/0, /*length=*/0); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::TransferReadOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TransferWriteOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TransferWriteOpGenericAdaptorBase { +public: + struct Properties { + using in_boundsTy = ::mlir::ArrayAttr; + in_boundsTy in_bounds; + + auto getInBounds() const { + auto &propStorage = this->in_bounds; + return ::llvm::cast<::mlir::ArrayAttr>(propStorage); + } + void setInBounds(const ::mlir::ArrayAttr &propValue) { + this->in_bounds = propValue; + } + using permutation_mapTy = ::mlir::AffineMapAttr; + permutation_mapTy permutation_map; + + auto getPermutationMap() const { + auto &propStorage = this->permutation_map; + return ::llvm::cast<::mlir::AffineMapAttr>(propStorage); + } + void setPermutationMap(const ::mlir::AffineMapAttr &propValue) { + this->permutation_map = propValue; + } + using operandSegmentSizesTy = std::array; + operandSegmentSizesTy operandSegmentSizes; + ::llvm::ArrayRef getOperandSegmentSizes() const { + auto &propStorage = this->operandSegmentSizes; + return propStorage; + } + void setOperandSegmentSizes(::llvm::ArrayRef propValue) { + auto &propStorage = this->operandSegmentSizes; + ::llvm::copy(propValue, propStorage.begin()); + } + bool operator==(const Properties &rhs) const { + return + rhs.in_bounds == this->in_bounds && + rhs.permutation_map == this->permutation_map && + rhs.operandSegmentSizes == this->operandSegmentSizes && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + TransferWriteOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.transfer_write", odsAttrs.getContext()); + } + + TransferWriteOpGenericAdaptorBase(TransferWriteOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::AffineMapAttr getPermutationMapAttr() { + auto attr = ::llvm::cast<::mlir::AffineMapAttr>(getProperties().permutation_map); + return attr; + } + + ::mlir::AffineMap getPermutationMap(); + ::mlir::ArrayAttr getInBoundsAttr() { + auto attr = ::llvm::cast<::mlir::ArrayAttr>(getProperties().in_bounds); + return attr; + } + + ::mlir::ArrayAttr getInBounds(); +}; +} // namespace detail +template +class TransferWriteOpGenericAdaptor : public detail::TransferWriteOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TransferWriteOpGenericAdaptorBase; +public: + TransferWriteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TransferWriteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TransferWriteOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + TransferWriteOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs) : TransferWriteOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + TransferWriteOpGenericAdaptor(RangeT values, const TransferWriteOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + TransferWriteOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getValueToStore() { + return (*getODSOperands(0).begin()); + } + + ValueT getBase() { + return (*getODSOperands(1).begin()); + } + + RangeT getIndices() { + return getODSOperands(2); + } + + ValueT getMask() { + auto operands = getODSOperands(3); + return operands.empty() ? ValueT{} : (*operands.begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TransferWriteOpAdaptor : public TransferWriteOpGenericAdaptor<::mlir::ValueRange> { +public: + using TransferWriteOpGenericAdaptor::TransferWriteOpGenericAdaptor; + TransferWriteOpAdaptor(TransferWriteOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class TransferWriteOp : public ::mlir::Op::Impl, ::mlir::OpTrait::AttrSizedOperandSegments, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::VectorTransferOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait, ::mlir::vector::MaskableOpInterface::Trait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::DestinationStyleOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TransferWriteOpAdaptor; + template + using GenericAdaptor = TransferWriteOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("in_bounds"), ::llvm::StringRef("permutation_map"), ::llvm::StringRef("operandSegmentSizes")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getInBoundsAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getInBoundsAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + ::mlir::StringAttr getPermutationMapAttrName() { + return getAttributeNameForIndex(1); + } + + static ::mlir::StringAttr getPermutationMapAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 1); + } + + ::mlir::StringAttr getOperandSegmentSizesAttrName() { + return (*this)->getName().getAttributeNames().back(); + } + + static ::mlir::StringAttr getOperandSegmentSizesAttrName(::mlir::OperationName name) { + return name.getAttributeNames().back(); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.transfer_write"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getValueToStore() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::TypedValue<::mlir::ShapedType> getBase() { + return ::llvm::cast<::mlir::TypedValue<::mlir::ShapedType>>(*getODSOperands(1).begin()); + } + + ::mlir::Operation::operand_range getIndices() { + return getODSOperands(2); + } + + ::mlir::TypedValue<::mlir::VectorType> getMask() { + auto operands = getODSOperands(3); + return operands.empty() ? ::mlir::TypedValue<::mlir::VectorType>{} : ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*operands.begin()); + } + + ::mlir::OpOperand &getValueToStoreMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::OpOperand &getBaseMutable() { + auto range = getODSOperandIndexAndLength(1); + return getOperation()->getOpOperand(range.first); + } + + ::mlir::MutableOperandRange getIndicesMutable(); + ::mlir::MutableOperandRange getMaskMutable(); + std::pair getODSResultIndexAndLength(unsigned index); + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::RankedTensorType> getResult() { + auto results = getODSResults(0); + return results.empty() ? ::mlir::TypedValue<::mlir::RankedTensorType>() : ::llvm::cast<::mlir::TypedValue<::mlir::RankedTensorType>>(*results.begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::AffineMapAttr getPermutationMapAttr() { + return ::llvm::cast<::mlir::AffineMapAttr>(getProperties().permutation_map); + } + + ::mlir::AffineMap getPermutationMap(); + ::mlir::ArrayAttr getInBoundsAttr() { + return ::llvm::cast<::mlir::ArrayAttr>(getProperties().in_bounds); + } + + ::mlir::ArrayAttr getInBounds(); + void setPermutationMapAttr(::mlir::AffineMapAttr attr) { + getProperties().permutation_map = attr; + } + + void setPermutationMap(::mlir::AffineMap attrValue); + void setInBoundsAttr(::mlir::ArrayAttr attr) { + getProperties().in_bounds = attr; + } + + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value vector, Value dest, ValueRange indices, AffineMapAttr permutationMapAttr, Value mask, ArrayAttr inBoundsAttr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value vector, Value dest, ValueRange indices, AffineMapAttr permutationMapAttr, ArrayAttr inBoundsAttr); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value vector, Value dest, ValueRange indices, AffineMap permutationMap, std::optional> inBounds = ::std::nullopt); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value vector, Value dest, ValueRange indices, std::optional> inBounds = ::std::nullopt); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMapAttr permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, /*optional*/::mlir::Type result, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value valueToStore, ::mlir::Value base, ::mlir::ValueRange indices, ::mlir::AffineMap permutation_map, /*optional*/::mlir::Value mask, ::mlir::ArrayAttr in_bounds); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &p); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::llvm::LogicalResult fold(FoldAdaptor adaptor, ::llvm::SmallVectorImpl<::mlir::OpFoldResult> &results); + ::mlir::Value getVector(); + ::mlir::VectorType getVectorType(); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + mlir::Type getExpectedMaskType(); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); + ::mlir::Speculation::Speculatability getSpeculatability(); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 2 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + /// This method is added to maintain uniformity with load/store + /// ops of other dialects. + Value getValue() { return getVector(); } + + MutableOperandRange getDpsInitsMutable() { return getBaseMutable(); } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::TransferWriteOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TransposeOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TransposeOpGenericAdaptorBase { +public: + struct Properties { + using permutationTy = ::mlir::DenseI64ArrayAttr; + permutationTy permutation; + + auto getPermutation() const { + auto &propStorage = this->permutation; + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(propStorage); + } + void setPermutation(const ::mlir::DenseI64ArrayAttr &propValue) { + this->permutation = propValue; + } + bool operator==(const Properties &rhs) const { + return + rhs.permutation == this->permutation && + true; + } + bool operator!=(const Properties &rhs) const { + return !(*this == rhs); + } + }; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + TransposeOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.transpose", odsAttrs.getContext()); + } + + TransposeOpGenericAdaptorBase(TransposeOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + + ::mlir::DenseI64ArrayAttr getPermutationAttr() { + auto attr = ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().permutation); + return attr; + } + + ::llvm::ArrayRef getPermutation(); +}; +} // namespace detail +template +class TransposeOpGenericAdaptor : public detail::TransposeOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TransposeOpGenericAdaptorBase; +public: + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TransposeOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + TransposeOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : TransposeOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + TransposeOpGenericAdaptor(RangeT values, const TransposeOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + TransposeOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getVector() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TransposeOpAdaptor : public TransposeOpGenericAdaptor<::mlir::ValueRange> { +public: + using TransposeOpGenericAdaptor::TransposeOpGenericAdaptor; + TransposeOpAdaptor(TransposeOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class TransposeOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::BytecodeOpInterface::Trait, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::VectorUnrollOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TransposeOpAdaptor; + template + using GenericAdaptor = TransposeOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + static ::llvm::StringRef attrNames[] = {::llvm::StringRef("permutation")}; + return ::llvm::ArrayRef(attrNames); + } + + ::mlir::StringAttr getPermutationAttrName() { + return getAttributeNameForIndex(0); + } + + static ::mlir::StringAttr getPermutationAttrName(::mlir::OperationName name) { + return getAttributeNameForIndex(name, 0); + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.transpose"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getVector() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getVectorMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::VectorType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::VectorType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::llvm::LogicalResult readProperties(::mlir::DialectBytecodeReader &reader, ::mlir::OperationState &state); + void writeProperties(::mlir::DialectBytecodeWriter &writer); + ::mlir::DenseI64ArrayAttr getPermutationAttr() { + return ::llvm::cast<::mlir::DenseI64ArrayAttr>(getProperties().permutation); + } + + ::llvm::ArrayRef getPermutation(); + void setPermutationAttr(::mlir::DenseI64ArrayAttr attr) { + getProperties().permutation = attr; + } + + void setPermutation(::llvm::ArrayRef attrValue); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value vector, ArrayRef permutation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::mlir::DenseI64ArrayAttr permutation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::mlir::DenseI64ArrayAttr permutation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value vector, ::llvm::ArrayRef permutation); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value vector, ::llvm::ArrayRef permutation); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static void getCanonicalizationPatterns(::mlir::RewritePatternSet &results, ::mlir::MLIRContext *context); + ::mlir::OpFoldResult fold(FoldAdaptor adaptor); + ::std::optional<::llvm::SmallVector> getShapeForUnroll(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +private: + ::mlir::StringAttr getAttributeNameForIndex(unsigned index) { + return getAttributeNameForIndex((*this)->getName(), index); + } + + static ::mlir::StringAttr getAttributeNameForIndex(::mlir::OperationName name, unsigned index) { + assert(index < 1 && "invalid attribute index"); + assert(name.getStringRef() == getOperationName() && "invalid operation name"); + assert(name.isRegistered() && "Operation isn't registered, missing a " + "dependent dialect loading?"); + return name.getAttributeNames()[index]; + } + +public: + VectorType getSourceVectorType() { + return ::llvm::cast(getVector().getType()); + } + VectorType getResultVectorType() { + return ::llvm::cast(getResult().getType()); + } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::TransposeOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::TypeCastOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class TypeCastOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + TypeCastOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.type_cast", odsAttrs.getContext()); + } + + TypeCastOpGenericAdaptorBase(TypeCastOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize) { + return {index, 1}; + } + + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class TypeCastOpGenericAdaptor : public detail::TypeCastOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::TypeCastOpGenericAdaptorBase; +public: + TypeCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + TypeCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : TypeCastOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + TypeCastOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : TypeCastOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + TypeCastOpGenericAdaptor(RangeT values, const TypeCastOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + TypeCastOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + ValueT getMemref() { + return (*getODSOperands(0).begin()); + } + + RangeT getOperands() { + return odsOperands; + } + +private: + RangeT odsOperands; +}; +class TypeCastOpAdaptor : public TypeCastOpGenericAdaptor<::mlir::ValueRange> { +public: + using TypeCastOpGenericAdaptor::TypeCastOpGenericAdaptor; + TypeCastOpAdaptor(TypeCastOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class TypeCastOp : public ::mlir::Op::Impl, ::mlir::OpTrait::ZeroSuccessors, ::mlir::OpTrait::OneOperand, ::mlir::OpTrait::OpInvariants, ::mlir::ConditionallySpeculatable::Trait, ::mlir::OpTrait::AlwaysSpeculatableImplTrait, ::mlir::MemoryEffectOpInterface::Trait, ::mlir::ViewLikeOpInterface::Trait> { +public: + using Op::Op; + using Op::print; + using Adaptor = TypeCastOpAdaptor; + template + using GenericAdaptor = TypeCastOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.type_cast"); + } + + std::pair getODSOperandIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getMemref() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSOperands(0).begin()); + } + + ::mlir::OpOperand &getMemrefMutable() { + auto range = getODSOperandIndexAndLength(0); + return getOperation()->getOpOperand(range.first); + } + + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::TypedValue<::mlir::MemRefType> getResult() { + return ::llvm::cast<::mlir::TypedValue<::mlir::MemRefType>>(*getODSResults(0).begin()); + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, Value source); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::Type result, ::mlir::Value memref); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::Value memref); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::llvm::LogicalResult verify(); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: + MemRefType getMemRefType() { + return ::llvm::cast(getMemref().getType()); + } + MemRefType getResultMemRefType() { + return ::llvm::cast(getResult().getType()); + } + // Implement ViewLikeOpInterface. + Value getViewSource() { return getMemref(); } +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::TypeCastOp) + +namespace mlir { +namespace vector { + +//===----------------------------------------------------------------------===// +// ::mlir::vector::YieldOp declarations +//===----------------------------------------------------------------------===// + +namespace detail { +class YieldOpGenericAdaptorBase { +public: + using Properties = ::mlir::EmptyProperties; +protected: + ::mlir::DictionaryAttr odsAttrs; + ::std::optional<::mlir::OperationName> odsOpName; + Properties properties; + ::mlir::RegionRange odsRegions; +public: + YieldOpGenericAdaptorBase(::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : odsAttrs(attrs), properties(properties), odsRegions(regions) { if (odsAttrs) + odsOpName.emplace("vector.yield", odsAttrs.getContext()); + } + + YieldOpGenericAdaptorBase(YieldOp op); + + std::pair getODSOperandIndexAndLength(unsigned index, unsigned odsOperandsSize); + const Properties &getProperties() { + return properties; + } + + ::mlir::DictionaryAttr getAttributes() { + return odsAttrs; + } + +}; +} // namespace detail +template +class YieldOpGenericAdaptor : public detail::YieldOpGenericAdaptorBase { + using ValueT = ::llvm::detail::ValueOfRange; + using Base = detail::YieldOpGenericAdaptorBase; +public: + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, const Properties &properties, ::mlir::RegionRange regions = {}) : Base(attrs, properties, regions), odsOperands(values) {} + + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs, ::mlir::OpaqueProperties properties, ::mlir::RegionRange regions = {}) : YieldOpGenericAdaptor(values, attrs, (properties ? *properties.as() : Properties{}), regions) {} + + YieldOpGenericAdaptor(RangeT values, ::mlir::DictionaryAttr attrs = nullptr) : YieldOpGenericAdaptor(values, attrs, Properties{}, {}) {} + + YieldOpGenericAdaptor(RangeT values, const YieldOpGenericAdaptorBase &base) : Base(base), odsOperands(values) {} + + template >> + YieldOpGenericAdaptor(RangeT values, LateInst op) : Base(op), odsOperands(values) {} + + std::pair getODSOperandIndexAndLength(unsigned index) { + return Base::getODSOperandIndexAndLength(index, odsOperands.size()); + } + + RangeT getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(odsOperands.begin(), valueRange.first), + std::next(odsOperands.begin(), valueRange.first + valueRange.second)}; + } + + RangeT getOperands() { + return getODSOperands(0); + } + +private: + RangeT odsOperands; +}; +class YieldOpAdaptor : public YieldOpGenericAdaptor<::mlir::ValueRange> { +public: + using YieldOpGenericAdaptor::YieldOpGenericAdaptor; + YieldOpAdaptor(YieldOp op); + + ::llvm::LogicalResult verify(::mlir::Location loc); +}; +class YieldOp : public ::mlir::Op { +public: + using Op::Op; + using Op::print; + using Adaptor = YieldOpAdaptor; + template + using GenericAdaptor = YieldOpGenericAdaptor; + using FoldAdaptor = GenericAdaptor<::llvm::ArrayRef<::mlir::Attribute>>; + using Properties = FoldAdaptor::Properties; + static ::llvm::ArrayRef<::llvm::StringRef> getAttributeNames() { + return {}; + } + + static constexpr ::llvm::StringLiteral getOperationName() { + return ::llvm::StringLiteral("vector.yield"); + } + + std::pair getODSOperandIndexAndLength(unsigned index); + ::mlir::Operation::operand_range getODSOperands(unsigned index) { + auto valueRange = getODSOperandIndexAndLength(index); + return {std::next(getOperation()->operand_begin(), valueRange.first), + std::next(getOperation()->operand_begin(), valueRange.first + valueRange.second)}; + } + + ::mlir::Operation::operand_range getOperands() { + return getODSOperands(0); + } + + ::mlir::MutableOperandRange getOperandsMutable(); + std::pair getODSResultIndexAndLength(unsigned index) { + return {index, 1}; + } + + ::mlir::Operation::result_range getODSResults(unsigned index) { + auto valueRange = getODSResultIndexAndLength(index); + return {std::next(getOperation()->result_begin(), valueRange.first), + std::next(getOperation()->result_begin(), valueRange.first + valueRange.second)}; + } + + static ::llvm::LogicalResult setPropertiesFromAttr(Properties &prop, ::mlir::Attribute attr, ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static ::mlir::Attribute getPropertiesAsAttr(::mlir::MLIRContext *ctx, const Properties &prop); + static llvm::hash_code computePropertiesHash(const Properties &prop); + static std::optional getInherentAttr(::mlir::MLIRContext *ctx, const Properties &prop, llvm::StringRef name); + static void setInherentAttr(Properties &prop, llvm::StringRef name, mlir::Attribute value); + static void populateInherentAttrs(::mlir::MLIRContext *ctx, const Properties &prop, ::mlir::NamedAttrList &attrs); + static ::llvm::LogicalResult verifyInherentAttrs(::mlir::OperationName opName, ::mlir::NamedAttrList &attrs, llvm::function_ref<::mlir::InFlightDiagnostic()> emitError); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState); + static void build(::mlir::OpBuilder &odsBuilder, ::mlir::OperationState &odsState, ::mlir::ValueRange operands); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, ::llvm::ArrayRef<::mlir::NamedAttribute> attributes = {}); + static void build(::mlir::OpBuilder &, ::mlir::OperationState &odsState, ::mlir::TypeRange resultTypes, ::mlir::ValueRange operands, const Properties &properties, ::llvm::ArrayRef<::mlir::NamedAttribute> discardableAttributes = {}); + ::llvm::LogicalResult verifyInvariantsImpl(); + ::llvm::LogicalResult verifyInvariants(); + ::mlir::MutableOperandRange getMutableSuccessorOperands(::mlir::RegionBranchPoint point); + static ::mlir::ParseResult parse(::mlir::OpAsmParser &parser, ::mlir::OperationState &result); + void print(::mlir::OpAsmPrinter &_odsPrinter); + void getEffects(::llvm::SmallVectorImpl<::mlir::SideEffects::EffectInstance<::mlir::MemoryEffects::Effect>> &effects); +public: +}; +} // namespace vector +} // namespace mlir +MLIR_DECLARE_EXPLICIT_TYPE_ID(::mlir::vector::YieldOp) + + +#endif // GET_OP_CLASSES + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..ab8de98618eb805db769ea833e0ae408d82801e0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.cpp.inc @@ -0,0 +1,28 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + + +/// Returns true if the operation is masked by a MaskingOpInterface. +bool mlir::vector::MaskableOpInterface::isMasked() { + return getImpl()->isMasked(getImpl(), getOperation()); + } + +/// Returns the MaskingOpInterface masking this operation. +mlir::vector::MaskingOpInterface mlir::vector::MaskableOpInterface::getMaskingOp() { + return getImpl()->getMaskingOp(getImpl(), getOperation()); + } + +/// Returns true if the operation can have a passthru argument when masked. +bool mlir::vector::MaskableOpInterface::supportsPassthru() { + return getImpl()->supportsPassthru(getImpl(), getOperation()); + } + +/// Returns the mask type expected by this operation. Mostly used for verification purposes. It requires the operation to be vectorized. +mlir::Type mlir::vector::MaskableOpInterface::getExpectedMaskType() { + return getImpl()->getExpectedMaskType(getImpl(), getOperation()); + } diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..01c968570b93dab445a2f2ddb2d322162c8fb824 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h @@ -0,0 +1,23 @@ +//===- MaskableOpInterface.h ----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the MaskableOpInterface. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_INTERFACES_MASKABLEOPINTERFACE_H_ +#define MLIR_DIALECT_VECTOR_INTERFACES_MASKABLEOPINTERFACE_H_ + +#include "mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/OpDefinition.h" + +// Include the generated interface declarations. +#include "mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h.inc" + +#endif // MLIR_DIALECT_VECTOR_INTERFACES_MASKABLEOPINTERFACE_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..7112b5fe39f21e70ff959da00c9df7de85713d9a --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskableOpInterface.h.inc @@ -0,0 +1,152 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { +/// The 'MaskableOpInterface' defines an operation that can be masked using a +/// MaskingOpInterface (e.g., `vector.mask`) and provides information about its +/// masking constraints and semantics. +class MaskableOpInterface; +namespace detail { +struct MaskableOpInterfaceInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + bool (*isMasked)(const Concept *impl, ::mlir::Operation *); + mlir::vector::MaskingOpInterface (*getMaskingOp)(const Concept *impl, ::mlir::Operation *); + bool (*supportsPassthru)(const Concept *impl, ::mlir::Operation *); + mlir::Type (*getExpectedMaskType)(const Concept *impl, ::mlir::Operation *); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::vector::MaskableOpInterface; + Model() : Concept{isMasked, getMaskingOp, supportsPassthru, getExpectedMaskType} {} + + static inline bool isMasked(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline mlir::vector::MaskingOpInterface getMaskingOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline bool supportsPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline mlir::Type getExpectedMaskType(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::vector::MaskableOpInterface; + FallbackModel() : Concept{isMasked, getMaskingOp, supportsPassthru, getExpectedMaskType} {} + + static inline bool isMasked(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline mlir::vector::MaskingOpInterface getMaskingOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline bool supportsPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline mlir::Type getExpectedMaskType(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteOp; + bool isMasked(::mlir::Operation *tablegen_opaque_val) const; + mlir::vector::MaskingOpInterface getMaskingOp(::mlir::Operation *tablegen_opaque_val) const; + bool supportsPassthru(::mlir::Operation *tablegen_opaque_val) const; + }; +}; +template +struct MaskableOpInterfaceTrait; + +} // namespace detail +class MaskableOpInterface : public ::mlir::OpInterface { +public: + using ::mlir::OpInterface::OpInterface; + template + struct Trait : public detail::MaskableOpInterfaceTrait {}; + + /// Returns true if the operation is masked by a MaskingOpInterface. + bool isMasked(); + + /// Returns the MaskingOpInterface masking this operation. + mlir::vector::MaskingOpInterface getMaskingOp(); + + /// Returns true if the operation can have a passthru argument when masked. + bool supportsPassthru(); + + /// Returns the mask type expected by this operation. Mostly used for verification purposes. It requires the operation to be vectorized. + mlir::Type getExpectedMaskType(); +}; +namespace detail { + template + struct MaskableOpInterfaceTrait : public ::mlir::OpInterface::Trait { + + /// Returns true if the operation is masked by a MaskingOpInterface. + bool isMasked() { + mlir::Operation *parentOp = (*static_cast(this))->getParentOp(); + return parentOp && + mlir::isa(parentOp); + } + + /// Returns the MaskingOpInterface masking this operation. + mlir::vector::MaskingOpInterface getMaskingOp() { + return mlir::cast( + (*static_cast(this))->getParentOp()); + } + + /// Returns true if the operation can have a passthru argument when masked. + bool supportsPassthru() { + return false; + } + }; +}// namespace detail +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +template +bool detail::MaskableOpInterfaceInterfaceTraits::Model::isMasked(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).isMasked(); +} +template +mlir::vector::MaskingOpInterface detail::MaskableOpInterfaceInterfaceTraits::Model::getMaskingOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getMaskingOp(); +} +template +bool detail::MaskableOpInterfaceInterfaceTraits::Model::supportsPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).supportsPassthru(); +} +template +mlir::Type detail::MaskableOpInterfaceInterfaceTraits::Model::getExpectedMaskType(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getExpectedMaskType(); +} +template +bool detail::MaskableOpInterfaceInterfaceTraits::FallbackModel::isMasked(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->isMasked(tablegen_opaque_val); +} +template +mlir::vector::MaskingOpInterface detail::MaskableOpInterfaceInterfaceTraits::FallbackModel::getMaskingOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getMaskingOp(tablegen_opaque_val); +} +template +bool detail::MaskableOpInterfaceInterfaceTraits::FallbackModel::supportsPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->supportsPassthru(tablegen_opaque_val); +} +template +mlir::Type detail::MaskableOpInterfaceInterfaceTraits::FallbackModel::getExpectedMaskType(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getExpectedMaskType(tablegen_opaque_val); +} +template +bool detail::MaskableOpInterfaceInterfaceTraits::ExternalModel::isMasked(::mlir::Operation *tablegen_opaque_val) const { +mlir::Operation *parentOp = (llvm::cast(tablegen_opaque_val))->getParentOp(); + return parentOp && + mlir::isa(parentOp); +} +template +mlir::vector::MaskingOpInterface detail::MaskableOpInterfaceInterfaceTraits::ExternalModel::getMaskingOp(::mlir::Operation *tablegen_opaque_val) const { +return mlir::cast( + (llvm::cast(tablegen_opaque_val))->getParentOp()); +} +template +bool detail::MaskableOpInterfaceInterfaceTraits::ExternalModel::supportsPassthru(::mlir::Operation *tablegen_opaque_val) const { +return false; +} +} // namespace vector +} // namespace mlir diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.cpp.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.cpp.inc new file mode 100644 index 0000000000000000000000000000000000000000..d95e8dcb70c6cef2ecc743282d5b000b807e1ba1 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.cpp.inc @@ -0,0 +1,28 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Definitions *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + + +/// Returns the mask value of this masking operation. +mlir::Value mlir::vector::MaskingOpInterface::getMask() { + return getImpl()->getMask(getImpl(), getOperation()); + } + +/// Returns the operation masked by this masking operation. +Operation *mlir::vector::MaskingOpInterface::getMaskableOp() { + return getImpl()->getMaskableOp(getImpl(), getOperation()); + } + +/// Returns true if the masking operation has a passthru value. +bool mlir::vector::MaskingOpInterface::hasPassthru() { + return getImpl()->hasPassthru(getImpl(), getOperation()); + } + +/// Returns the passthru value of this masking operation. +mlir::Value mlir::vector::MaskingOpInterface::getPassthru() { + return getImpl()->getPassthru(getImpl(), getOperation()); + } diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..5eb613a6024c376c1132981cd966ed2fc82cdf30 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h @@ -0,0 +1,22 @@ +//===- MaskingOpInterface.h -----------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements the MaskingOpInterface. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_INTERFACES_MASKINGOPINTERFACE_H_ +#define MLIR_DIALECT_VECTOR_INTERFACES_MASKINGOPINTERFACE_H_ + +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/OpDefinition.h" + +// Include the generated interface declarations. +#include "mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h.inc" + +#endif // MLIR_DIALECT_VECTOR_INTERFACES_MASKINGOPINTERFACE_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..bab870de0604d8240d75b9b7718a73af8af81733 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Interfaces/MaskingOpInterface.h.inc @@ -0,0 +1,115 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Interface Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { +/// The 'MaskingOpInterface' defines an vector operation that can apply masking +/// to its own or other vector operations. +class MaskingOpInterface; +namespace detail { +struct MaskingOpInterfaceInterfaceTraits { + struct Concept { + /// The methods defined by the interface. + mlir::Value (*getMask)(const Concept *impl, ::mlir::Operation *); + Operation *(*getMaskableOp)(const Concept *impl, ::mlir::Operation *); + bool (*hasPassthru)(const Concept *impl, ::mlir::Operation *); + mlir::Value (*getPassthru)(const Concept *impl, ::mlir::Operation *); + }; + template + class Model : public Concept { + public: + using Interface = ::mlir::vector::MaskingOpInterface; + Model() : Concept{getMask, getMaskableOp, hasPassthru, getPassthru} {} + + static inline mlir::Value getMask(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline Operation *getMaskableOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline bool hasPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline mlir::Value getPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class FallbackModel : public Concept { + public: + using Interface = ::mlir::vector::MaskingOpInterface; + FallbackModel() : Concept{getMask, getMaskableOp, hasPassthru, getPassthru} {} + + static inline mlir::Value getMask(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline Operation *getMaskableOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline bool hasPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + static inline mlir::Value getPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val); + }; + template + class ExternalModel : public FallbackModel { + public: + using ConcreteEntity = ConcreteOp; + }; +}; +template +struct MaskingOpInterfaceTrait; + +} // namespace detail +class MaskingOpInterface : public ::mlir::OpInterface { +public: + using ::mlir::OpInterface::OpInterface; + template + struct Trait : public detail::MaskingOpInterfaceTrait {}; + + /// Returns the mask value of this masking operation. + mlir::Value getMask(); + + /// Returns the operation masked by this masking operation. + Operation *getMaskableOp(); + + /// Returns true if the masking operation has a passthru value. + bool hasPassthru(); + + /// Returns the passthru value of this masking operation. + mlir::Value getPassthru(); +}; +namespace detail { + template + struct MaskingOpInterfaceTrait : public ::mlir::OpInterface::Trait { + }; +}// namespace detail +} // namespace vector +} // namespace mlir +namespace mlir { +namespace vector { +template +mlir::Value detail::MaskingOpInterfaceInterfaceTraits::Model::getMask(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getMask(); +} +template +Operation *detail::MaskingOpInterfaceInterfaceTraits::Model::getMaskableOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getMaskableOp(); +} +template +bool detail::MaskingOpInterfaceInterfaceTraits::Model::hasPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).hasPassthru(); +} +template +mlir::Value detail::MaskingOpInterfaceInterfaceTraits::Model::getPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return (llvm::cast(tablegen_opaque_val)).getPassthru(); +} +template +mlir::Value detail::MaskingOpInterfaceInterfaceTraits::FallbackModel::getMask(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getMask(tablegen_opaque_val); +} +template +Operation *detail::MaskingOpInterfaceInterfaceTraits::FallbackModel::getMaskableOp(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getMaskableOp(tablegen_opaque_val); +} +template +bool detail::MaskingOpInterfaceInterfaceTraits::FallbackModel::hasPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->hasPassthru(tablegen_opaque_val); +} +template +mlir::Value detail::MaskingOpInterfaceInterfaceTraits::FallbackModel::getPassthru(const Concept *impl, ::mlir::Operation *tablegen_opaque_val) { + return static_cast(impl)->getPassthru(tablegen_opaque_val); +} +} // namespace vector +} // namespace mlir diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..bd1a7f3aa102e44108b0415f1db348129cfd8a8f --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h @@ -0,0 +1,21 @@ +//===- BufferizableOpInterfaceImpl.h - Impl. of BufferizableOpInterface ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_BUFFERIZABLEOPINTERFACEIMPL_H +#define MLIR_DIALECT_VECTOR_BUFFERIZABLEOPINTERFACEIMPL_H + +namespace mlir { + +class DialectRegistry; + +namespace vector { +void registerBufferizableOpInterfaceExternalModels(DialectRegistry ®istry); +} // namespace vector +} // namespace mlir + +#endif // MLIR_DIALECT_VECTOR_BUFFERIZABLEOPINTERFACEIMPL_H diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/VectorDistribution.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/VectorDistribution.h new file mode 100644 index 0000000000000000000000000000000000000000..dda45219b2acc26bda036c362dd81f7d1958ac25 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/VectorDistribution.h @@ -0,0 +1,115 @@ +//===- VectorDistribution.h - Vector distribution patterns --*- C++------*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_TRANSFORMS_VECTORDISTRIBUTION_H_ +#define MLIR_DIALECT_VECTOR_TRANSFORMS_VECTORDISTRIBUTION_H_ + +#include "mlir/Dialect/GPU/IR/GPUDialect.h" +#include "mlir/Dialect/Vector/IR/VectorOps.h" + +namespace mlir { +class RewritePatternSet; +namespace vector { + +struct WarpExecuteOnLane0LoweringOptions { + /// Lamdba function to let users allocate memory needed for the lowering of + /// WarpExecuteOnLane0Op. + /// The function needs to return an allocation that the lowering can use as + /// temporary memory. The allocation needs to match the shape of the type (the + /// type may be VectorType or a scalar) and be availble for the current warp. + /// If there are several warps running in parallel the allocation needs to be + /// split so that each warp has its own allocation. + using WarpAllocationFn = std::function; + WarpAllocationFn warpAllocationFn = nullptr; + + /// Lamdba function to let user emit operation to syncronize all the thread + /// within a warp. After this operation all the threads can see any memory + /// written before the operation. + using WarpSyncronizationFn = + std::function; + WarpSyncronizationFn warpSyncronizationFn = nullptr; +}; + +void populateWarpExecuteOnLane0OpToScfForPattern( + RewritePatternSet &patterns, + const WarpExecuteOnLane0LoweringOptions &options, + PatternBenefit benefit = 1); + +using DistributionMapFn = std::function; + +/// Distribute transfer_write ops based on the affine map returned by +/// `distributionMapFn`. Writes of size more than `maxNumElementToExtract` +/// will not be distributed (it should be less than the warp size). +/// +/// Example: +/// ``` +/// %0 = gpu.warp_execute_on_lane_0(%id){ +/// ... +/// vector.transfer_write %v, %A[%c0] : vector<32xf32>, memref<128xf32> +/// gpu.yield +/// } +/// ``` +/// To +/// ``` +/// %r:3 = gpu.warp_execute_on_lane_0(%id) -> (vector<1xf32>) { +/// ... +/// gpu.yield %v : vector<32xf32> +/// } +/// vector.transfer_write %v, %A[%id] : vector<1xf32>, memref<128xf32> +/// +/// When applied at the same time as the vector propagation patterns, +/// distribution of `vector.transfer_write` is expected to have the highest +/// priority (pattern benefit). By making propagation of `vector.transfer_read` +/// be the lowest priority pattern, it will be the last vector operation to +/// distribute, meaning writes should propagate first. +void populateDistributeTransferWriteOpPatterns( + RewritePatternSet &patterns, const DistributionMapFn &distributionMapFn, + unsigned maxNumElementsToExtract, PatternBenefit benefit = 2); + +/// Move scalar operations with no dependency on the warp op outside of the +/// region. +void moveScalarUniformCode(gpu::WarpExecuteOnLane0Op op); + +/// Lambda signature to compute a warp shuffle of a given value of a given lane +/// within a given warp size. +using WarpShuffleFromIdxFn = + std::function; + +/// Collect patterns to propagate warp distribution. `distributionMapFn` is used +/// to decide how a value should be distributed when this cannot be inferred +/// from its uses. +/// +/// The separate control over the `vector.transfer_read` op pattern benefit +/// is given to ensure the order of reads/writes before and after distribution +/// is consistent. As noted above, writes are expected to have the highest +/// priority for distribution, but are only ever distributed if adjacent to the +/// yield. By making reads the lowest priority pattern, it will be the last +/// vector operation to distribute, meaning writes should propagate first. This +/// is relatively brittle when ops fail to distribute, but that is a limitation +/// of these propagation patterns when there is a dependency not modeled by SSA. +void populatePropagateWarpVectorDistributionPatterns( + RewritePatternSet &pattern, const DistributionMapFn &distributionMapFn, + const WarpShuffleFromIdxFn &warpShuffleFromIdxFn, + PatternBenefit benefit = 1, PatternBenefit readBenefit = 0); + +/// Lambda signature to compute a reduction of a distributed value for the given +/// reduction kind and size. +using DistributedReductionFn = + std::function; + +/// Collect patterns to distribute vector reduction ops using given lamdba to +/// distribute reduction op. +void populateDistributeReduction( + RewritePatternSet &pattern, + const DistributedReductionFn &distributedReductionFn, + PatternBenefit benefit = 1); + +} // namespace vector +} // namespace mlir +#endif // MLIR_DIALECT_VECTOR_TRANSFORMS_VECTORDISTRIBUTION_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/VectorTransformsEnums.h.inc b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/VectorTransformsEnums.h.inc new file mode 100644 index 0000000000000000000000000000000000000000..b998e1e9c2f4867aafec97e62e6d7cd88e0282f6 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Transforms/VectorTransformsEnums.h.inc @@ -0,0 +1,465 @@ +/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\ +|* *| +|* Enum Utility Declarations *| +|* *| +|* Automatically generated file, do not edit! *| +|* From: VectorTransformsBase.td *| +|* *| +\*===----------------------------------------------------------------------===*/ + +namespace mlir { +namespace vector { +// control the lowering of `vector.contract` operations. +enum class VectorContractLowering : uint32_t { + Dot = 0, + Matmul = 1, + OuterProduct = 2, + ParallelArith = 3, +}; + +::std::optional symbolizeVectorContractLowering(uint32_t); +::llvm::StringRef stringifyVectorContractLowering(VectorContractLowering); +::std::optional symbolizeVectorContractLowering(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForVectorContractLowering() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(VectorContractLowering enumValue) { + return stringifyVectorContractLowering(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeVectorContractLowering(str); +} + +class VectorContractLoweringAttr : public ::mlir::IntegerAttr { +public: + using ValueType = VectorContractLowering; + using ::mlir::IntegerAttr::IntegerAttr; + static bool classof(::mlir::Attribute attr); + static VectorContractLoweringAttr get(::mlir::MLIRContext *context, VectorContractLowering val); + VectorContractLowering getValue() const; +}; +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::VectorContractLowering, ::mlir::vector::VectorContractLowering> { + template + static FailureOr<::mlir::vector::VectorContractLowering> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for control the lowering of `vector.contract` operations."); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorContractLowering> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorContractLowering>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [dot, matmulintrinsics, outerproduct, parallelarith] for control the lowering of `vector.contract` operations., got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::VectorContractLowering>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::VectorContractLowering>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorContractLowering> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorContractLowering>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [dot, matmulintrinsics, outerproduct, parallelarith] for control the lowering of `vector.contract` operations., got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::VectorContractLowering value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::VectorContractLowering> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::VectorContractLowering getEmptyKey() { + return static_cast<::mlir::vector::VectorContractLowering>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::VectorContractLowering getTombstoneKey() { + return static_cast<::mlir::vector::VectorContractLowering>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::VectorContractLowering &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::VectorContractLowering &lhs, const ::mlir::vector::VectorContractLowering &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace vector { +// control the lowering of `vector.multi_reduction`. +enum class VectorMultiReductionLowering : uint32_t { + InnerParallel = 0, + InnerReduction = 1, +}; + +::std::optional symbolizeVectorMultiReductionLowering(uint32_t); +::llvm::StringRef stringifyVectorMultiReductionLowering(VectorMultiReductionLowering); +::std::optional symbolizeVectorMultiReductionLowering(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForVectorMultiReductionLowering() { + return 1; +} + + +inline ::llvm::StringRef stringifyEnum(VectorMultiReductionLowering enumValue) { + return stringifyVectorMultiReductionLowering(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeVectorMultiReductionLowering(str); +} + +class VectorMultiReductionLoweringAttr : public ::mlir::IntegerAttr { +public: + using ValueType = VectorMultiReductionLowering; + using ::mlir::IntegerAttr::IntegerAttr; + static bool classof(::mlir::Attribute attr); + static VectorMultiReductionLoweringAttr get(::mlir::MLIRContext *context, VectorMultiReductionLowering val); + VectorMultiReductionLowering getValue() const; +}; +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::VectorMultiReductionLowering, ::mlir::vector::VectorMultiReductionLowering> { + template + static FailureOr<::mlir::vector::VectorMultiReductionLowering> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for control the lowering of `vector.multi_reduction`."); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorMultiReductionLowering> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorMultiReductionLowering>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [innerparallel, innerreduction] for control the lowering of `vector.multi_reduction`., got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::VectorMultiReductionLowering>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::VectorMultiReductionLowering>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorMultiReductionLowering> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorMultiReductionLowering>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [innerparallel, innerreduction] for control the lowering of `vector.multi_reduction`., got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::VectorMultiReductionLowering value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::VectorMultiReductionLowering> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::VectorMultiReductionLowering getEmptyKey() { + return static_cast<::mlir::vector::VectorMultiReductionLowering>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::VectorMultiReductionLowering getTombstoneKey() { + return static_cast<::mlir::vector::VectorMultiReductionLowering>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::VectorMultiReductionLowering &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::VectorMultiReductionLowering &lhs, const ::mlir::vector::VectorMultiReductionLowering &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace vector { +// control the splitting of `vector.transfer` operations into in-bounds and out-of-bounds variants. +enum class VectorTransferSplit : uint32_t { + None = 0, + VectorTransfer = 1, + LinalgCopy = 2, + ForceInBounds = 3, +}; + +::std::optional symbolizeVectorTransferSplit(uint32_t); +::llvm::StringRef stringifyVectorTransferSplit(VectorTransferSplit); +::std::optional symbolizeVectorTransferSplit(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForVectorTransferSplit() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(VectorTransferSplit enumValue) { + return stringifyVectorTransferSplit(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeVectorTransferSplit(str); +} + +class VectorTransferSplitAttr : public ::mlir::IntegerAttr { +public: + using ValueType = VectorTransferSplit; + using ::mlir::IntegerAttr::IntegerAttr; + static bool classof(::mlir::Attribute attr); + static VectorTransferSplitAttr get(::mlir::MLIRContext *context, VectorTransferSplit val); + VectorTransferSplit getValue() const; +}; +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::VectorTransferSplit, ::mlir::vector::VectorTransferSplit> { + template + static FailureOr<::mlir::vector::VectorTransferSplit> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for control the splitting of `vector.transfer` operations into in-bounds and out-of-bounds variants."); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorTransferSplit> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorTransferSplit>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [none, \"vector-transfer\"vector-transfer, \"linalg-copy\"linalg-copy, \"force-in-bounds\"force-in-bounds] for control the splitting of `vector.transfer` operations into in-bounds and out-of-bounds variants., got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::VectorTransferSplit>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::VectorTransferSplit>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorTransferSplit> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorTransferSplit>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [none, \"vector-transfer\"vector-transfer, \"linalg-copy\"linalg-copy, \"force-in-bounds\"force-in-bounds] for control the splitting of `vector.transfer` operations into in-bounds and out-of-bounds variants., got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::VectorTransferSplit value) { + auto valueStr = stringifyEnum(value); + switch (value) { + case ::mlir::vector::VectorTransferSplit::None: + break; + default: + return p << '"' << valueStr << '"'; + } + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::VectorTransferSplit> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::VectorTransferSplit getEmptyKey() { + return static_cast<::mlir::vector::VectorTransferSplit>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::VectorTransferSplit getTombstoneKey() { + return static_cast<::mlir::vector::VectorTransferSplit>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::VectorTransferSplit &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::VectorTransferSplit &lhs, const ::mlir::vector::VectorTransferSplit &rhs) { + return lhs == rhs; + } +}; +} + +namespace mlir { +namespace vector { +// control the lowering of `vector.transpose` operations. +enum class VectorTransposeLowering : uint32_t { + EltWise = 0, + Flat = 1, + Shuffle1D = 2, + Shuffle16x16 = 3, +}; + +::std::optional symbolizeVectorTransposeLowering(uint32_t); +::llvm::StringRef stringifyVectorTransposeLowering(VectorTransposeLowering); +::std::optional symbolizeVectorTransposeLowering(::llvm::StringRef); +inline constexpr unsigned getMaxEnumValForVectorTransposeLowering() { + return 3; +} + + +inline ::llvm::StringRef stringifyEnum(VectorTransposeLowering enumValue) { + return stringifyVectorTransposeLowering(enumValue); +} + +template +::std::optional symbolizeEnum(::llvm::StringRef); + +template <> +inline ::std::optional symbolizeEnum(::llvm::StringRef str) { + return symbolizeVectorTransposeLowering(str); +} + +class VectorTransposeLoweringAttr : public ::mlir::IntegerAttr { +public: + using ValueType = VectorTransposeLowering; + using ::mlir::IntegerAttr::IntegerAttr; + static bool classof(::mlir::Attribute attr); + static VectorTransposeLoweringAttr get(::mlir::MLIRContext *context, VectorTransposeLowering val); + VectorTransposeLowering getValue() const; +}; +} // namespace vector +} // namespace mlir + +namespace mlir { +template +struct FieldParser; + +template<> +struct FieldParser<::mlir::vector::VectorTransposeLowering, ::mlir::vector::VectorTransposeLowering> { + template + static FailureOr<::mlir::vector::VectorTransposeLowering> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return parser.emitError(loc, "expected keyword for control the lowering of `vector.transpose` operations."); + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorTransposeLowering> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorTransposeLowering>(enumKeyword)) + return *attr; + return parser.emitError(loc, "expected one of [eltwise, flat_transpose, shuffle_1d, shuffle_16x16] for control the lowering of `vector.transpose` operations., got: ") << enumKeyword; + } +}; + +/// Support for std::optional, useful in attribute/type definition where the enum is +/// used as: +/// +/// let parameters = (ins OptionalParameter<"std::optional">:$value); +template<> +struct FieldParser, std::optional<::mlir::vector::VectorTransposeLowering>> { + template + static FailureOr> parse(ParserT &parser) { + // Parse the keyword/string containing the enum. + std::string enumKeyword; + auto loc = parser.getCurrentLocation(); + if (failed(parser.parseOptionalKeywordOrString(&enumKeyword))) + return std::optional<::mlir::vector::VectorTransposeLowering>{}; + + // Symbolize the keyword. + if (::std::optional<::mlir::vector::VectorTransposeLowering> attr = ::mlir::vector::symbolizeEnum<::mlir::vector::VectorTransposeLowering>(enumKeyword)) + return attr; + return parser.emitError(loc, "expected one of [eltwise, flat_transpose, shuffle_1d, shuffle_16x16] for control the lowering of `vector.transpose` operations., got: ") << enumKeyword; + } +}; +} // namespace mlir + +namespace llvm { +inline ::llvm::raw_ostream &operator<<(::llvm::raw_ostream &p, ::mlir::vector::VectorTransposeLowering value) { + auto valueStr = stringifyEnum(value); + return p << valueStr; +} +} // namespace llvm + +namespace llvm { +template<> struct DenseMapInfo<::mlir::vector::VectorTransposeLowering> { + using StorageInfo = ::llvm::DenseMapInfo; + + static inline ::mlir::vector::VectorTransposeLowering getEmptyKey() { + return static_cast<::mlir::vector::VectorTransposeLowering>(StorageInfo::getEmptyKey()); + } + + static inline ::mlir::vector::VectorTransposeLowering getTombstoneKey() { + return static_cast<::mlir::vector::VectorTransposeLowering>(StorageInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const ::mlir::vector::VectorTransposeLowering &val) { + return StorageInfo::getHashValue(static_cast(val)); + } + + static bool isEqual(const ::mlir::vector::VectorTransposeLowering &lhs, const ::mlir::vector::VectorTransposeLowering &rhs) { + return lhs == rhs; + } +}; +} + diff --git a/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Utils/VectorUtils.h b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Utils/VectorUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..6609b28d77b6cba469ba1a661225d7f2795e89e2 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/Dialect/Vector/Utils/VectorUtils.h @@ -0,0 +1,326 @@ +//===- VectorUtils.h - Vector Utilities -------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_DIALECT_VECTOR_UTILS_VECTORUTILS_H_ +#define MLIR_DIALECT_VECTOR_UTILS_VECTORUTILS_H_ + +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/Dialect/Utils/IndexingUtils.h" +#include "mlir/Dialect/Vector/IR/VectorOps.h" +#include "mlir/IR/BuiltinAttributes.h" +#include "mlir/Support/LLVM.h" + +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/TypeSwitch.h" + +namespace mlir { + +// Forward declarations. +class AffineMap; +class Block; +class Location; +class OpBuilder; +class Operation; +class ShapedType; +class Value; +class VectorType; +class VectorTransferOpInterface; + +namespace affine { +class AffineApplyOp; +class AffineForOp; +} // namespace affine + +namespace vector { +/// Helper function that creates a memref::DimOp or tensor::DimOp depending on +/// the type of `source`. +Value createOrFoldDimOp(OpBuilder &b, Location loc, Value source, int64_t dim); + +/// Returns two dims that are greater than one if the transposition is applied +/// on a 2D slice. Otherwise, returns a failure. +FailureOr> isTranspose2DSlice(vector::TransposeOp op); + +/// Return true if `vectorType` is a contiguous slice of `memrefType`. +/// +/// Only the N = vectorType.getRank() trailing dims of `memrefType` are +/// checked (the other dims are not relevant). Note that for `vectorType` to be +/// a contiguous slice of `memrefType`, the trailing dims of the latter have +/// to be contiguous - this is checked by looking at the corresponding strides. +/// +/// There might be some restriction on the leading dim of `VectorType`: +/// +/// Case 1. If all the trailing dims of `vectorType` match the trailing dims +/// of `memrefType` then the leading dim of `vectorType` can be +/// arbitrary. +/// +/// Ex. 1.1 contiguous slice, perfect match +/// vector<4x3x2xi32> from memref<5x4x3x2xi32> +/// Ex. 1.2 contiguous slice, the leading dim does not match (2 != 4) +/// vector<2x3x2xi32> from memref<5x4x3x2xi32> +/// +/// Case 2. If an "internal" dim of `vectorType` does not match the +/// corresponding trailing dim in `memrefType` then the remaining +/// leading dims of `vectorType` have to be 1 (the first non-matching +/// dim can be arbitrary). +/// +/// Ex. 2.1 non-contiguous slice, 2 != 3 and the leading dim != <1> +/// vector<2x2x2xi32> from memref<5x4x3x2xi32> +/// Ex. 2.2 contiguous slice, 2 != 3 and the leading dim == <1> +/// vector<1x2x2xi32> from memref<5x4x3x2xi32> +/// Ex. 2.3. contiguous slice, 2 != 3 and the leading dims == <1x1> +/// vector<1x1x2x2xi32> from memref<5x4x3x2xi32> +/// Ex. 2.4. non-contiguous slice, 2 != 3 and the leading dims != <1x1> +/// vector<2x1x2x2xi32> from memref<5x4x3x2xi32>) +bool isContiguousSlice(MemRefType memrefType, VectorType vectorType); + +/// Returns an iterator for all positions in the leading dimensions of `vType` +/// up to the `targetRank`. If any leading dimension before the `targetRank` is +/// scalable (so cannot be unrolled), it will return an iterator for positions +/// up to the first scalable dimension. +/// +/// If no leading dimensions can be unrolled an empty optional will be returned. +/// +/// Examples: +/// +/// For vType = vector<2x3x4> and targetRank = 1 +/// +/// The resulting iterator will yield: +/// [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2] +/// +/// For vType = vector<3x[4]x5> and targetRank = 0 +/// +/// The scalable dimension blocks unrolling so the iterator yields only: +/// [0], [1], [2] +/// +std::optional +createUnrollIterator(VectorType vType, int64_t targetRank = 1); + +/// Returns a functor (int64_t -> Value) which returns a constant vscale +/// multiple. +/// +/// Example: +/// ```c++ +/// auto createVscaleMultiple = makeVscaleConstantBuilder(rewriter, loc); +/// auto c4Vscale = createVscaleMultiple(4); // 4 * vector.vscale +/// ``` +inline auto makeVscaleConstantBuilder(PatternRewriter &rewriter, Location loc) { + Value vscale = nullptr; + return [loc, vscale, &rewriter](int64_t multiplier) mutable { + if (!vscale) + vscale = rewriter.create(loc); + return rewriter.create( + loc, vscale, rewriter.create(loc, multiplier)); + }; +} + +/// Returns a range over the dims (size and scalability) of a VectorType. +inline auto getDims(VectorType vType) { + return llvm::zip_equal(vType.getShape(), vType.getScalableDims()); +} + +/// A wrapper for getMixedSizes for vector.transfer_read and +/// vector.transfer_write Ops (for source and destination, respectively). +/// +/// Tensor and MemRef types implement their own, very similar version of +/// getMixedSizes. This method will call the appropriate version (depending on +/// `hasTensorSemantics`). It will also automatically extract the operand for +/// which to call it on (source for "read" and destination for "write" ops). +SmallVector getMixedSizesXfer(bool hasTensorSemantics, + Operation *xfer, + RewriterBase &rewriter); + +/// A pattern for ops that implement `MaskableOpInterface` and that _might_ be +/// masked (i.e. inside `vector.mask` Op region). In particular: +/// 1. Matches `SourceOp` operation, Op. +/// 2.1. If Op is masked, retrieves the masking Op, maskOp, and updates the +/// insertion point to avoid inserting new ops into the `vector.mask` Op +/// region (which only allows one Op). +/// 2.2 If Op is not masked, this step is skipped. +/// 3. Invokes `matchAndRewriteMaskableOp` on Op and optionally maskOp if +/// found in step 2.1. +/// +/// This wrapper frees patterns from re-implementing the logic to update the +/// insertion point when a maskable Op is masked. Such patterns are still +/// responsible for providing an updated ("rewritten") version of: +/// a. the source Op when mask _is not_ present, +/// b. the source Op and the masking Op when mask _is_ present. +/// To use this pattern, implement `matchAndRewriteMaskableOp`. Note that +/// the return value will depend on the case above. +template +struct MaskableOpRewritePattern : OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + +private: + LogicalResult matchAndRewrite(SourceOp sourceOp, + PatternRewriter &rewriter) const final { + auto maskableOp = dyn_cast(sourceOp.getOperation()); + if (!maskableOp) + return failure(); + + Operation *rootOp = sourceOp; + + // If this Op is masked, update the insertion point to avoid inserting into + // the vector.mask Op region. + OpBuilder::InsertionGuard guard(rewriter); + MaskingOpInterface maskOp; + if (maskableOp.isMasked()) { + maskOp = maskableOp.getMaskingOp(); + rewriter.setInsertionPoint(maskOp); + rootOp = maskOp; + } + + FailureOr newOp = + matchAndRewriteMaskableOp(sourceOp, maskOp, rewriter); + if (failed(newOp)) + return failure(); + + // Rewriting succeeded but there are no values to replace. + if (rootOp->getNumResults() == 0) { + rewriter.eraseOp(rootOp); + } else { + assert(*newOp != Value() && + "Cannot replace an op's use with an empty value."); + rewriter.replaceOp(rootOp, *newOp); + } + return success(); + } + +public: + // Matches `sourceOp` that can potentially be masked with `maskingOp`. If the + // latter is present, returns a replacement for `maskingOp`. Otherwise, + // returns a replacement for `sourceOp`. + virtual FailureOr + matchAndRewriteMaskableOp(SourceOp sourceOp, MaskingOpInterface maskingOp, + PatternRewriter &rewriter) const = 0; +}; + +/// Returns true if the input Vector type can be linearized. +/// +/// Linearization is meant in the sense of flattening vectors, e.g.: +/// * vector -> vector +/// In this sense, Vectors that are either: +/// * already linearized, or +/// * contain more than 1 scalable dimensions, +/// are not linearizable. +bool isLinearizableVector(VectorType type); + +/// Creates a TransferReadOp from `source`. +/// +/// The shape of the vector to read is specified via `inputVectorSizes`. If the +/// shape of the output vector differs from the shape of the value being read, +/// masking is used to avoid out-of-bounds accesses. Set +/// `useInBoundsInsteadOfMasking` to `true` to use the "in_bounds" attribute +/// instead of explicit masks. +/// +/// Note: all read offsets are set to 0. +Value createReadOrMaskedRead(OpBuilder &builder, Location loc, Value source, + ArrayRef inputVectorSizes, Value padValue, + bool useInBoundsInsteadOfMasking = false); + +/// Returns success if `inputVectorSizes` is a valid masking configuraion for +/// given `shape`, i.e., it meets: +/// 1. The numbers of elements in both array are equal. +/// 2. `inputVectorSizes` does not have dynamic dimensions. +/// 3. All the values in `inputVectorSizes` are greater than or equal to +/// static sizes in `shape`. +LogicalResult isValidMaskedInputVector(ArrayRef shape, + ArrayRef inputVectorSizes); +} // namespace vector + +/// Constructs a permutation map of invariant memref indices to vector +/// dimension. +/// +/// If no index is found to be invariant, 0 is added to the permutation_map and +/// corresponds to a vector broadcast along that dimension. +/// +/// The implementation uses the knowledge of the mapping of loops to +/// vector dimension. `loopToVectorDim` carries this information as a map with: +/// - keys representing "vectorized enclosing loops"; +/// - values representing the corresponding vector dimension. +/// Note that loopToVectorDim is a whole function map from which only enclosing +/// loop information is extracted. +/// +/// Prerequisites: `indices` belong to a vectorizable load or store operation +/// (i.e. at most one invariant index along each AffineForOp of +/// `loopToVectorDim`). `insertPoint` is the insertion point for the vectorized +/// load or store operation. +/// +/// Example 1: +/// The following MLIR snippet: +/// +/// ```mlir +/// affine.for %i3 = 0 to %0 { +/// affine.for %i4 = 0 to %1 { +/// affine.for %i5 = 0 to %2 { +/// %a5 = load %arg0[%i4, %i5, %i3] : memref +/// }}} +/// ``` +/// +/// may vectorize with {permutation_map: (d0, d1, d2) -> (d2, d1)} into: +/// +/// ```mlir +/// affine.for %i3 = 0 to %0 step 32 { +/// affine.for %i4 = 0 to %1 { +/// affine.for %i5 = 0 to %2 step 256 { +/// %4 = vector.transfer_read %arg0, %i4, %i5, %i3 +/// {permutation_map: (d0, d1, d2) -> (d2, d1)} : +/// (memref, index, index) -> vector<32x256xf32> +/// }}} +/// ``` +/// +/// Meaning that vector.transfer_read will be responsible for reading the slice: +/// `%arg0[%i4, %i5:%15+256, %i3:%i3+32]` into vector<32x256xf32>. +/// +/// Example 2: +/// The following MLIR snippet: +/// +/// ```mlir +/// %cst0 = arith.constant 0 : index +/// affine.for %i0 = 0 to %0 { +/// %a0 = load %arg0[%cst0, %cst0] : memref +/// } +/// ``` +/// +/// may vectorize with {permutation_map: (d0) -> (0)} into: +/// +/// ```mlir +/// affine.for %i0 = 0 to %0 step 128 { +/// %3 = vector.transfer_read %arg0, %c0_0, %c0_0 +/// {permutation_map: (d0, d1) -> (0)} : +/// (memref, index, index) -> vector<128xf32> +/// } +/// ```` +/// +/// Meaning that vector.transfer_read will be responsible of reading the slice +/// `%arg0[%c0, %c0]` into vector<128xf32> which needs a 1-D vector broadcast. +/// +AffineMap +makePermutationMap(Block *insertPoint, ArrayRef indices, + const DenseMap &loopToVectorDim); +AffineMap +makePermutationMap(Operation *insertPoint, ArrayRef indices, + const DenseMap &loopToVectorDim); + +namespace matcher { + +/// Matches vector.transfer_read, vector.transfer_write and ops that return a +/// vector type that is a multiple of the sub-vector type. This allows passing +/// over other smaller vector types in the function and avoids interfering with +/// operations on those. +/// This is a first approximation, it can easily be extended in the future. +/// TODO: this could all be much simpler if we added a bit that a vector type to +/// mark that a vector is a strict super-vector but it still does not warrant +/// adding even 1 extra bit in the IR for now. +bool operatesOnSuperVectorsOf(Operation &op, VectorType subVectorType); + +} // namespace matcher +} // namespace mlir + +#endif // MLIR_DIALECT_VECTOR_UTILS_VECTORUTILS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/CRunnerUtils.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/CRunnerUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..812f719e723eb38b8fc2cfd7d2cdea0b5e6fd5c1 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/CRunnerUtils.h @@ -0,0 +1,505 @@ +//===- CRunnerUtils.h - Utils for debugging MLIR execution ----------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file declares basic classes and functions to manipulate structured MLIR +// types at runtime. Entities in this file must be compliant with C++11 and be +// retargetable, including on targets without a C++ runtime. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_CRUNNERUTILS_H +#define MLIR_EXECUTIONENGINE_CRUNNERUTILS_H + +#ifdef _WIN32 +#ifndef MLIR_CRUNNERUTILS_EXPORT +#ifdef mlir_c_runner_utils_EXPORTS +// We are building this library +#define MLIR_CRUNNERUTILS_EXPORT __declspec(dllexport) +#define MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS +#else +// We are using this library +#define MLIR_CRUNNERUTILS_EXPORT __declspec(dllimport) +#endif // mlir_c_runner_utils_EXPORTS +#endif // MLIR_CRUNNERUTILS_EXPORT +#else // _WIN32 +// Non-windows: use visibility attributes. +#define MLIR_CRUNNERUTILS_EXPORT __attribute__((visibility("default"))) +#define MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS +#endif // _WIN32 + +#include +#include +#include +#include +#include + +//===----------------------------------------------------------------------===// +// Codegen-compatible structures for Vector type. +//===----------------------------------------------------------------------===// +namespace mlir { +namespace detail { + +constexpr bool isPowerOf2(int n) { return (!(n & (n - 1))); } + +constexpr unsigned nextPowerOf2(int n) { + return (n <= 1) ? 1 : (isPowerOf2(n) ? n : (2 * nextPowerOf2((n + 1) / 2))); +} + +template +struct Vector1D; + +template +struct Vector1D { + Vector1D() { + static_assert(detail::nextPowerOf2(sizeof(T[Dim])) == sizeof(T[Dim]), + "size error"); + } + inline T &operator[](unsigned i) { return vector[i]; } + inline const T &operator[](unsigned i) const { return vector[i]; } + +private: + T vector[Dim]; +}; + +// 1-D vector, padded to the next power of 2 allocation. +// Specialization occurs to avoid zero size arrays (which fail in -Werror). +template +struct Vector1D { + Vector1D() { + static_assert(nextPowerOf2(sizeof(T[Dim])) > sizeof(T[Dim]), "size error"); + static_assert(nextPowerOf2(sizeof(T[Dim])) < 2 * sizeof(T[Dim]), + "size error"); + } + inline T &operator[](unsigned i) { return vector[i]; } + inline const T &operator[](unsigned i) const { return vector[i]; } + +private: + T vector[Dim]; + char padding[nextPowerOf2(sizeof(T[Dim])) - sizeof(T[Dim])]; +}; +} // namespace detail +} // namespace mlir + +// N-D vectors recurse down to 1-D. +template +struct Vector { + inline Vector &operator[](unsigned i) { return vector[i]; } + inline const Vector &operator[](unsigned i) const { + return vector[i]; + } + +private: + Vector vector[Dim]; +}; + +// 1-D vectors in LLVM are automatically padded to the next power of 2. +// We insert explicit padding in to account for this. +template +struct Vector + : public mlir::detail::Vector1D { +}; + +template +using Vector1D = Vector; +template +using Vector2D = Vector; +template +using Vector3D = Vector; +template +using Vector4D = Vector; + +template +void dropFront(int64_t arr[N], int64_t *res) { + for (unsigned i = 1; i < N; ++i) + *(res + i - 1) = arr[i]; +} + +//===----------------------------------------------------------------------===// +// Codegen-compatible structures for StridedMemRef type. +//===----------------------------------------------------------------------===// +template +class StridedMemrefIterator; + +/// StridedMemRef descriptor type with static rank. +template +struct StridedMemRefType { + T *basePtr; + T *data; + int64_t offset; + int64_t sizes[N]; + int64_t strides[N]; + + template ().begin())> + T &operator[](Range &&indices) { + assert(indices.size() == N && + "indices should match rank in memref subscript"); + int64_t curOffset = offset; + for (int dim = N - 1; dim >= 0; --dim) { + int64_t currentIndex = *(indices.begin() + dim); + assert(currentIndex < sizes[dim] && "Index overflow"); + curOffset += currentIndex * strides[dim]; + } + return data[curOffset]; + } + + StridedMemrefIterator begin() { return {*this, offset}; } + StridedMemrefIterator end() { return {*this, -1}; } + + // This operator[] is extremely slow and only for sugaring purposes. + StridedMemRefType operator[](int64_t idx) { + StridedMemRefType res; + res.basePtr = basePtr; + res.data = data; + res.offset = offset + idx * strides[0]; + dropFront(sizes, res.sizes); + dropFront(strides, res.strides); + return res; + } +}; + +/// StridedMemRef descriptor type specialized for rank 1. +template +struct StridedMemRefType { + T *basePtr; + T *data; + int64_t offset; + int64_t sizes[1]; + int64_t strides[1]; + + template ().begin())> + T &operator[](Range indices) { + assert(indices.size() == 1 && + "indices should match rank in memref subscript"); + return (*this)[*indices.begin()]; + } + + StridedMemrefIterator begin() { return {*this, offset}; } + StridedMemrefIterator end() { return {*this, -1}; } + + T &operator[](int64_t idx) { return *(data + offset + idx * strides[0]); } +}; + +/// StridedMemRef descriptor type specialized for rank 0. +template +struct StridedMemRefType { + T *basePtr; + T *data; + int64_t offset; + + template ().begin())> + T &operator[](Range indices) { + assert((indices.size() == 0) && + "Expect empty indices for 0-rank memref subscript"); + return data[offset]; + } + + StridedMemrefIterator begin() { return {*this, offset}; } + StridedMemrefIterator end() { return {*this, offset + 1}; } +}; + +/// Iterate over all elements in a strided memref. +template +class StridedMemrefIterator { +public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T *; + using reference = T &; + + StridedMemrefIterator(StridedMemRefType &descriptor, + int64_t offset = 0) + : offset(offset), descriptor(&descriptor) {} + StridedMemrefIterator &operator++() { + int dim = Rank - 1; + while (dim >= 0 && indices[dim] == (descriptor->sizes[dim] - 1)) { + offset -= indices[dim] * descriptor->strides[dim]; + indices[dim] = 0; + --dim; + } + if (dim < 0) { + offset = -1; + return *this; + } + ++indices[dim]; + offset += descriptor->strides[dim]; + return *this; + } + + reference operator*() { return descriptor->data[offset]; } + pointer operator->() { return &descriptor->data[offset]; } + + const std::array &getIndices() { return indices; } + + bool operator==(const StridedMemrefIterator &other) const { + return other.offset == offset && other.descriptor == descriptor; + } + + bool operator!=(const StridedMemrefIterator &other) const { + return !(*this == other); + } + +private: + /// Offset in the buffer. This can be derived from the indices and the + /// descriptor. + int64_t offset = 0; + + /// Array of indices in the multi-dimensional memref. + std::array indices = {}; + + /// Descriptor for the strided memref. + StridedMemRefType *descriptor; +}; + +/// Iterate over all elements in a 0-ranked strided memref. +template +class StridedMemrefIterator { +public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T *; + using reference = T &; + + StridedMemrefIterator(StridedMemRefType &descriptor, int64_t offset = 0) + : elt(descriptor.data + offset) {} + + StridedMemrefIterator &operator++() { + ++elt; + return *this; + } + + reference operator*() { return *elt; } + pointer operator->() { return elt; } + + // There are no indices for a 0-ranked memref, but this API is provided for + // consistency with the general case. + const std::array &getIndices() { + // Since this is a 0-array of indices we can keep a single global const + // copy. + static const std::array indices = {}; + return indices; + } + + bool operator==(const StridedMemrefIterator &other) const { + return other.elt == elt; + } + + bool operator!=(const StridedMemrefIterator &other) const { + return !(*this == other); + } + +private: + /// Pointer to the single element in the zero-ranked memref. + T *elt; +}; + +//===----------------------------------------------------------------------===// +// Codegen-compatible structure for UnrankedMemRef type. +//===----------------------------------------------------------------------===// +// Unranked MemRef +template +struct UnrankedMemRefType { + int64_t rank; + void *descriptor; +}; + +//===----------------------------------------------------------------------===// +// DynamicMemRefType type. +//===----------------------------------------------------------------------===// +template +class DynamicMemRefIterator; + +// A reference to one of the StridedMemRef types. +template +class DynamicMemRefType { +public: + int64_t rank; + T *basePtr; + T *data; + int64_t offset; + const int64_t *sizes; + const int64_t *strides; + + explicit DynamicMemRefType(const StridedMemRefType &memRef) + : rank(0), basePtr(memRef.basePtr), data(memRef.data), + offset(memRef.offset), sizes(nullptr), strides(nullptr) {} + template + explicit DynamicMemRefType(const StridedMemRefType &memRef) + : rank(N), basePtr(memRef.basePtr), data(memRef.data), + offset(memRef.offset), sizes(memRef.sizes), strides(memRef.strides) {} + explicit DynamicMemRefType(const ::UnrankedMemRefType &memRef) + : rank(memRef.rank) { + auto *desc = static_cast *>(memRef.descriptor); + basePtr = desc->basePtr; + data = desc->data; + offset = desc->offset; + sizes = rank == 0 ? nullptr : desc->sizes; + strides = sizes + rank; + } + + template ().begin())> + T &operator[](Range &&indices) { + assert(indices.size() == rank && + "indices should match rank in memref subscript"); + if (rank == 0) + return data[offset]; + + int64_t curOffset = offset; + for (int dim = rank - 1; dim >= 0; --dim) { + int64_t currentIndex = *(indices.begin() + dim); + assert(currentIndex < sizes[dim] && "Index overflow"); + curOffset += currentIndex * strides[dim]; + } + return data[curOffset]; + } + + DynamicMemRefIterator begin() { return {*this, offset}; } + DynamicMemRefIterator end() { return {*this, -1}; } + + // This operator[] is extremely slow and only for sugaring purposes. + DynamicMemRefType operator[](int64_t idx) { + assert(rank > 0 && "can't make a subscript of a zero ranked array"); + + DynamicMemRefType res(*this); + --res.rank; + res.offset += idx * res.strides[0]; + ++res.sizes; + ++res.strides; + return res; + } + + // This operator* can be used in conjunction with the previous operator[] in + // order to access the underlying value in case of zero-ranked memref. + T &operator*() { + assert(rank == 0 && "not a zero-ranked memRef"); + return data[offset]; + } +}; + +/// Iterate over all elements in a dynamic memref. +template +class DynamicMemRefIterator { +public: + using iterator_category = std::forward_iterator_tag; + using value_type = T; + using difference_type = std::ptrdiff_t; + using pointer = T *; + using reference = T &; + + DynamicMemRefIterator(DynamicMemRefType &descriptor, int64_t offset = 0) + : offset(offset), descriptor(&descriptor) { + indices.resize(descriptor.rank, 0); + } + + DynamicMemRefIterator &operator++() { + if (descriptor->rank == 0) { + offset = -1; + return *this; + } + + int dim = descriptor->rank - 1; + + while (dim >= 0 && indices[dim] == (descriptor->sizes[dim] - 1)) { + offset -= indices[dim] * descriptor->strides[dim]; + indices[dim] = 0; + --dim; + } + + if (dim < 0) { + offset = -1; + return *this; + } + + ++indices[dim]; + offset += descriptor->strides[dim]; + return *this; + } + + reference operator*() { return descriptor->data[offset]; } + pointer operator->() { return &descriptor->data[offset]; } + + const std::vector &getIndices() { return indices; } + + bool operator==(const DynamicMemRefIterator &other) const { + return other.offset == offset && other.descriptor == descriptor; + } + + bool operator!=(const DynamicMemRefIterator &other) const { + return !(*this == other); + } + +private: + /// Offset in the buffer. This can be derived from the indices and the + /// descriptor. + int64_t offset = 0; + + /// Array of indices in the multi-dimensional memref. + std::vector indices = {}; + + /// Descriptor for the dynamic memref. + DynamicMemRefType *descriptor; +}; + +//===----------------------------------------------------------------------===// +// Small runtime support library for memref.copy lowering during codegen. +//===----------------------------------------------------------------------===// +extern "C" MLIR_CRUNNERUTILS_EXPORT void +memrefCopy(int64_t elemSize, ::UnrankedMemRefType *src, + ::UnrankedMemRefType *dst); + +//===----------------------------------------------------------------------===// +// Small runtime support library for vector.print lowering during codegen. +//===----------------------------------------------------------------------===// +extern "C" MLIR_CRUNNERUTILS_EXPORT void printI64(int64_t i); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printU64(uint64_t u); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printF32(float f); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printF64(double d); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printString(char const *s); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printOpen(); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printClose(); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printComma(); +extern "C" MLIR_CRUNNERUTILS_EXPORT void printNewline(); + +//===----------------------------------------------------------------------===// +// Small runtime support library for timing execution and printing GFLOPS +//===----------------------------------------------------------------------===// +extern "C" MLIR_CRUNNERUTILS_EXPORT void printFlops(double flops); +extern "C" MLIR_CRUNNERUTILS_EXPORT double rtclock(); + +//===----------------------------------------------------------------------===// +// Runtime support library for random number generation. +//===----------------------------------------------------------------------===// +// Uses a seed to initialize a random generator and returns the generator. +extern "C" MLIR_CRUNNERUTILS_EXPORT void *rtsrand(uint64_t s); +// Uses a random number generator g and returns a random number +// in the range of [0, m). +extern "C" MLIR_CRUNNERUTILS_EXPORT uint64_t rtrand(void *g, uint64_t m); +// Deletes the random number generator. +extern "C" MLIR_CRUNNERUTILS_EXPORT void rtdrand(void *g); +// Uses a random number generator g and std::shuffle to modify mref +// in place. Memref mref will be a permutation of all numbers +// in the range of [0, size of mref). +extern "C" MLIR_CRUNNERUTILS_EXPORT void +_mlir_ciface_shuffle(StridedMemRefType *mref, void *g); + +//===----------------------------------------------------------------------===// +// Runtime support library to allow the use of std::sort in MLIR program. +//===----------------------------------------------------------------------===// +extern "C" MLIR_CRUNNERUTILS_EXPORT void +_mlir_ciface_stdSortI64(uint64_t n, StridedMemRefType *vref); +extern "C" MLIR_CRUNNERUTILS_EXPORT void +_mlir_ciface_stdSortF64(uint64_t n, StridedMemRefType *vref); +extern "C" MLIR_CRUNNERUTILS_EXPORT void +_mlir_ciface_stdSortF32(uint64_t n, StridedMemRefType *vref); +#endif // MLIR_EXECUTIONENGINE_CRUNNERUTILS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/Float16bits.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/Float16bits.h new file mode 100644 index 0000000000000000000000000000000000000000..ad409841b2a927a47ff0e6120c4ce6e97e7de807 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/Float16bits.h @@ -0,0 +1,58 @@ +//===--- Float16bits.h - supports 2-byte floats ---------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements f16 and bf16 to support the compilation and execution +// of programs using these types. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_FLOAT16BITS_H_ +#define MLIR_EXECUTIONENGINE_FLOAT16BITS_H_ + +#include +#include + +#ifdef _WIN32 +#ifdef mlir_float16_utils_EXPORTS // We are building this library +#define MLIR_FLOAT16_EXPORT __declspec(dllexport) +#define MLIR_FLOAT16_DEFINE_FUNCTIONS +#else // We are using this library +#define MLIR_FLOAT16_EXPORT __declspec(dllimport) +#endif // mlir_float16_utils_EXPORTS +#else // Non-windows: use visibility attributes. +#define MLIR_FLOAT16_EXPORT __attribute__((visibility("default"))) +#define MLIR_FLOAT16_DEFINE_FUNCTIONS +#endif // _WIN32 + +// Implements half precision and bfloat with f16 and bf16, using the MLIR type +// names. These data types are also used for c-interface runtime routines. +extern "C" { +struct MLIR_FLOAT16_EXPORT f16 { + f16(float f = 0); + uint16_t bits; +}; + +struct MLIR_FLOAT16_EXPORT bf16 { + bf16(float f = 0); + uint16_t bits; +}; +} + +// Outputs a half precision value. +MLIR_FLOAT16_EXPORT std::ostream &operator<<(std::ostream &os, const f16 &f); +// Outputs a bfloat value. +MLIR_FLOAT16_EXPORT std::ostream &operator<<(std::ostream &os, const bf16 &d); + +MLIR_FLOAT16_EXPORT bool operator==(const f16 &f1, const f16 &f2); +MLIR_FLOAT16_EXPORT bool operator==(const bf16 &bf1, const bf16 &bf2); + +extern "C" MLIR_FLOAT16_EXPORT void printF16(uint16_t bits); +extern "C" MLIR_FLOAT16_EXPORT void printBF16(uint16_t bits); + +#undef MLIR_FLOAT16_EXPORT +#endif // MLIR_EXECUTIONENGINE_FLOAT16BITS_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/Msan.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/Msan.h new file mode 100644 index 0000000000000000000000000000000000000000..ee94660ae650c769f7539cc6f0e7833e372282af --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/Msan.h @@ -0,0 +1,35 @@ +//===- Msan.h - Utils related to the memory sanitizer ---------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file declares and defines macros related to msan. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_MSAN_H +#define MLIR_EXECUTIONENGINE_MSAN_H + +// Memory sanitizer currently can't be enabled for the jit-compiled code, and +// to suppress msan warnings we need to unpoison pointers and pointed-to +// datastructures before they can be accessed. + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#if __has_feature(memory_sanitizer) && !defined(MLIR_MEMORY_SANITIZER) +#define MLIR_MEMORY_SANITIZER +#endif + +#if defined(MLIR_MEMORY_SANITIZER) +#include +#define MLIR_MSAN_MEMORY_IS_INITIALIZED(p, s) __msan_unpoison((p), (s)) +#else // Memory sanitizer: OFF +#define MLIR_MSAN_MEMORY_IS_INITIALIZED(p, s) +#endif // MLIR_MEMORY_SANITIZER + +#endif // MLIR_EXECUTIONENGINE_MSAN_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/OptUtils.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/OptUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..4cee8c6d60ff11ee044190814148e66ed5167b73 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/OptUtils.h @@ -0,0 +1,39 @@ +//===- OptUtils.h - MLIR Execution Engine opt pass utilities ----*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file declares the utility functions to trigger LLVM optimizations from +// MLIR Execution Engine. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_OPTUTILS_H +#define MLIR_EXECUTIONENGINE_OPTUTILS_H + +#include +#include + +namespace llvm { +class Module; +class Error; +class TargetMachine; +} // namespace llvm + +namespace mlir { + +/// Create a module transformer function for MLIR ExecutionEngine that runs +/// LLVM IR passes corresponding to the given speed and size optimization +/// levels (e.g. -O2 or -Os). If not null, `targetMachine` is used to +/// initialize passes that provide target-specific information to the LLVM +/// optimizer. `targetMachine` must outlive the returned std::function. +std::function +makeOptimizingTransformer(unsigned optLevel, unsigned sizeLevel, + llvm::TargetMachine *targetMachine); + +} // namespace mlir + +#endif // MLIR_EXECUTIONENGINE_OPTUTILS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/ArithmeticUtils.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/ArithmeticUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..32b7d6ef1f668c318c96023ac84571d4ac179a20 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/ArithmeticUtils.h @@ -0,0 +1,133 @@ +//===- ArithmeticUtils.h - Arithmetic helper functions ----------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A collection of "safe" arithmetic helper methods. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_SPARSETENSOR_ARITHMETICUTILS_H +#define MLIR_EXECUTIONENGINE_SPARSETENSOR_ARITHMETICUTILS_H + +#include +#include +#include +#include + +namespace mlir { +namespace sparse_tensor { +namespace detail { + +//===----------------------------------------------------------------------===// +// +// Safe comparison functions. +// +// Variants of the `==`, `!=`, `<`, `<=`, `>`, and `>=` operators which +// are careful to ensure that negatives are always considered strictly +// less than non-negatives regardless of the signedness of the types of +// the two arguments. They are "safe" in that they guarantee to *always* +// give an output and that that output is correct; in particular this means +// they never use assertions or other mechanisms for "returning an error". +// +// These functions are C++17-compatible backports of the safe comparison +// functions added in C++20, and the implementations are based on the +// sample implementations provided by the standard: +// . +// +//===----------------------------------------------------------------------===// + +template +constexpr bool safelyEQ(T t, U u) noexcept { + using UT = std::make_unsigned_t; + using UU = std::make_unsigned_t; + if constexpr (std::is_signed_v == std::is_signed_v) + return t == u; + else if constexpr (std::is_signed_v) + return t < 0 ? false : static_cast(t) == u; + else + return u < 0 ? false : t == static_cast(u); +} + +template +constexpr bool safelyNE(T t, U u) noexcept { + return !safelyEQ(t, u); +} + +template +constexpr bool safelyLT(T t, U u) noexcept { + using UT = std::make_unsigned_t; + using UU = std::make_unsigned_t; + if constexpr (std::is_signed_v == std::is_signed_v) + return t < u; + else if constexpr (std::is_signed_v) + return t < 0 ? true : static_cast(t) < u; + else + return u < 0 ? false : t < static_cast(u); +} + +template +constexpr bool safelyGT(T t, U u) noexcept { + return safelyLT(u, t); +} + +template +constexpr bool safelyLE(T t, U u) noexcept { + return !safelyGT(t, u); +} + +template +constexpr bool safelyGE(T t, U u) noexcept { + return !safelyLT(t, u); +} + +//===----------------------------------------------------------------------===// +// +// Overflow checking functions. +// +// These functions use assertions to ensure correctness with respect to +// overflow/underflow. Unlike the "safe" functions above, these "checked" +// functions only guarantee that *if* they return an answer then that answer +// is correct. When assertions are enabled, they do their best to remain +// as fast as possible (since MLIR keeps assertions enabled by default, +// even for optimized builds). When assertions are disabled, they use the +// standard unchecked implementations. +// +//===----------------------------------------------------------------------===// + +/// A version of `static_cast` which checks for overflow/underflow. +/// The implementation avoids performing runtime assertions whenever +/// the types alone are sufficient to statically prove that overflow +/// cannot happen. +template +[[nodiscard]] inline To checkOverflowCast(From x) { + // Check the lower bound. (For when casting from signed types.) + constexpr To minTo = std::numeric_limits::min(); + constexpr From minFrom = std::numeric_limits::min(); + if constexpr (!safelyGE(minFrom, minTo)) + assert(safelyGE(x, minTo) && "cast would underflow"); + // Check the upper bound. + constexpr To maxTo = std::numeric_limits::max(); + constexpr From maxFrom = std::numeric_limits::max(); + if constexpr (!safelyLE(maxFrom, maxTo)) + assert(safelyLE(x, maxTo) && "cast would overflow"); + // Now do the cast itself. + return static_cast(x); +} + +/// A version of `operator*` on `uint64_t` which guards against overflows +/// (when assertions are enabled). +inline uint64_t checkedMul(uint64_t lhs, uint64_t rhs) { + assert((lhs == 0 || rhs <= std::numeric_limits::max() / lhs) && + "Integer overflow"); + return lhs * rhs; +} + +} // namespace detail +} // namespace sparse_tensor +} // namespace mlir + +#endif // MLIR_EXECUTIONENGINE_SPARSETENSOR_ARITHMETICUTILS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/COO.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/COO.h new file mode 100644 index 0000000000000000000000000000000000000000..721e9bc69adac2022f82997cf765e5cb2427addf --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/COO.h @@ -0,0 +1,150 @@ +//===- COO.h - Coordinate-scheme sparse tensor representation ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains a coordinate-scheme representation of sparse tensors. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_SPARSETENSOR_COO_H +#define MLIR_EXECUTIONENGINE_SPARSETENSOR_COO_H + +#include +#include +#include +#include +#include + +namespace mlir { +namespace sparse_tensor { + +/// An element of a sparse tensor in coordinate-scheme representation +/// (i.e., a pair of coordinates and value). For example, a rank-1 +/// vector element would look like +/// ({i}, a[i]) +/// and a rank-5 tensor element would look like +/// ({i,j,k,l,m}, a[i,j,k,l,m]) +/// +/// The coordinates are represented as a (non-owning) pointer into a +/// shared pool of coordinates, rather than being stored directly in this +/// object. This significantly improves performance because it reduces the +/// per-element memory footprint and centralizes the memory management for +/// coordinates. The only downside is that the coordinates themselves cannot +/// be retrieved without knowing the rank of the tensor to which this element +/// belongs (and that rank is not stored in this object). +template +struct Element final { + Element(const uint64_t *coords, V val) : coords(coords), value(val){}; + const uint64_t *coords; // pointer into shared coordinates pool + V value; +}; + +/// Closure object for `operator<` on `Element` with a given rank. +template +struct ElementLT final { + ElementLT(uint64_t rank) : rank(rank) {} + bool operator()(const Element &e1, const Element &e2) const { + for (uint64_t d = 0; d < rank; ++d) { + if (e1.coords[d] == e2.coords[d]) + continue; + return e1.coords[d] < e2.coords[d]; + } + return false; + } + const uint64_t rank; +}; + +/// A memory-resident sparse tensor in coordinate-scheme representation +/// (a collection of `Element`s). This data structure is used as an +/// intermediate representation, e.g., for reading sparse tensors from +/// external formats into memory. +template +class SparseTensorCOO final { +public: + /// Constructs a new coordinate-scheme sparse tensor with the given + /// sizes and an optional initial storage capacity. + explicit SparseTensorCOO(const std::vector &dimSizes, + uint64_t capacity = 0) + : SparseTensorCOO(dimSizes.size(), dimSizes.data(), capacity) {} + + /// Constructs a new coordinate-scheme sparse tensor with the given + /// sizes and an optional initial storage capacity. The size of the + /// dimSizes array is determined by dimRank. + explicit SparseTensorCOO(uint64_t dimRank, const uint64_t *dimSizes, + uint64_t capacity = 0) + : dimSizes(dimSizes, dimSizes + dimRank), isSorted(true) { + assert(dimRank > 0 && "Trivial shape is not supported"); + for (uint64_t d = 0; d < dimRank; ++d) + assert(dimSizes[d] > 0 && "Dimension size zero has trivial storage"); + if (capacity) { + elements.reserve(capacity); + coordinates.reserve(capacity * dimRank); + } + } + + /// Gets the dimension-rank of the tensor. + uint64_t getRank() const { return dimSizes.size(); } + + /// Gets the dimension-sizes array. + const std::vector &getDimSizes() const { return dimSizes; } + + /// Gets the elements array. + const std::vector> &getElements() const { return elements; } + + /// Returns the `operator<` closure object for the COO's element type. + ElementLT getElementLT() const { return ElementLT(getRank()); } + + /// Adds an element to the tensor. + void add(const std::vector &dimCoords, V val) { + const uint64_t *base = coordinates.data(); + const uint64_t size = coordinates.size(); + const uint64_t dimRank = getRank(); + assert(dimCoords.size() == dimRank && "Element rank mismatch"); + for (uint64_t d = 0; d < dimRank; ++d) { + assert(dimCoords[d] < dimSizes[d] && + "Coordinate is too large for the dimension"); + coordinates.push_back(dimCoords[d]); + } + // This base only changes if `coordinates` was reallocated. In which + // case, we need to correct all previous pointers into the vector. + // Note that this only happens if we did not set the initial capacity + // right, and then only for every internal vector reallocation (which + // with the doubling rule should only incur an amortized linear overhead). + const uint64_t *const newBase = coordinates.data(); + if (newBase != base) { + for (uint64_t i = 0, n = elements.size(); i < n; ++i) + elements[i].coords = newBase + (elements[i].coords - base); + base = newBase; + } + // Add the new element and update the sorted bit. + const Element addedElem(base + size, val); + if (!elements.empty() && isSorted) + isSorted = getElementLT()(elements.back(), addedElem); + elements.push_back(addedElem); + } + + /// Sorts elements lexicographically by coordinates. If a coordinate + /// is mapped to multiple values, then the relative order of those + /// values is unspecified. + void sort() { + if (isSorted) + return; + std::sort(elements.begin(), elements.end(), getElementLT()); + isSorted = true; + } + +private: + const std::vector dimSizes; // per-dimension sizes + std::vector> elements; // all COO elements + std::vector coordinates; // shared coordinate pool + bool isSorted; +}; + +} // namespace sparse_tensor +} // namespace mlir + +#endif // MLIR_EXECUTIONENGINE_SPARSETENSOR_COO_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/File.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/File.h new file mode 100644 index 0000000000000000000000000000000000000000..714e664dd0f4eb0db0bb0db8e7ee29cd8f0c452b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/File.h @@ -0,0 +1,366 @@ +//===- File.h - Reading sparse tensors from files ---------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file implements reading sparse tensor from files in one of the +// following external formats: +// +// (1) Matrix Market Exchange (MME): *.mtx +// https://math.nist.gov/MatrixMarket/formats.html +// +// (2) Formidable Repository of Open Sparse Tensors and Tools (FROSTT): *.tns +// http://frostt.io/tensors/file-formats.html +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_SPARSETENSOR_FILE_H +#define MLIR_EXECUTIONENGINE_SPARSETENSOR_FILE_H + +#include "mlir/ExecutionEngine/SparseTensor/MapRef.h" +#include "mlir/ExecutionEngine/SparseTensor/Storage.h" + +#include + +namespace mlir { +namespace sparse_tensor { + +namespace detail { + +template +struct is_complex final : public std::false_type {}; + +template +struct is_complex> final : public std::true_type {}; + +/// Returns an element-value of non-complex type. If `IsPattern` is true, +/// then returns an arbitrary value. If `IsPattern` is false, then +/// reads the value from the current line buffer beginning at `linePtr`. +template +inline std::enable_if_t::value, V> readValue(char **linePtr) { + // The external formats always store these numerical values with the type + // double, but we cast these values to the sparse tensor object type. + // For a pattern tensor, we arbitrarily pick the value 1 for all entries. + if constexpr (IsPattern) + return 1.0; + return strtod(*linePtr, linePtr); +} + +/// Returns an element-value of complex type. If `IsPattern` is true, +/// then returns an arbitrary value. If `IsPattern` is false, then reads +/// the value from the current line buffer beginning at `linePtr`. +template +inline std::enable_if_t::value, V> readValue(char **linePtr) { + // Read two values to make a complex. The external formats always store + // numerical values with the type double, but we cast these values to the + // sparse tensor object type. For a pattern tensor, we arbitrarily pick the + // value 1 for all entries. + if constexpr (IsPattern) + return V(1.0, 1.0); + double re = strtod(*linePtr, linePtr); + double im = strtod(*linePtr, linePtr); + // Avoiding brace-notation since that forbids narrowing to `float`. + return V(re, im); +} + +/// Returns an element-value. If `isPattern` is true, then returns an +/// arbitrary value. If `isPattern` is false, then reads the value from +/// the current line buffer beginning at `linePtr`. +template +inline V readValue(char **linePtr, bool isPattern) { + return isPattern ? readValue(linePtr) : readValue(linePtr); +} + +} // namespace detail + +//===----------------------------------------------------------------------===// +// +// Reader class. +// +//===----------------------------------------------------------------------===// + +/// This class abstracts over the information stored in file headers, +/// as well as providing the buffers and methods for parsing those headers. +class SparseTensorReader final { +public: + enum class ValueKind : uint8_t { + // The value before calling `readHeader`. + kInvalid = 0, + // Values that can be set by `readMMEHeader`. + kPattern = 1, + kReal = 2, + kInteger = 3, + kComplex = 4, + // The value set by `readExtFROSTTHeader`. + kUndefined = 5 + }; + + explicit SparseTensorReader(const char *filename) : filename(filename) { + assert(filename && "Received nullptr for filename"); + } + + // Disallows copying, to avoid duplicating the `file` pointer. + SparseTensorReader(const SparseTensorReader &) = delete; + SparseTensorReader &operator=(const SparseTensorReader &) = delete; + + /// Factory method to allocate a new reader, open the file, read the + /// header, and validate that the actual contents of the file match + /// the expected `dimShape` and `valTp`. + static SparseTensorReader *create(const char *filename, uint64_t dimRank, + const uint64_t *dimShape, + PrimaryType valTp) { + SparseTensorReader *reader = new SparseTensorReader(filename); + reader->openFile(); + reader->readHeader(); + if (!reader->canReadAs(valTp)) { + fprintf(stderr, + "Tensor element type %d not compatible with values in file %s\n", + static_cast(valTp), filename); + exit(1); + } + reader->assertMatchesShape(dimRank, dimShape); + return reader; + } + + // This dtor tries to avoid leaking the `file`. (Though it's better + // to call `closeFile` explicitly when possible, since there are + // circumstances where dtors are not called reliably.) + ~SparseTensorReader() { closeFile(); } + + /// Opens the file for reading. + void openFile(); + + /// Closes the file. + void closeFile(); + + /// Reads and parses the file's header. + void readHeader(); + + /// Returns the stored value kind. + ValueKind getValueKind() const { return valueKind_; } + + /// Checks if a header has been successfully read. + bool isValid() const { return valueKind_ != ValueKind::kInvalid; } + + /// Checks if the file's ValueKind can be converted into the given + /// tensor PrimaryType. Is only valid after parsing the header. + bool canReadAs(PrimaryType valTy) const; + + /// Gets the MME "pattern" property setting. Is only valid after + /// parsing the header. + bool isPattern() const { + assert(isValid() && "Attempt to isPattern() before readHeader()"); + return valueKind_ == ValueKind::kPattern; + } + + /// Gets the MME "symmetric" property setting. Is only valid after + /// parsing the header. + bool isSymmetric() const { + assert(isValid() && "Attempt to isSymmetric() before readHeader()"); + return isSymmetric_; + } + + /// Gets the dimension-rank of the tensor. Is only valid after parsing + /// the header. + uint64_t getRank() const { + assert(isValid() && "Attempt to getRank() before readHeader()"); + return idata[0]; + } + + /// Gets the number of stored elements. Is only valid after parsing + /// the header. + uint64_t getNSE() const { + assert(isValid() && "Attempt to getNSE() before readHeader()"); + return idata[1]; + } + + /// Gets the dimension-sizes array. The pointer itself is always + /// valid; however, the values stored therein are only valid after + /// parsing the header. + const uint64_t *getDimSizes() const { return idata + 2; } + + /// Safely gets the size of the given dimension. Is only valid + /// after parsing the header. + uint64_t getDimSize(uint64_t d) const { + assert(d < getRank() && "Dimension out of bounds"); + return idata[2 + d]; + } + + /// Asserts the shape subsumes the actual dimension sizes. Is only + /// valid after parsing the header. + void assertMatchesShape(uint64_t rank, const uint64_t *shape) const; + + /// Allocates a new sparse-tensor storage object with the given encoding, + /// initializes it by reading all the elements from the file, and then + /// closes the file. Templated on P, I, and V. + template + SparseTensorStorage * + readSparseTensor(uint64_t lvlRank, const uint64_t *lvlSizes, + const LevelType *lvlTypes, const uint64_t *dim2lvl, + const uint64_t *lvl2dim) { + const uint64_t dimRank = getRank(); + MapRef map(dimRank, lvlRank, dim2lvl, lvl2dim); + auto *lvlCOO = readCOO(map, lvlSizes); + auto *tensor = SparseTensorStorage::newFromCOO( + dimRank, getDimSizes(), lvlRank, lvlSizes, lvlTypes, dim2lvl, lvl2dim, + lvlCOO); + delete lvlCOO; + return tensor; + } + + /// Reads the COO tensor from the file, stores the coordinates and values to + /// the given buffers, returns a boolean value to indicate whether the COO + /// elements are sorted. + template + bool readToBuffers(uint64_t lvlRank, const uint64_t *dim2lvl, + const uint64_t *lvl2dim, C *lvlCoordinates, V *values); + +private: + /// Attempts to read a line from the file. + void readLine(); + + /// Reads the next line of the input file and parses the coordinates + /// into the `dimCoords` argument. Returns the position in the `line` + /// buffer where the element's value should be parsed from. + template + char *readCoords(C *dimCoords) { + readLine(); + // Local variable for tracking the parser's position in the `line` buffer. + char *linePtr = line; + for (uint64_t dimRank = getRank(), d = 0; d < dimRank; ++d) { + // Parse the 1-based coordinate. + uint64_t c = strtoul(linePtr, &linePtr, 10); + // Store the 0-based coordinate. + dimCoords[d] = static_cast(c - 1); + } + return linePtr; + } + + /// Reads all the elements from the file while applying the given map. + template + SparseTensorCOO *readCOO(const MapRef &map, const uint64_t *lvlSizes); + + /// The implementation of `readCOO` that is templated `IsPattern` in order + /// to perform LICM without needing to duplicate the source code. + template + void readCOOLoop(const MapRef &map, SparseTensorCOO *coo); + + /// The internal implementation of `readToBuffers`. We template over + /// `IsPattern` in order to perform LICM without needing to duplicate + /// the source code. + template + bool readToBuffersLoop(const MapRef &map, C *lvlCoordinates, V *values); + + /// Reads the MME header of a general sparse matrix of type real. + void readMMEHeader(); + + /// Reads the "extended" FROSTT header. Although not part of the + /// documented format, we assume that the file starts with optional + /// comments followed by two lines that define the rank, the number of + /// nonzeros, and the dimensions sizes (one per rank) of the sparse tensor. + void readExtFROSTTHeader(); + + static constexpr int kColWidth = 1025; + const char *const filename; + FILE *file = nullptr; + ValueKind valueKind_ = ValueKind::kInvalid; + bool isSymmetric_ = false; + uint64_t idata[512]; + char line[kColWidth]; +}; + +//===----------------------------------------------------------------------===// +// +// Reader class methods. +// +//===----------------------------------------------------------------------===// + +template +SparseTensorCOO *SparseTensorReader::readCOO(const MapRef &map, + const uint64_t *lvlSizes) { + assert(isValid() && "Attempt to readCOO() before readHeader()"); + // Prepare a COO object with the number of stored elems as initial capacity. + auto *coo = new SparseTensorCOO(map.getLvlRank(), lvlSizes, getNSE()); + // Enter the reading loop. + if (isPattern()) + readCOOLoop(map, coo); + else + readCOOLoop(map, coo); + // Close the file and return the COO. + closeFile(); + return coo; +} + +template +void SparseTensorReader::readCOOLoop(const MapRef &map, + SparseTensorCOO *coo) { + const uint64_t dimRank = map.getDimRank(); + const uint64_t lvlRank = map.getLvlRank(); + assert(dimRank == getRank()); + std::vector dimCoords(dimRank); + std::vector lvlCoords(lvlRank); + for (uint64_t k = 0, nse = getNSE(); k < nse; k++) { + char *linePtr = readCoords(dimCoords.data()); + const V value = detail::readValue(&linePtr); + map.pushforward(dimCoords.data(), lvlCoords.data()); + coo->add(lvlCoords, value); + } +} + +template +bool SparseTensorReader::readToBuffers(uint64_t lvlRank, + const uint64_t *dim2lvl, + const uint64_t *lvl2dim, + C *lvlCoordinates, V *values) { + assert(isValid() && "Attempt to readCOO() before readHeader()"); + MapRef map(getRank(), lvlRank, dim2lvl, lvl2dim); + bool isSorted = + isPattern() ? readToBuffersLoop(map, lvlCoordinates, values) + : readToBuffersLoop(map, lvlCoordinates, values); + closeFile(); + return isSorted; +} + +template +bool SparseTensorReader::readToBuffersLoop(const MapRef &map, C *lvlCoordinates, + V *values) { + const uint64_t dimRank = map.getDimRank(); + const uint64_t lvlRank = map.getLvlRank(); + const uint64_t nse = getNSE(); + assert(dimRank == getRank()); + std::vector dimCoords(dimRank); + bool isSorted = false; + char *linePtr; + const auto readNextElement = [&]() { + linePtr = readCoords(dimCoords.data()); + map.pushforward(dimCoords.data(), lvlCoordinates); + *values = detail::readValue(&linePtr); + if (isSorted) { + // Note that isSorted is set to false when reading the first element, + // to guarantee the safeness of using prevLvlCoords. + C *prevLvlCoords = lvlCoordinates - lvlRank; + for (uint64_t l = 0; l < lvlRank; ++l) { + if (prevLvlCoords[l] != lvlCoordinates[l]) { + if (prevLvlCoords[l] > lvlCoordinates[l]) + isSorted = false; + break; + } + } + } + lvlCoordinates += lvlRank; + ++values; + }; + readNextElement(); + isSorted = true; + for (uint64_t n = 1; n < nse; ++n) + readNextElement(); + return isSorted; +} + +} // namespace sparse_tensor +} // namespace mlir + +#endif // MLIR_EXECUTIONENGINE_SPARSETENSOR_FILE_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/MapRef.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/MapRef.h new file mode 100644 index 0000000000000000000000000000000000000000..b0653913ff89d001116e302bc9458124fc76f4b9 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/MapRef.h @@ -0,0 +1,101 @@ +//===- MapRef.h - A dim2lvl/lvl2dim map encoding ----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// A dim2lvl/lvl2dim map encoding class, with utility methods. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_SPARSETENSOR_MAPREF_H +#define MLIR_EXECUTIONENGINE_SPARSETENSOR_MAPREF_H + +#include + +#include + +namespace mlir { +namespace sparse_tensor { + +/// A class for capturing the sparse tensor type map with a compact encoding. +/// +/// Currently, the following situations are supported: +/// (1) map is a permutation +/// (2) map has affine ops (restricted set) +/// +/// The pushforward/backward operations are fast for (1) but incur some obvious +/// overhead for situation (2). +/// +class MapRef final { +public: + MapRef(uint64_t d, uint64_t l, const uint64_t *d2l, const uint64_t *l2d); + + // + // Push forward maps from dimensions to levels. + // + + // Map from dimRank in to lvlRank out. + template + inline void pushforward(const T *in, T *out) const { + if (isPermutation) { + for (uint64_t l = 0; l < lvlRank; l++) { + out[l] = in[dim2lvl[l]]; + } + } else { + uint64_t i, c; + for (uint64_t l = 0; l < lvlRank; l++) + if (isFloor(l, i, c)) { + out[l] = in[i] / c; + } else if (isMod(l, i, c)) { + out[l] = in[i] % c; + } else { + out[l] = in[dim2lvl[l]]; + } + } + } + + // + // Push backward maps from levels to dimensions. + // + + // Map from lvlRank in to dimRank out. + template + inline void pushbackward(const T *in, T *out) const { + if (isPermutation) { + for (uint64_t d = 0; d < dimRank; d++) + out[d] = in[lvl2dim[d]]; + } else { + uint64_t i, c, ii; + for (uint64_t d = 0; d < dimRank; d++) + if (isMul(d, i, c, ii)) { + out[d] = in[i] + c * in[ii]; + } else { + out[d] = in[lvl2dim[d]]; + } + } + } + + uint64_t getDimRank() const { return dimRank; } + uint64_t getLvlRank() const { return lvlRank; } + +private: + bool isPermutationMap() const; + + bool isFloor(uint64_t l, uint64_t &i, uint64_t &c) const; + bool isMod(uint64_t l, uint64_t &i, uint64_t &c) const; + bool isMul(uint64_t d, uint64_t &i, uint64_t &c, uint64_t &ii) const; + + const uint64_t dimRank; + const uint64_t lvlRank; + const uint64_t *const dim2lvl; // non-owning pointer + const uint64_t *const lvl2dim; // non-owning pointer + const bool isPermutation; +}; + +} // namespace sparse_tensor +} // namespace mlir + +#endif // MLIR_EXECUTIONENGINE_SPARSETENSOR_MAPREF_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/Storage.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/Storage.h new file mode 100644 index 0000000000000000000000000000000000000000..80e3fec22694fbfdb0064770aa6cbe8c35172ffc --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensor/Storage.h @@ -0,0 +1,742 @@ +//===- Storage.h - TACO-flavored sparse tensor representation ---*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains definitions for the following classes: +// +// * `SparseTensorStorageBase` +// * `SparseTensorStorage` +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_SPARSETENSOR_STORAGE_H +#define MLIR_EXECUTIONENGINE_SPARSETENSOR_STORAGE_H + +#include "mlir/Dialect/SparseTensor/IR/Enums.h" +#include "mlir/ExecutionEngine/Float16bits.h" +#include "mlir/ExecutionEngine/SparseTensor/ArithmeticUtils.h" +#include "mlir/ExecutionEngine/SparseTensor/COO.h" +#include "mlir/ExecutionEngine/SparseTensor/MapRef.h" + +namespace mlir { +namespace sparse_tensor { + +//===----------------------------------------------------------------------===// +// +// SparseTensorStorage Classes +// +//===----------------------------------------------------------------------===// + +/// Abstract base class for `SparseTensorStorage`. This class +/// takes responsibility for all the ``-independent aspects +/// of the tensor (e.g., sizes, sparsity, mapping). In addition, +/// we use function overloading to implement "partial" method +/// specialization, which the C-API relies on to catch type errors +/// arising from our use of opaque pointers. +/// +/// Because this class forms a bridge between the denotational semantics +/// of "tensors" and the operational semantics of how we store and +/// compute with them, it also distinguishes between two different +/// coordinate spaces (and their associated rank, sizes, etc). +/// Denotationally, we have the *dimensions* of the tensor represented +/// by this object. Operationally, we have the *levels* of the storage +/// representation itself. +/// +/// The *size* of an axis is the cardinality of possible coordinate +/// values along that axis (regardless of which coordinates have stored +/// element values). As such, each size must be non-zero since if any +/// axis has size-zero then the whole tensor would have trivial storage +/// (since there are no possible coordinates). Thus we use the plural +/// term *sizes* for a collection of non-zero cardinalities, and use +/// this term whenever referring to run-time cardinalities. Whereas we +/// use the term *shape* for a collection of compile-time cardinalities, +/// where zero is used to indicate cardinalities which are dynamic (i.e., +/// unknown/unspecified at compile-time). At run-time, these dynamic +/// cardinalities will be inferred from or checked against sizes otherwise +/// specified. Thus, dynamic cardinalities always have an "immutable but +/// unknown" value; so the term "dynamic" should not be taken to indicate +/// run-time mutability. +class SparseTensorStorageBase { +protected: + SparseTensorStorageBase(const SparseTensorStorageBase &) = default; + SparseTensorStorageBase &operator=(const SparseTensorStorageBase &) = delete; + +public: + /// Constructs a new sparse-tensor storage object with the given encoding. + SparseTensorStorageBase(uint64_t dimRank, const uint64_t *dimSizes, + uint64_t lvlRank, const uint64_t *lvlSizes, + const LevelType *lvlTypes, const uint64_t *dim2lvl, + const uint64_t *lvl2dim); + virtual ~SparseTensorStorageBase() = default; + + /// Gets the number of tensor-dimensions. + uint64_t getDimRank() const { return dimSizes.size(); } + + /// Gets the number of storage-levels. + uint64_t getLvlRank() const { return lvlSizes.size(); } + + /// Gets the tensor-dimension sizes array. + const std::vector &getDimSizes() const { return dimSizes; } + + /// Safely looks up the size of the given tensor-dimension. + uint64_t getDimSize(uint64_t d) const { + assert(d < getDimRank()); + return dimSizes[d]; + } + + /// Gets the storage-level sizes array. + const std::vector &getLvlSizes() const { return lvlSizes; } + + /// Safely looks up the size of the given storage-level. + uint64_t getLvlSize(uint64_t l) const { + assert(l < getLvlRank()); + return lvlSizes[l]; + } + + /// Gets the level-types array. + const std::vector &getLvlTypes() const { return lvlTypes; } + + /// Safely looks up the type of the given level. + LevelType getLvlType(uint64_t l) const { + assert(l < getLvlRank()); + return lvlTypes[l]; + } + + /// Safely checks if the level uses dense storage. + bool isDenseLvl(uint64_t l) const { return isDenseLT(getLvlType(l)); } + + /// Safely checks if the level uses compressed storage. + bool isCompressedLvl(uint64_t l) const { + return isCompressedLT(getLvlType(l)); + } + + /// Safely checks if the level uses loose compressed storage. + bool isLooseCompressedLvl(uint64_t l) const { + return isLooseCompressedLT(getLvlType(l)); + } + + /// Safely checks if the level uses singleton storage. + bool isSingletonLvl(uint64_t l) const { return isSingletonLT(getLvlType(l)); } + + /// Safely checks if the level uses n out of m storage. + bool isNOutOfMLvl(uint64_t l) const { return isNOutOfMLT(getLvlType(l)); } + + /// Safely checks if the level is ordered. + bool isOrderedLvl(uint64_t l) const { return isOrderedLT(getLvlType(l)); } + + /// Safely checks if the level is unique. + bool isUniqueLvl(uint64_t l) const { return isUniqueLT(getLvlType(l)); } + + /// Gets positions-overhead storage for the given level. +#define DECL_GETPOSITIONS(PNAME, P) \ + virtual void getPositions(std::vector

**, uint64_t); + MLIR_SPARSETENSOR_FOREVERY_FIXED_O(DECL_GETPOSITIONS) +#undef DECL_GETPOSITIONS + + /// Gets coordinates-overhead storage for the given level. +#define DECL_GETCOORDINATES(INAME, C) \ + virtual void getCoordinates(std::vector **, uint64_t); + MLIR_SPARSETENSOR_FOREVERY_FIXED_O(DECL_GETCOORDINATES) +#undef DECL_GETCOORDINATES + + /// Gets coordinates-overhead storage buffer for the given level. +#define DECL_GETCOORDINATESBUFFER(INAME, C) \ + virtual void getCoordinatesBuffer(std::vector **, uint64_t); + MLIR_SPARSETENSOR_FOREVERY_FIXED_O(DECL_GETCOORDINATESBUFFER) +#undef DECL_GETCOORDINATESBUFFER + + /// Gets primary storage. +#define DECL_GETVALUES(VNAME, V) virtual void getValues(std::vector **); + MLIR_SPARSETENSOR_FOREVERY_V(DECL_GETVALUES) +#undef DECL_GETVALUES + + /// Element-wise insertion in lexicographic coordinate order. The first + /// argument is the level-coordinates for the value being inserted. +#define DECL_LEXINSERT(VNAME, V) virtual void lexInsert(const uint64_t *, V); + MLIR_SPARSETENSOR_FOREVERY_V(DECL_LEXINSERT) +#undef DECL_LEXINSERT + + /// Expanded insertion. Note that this method resets the + /// values/filled-switch array back to all-zero/false while only + /// iterating over the nonzero elements. +#define DECL_EXPINSERT(VNAME, V) \ + virtual void expInsert(uint64_t *, V *, bool *, uint64_t *, uint64_t, \ + uint64_t); + MLIR_SPARSETENSOR_FOREVERY_V(DECL_EXPINSERT) +#undef DECL_EXPINSERT + + /// Finalizes lexicographic insertions. + virtual void endLexInsert() = 0; + +private: + const std::vector dimSizes; + const std::vector lvlSizes; + const std::vector lvlTypes; + const std::vector dim2lvlVec; + const std::vector lvl2dimVec; + +protected: + const MapRef map; // non-owning pointers into dim2lvl/lvl2dim vectors + const bool allDense; +}; + +/// A memory-resident sparse tensor using a storage scheme based on +/// per-level sparse/dense annotations. This data structure provides +/// a bufferized form of a sparse tensor type. In contrast to generating +/// setup methods for each differently annotated sparse tensor, this +/// method provides a convenient "one-size-fits-all" solution that simply +/// takes an input tensor and annotations to implement all required setup +/// in a general manner. +template +class SparseTensorStorage final : public SparseTensorStorageBase { + /// Private constructor to share code between the other constructors. + /// Beware that the object is not necessarily guaranteed to be in a + /// valid state after this constructor alone; e.g., `isCompressedLvl(l)` + /// doesn't entail `!(positions[l].empty())`. + SparseTensorStorage(uint64_t dimRank, const uint64_t *dimSizes, + uint64_t lvlRank, const uint64_t *lvlSizes, + const LevelType *lvlTypes, const uint64_t *dim2lvl, + const uint64_t *lvl2dim) + : SparseTensorStorageBase(dimRank, dimSizes, lvlRank, lvlSizes, lvlTypes, + dim2lvl, lvl2dim), + positions(lvlRank), coordinates(lvlRank), lvlCursor(lvlRank) {} + +public: + /// Constructs a sparse tensor with the given encoding, and allocates + /// overhead storage according to some simple heuristics. When lvlCOO + /// is set, the sparse tensor initializes with the contents from that + /// data structure. Otherwise, an empty sparse tensor results. + SparseTensorStorage(uint64_t dimRank, const uint64_t *dimSizes, + uint64_t lvlRank, const uint64_t *lvlSizes, + const LevelType *lvlTypes, const uint64_t *dim2lvl, + const uint64_t *lvl2dim, SparseTensorCOO *lvlCOO); + + /// Constructs a sparse tensor with the given encoding, and initializes + /// the contents from the level buffers. The constructor assumes that the + /// data provided by `lvlBufs` can be directly used to interpret the result + /// sparse tensor and performs no integrity test on the input data. + SparseTensorStorage(uint64_t dimRank, const uint64_t *dimSizes, + uint64_t lvlRank, const uint64_t *lvlSizes, + const LevelType *lvlTypes, const uint64_t *dim2lvl, + const uint64_t *lvl2dim, const intptr_t *lvlBufs); + + /// Allocates a new empty sparse tensor. + static SparseTensorStorage * + newEmpty(uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim); + + /// Allocates a new sparse tensor and initializes it from the given COO. + static SparseTensorStorage * + newFromCOO(uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim, + SparseTensorCOO *lvlCOO); + + /// Allocates a new sparse tensor and initialize it from the given buffers. + static SparseTensorStorage * + newFromBuffers(uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim, + uint64_t srcRank, const intptr_t *buffers); + + ~SparseTensorStorage() final = default; + + /// Partially specialize these getter methods based on template types. + void getPositions(std::vector

**out, uint64_t lvl) final { + assert(out && "Received nullptr for out parameter"); + assert(lvl < getLvlRank()); + *out = &positions[lvl]; + } + void getCoordinates(std::vector **out, uint64_t lvl) final { + assert(out && "Received nullptr for out parameter"); + assert(lvl < getLvlRank()); + *out = &coordinates[lvl]; + } + void getCoordinatesBuffer(std::vector **out, uint64_t lvl) final { + assert(out && "Received nullptr for out parameter"); + assert(lvl < getLvlRank()); + // Note that the sparse tensor support library always stores COO in SoA + // format, even when AoS is requested. This is never an issue, since all + // actual code/library generation requests "views" into the coordinate + // storage for the individual levels, which is trivially provided for + // both AoS and SoA (as well as all the other storage formats). The only + // exception is when the buffer version of coordinate storage is requested + // (currently only for printing). In that case, we do the following + // potentially expensive transformation to provide that view. If this + // operation becomes more common beyond debugging, we should consider + // implementing proper AoS in the support library as well. + uint64_t lvlRank = getLvlRank(); + uint64_t nnz = values.size(); + crdBuffer.clear(); + crdBuffer.reserve(nnz * (lvlRank - lvl)); + for (uint64_t i = 0; i < nnz; i++) { + for (uint64_t l = lvl; l < lvlRank; l++) { + assert(i < coordinates[l].size()); + crdBuffer.push_back(coordinates[l][i]); + } + } + *out = &crdBuffer; + } + void getValues(std::vector **out) final { + assert(out && "Received nullptr for out parameter"); + *out = &values; + } + + /// Partially specialize lexicographical insertions based on template types. + void lexInsert(const uint64_t *lvlCoords, V val) final { + assert(lvlCoords); + if (allDense) { + uint64_t lvlRank = getLvlRank(); + uint64_t valIdx = 0; + // Linearize the address. + for (uint64_t l = 0; l < lvlRank; l++) + valIdx = valIdx * getLvlSize(l) + lvlCoords[l]; + values[valIdx] = val; + return; + } + // First, wrap up pending insertion path. + uint64_t diffLvl = 0; + uint64_t full = 0; + if (!values.empty()) { + diffLvl = lexDiff(lvlCoords); + endPath(diffLvl + 1); + full = lvlCursor[diffLvl] + 1; + } + // Then continue with insertion path. + insPath(lvlCoords, diffLvl, full, val); + } + + /// Partially specialize expanded insertions based on template types. + void expInsert(uint64_t *lvlCoords, V *values, bool *filled, uint64_t *added, + uint64_t count, uint64_t expsz) final { + assert((lvlCoords && values && filled && added) && "Received nullptr"); + if (count == 0) + return; + // Sort. + std::sort(added, added + count); + // Restore insertion path for first insert. + const uint64_t lastLvl = getLvlRank() - 1; + uint64_t c = added[0]; + assert(c <= expsz); + assert(filled[c] && "added coordinate is not filled"); + lvlCoords[lastLvl] = c; + lexInsert(lvlCoords, values[c]); + values[c] = 0; + filled[c] = false; + // Subsequent insertions are quick. + for (uint64_t i = 1; i < count; i++) { + assert(c < added[i] && "non-lexicographic insertion"); + c = added[i]; + assert(c <= expsz); + assert(filled[c] && "added coordinate is not filled"); + lvlCoords[lastLvl] = c; + insPath(lvlCoords, lastLvl, added[i - 1] + 1, values[c]); + values[c] = 0; + filled[c] = false; + } + } + + /// Finalizes lexicographic insertions. + void endLexInsert() final { + if (!allDense) { + if (values.empty()) + finalizeSegment(0); + else + endPath(0); + } + } + + /// Sort the unordered tensor in place, the method assumes that it is + /// an unordered COO tensor. + void sortInPlace() { + uint64_t nnz = values.size(); +#ifndef NDEBUG + for (uint64_t l = 0; l < getLvlRank(); l++) + assert(nnz == coordinates[l].size()); +#endif + + // In-place permutation. + auto applyPerm = [this](std::vector &perm) { + uint64_t length = perm.size(); + uint64_t lvlRank = getLvlRank(); + // Cache for the current level coordinates. + std::vector

lvlCrds(lvlRank); + for (uint64_t i = 0; i < length; i++) { + uint64_t current = i; + if (i != perm[current]) { + for (uint64_t l = 0; l < lvlRank; l++) + lvlCrds[l] = coordinates[l][i]; + V val = values[i]; + // Deals with a permutation cycle. + while (i != perm[current]) { + uint64_t next = perm[current]; + // Swaps the level coordinates and value. + for (uint64_t l = 0; l < lvlRank; l++) + coordinates[l][current] = coordinates[l][next]; + values[current] = values[next]; + perm[current] = current; + current = next; + } + for (uint64_t l = 0; l < lvlRank; l++) + coordinates[l][current] = lvlCrds[l]; + values[current] = val; + perm[current] = current; + } + } + }; + + std::vector sortedIdx(nnz, 0); + for (uint64_t i = 0; i < nnz; i++) + sortedIdx[i] = i; + + std::sort(sortedIdx.begin(), sortedIdx.end(), + [this](uint64_t lhs, uint64_t rhs) { + for (uint64_t l = 0; l < getLvlRank(); l++) { + if (coordinates[l][lhs] == coordinates[l][rhs]) + continue; + return coordinates[l][lhs] < coordinates[l][rhs]; + } + assert(lhs == rhs && "duplicate coordinates"); + return false; + }); + + applyPerm(sortedIdx); + } + +private: + /// Appends coordinate `crd` to level `lvl`, in the semantically + /// general sense. For non-dense levels, that means appending to the + /// `coordinates[lvl]` array, checking that `crd` is representable in + /// the `C` type; however, we do not verify other semantic requirements + /// (e.g., that `crd` is in bounds for `lvlSizes[lvl]`, and not previously + /// occurring in the same segment). For dense levels, this method instead + /// appends the appropriate number of zeros to the `values` array, where + /// `full` is the number of "entries" already written to `values` for this + /// segment (aka one after the highest coordinate previously appended). + void appendCrd(uint64_t lvl, uint64_t full, uint64_t crd) { + if (!isDenseLvl(lvl)) { + assert(isCompressedLvl(lvl) || isLooseCompressedLvl(lvl) || + isSingletonLvl(lvl) || isNOutOfMLvl(lvl)); + coordinates[lvl].push_back(detail::checkOverflowCast(crd)); + } else { // Dense level. + assert(crd >= full && "Coordinate was already filled"); + if (crd == full) + return; // Short-circuit, since it'll be a nop. + if (lvl + 1 == getLvlRank()) + values.insert(values.end(), crd - full, 0); + else + finalizeSegment(lvl + 1, 0, crd - full); + } + } + + /// Computes the assembled-size associated with the `l`-th level, + /// given the assembled-size associated with the `(l-1)`-th level. + uint64_t assembledSize(uint64_t parentSz, uint64_t l) const { + if (isCompressedLvl(l)) + return positions[l][parentSz]; + if (isLooseCompressedLvl(l)) + return positions[l][2 * parentSz - 1]; + if (isSingletonLvl(l) || isNOutOfMLvl(l)) + return parentSz; // new size same as the parent + assert(isDenseLvl(l)); + return parentSz * getLvlSize(l); + } + + /// Initializes sparse tensor storage scheme from a memory-resident sparse + /// tensor in coordinate scheme. This method prepares the positions and + /// coordinates arrays under the given per-level dense/sparse annotations. + void fromCOO(const std::vector> &lvlElements, uint64_t lo, + uint64_t hi, uint64_t l) { + const uint64_t lvlRank = getLvlRank(); + assert(l <= lvlRank && hi <= lvlElements.size()); + // Once levels are exhausted, insert the numerical values. + if (l == lvlRank) { + assert(lo < hi); + values.push_back(lvlElements[lo].value); + return; + } + // Visit all elements in this interval. + uint64_t full = 0; + while (lo < hi) { // If `hi` is unchanged, then `lo < lvlElements.size()`. + // Find segment in interval with same coordinate at this level. + const uint64_t c = lvlElements[lo].coords[l]; + uint64_t seg = lo + 1; + if (isUniqueLvl(l)) + while (seg < hi && lvlElements[seg].coords[l] == c) + seg++; + // Handle segment in interval for sparse or dense level. + appendCrd(l, full, c); + full = c + 1; + fromCOO(lvlElements, lo, seg, l + 1); + // And move on to next segment in interval. + lo = seg; + } + // Finalize the sparse position structure at this level. + finalizeSegment(l, full); + } + + /// Finalizes the sparse position structure at this level. + void finalizeSegment(uint64_t l, uint64_t full = 0, uint64_t count = 1) { + if (count == 0) + return; // Short-circuit, since it'll be a nop. + if (isCompressedLvl(l)) { + uint64_t pos = coordinates[l].size(); + positions[l].insert(positions[l].end(), count, + detail::checkOverflowCast

(pos)); + } else if (isLooseCompressedLvl(l)) { + // Finish this level, and push pairs for the empty ones, and one + // more for next level. Note that this always leaves one extra + // unused element at the end. + uint64_t pos = coordinates[l].size(); + positions[l].insert(positions[l].end(), 2 * count, + detail::checkOverflowCast

(pos)); + } else if (isSingletonLvl(l) || isNOutOfMLvl(l)) { + return; // Nothing to finalize. + } else { // Dense dimension. + assert(isDenseLvl(l)); + const uint64_t sz = getLvlSizes()[l]; + assert(sz >= full && "Segment is overfull"); + count = detail::checkedMul(count, sz - full); + // For dense storage we must enumerate all the remaining coordinates + // in this level (i.e., coordinates after the last non-zero + // element), and either fill in their zero values or else recurse + // to finalize some deeper level. + if (l + 1 == getLvlRank()) + values.insert(values.end(), count, 0); + else + finalizeSegment(l + 1, 0, count); + } + } + + /// Wraps up a single insertion path, inner to outer. + void endPath(uint64_t diffLvl) { + const uint64_t lvlRank = getLvlRank(); + const uint64_t lastLvl = lvlRank - 1; + assert(diffLvl <= lvlRank); + const uint64_t stop = lvlRank - diffLvl; + for (uint64_t i = 0; i < stop; i++) { + const uint64_t l = lastLvl - i; + finalizeSegment(l, lvlCursor[l] + 1); + } + } + + /// Continues a single insertion path, outer to inner. The first + /// argument is the level-coordinates for the value being inserted. + void insPath(const uint64_t *lvlCoords, uint64_t diffLvl, uint64_t full, + V val) { + const uint64_t lvlRank = getLvlRank(); + assert(diffLvl <= lvlRank); + for (uint64_t l = diffLvl; l < lvlRank; l++) { + const uint64_t c = lvlCoords[l]; + appendCrd(l, full, c); + full = 0; + lvlCursor[l] = c; + } + values.push_back(val); + } + + /// Finds the lexicographically first level where the level-coordinates + /// in the argument differ from those in the current cursor. + uint64_t lexDiff(const uint64_t *lvlCoords) const { + const uint64_t lvlRank = getLvlRank(); + for (uint64_t l = 0; l < lvlRank; l++) { + const auto crd = lvlCoords[l]; + const auto cur = lvlCursor[l]; + if (crd > cur || (crd == cur && !isUniqueLvl(l)) || + (crd < cur && !isOrderedLvl(l))) { + return l; + } + if (crd < cur) { + assert(false && "non-lexicographic insertion"); + return -1u; + } + } + assert(false && "duplicate insertion"); + return -1u; + } + + // Sparse tensor storage components. + std::vector> positions; + std::vector> coordinates; + std::vector values; + + // Auxiliary data structures. + std::vector lvlCursor; + std::vector crdBuffer; // just for AoS view +}; + +//===----------------------------------------------------------------------===// +// +// SparseTensorStorage Factories +// +//===----------------------------------------------------------------------===// + +template +SparseTensorStorage *SparseTensorStorage::newEmpty( + uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim) { + SparseTensorCOO *noLvlCOO = nullptr; + return new SparseTensorStorage(dimRank, dimSizes, lvlRank, lvlSizes, + lvlTypes, dim2lvl, lvl2dim, noLvlCOO); +} + +template +SparseTensorStorage *SparseTensorStorage::newFromCOO( + uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim, + SparseTensorCOO *lvlCOO) { + assert(lvlCOO); + return new SparseTensorStorage(dimRank, dimSizes, lvlRank, lvlSizes, + lvlTypes, dim2lvl, lvl2dim, lvlCOO); +} + +template +SparseTensorStorage *SparseTensorStorage::newFromBuffers( + uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim, uint64_t srcRank, + const intptr_t *buffers) { + return new SparseTensorStorage(dimRank, dimSizes, lvlRank, lvlSizes, + lvlTypes, dim2lvl, lvl2dim, buffers); +} + +//===----------------------------------------------------------------------===// +// +// SparseTensorStorage Constructors +// +//===----------------------------------------------------------------------===// + +template +SparseTensorStorage::SparseTensorStorage( + uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim, + SparseTensorCOO *lvlCOO) + : SparseTensorStorage(dimRank, dimSizes, lvlRank, lvlSizes, lvlTypes, + dim2lvl, lvl2dim) { + // Provide hints on capacity of positions and coordinates. + // TODO: needs much fine-tuning based on actual sparsity; currently + // we reserve position/coordinate space based on all previous dense + // levels, which works well up to first sparse level; but we should + // really use nnz and dense/sparse distribution. + uint64_t sz = 1; + for (uint64_t l = 0; l < lvlRank; l++) { + if (isCompressedLvl(l)) { + positions[l].reserve(sz + 1); + positions[l].push_back(0); + coordinates[l].reserve(sz); + sz = 1; + } else if (isLooseCompressedLvl(l)) { + positions[l].reserve(2 * sz + 1); // last one unused + positions[l].push_back(0); + coordinates[l].reserve(sz); + sz = 1; + } else if (isSingletonLvl(l)) { + coordinates[l].reserve(sz); + sz = 1; + } else if (isNOutOfMLvl(l)) { + assert(l == lvlRank - 1 && "unexpected n:m usage"); + sz = detail::checkedMul(sz, lvlSizes[l]) / 2; + coordinates[l].reserve(sz); + values.reserve(sz); + } else { // Dense level. + assert(isDenseLvl(l)); + sz = detail::checkedMul(sz, lvlSizes[l]); + } + } + if (lvlCOO) { + /* New from COO: ensure it is sorted. */ + assert(lvlCOO->getRank() == lvlRank); + lvlCOO->sort(); + // Now actually insert the `elements`. + const auto &elements = lvlCOO->getElements(); + const uint64_t nse = elements.size(); + assert(values.size() == 0); + values.reserve(nse); + fromCOO(elements, 0, nse, 0); + } else if (allDense) { + /* New empty (all dense) */ + values.resize(sz, 0); + } +} + +template +SparseTensorStorage::SparseTensorStorage( + uint64_t dimRank, const uint64_t *dimSizes, uint64_t lvlRank, + const uint64_t *lvlSizes, const LevelType *lvlTypes, + const uint64_t *dim2lvl, const uint64_t *lvl2dim, const intptr_t *lvlBufs) + : SparseTensorStorage(dimRank, dimSizes, lvlRank, lvlSizes, lvlTypes, + dim2lvl, lvl2dim) { + // Note that none of the buffers can be reused because ownership + // of the memory passed from clients is not necessarily transferred. + // Therefore, all data is copied over into a new SparseTensorStorage. + uint64_t trailCOOLen = 0, parentSz = 1, bufIdx = 0; + for (uint64_t l = 0; l < lvlRank; l++) { + if (!isUniqueLvl(l) && (isCompressedLvl(l) || isLooseCompressedLvl(l))) { + // A `(loose)compressed_nu` level marks the start of trailing COO + // start level. Since the coordinate buffer used for trailing COO + // is passed in as AoS scheme and SparseTensorStorage uses a SoA + // scheme, we cannot simply copy the value from the provided buffers. + trailCOOLen = lvlRank - l; + break; + } + if (isCompressedLvl(l) || isLooseCompressedLvl(l)) { + P *posPtr = reinterpret_cast

(lvlBufs[bufIdx++]); + C *crdPtr = reinterpret_cast(lvlBufs[bufIdx++]); + if (isLooseCompressedLvl(l)) { + positions[l].assign(posPtr, posPtr + 2 * parentSz); + coordinates[l].assign(crdPtr, crdPtr + positions[l][2 * parentSz - 1]); + } else { + positions[l].assign(posPtr, posPtr + parentSz + 1); + coordinates[l].assign(crdPtr, crdPtr + positions[l][parentSz]); + } + } else if (isSingletonLvl(l)) { + assert(0 && "general singleton not supported yet"); + } else if (isNOutOfMLvl(l)) { + assert(0 && "n ouf of m not supported yet"); + } else { + assert(isDenseLvl(l)); + } + parentSz = assembledSize(parentSz, l); + } + + // Handle Aos vs. SoA mismatch for COO. + if (trailCOOLen != 0) { + uint64_t cooStartLvl = lvlRank - trailCOOLen; + assert(!isUniqueLvl(cooStartLvl) && + (isCompressedLvl(cooStartLvl) || isLooseCompressedLvl(cooStartLvl))); + P *posPtr = reinterpret_cast

(lvlBufs[bufIdx++]); + C *aosCrdPtr = reinterpret_cast(lvlBufs[bufIdx++]); + P crdLen; + if (isLooseCompressedLvl(cooStartLvl)) { + positions[cooStartLvl].assign(posPtr, posPtr + 2 * parentSz); + crdLen = positions[cooStartLvl][2 * parentSz - 1]; + } else { + positions[cooStartLvl].assign(posPtr, posPtr + parentSz + 1); + crdLen = positions[cooStartLvl][parentSz]; + } + for (uint64_t l = cooStartLvl; l < lvlRank; l++) { + coordinates[l].resize(crdLen); + for (uint64_t n = 0; n < crdLen; n++) { + coordinates[l][n] = *(aosCrdPtr + (l - cooStartLvl) + n * trailCOOLen); + } + } + parentSz = assembledSize(parentSz, cooStartLvl); + } + + // Copy the values buffer. + V *valPtr = reinterpret_cast(lvlBufs[bufIdx]); + values.assign(valPtr, valPtr + parentSz); +} + +} // namespace sparse_tensor +} // namespace mlir + +#endif // MLIR_EXECUTIONENGINE_SPARSETENSOR_STORAGE_H diff --git a/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensorRuntime.h b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensorRuntime.h new file mode 100644 index 0000000000000000000000000000000000000000..d53f2d86bc01d2968b8551617d8b7ea036e8f05b --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/ExecutionEngine/SparseTensorRuntime.h @@ -0,0 +1,186 @@ +//===- SparseTensorRuntime.h - SparseTensor runtime support lib -*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This header file provides the functions which comprise the public API of the +// sparse tensor runtime support library for the SparseTensor dialect. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_EXECUTIONENGINE_SPARSETENSORRUNTIME_H +#define MLIR_EXECUTIONENGINE_SPARSETENSORRUNTIME_H + +#include "mlir/Dialect/SparseTensor/IR/Enums.h" +#include "mlir/ExecutionEngine/CRunnerUtils.h" +#include "mlir/ExecutionEngine/Float16bits.h" + +#include +#include + +using namespace mlir::sparse_tensor; + +extern "C" { + +//===----------------------------------------------------------------------===// +// +// Public functions which operate on MLIR buffers (memrefs) to interact +// with sparse tensors (which are only visible as opaque pointers externally). +// Because these functions deal with memrefs, they should only be used +// by MLIR compiler-generated code (or code that is in sync with MLIR). +// +//===----------------------------------------------------------------------===// + +/// This is the "swiss army knife" method for materializing sparse +/// tensors into the computation. The types of the `ptr` argument and +/// the result depend on the action, as explained in the following table, +/// where "STS" means a sparse-tensor-storage object. +/// +/// Action: `ptr`: Returns: +/// --------------------------------------------------------------------------- +/// kEmpty - STS, empty +/// kFromReader reader STS, input from reader +/// kPack buffers STS, from level buffers +/// kSortCOOInPlace STS STS, sorted in place +MLIR_CRUNNERUTILS_EXPORT void *_mlir_ciface_newSparseTensor( // NOLINT + StridedMemRefType *dimSizesRef, + StridedMemRefType *lvlSizesRef, + StridedMemRefType *lvlTypesRef, + StridedMemRefType *dim2lvlRef, + StridedMemRefType *lvl2dimRef, OverheadType posTp, + OverheadType crdTp, PrimaryType valTp, Action action, void *ptr); + +/// Tensor-storage method to obtain direct access to the values array. +#define DECL_SPARSEVALUES(VNAME, V) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_sparseValues##VNAME( \ + StridedMemRefType *out, void *tensor); +MLIR_SPARSETENSOR_FOREVERY_V(DECL_SPARSEVALUES) +#undef DECL_SPARSEVALUES + +/// Tensor-storage method to obtain direct access to the positions array +/// for the given level. +#define DECL_SPARSEPOSITIONS(PNAME, P) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_sparsePositions##PNAME( \ + StridedMemRefType *out, void *tensor, index_type lvl); +MLIR_SPARSETENSOR_FOREVERY_O(DECL_SPARSEPOSITIONS) +#undef DECL_SPARSEPOSITIONS + +/// Tensor-storage method to obtain direct access to the coordinates array +/// for the given level. +#define DECL_SPARSECOORDINATES(CNAME, C) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_sparseCoordinates##CNAME( \ + StridedMemRefType *out, void *tensor, index_type lvl); +MLIR_SPARSETENSOR_FOREVERY_O(DECL_SPARSECOORDINATES) +#undef DECL_SPARSECOORDINATES + +/// Tensor-storage method to obtain direct access to the coordinates array +/// buffer for the given level (provides an AoS view into the library). +#define DECL_SPARSECOORDINATES(CNAME, C) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_sparseCoordinatesBuffer##CNAME( \ + StridedMemRefType *out, void *tensor, index_type lvl); +MLIR_SPARSETENSOR_FOREVERY_O(DECL_SPARSECOORDINATES) +#undef DECL_SPARSECOORDINATES + +/// Tensor-storage method to insert elements in lexicographical +/// level-coordinate order. +#define DECL_LEXINSERT(VNAME, V) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_lexInsert##VNAME( \ + void *tensor, StridedMemRefType *lvlCoordsRef, \ + StridedMemRefType *vref); +MLIR_SPARSETENSOR_FOREVERY_V(DECL_LEXINSERT) +#undef DECL_LEXINSERT + +/// Tensor-storage method to insert using expansion. +#define DECL_EXPINSERT(VNAME, V) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_expInsert##VNAME( \ + void *tensor, StridedMemRefType *lvlCoordsRef, \ + StridedMemRefType *vref, StridedMemRefType *fref, \ + StridedMemRefType *aref, index_type count); +MLIR_SPARSETENSOR_FOREVERY_V(DECL_EXPINSERT) +#undef DECL_EXPINSERT + +/// Constructs a new SparseTensorReader object, opens the file, reads the +/// header, and validates that the actual contents of the file match +/// the expected `dimShapeRef` and `valTp`. +MLIR_CRUNNERUTILS_EXPORT void *_mlir_ciface_createCheckedSparseTensorReader( + char *filename, StridedMemRefType *dimShapeRef, + PrimaryType valTp); + +/// SparseTensorReader method to obtain direct access to the +/// dimension-sizes array. +MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_getSparseTensorReaderDimSizes( + StridedMemRefType *out, void *p); + +/// Reads the sparse tensor, stores the coordinates and values to the given +/// memrefs of a COO in AoS format. Returns a boolean to indicate whether +/// the COO elements are sorted. +#define DECL_READTOBUFFERS(VNAME, V, CNAME, C) \ + MLIR_CRUNNERUTILS_EXPORT bool \ + _mlir_ciface_getSparseTensorReaderReadToBuffers##CNAME##VNAME( \ + void *p, StridedMemRefType *dim2lvlRef, \ + StridedMemRefType *lvl2dimRef, \ + StridedMemRefType *cref, StridedMemRefType *vref) \ + MLIR_SPARSETENSOR_FOREVERY_V_O(DECL_READTOBUFFERS) +#undef DECL_READTOBUFFERS + +/// Outputs the sparse tensor dim-rank, nse, and dim-shape. +MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_outSparseTensorWriterMetaData( + void *p, index_type dimRank, index_type nse, + StridedMemRefType *dimSizesRef); + +/// Outputs an element for the sparse tensor. +#define DECL_OUTNEXT(VNAME, V) \ + MLIR_CRUNNERUTILS_EXPORT void _mlir_ciface_outSparseTensorWriterNext##VNAME( \ + void *p, index_type dimRank, \ + StridedMemRefType *dimCoordsRef, \ + StridedMemRefType *vref); +MLIR_SPARSETENSOR_FOREVERY_V(DECL_OUTNEXT) +#undef DECL_OUTNEXT + +//===----------------------------------------------------------------------===// +// +// Public functions which accept only C-style data structures to interact +// with sparse tensors (which are only visible as opaque pointers externally). +// These functions can be used both by MLIR compiler-generated code +// as well as by any external runtime that wants to interact with MLIR +// compiler-generated code. +// +//===----------------------------------------------------------------------===// + +/// Tensor-storage method to get the size of the given level. +MLIR_CRUNNERUTILS_EXPORT index_type sparseLvlSize(void *tensor, index_type l); + +/// Tensor-storage method to get the size of the given dimension. +MLIR_CRUNNERUTILS_EXPORT index_type sparseDimSize(void *tensor, index_type d); + +/// Tensor-storage method to finalize lexicographic insertions. +MLIR_CRUNNERUTILS_EXPORT void endLexInsert(void *tensor); + +/// Releases the memory for the tensor-storage object. +MLIR_CRUNNERUTILS_EXPORT void delSparseTensor(void *tensor); + +/// Helper function to read a sparse tensor filename from the environment, +/// defined with the naming convention ${TENSOR0}, ${TENSOR1}, etc. +MLIR_CRUNNERUTILS_EXPORT char *getTensorFilename(index_type id); + +/// Returns the number of stored elements for the sparse tensor being read. +MLIR_CRUNNERUTILS_EXPORT index_type getSparseTensorReaderNSE(void *p); + +/// Releases the SparseTensorReader and closes the associated file. +MLIR_CRUNNERUTILS_EXPORT void delSparseTensorReader(void *p); + +/// Creates a SparseTensorWriter for outputting a sparse tensor to a file +/// with the given file name. When the file name is empty, std::cout is used. +/// Only the extended FROSTT format is supported currently. +MLIR_CRUNNERUTILS_EXPORT void *createSparseTensorWriter(char *filename); + +/// Finalizes the outputing of a sparse tensor to a file and releases the +/// SparseTensorWriter. +MLIR_CRUNNERUTILS_EXPORT void delSparseTensorWriter(void *p); + +} // extern "C" + +#endif // MLIR_EXECUTIONENGINE_SPARSETENSORRUNTIME_H diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/Action.h b/deps/exla/cache/xla_extension/include/mlir/IR/Action.h new file mode 100644 index 0000000000000000000000000000000000000000..2fad47768ceff9461c610ebcc90c0d8303d0aed0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/Action.h @@ -0,0 +1,93 @@ +//===- Action.h - Action Support ---------------------*- C++ -*-=============// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains definitions for the action framework. This framework +// allows for external entities to control certain actions taken by the compiler +// by registering handler functions. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_ACTION_H +#define MLIR_IR_ACTION_H + +#include "mlir/IR/Unit.h" +#include "mlir/Support/TypeID.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Sequence.h" +#include "llvm/ADT/StringMap.h" +#include "llvm/Support/TypeName.h" +#include "llvm/Support/raw_ostream.h" +#include +#include + +namespace mlir { +namespace tracing { + +/// An action is a specific action that is to be taken by the compiler, +/// that can be toggled and controlled by an external user. There are no +/// constraints on the granularity of an action, it could be as simple as +/// "perform this fold" and as complex as "run this pass pipeline". +/// +/// This class represents the base class of the ActionImpl class (see below). +/// This holds the template-invariant elements of the Action class. +class Action { +public: + virtual ~Action() = default; + + /// Return the unique action id of this action, use for casting + /// functionality. + TypeID getActionID() const { return actionID; } + + /// Return a string "tag" which intends to uniquely identify this type of + /// action. For example "pass-application" or "pattern-rewrite". + virtual StringRef getTag() const = 0; + + virtual void print(raw_ostream &os) const { + os << "Action \"" << getTag() << "\""; + } + + /// Return the set of IR units that are associated with this action. + virtual ArrayRef getContextIRUnits() const { return irUnits; } + +protected: + Action(TypeID actionID, ArrayRef irUnits) + : actionID(actionID), irUnits(irUnits) {} + + /// The type of the derived action class, used for `isa`/`dyn_cast`. + TypeID actionID; + + /// Set of IR units (operations, regions, blocks, values) that are associated + /// with this action. + ArrayRef irUnits; +}; + +/// CRTP Implementation of an action. This class provides a base class for +/// implementing specific actions. +/// Derived classes are expected to provide the following: +/// * static constexpr StringLiteral tag = "..."; +/// - This method returns a unique string identifier, similar to a command +/// line flag or DEBUG_TYPE. +template +class ActionImpl : public Action { +public: + ActionImpl(ArrayRef irUnits = {}) + : Action(TypeID::get(), irUnits) {} + + /// Provide classof to allow casting between action types. + static bool classof(const Action *action) { + return action->getActionID() == TypeID::get(); + } + + /// Forward tag access to the derived class. + StringRef getTag() const final { return Derived::tag; } +}; + +} // namespace tracing +} // namespace mlir + +#endif // MLIR_IR_ACTION_H diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/AffineExpr.h b/deps/exla/cache/xla_extension/include/mlir/IR/AffineExpr.h new file mode 100644 index 0000000000000000000000000000000000000000..94eacdb4735f8915670e52c97e1c6982a93bfec0 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/AffineExpr.h @@ -0,0 +1,404 @@ +//===- AffineExpr.h - MLIR Affine Expr Class --------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// An affine expression is an affine combination of dimension identifiers and +// symbols, including ceildiv/floordiv/mod by a constant integer. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_AFFINEEXPR_H +#define MLIR_IR_AFFINEEXPR_H + +#include "mlir/IR/Visitors.h" +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include + +namespace mlir { + +class MLIRContext; +class AffineMap; +class IntegerSet; + +namespace detail { + +struct AffineExprStorage; +struct AffineBinaryOpExprStorage; +struct AffineDimExprStorage; +struct AffineConstantExprStorage; + +} // namespace detail + +enum class AffineExprKind { + Add, + /// RHS of mul is always a constant or a symbolic expression. + Mul, + /// RHS of mod is always a constant or a symbolic expression with a positive + /// value. + Mod, + /// RHS of floordiv is always a constant or a symbolic expression. + FloorDiv, + /// RHS of ceildiv is always a constant or a symbolic expression. + CeilDiv, + + /// This is a marker for the last affine binary op. The range of binary + /// op's is expected to be this element and earlier. + LAST_AFFINE_BINARY_OP = CeilDiv, + + /// Constant integer. + Constant, + /// Dimensional identifier. + DimId, + /// Symbolic identifier. + SymbolId, +}; + +/// Base type for affine expression. +/// AffineExpr's are immutable value types with intuitive operators to +/// operate on chainable, lightweight compositions. +/// An AffineExpr is an interface to the underlying storage type pointer. +class AffineExpr { +public: + using ImplType = detail::AffineExprStorage; + + constexpr AffineExpr() {} + /* implicit */ AffineExpr(const ImplType *expr) + : expr(const_cast(expr)) {} + + bool operator==(AffineExpr other) const { return expr == other.expr; } + bool operator!=(AffineExpr other) const { return !(*this == other); } + bool operator==(int64_t v) const; + bool operator!=(int64_t v) const { return !(*this == v); } + explicit operator bool() const { return expr; } + + bool operator!() const { return expr == nullptr; } + + MLIRContext *getContext() const; + + /// Return the classification for this type. + AffineExprKind getKind() const; + + void print(raw_ostream &os) const; + void dump() const; + + /// Returns true if this expression is made out of only symbols and + /// constants, i.e., it does not involve dimensional identifiers. + bool isSymbolicOrConstant() const; + + /// Returns true if this is a pure affine expression, i.e., multiplication, + /// floordiv, ceildiv, and mod is only allowed w.r.t constants. + bool isPureAffine() const; + + /// Returns the greatest known integral divisor of this affine expression. The + /// result is always positive. + int64_t getLargestKnownDivisor() const; + + /// Return true if the affine expression is a multiple of 'factor'. + bool isMultipleOf(int64_t factor) const; + + /// Return true if the affine expression involves AffineDimExpr `position`. + bool isFunctionOfDim(unsigned position) const; + + /// Return true if the affine expression involves AffineSymbolExpr `position`. + bool isFunctionOfSymbol(unsigned position) const; + + /// Walk all of the AffineExpr's in this expression in postorder. This allows + /// a lambda walk function that can either return `void` or a WalkResult. With + /// a WalkResult, interrupting is supported. + template > + RetT walk(FnT &&callback) const { + return walk(*this, callback); + } + + /// This method substitutes any uses of dimensions and symbols (e.g. + /// dim#0 with dimReplacements[0]) and returns the modified expression tree. + /// This is a dense replacement method: a replacement must be specified for + /// every single dim and symbol. + AffineExpr replaceDimsAndSymbols(ArrayRef dimReplacements, + ArrayRef symReplacements) const; + + /// Dim-only version of replaceDimsAndSymbols. + AffineExpr replaceDims(ArrayRef dimReplacements) const; + + /// Symbol-only version of replaceDimsAndSymbols. + AffineExpr replaceSymbols(ArrayRef symReplacements) const; + + /// Sparse replace method. Replace `expr` by `replacement` and return the + /// modified expression tree. + AffineExpr replace(AffineExpr expr, AffineExpr replacement) const; + + /// Sparse replace method. If `*this` appears in `map` replaces it by + /// `map[*this]` and return the modified expression tree. Otherwise traverse + /// `*this` and apply replace with `map` on its subexpressions. + AffineExpr replace(const DenseMap &map) const; + + /// Replace dims[offset ... numDims) + /// by dims[offset + shift ... shift + numDims). + AffineExpr shiftDims(unsigned numDims, unsigned shift, + unsigned offset = 0) const; + + /// Replace symbols[offset ... numSymbols) + /// by symbols[offset + shift ... shift + numSymbols). + AffineExpr shiftSymbols(unsigned numSymbols, unsigned shift, + unsigned offset = 0) const; + + AffineExpr operator+(int64_t v) const; + AffineExpr operator+(AffineExpr other) const; + AffineExpr operator-() const; + AffineExpr operator-(int64_t v) const; + AffineExpr operator-(AffineExpr other) const; + AffineExpr operator*(int64_t v) const; + AffineExpr operator*(AffineExpr other) const; + AffineExpr floorDiv(uint64_t v) const; + AffineExpr floorDiv(AffineExpr other) const; + AffineExpr ceilDiv(uint64_t v) const; + AffineExpr ceilDiv(AffineExpr other) const; + AffineExpr operator%(uint64_t v) const; + AffineExpr operator%(AffineExpr other) const; + + /// Compose with an AffineMap. + /// Returns the composition of this AffineExpr with `map`. + /// + /// Prerequisites: + /// `this` and `map` are composable, i.e. that the number of AffineDimExpr of + /// `this` is smaller than the number of results of `map`. If a result of a + /// map does not have a corresponding AffineDimExpr, that result simply does + /// not appear in the produced AffineExpr. + /// + /// Example: + /// expr: `d0 + d2` + /// map: `(d0, d1, d2)[s0, s1] -> (d0 + s1, d1 + s0, d0 + d1 + d2)` + /// returned expr: `d0 * 2 + d1 + d2 + s1` + AffineExpr compose(AffineMap map) const; + + friend ::llvm::hash_code hash_value(AffineExpr arg); + + /// Methods supporting C API. + const void *getAsOpaquePointer() const { + return static_cast(expr); + } + static AffineExpr getFromOpaquePointer(const void *pointer) { + return AffineExpr( + reinterpret_cast(const_cast(pointer))); + } + + ImplType *getImpl() const { return expr; } + +protected: + ImplType *expr{nullptr}; + +private: + /// A trampoline for the templated non-static AffineExpr::walk method to + /// dispatch lambda `callback`'s of either a void result type or a + /// WalkResult type. Walk all of the AffineExprs in `e` in postorder. Users + /// should use the regular (non-static) `walk` method. + template + static WalkRetTy walk(AffineExpr e, + function_ref callback); +}; + +/// Affine binary operation expression. An affine binary operation could be an +/// add, mul, floordiv, ceildiv, or a modulo operation. (Subtraction is +/// represented through a multiply by -1 and add.) These expressions are always +/// constructed in a simplified form. For eg., the LHS and RHS operands can't +/// both be constants. There are additional canonicalizing rules depending on +/// the op type: see checks in the constructor. +class AffineBinaryOpExpr : public AffineExpr { +public: + using ImplType = detail::AffineBinaryOpExprStorage; + /* implicit */ AffineBinaryOpExpr(AffineExpr::ImplType *ptr); + AffineExpr getLHS() const; + AffineExpr getRHS() const; +}; + +/// A dimensional identifier appearing in an affine expression. +class AffineDimExpr : public AffineExpr { +public: + using ImplType = detail::AffineDimExprStorage; + /* implicit */ AffineDimExpr(AffineExpr::ImplType *ptr); + unsigned getPosition() const; +}; + +/// A symbolic identifier appearing in an affine expression. +class AffineSymbolExpr : public AffineExpr { +public: + using ImplType = detail::AffineDimExprStorage; + /* implicit */ AffineSymbolExpr(AffineExpr::ImplType *ptr); + unsigned getPosition() const; +}; + +/// An integer constant appearing in affine expression. +class AffineConstantExpr : public AffineExpr { +public: + using ImplType = detail::AffineConstantExprStorage; + /* implicit */ AffineConstantExpr(AffineExpr::ImplType *ptr = nullptr); + int64_t getValue() const; +}; + +/// Make AffineExpr hashable. +inline ::llvm::hash_code hash_value(AffineExpr arg) { + return ::llvm::hash_value(arg.expr); +} + +inline AffineExpr operator+(int64_t val, AffineExpr expr) { return expr + val; } +inline AffineExpr operator*(int64_t val, AffineExpr expr) { return expr * val; } +inline AffineExpr operator-(int64_t val, AffineExpr expr) { + return expr * (-1) + val; +} + +/// These free functions allow clients of the API to not use classes in detail. +AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context); +AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context); +AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context); +SmallVector getAffineConstantExprs(ArrayRef constants, + MLIRContext *context); +AffineExpr getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs, + AffineExpr rhs); + +/// Constructs an affine expression from a flat ArrayRef. If there are local +/// identifiers (neither dimensional nor symbolic) that appear in the sum of +/// products expression, 'localExprs' is expected to have the AffineExpr +/// for it, and is substituted into. The ArrayRef 'eq' is expected to be in the +/// format [dims, symbols, locals, constant term]. +AffineExpr getAffineExprFromFlatForm(ArrayRef flatExprs, + unsigned numDims, unsigned numSymbols, + ArrayRef localExprs, + MLIRContext *context); + +raw_ostream &operator<<(raw_ostream &os, AffineExpr expr); + +/// Simplify an affine expression by flattening and some amount of simple +/// analysis. This has complexity linear in the number of nodes in 'expr'. +/// Returns the simplified expression, which is the same as the input expression +/// if it can't be simplified. When `expr` is semi-affine, a simplified +/// semi-affine expression is constructed in the sorted order of dimension and +/// symbol positions. +AffineExpr simplifyAffineExpr(AffineExpr expr, unsigned numDims, + unsigned numSymbols); + +namespace detail { +template +void bindDims(MLIRContext *ctx) {} + +template +void bindDims(MLIRContext *ctx, AffineExprTy &e, AffineExprTy2 &...exprs) { + e = getAffineDimExpr(N, ctx); + bindDims(ctx, exprs...); +} + +template +void bindSymbols(MLIRContext *ctx) {} + +template +void bindSymbols(MLIRContext *ctx, AffineExprTy &e, AffineExprTy2 &...exprs) { + e = getAffineSymbolExpr(N, ctx); + bindSymbols(ctx, exprs...); +} + +} // namespace detail + +/// Bind a list of AffineExpr references to DimExpr at positions: +/// [0 .. sizeof...(exprs)] +template +void bindDims(MLIRContext *ctx, AffineExprTy &...exprs) { + detail::bindDims<0>(ctx, exprs...); +} + +template +void bindDimsList(MLIRContext *ctx, MutableArrayRef exprs) { + int idx = 0; + for (AffineExprTy &e : exprs) + e = getAffineDimExpr(idx++, ctx); +} + +/// Bind a list of AffineExpr references to SymbolExpr at positions: +/// [0 .. sizeof...(exprs)] +template +void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs) { + detail::bindSymbols<0>(ctx, exprs...); +} + +template +void bindSymbolsList(MLIRContext *ctx, MutableArrayRef exprs) { + int idx = 0; + for (AffineExprTy &e : exprs) + e = getAffineSymbolExpr(idx++, ctx); +} + +/// Get a lower or upper (depending on `isUpper`) bound for `expr` while using +/// the constant lower and upper bounds for its inputs provided in +/// `constLowerBounds` and `constUpperBounds`. Return std::nullopt if such a +/// bound can't be computed. This method only handles simple sum of product +/// expressions (w.r.t constant coefficients) so as to not depend on anything +/// heavyweight in `Analysis`. Expressions of the form: c0*d0 + c1*d1 + c2*s0 + +/// ... + c_n are handled. Expressions involving floordiv, ceildiv, mod or +/// semi-affine ones will lead a none being returned. +std::optional +getBoundForAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols, + ArrayRef> constLowerBounds, + ArrayRef> constUpperBounds, + bool isUpper); + +} // namespace mlir + +namespace llvm { + +// AffineExpr hash just like pointers +template <> +struct DenseMapInfo { + static mlir::AffineExpr getEmptyKey() { + auto *pointer = llvm::DenseMapInfo::getEmptyKey(); + return mlir::AffineExpr(static_cast(pointer)); + } + static mlir::AffineExpr getTombstoneKey() { + auto *pointer = llvm::DenseMapInfo::getTombstoneKey(); + return mlir::AffineExpr(static_cast(pointer)); + } + static unsigned getHashValue(mlir::AffineExpr val) { + return mlir::hash_value(val); + } + static bool isEqual(mlir::AffineExpr LHS, mlir::AffineExpr RHS) { + return LHS == RHS; + } +}; + +/// Add support for llvm style casts. We provide a cast between To and From if +/// From is mlir::AffineExpr or derives from it. +template +struct CastInfo> || + std::is_base_of_v>> + : NullableValueCastFailed, + DefaultDoCastIfPossible> { + + static inline bool isPossible(mlir::AffineExpr expr) { + /// Return a constant true instead of a dynamic true when casting to self or + /// up the hierarchy. + if constexpr (std::is_base_of_v) { + return true; + } else { + if constexpr (std::is_same_v) + return expr.getKind() <= ::mlir::AffineExprKind::LAST_AFFINE_BINARY_OP; + if constexpr (std::is_same_v) + return expr.getKind() == ::mlir::AffineExprKind::DimId; + if constexpr (std::is_same_v) + return expr.getKind() == ::mlir::AffineExprKind::SymbolId; + if constexpr (std::is_same_v) + return expr.getKind() == ::mlir::AffineExprKind::Constant; + } + } + static inline To doCast(mlir::AffineExpr expr) { return To(expr.getImpl()); } +}; + +} // namespace llvm + +#endif // MLIR_IR_AFFINEEXPR_H diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/AffineExprVisitor.h b/deps/exla/cache/xla_extension/include/mlir/IR/AffineExprVisitor.h new file mode 100644 index 0000000000000000000000000000000000000000..1826f5fd8ad354599d968cd12ba035ecff199d2d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/AffineExprVisitor.h @@ -0,0 +1,456 @@ +//===- AffineExprVisitor.h - MLIR AffineExpr Visitor Class ------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines the AffineExpr visitor class. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_AFFINEEXPRVISITOR_H +#define MLIR_IR_AFFINEEXPRVISITOR_H + +#include "mlir/IR/AffineExpr.h" +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/ArrayRef.h" + +namespace mlir { + +/// Base class for AffineExpr visitors/walkers. +/// +/// AffineExpr visitors are used when you want to perform different actions +/// for different kinds of AffineExprs without having to use lots of casts +/// and a big switch instruction. +/// +/// To define your own visitor, inherit from this class, specifying your +/// new type for the 'SubClass' template parameter, and "override" visitXXX +/// functions in your class. This class is defined in terms of statically +/// resolved overloading, not virtual functions. +/// +/// The visitor is templated on its return type (`RetTy`). With a WalkResult +/// return type, the visitor supports interrupting walks. +/// +/// For example, here is a visitor that counts the number of for AffineDimExprs +/// in an AffineExpr. +/// +/// /// Declare the class. Note that we derive from AffineExprVisitor +/// /// instantiated with our new subclasses_ type. +/// +/// struct DimExprCounter : public AffineExprVisitor { +/// unsigned numDimExprs; +/// DimExprCounter() : numDimExprs(0) {} +/// void visitDimExpr(AffineDimExpr expr) { ++numDimExprs; } +/// }; +/// +/// And this class would be used like this: +/// DimExprCounter dec; +/// dec.visit(affineExpr); +/// numDimExprs = dec.numDimExprs; +/// +/// AffineExprVisitor provides visit methods for the following binary affine +/// op expressions: +/// AffineBinaryAddOpExpr, AffineBinaryMulOpExpr, +/// AffineBinaryModOpExpr, AffineBinaryFloorDivOpExpr, +/// AffineBinaryCeilDivOpExpr. Note that default implementations of these +/// methods will call the general AffineBinaryOpExpr method. +/// +/// In addition, visit methods are provided for the following affine +// expressions: AffineConstantExpr, AffineDimExpr, and +// AffineSymbolExpr. +/// +/// Note that if you don't implement visitXXX for some affine expression type, +/// the visitXXX method for Instruction superclass will be invoked. +/// +/// Note that this class is specifically designed as a template to avoid +/// virtual function call overhead. Defining and using a AffineExprVisitor is +/// just as efficient as having your own switch instruction over the instruction +/// opcode. +template +class AffineExprVisitorBase { +public: + // Function to visit an AffineExpr. + RetTy visit(AffineExpr expr) { + static_assert(std::is_base_of::value, + "Must instantiate with a derived type of AffineExprVisitor"); + auto self = static_cast(this); + switch (expr.getKind()) { + case AffineExprKind::Add: { + auto binOpExpr = cast(expr); + return self->visitAddExpr(binOpExpr); + } + case AffineExprKind::Mul: { + auto binOpExpr = cast(expr); + return self->visitMulExpr(binOpExpr); + } + case AffineExprKind::Mod: { + auto binOpExpr = cast(expr); + return self->visitModExpr(binOpExpr); + } + case AffineExprKind::FloorDiv: { + auto binOpExpr = cast(expr); + return self->visitFloorDivExpr(binOpExpr); + } + case AffineExprKind::CeilDiv: { + auto binOpExpr = cast(expr); + return self->visitCeilDivExpr(binOpExpr); + } + case AffineExprKind::Constant: + return self->visitConstantExpr(cast(expr)); + case AffineExprKind::DimId: + return self->visitDimExpr(cast(expr)); + case AffineExprKind::SymbolId: + return self->visitSymbolExpr(cast(expr)); + } + llvm_unreachable("Unknown AffineExpr"); + } + + //===--------------------------------------------------------------------===// + // Visitation functions... these functions provide default fallbacks in case + // the user does not specify what to do for a particular instruction type. + // The default behavior is to generalize the instruction type to its subtype + // and try visiting the subtype. All of this should be inlined perfectly, + // because there are no virtual functions to get in the way. + // + + // Default visit methods. Note that the default op-specific binary op visit + // methods call the general visitAffineBinaryOpExpr visit method. + RetTy visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) { return RetTy(); } + RetTy visitAddExpr(AffineBinaryOpExpr expr) { + return static_cast(this)->visitAffineBinaryOpExpr(expr); + } + RetTy visitMulExpr(AffineBinaryOpExpr expr) { + return static_cast(this)->visitAffineBinaryOpExpr(expr); + } + RetTy visitModExpr(AffineBinaryOpExpr expr) { + return static_cast(this)->visitAffineBinaryOpExpr(expr); + } + RetTy visitFloorDivExpr(AffineBinaryOpExpr expr) { + return static_cast(this)->visitAffineBinaryOpExpr(expr); + } + RetTy visitCeilDivExpr(AffineBinaryOpExpr expr) { + return static_cast(this)->visitAffineBinaryOpExpr(expr); + } + RetTy visitConstantExpr(AffineConstantExpr expr) { return RetTy(); } + RetTy visitDimExpr(AffineDimExpr expr) { return RetTy(); } + RetTy visitSymbolExpr(AffineSymbolExpr expr) { return RetTy(); } +}; + +/// See documentation for AffineExprVisitorBase. This visitor supports +/// interrupting walks when a `WalkResult` is used for `RetTy`. +template +class AffineExprVisitor : public AffineExprVisitorBase { + //===--------------------------------------------------------------------===// + // Interface code - This is the public interface of the AffineExprVisitor + // that you use to visit affine expressions... +public: + // Function to walk an AffineExpr (in post order). + RetTy walkPostOrder(AffineExpr expr) { + static_assert(std::is_base_of::value, + "Must instantiate with a derived type of AffineExprVisitor"); + auto self = static_cast(this); + switch (expr.getKind()) { + case AffineExprKind::Add: { + auto binOpExpr = cast(expr); + if constexpr (std::is_same::value) { + if (walkOperandsPostOrder(binOpExpr).wasInterrupted()) + return WalkResult::interrupt(); + } else { + walkOperandsPostOrder(binOpExpr); + } + return self->visitAddExpr(binOpExpr); + } + case AffineExprKind::Mul: { + auto binOpExpr = cast(expr); + if constexpr (std::is_same::value) { + if (walkOperandsPostOrder(binOpExpr).wasInterrupted()) + return WalkResult::interrupt(); + } else { + walkOperandsPostOrder(binOpExpr); + } + return self->visitMulExpr(binOpExpr); + } + case AffineExprKind::Mod: { + auto binOpExpr = cast(expr); + if constexpr (std::is_same::value) { + if (walkOperandsPostOrder(binOpExpr).wasInterrupted()) + return WalkResult::interrupt(); + } else { + walkOperandsPostOrder(binOpExpr); + } + return self->visitModExpr(binOpExpr); + } + case AffineExprKind::FloorDiv: { + auto binOpExpr = cast(expr); + if constexpr (std::is_same::value) { + if (walkOperandsPostOrder(binOpExpr).wasInterrupted()) + return WalkResult::interrupt(); + } else { + walkOperandsPostOrder(binOpExpr); + } + return self->visitFloorDivExpr(binOpExpr); + } + case AffineExprKind::CeilDiv: { + auto binOpExpr = cast(expr); + if constexpr (std::is_same::value) { + if (walkOperandsPostOrder(binOpExpr).wasInterrupted()) + return WalkResult::interrupt(); + } else { + walkOperandsPostOrder(binOpExpr); + } + return self->visitCeilDivExpr(binOpExpr); + } + case AffineExprKind::Constant: + return self->visitConstantExpr(cast(expr)); + case AffineExprKind::DimId: + return self->visitDimExpr(cast(expr)); + case AffineExprKind::SymbolId: + return self->visitSymbolExpr(cast(expr)); + } + llvm_unreachable("Unknown AffineExpr"); + } + +private: + // Walk the operands - each operand is itself walked in post order. + RetTy walkOperandsPostOrder(AffineBinaryOpExpr expr) { + if constexpr (std::is_same::value) { + if (walkPostOrder(expr.getLHS()).wasInterrupted()) + return WalkResult::interrupt(); + } else { + walkPostOrder(expr.getLHS()); + } + if constexpr (std::is_same::value) { + if (walkPostOrder(expr.getRHS()).wasInterrupted()) + return WalkResult::interrupt(); + return WalkResult::advance(); + } else { + return walkPostOrder(expr.getRHS()); + } + } +}; + +template +class AffineExprVisitor + : public AffineExprVisitorBase { + //===--------------------------------------------------------------------===// + // Interface code - This is the public interface of the AffineExprVisitor + // that you use to visit affine expressions... +public: + // Function to walk an AffineExpr (in post order). + LogicalResult walkPostOrder(AffineExpr expr) { + static_assert(std::is_base_of::value, + "Must instantiate with a derived type of AffineExprVisitor"); + auto self = static_cast(this); + switch (expr.getKind()) { + case AffineExprKind::Add: { + auto binOpExpr = cast(expr); + if (failed(walkOperandsPostOrder(binOpExpr))) + return failure(); + return self->visitAddExpr(binOpExpr); + } + case AffineExprKind::Mul: { + auto binOpExpr = cast(expr); + if (failed(walkOperandsPostOrder(binOpExpr))) + return failure(); + return self->visitMulExpr(binOpExpr); + } + case AffineExprKind::Mod: { + auto binOpExpr = cast(expr); + if (failed(walkOperandsPostOrder(binOpExpr))) + return failure(); + return self->visitModExpr(binOpExpr); + } + case AffineExprKind::FloorDiv: { + auto binOpExpr = cast(expr); + if (failed(walkOperandsPostOrder(binOpExpr))) + return failure(); + return self->visitFloorDivExpr(binOpExpr); + } + case AffineExprKind::CeilDiv: { + auto binOpExpr = cast(expr); + if (failed(walkOperandsPostOrder(binOpExpr))) + return failure(); + return self->visitCeilDivExpr(binOpExpr); + } + case AffineExprKind::Constant: + return self->visitConstantExpr(cast(expr)); + case AffineExprKind::DimId: + return self->visitDimExpr(cast(expr)); + case AffineExprKind::SymbolId: + return self->visitSymbolExpr(cast(expr)); + } + llvm_unreachable("Unknown AffineExpr"); + } + +private: + // Walk the operands - each operand is itself walked in post order. + LogicalResult walkOperandsPostOrder(AffineBinaryOpExpr expr) { + if (failed(walkPostOrder(expr.getLHS()))) + return failure(); + if (failed(walkPostOrder(expr.getRHS()))) + return failure(); + return success(); + } +}; + +// This class is used to flatten a pure affine expression (AffineExpr, +// which is in a tree form) into a sum of products (w.r.t constants) when +// possible, and in that process simplifying the expression. For a modulo, +// floordiv, or a ceildiv expression, an additional identifier, called a local +// identifier, is introduced to rewrite the expression as a sum of product +// affine expression. Each local identifier is always and by construction a +// floordiv of a pure add/mul affine function of dimensional, symbolic, and +// other local identifiers, in a non-mutually recursive way. Hence, every local +// identifier can ultimately always be recovered as an affine function of +// dimensional and symbolic identifiers (involving floordiv's); note however +// that by AffineExpr construction, some floordiv combinations are converted to +// mod's. The result of the flattening is a flattened expression and a set of +// constraints involving just the local variables. +// +// d2 + (d0 + d1) floordiv 4 is flattened to d2 + q where 'q' is the local +// variable introduced, with localVarCst containing 4*q <= d0 + d1 <= 4*q + 3. +// +// The simplification performed includes the accumulation of contributions for +// each dimensional and symbolic identifier together, the simplification of +// floordiv/ceildiv/mod expressions and other simplifications that in turn +// happen as a result. A simplification that this flattening naturally performs +// is of simplifying the numerator and denominator of floordiv/ceildiv, and +// folding a modulo expression to a zero, if possible. Three examples are below: +// +// (d0 + 3 * d1) + d0) - 2 * d1) - d0 simplified to d0 + d1 +// (d0 - d0 mod 4 + 4) mod 4 simplified to 0 +// (3*d0 + 2*d1 + d0) floordiv 2 + d1 simplified to 2*d0 + 2*d1 +// +// The way the flattening works for the second example is as follows: d0 % 4 is +// replaced by d0 - 4*q with q being introduced: the expression then simplifies +// to: (d0 - (d0 - 4q) + 4) = 4q + 4, modulo of which w.r.t 4 simplifies to +// zero. Note that an affine expression may not always be expressible purely as +// a sum of products involving just the original dimensional and symbolic +// identifiers due to the presence of modulo/floordiv/ceildiv expressions that +// may not be eliminated after simplification; in such cases, the final +// expression can be reconstructed by replacing the local identifiers with their +// corresponding explicit form stored in 'localExprs' (note that each of the +// explicit forms itself would have been simplified). +// +// The expression walk method here performs a linear time post order walk that +// performs the above simplifications through visit methods, with partial +// results being stored in 'operandExprStack'. When a parent expr is visited, +// the flattened expressions corresponding to its two operands would already be +// on the stack - the parent expression looks at the two flattened expressions +// and combines the two. It pops off the operand expressions and pushes the +// combined result (although this is done in-place on its LHS operand expr). +// When the walk is completed, the flattened form of the top-level expression +// would be left on the stack. +// +// A flattener can be repeatedly used for multiple affine expressions that bind +// to the same operands, for example, for all result expressions of an +// AffineMap or AffineValueMap. In such cases, using it for multiple expressions +// is more efficient than creating a new flattener for each expression since +// common identical div and mod expressions appearing across different +// expressions are mapped to the same local identifier (same column position in +// 'localVarCst'). +class SimpleAffineExprFlattener + : public AffineExprVisitor { +public: + // Flattend expression layout: [dims, symbols, locals, constant] + // Stack that holds the LHS and RHS operands while visiting a binary op expr. + // In future, consider adding a prepass to determine how big the SmallVector's + // will be, and linearize this to std::vector to prevent + // SmallVector moves on re-allocation. + std::vector> operandExprStack; + + unsigned numDims; + unsigned numSymbols; + + // Number of newly introduced identifiers to flatten mod/floordiv/ceildiv's. + unsigned numLocals; + + // AffineExpr's corresponding to the floordiv/ceildiv/mod expressions for + // which new identifiers were introduced; if the latter do not get canceled + // out, these expressions can be readily used to reconstruct the AffineExpr + // (tree) form. Note that these expressions themselves would have been + // simplified (recursively) by this pass. Eg. d0 + (d0 + 2*d1 + d0) ceildiv 4 + // will be simplified to d0 + q, where q = (d0 + d1) ceildiv 2. (d0 + d1) + // ceildiv 2 would be the local expression stored for q. + SmallVector localExprs; + + SimpleAffineExprFlattener(unsigned numDims, unsigned numSymbols); + + virtual ~SimpleAffineExprFlattener() = default; + + // Visitor method overrides. + LogicalResult visitMulExpr(AffineBinaryOpExpr expr); + LogicalResult visitAddExpr(AffineBinaryOpExpr expr); + LogicalResult visitDimExpr(AffineDimExpr expr); + LogicalResult visitSymbolExpr(AffineSymbolExpr expr); + LogicalResult visitConstantExpr(AffineConstantExpr expr); + LogicalResult visitCeilDivExpr(AffineBinaryOpExpr expr); + LogicalResult visitFloorDivExpr(AffineBinaryOpExpr expr); + + // + // t = expr mod c <=> t = expr - c*q and c*q <= expr <= c*q + c - 1 + // + // A mod expression "expr mod c" is thus flattened by introducing a new local + // variable q (= expr floordiv c), such that expr mod c is replaced with + // 'expr - c * q' and c * q <= expr <= c * q + c - 1 are added to localVarCst. + LogicalResult visitModExpr(AffineBinaryOpExpr expr); + +protected: + // Add a local identifier (needed to flatten a mod, floordiv, ceildiv expr). + // The local identifier added is always a floordiv of a pure add/mul affine + // function of other identifiers, coefficients of which are specified in + // dividend and with respect to a positive constant divisor. localExpr is the + // simplified tree expression (AffineExpr) corresponding to the quantifier. + virtual void addLocalFloorDivId(ArrayRef dividend, int64_t divisor, + AffineExpr localExpr); + + /// Add a local identifier (needed to flatten a mod, floordiv, ceildiv, mul + /// expr) when the rhs is a symbolic expression. The local identifier added + /// may be a floordiv, ceildiv, mul or mod of a pure affine/semi-affine + /// function of other identifiers, coefficients of which are specified in the + /// lhs of the mod, floordiv, ceildiv or mul expression and with respect to a + /// symbolic rhs expression. `localExpr` is the simplified tree expression + /// (AffineExpr) corresponding to the quantifier. + virtual LogicalResult addLocalIdSemiAffine(ArrayRef lhs, + ArrayRef rhs, + AffineExpr localExpr); + +private: + /// Adds `localExpr`, which may be mod, ceildiv, floordiv or mod expression + /// representing the affine expression corresponding to the quantifier + /// introduced as the local variable corresponding to `localExpr`. If the + /// quantifier is already present, we put the coefficient in the proper index + /// of `result`, otherwise we add a new local variable and put the coefficient + /// there. + LogicalResult addLocalVariableSemiAffine(ArrayRef lhs, + ArrayRef rhs, + AffineExpr localExpr, + SmallVectorImpl &result, + unsigned long resultSize); + + // t = expr floordiv c <=> t = q, c * q <= expr <= c * q + c - 1 + // A floordiv is thus flattened by introducing a new local variable q, and + // replacing that expression with 'q' while adding the constraints + // c * q <= expr <= c * q + c - 1 to localVarCst (done by + // IntegerRelation::addLocalFloorDiv). + // + // A ceildiv is similarly flattened: + // t = expr ceildiv c <=> t = (expr + c - 1) floordiv c + LogicalResult visitDivExpr(AffineBinaryOpExpr expr, bool isCeil); + + int findLocalId(AffineExpr localExpr); + + inline unsigned getNumCols() const { + return numDims + numSymbols + numLocals + 1; + } + inline unsigned getConstantIndex() const { return getNumCols() - 1; } + inline unsigned getLocalVarStartIndex() const { return numDims + numSymbols; } + inline unsigned getSymbolStartIndex() const { return numDims; } + inline unsigned getDimStartIndex() const { return 0; } +}; + +} // namespace mlir + +#endif // MLIR_IR_AFFINEEXPRVISITOR_H diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/AffineMap.h b/deps/exla/cache/xla_extension/include/mlir/IR/AffineMap.h new file mode 100644 index 0000000000000000000000000000000000000000..4bc40a7d4091a9fc40e69c8a4bf5c0298f7caf7d --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/AffineMap.h @@ -0,0 +1,736 @@ +//===- AffineMap.h - MLIR Affine Map Class ----------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// Affine maps are mathematical functions which map a list of dimension +// identifiers and symbols, to multidimensional affine expressions. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_AFFINEMAP_H +#define MLIR_IR_AFFINEMAP_H + +#include "mlir/IR/AffineExpr.h" +#include "mlir/IR/Value.h" +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/ADT/SmallBitVector.h" +#include "llvm/ADT/SmallVectorExtras.h" +#include + +namespace llvm { +class SmallBitVector; +} // namespace llvm + +namespace mlir { + +namespace detail { +struct AffineMapStorage; +} // namespace detail + +class Attribute; +class Builder; +class OpFoldResult; +class MLIRContext; + +/// A multi-dimensional affine map +/// Affine map's are immutable like Type's, and they are uniqued. +/// Eg: (d0, d1) -> (d0/128, d0 mod 128, d1) +/// The names used (d0, d1) don't matter - it's the mathematical function that +/// is unique to this affine map. +class AffineMap { +public: + using ImplType = detail::AffineMapStorage; + + constexpr AffineMap() = default; + explicit AffineMap(ImplType *map) : map(map) {} + + /// Returns a zero result affine map with no dimensions or symbols: () -> (). + static AffineMap get(MLIRContext *context); + + /// Returns a zero result affine map with `dimCount` dimensions and + /// `symbolCount` symbols, e.g.: `(...) -> ()`. + static AffineMap get(unsigned dimCount, unsigned symbolCount, + MLIRContext *context); + + /// Returns an affine map with `dimCount` dimensions and `symbolCount` mapping + /// to a single output dimension + static AffineMap get(unsigned dimCount, unsigned symbolCount, + AffineExpr result); + + /// Returns an affine map with `dimCount` dimensions and `symbolCount` mapping + /// to the given results. + static AffineMap get(unsigned dimCount, unsigned symbolCount, + ArrayRef results, MLIRContext *context); + + /// Returns a single constant result affine map. + static AffineMap getConstantMap(int64_t val, MLIRContext *context); + + /// Returns an AffineMap with 'numDims' identity result dim exprs. + static AffineMap getMultiDimIdentityMap(unsigned numDims, + MLIRContext *context); + + /// Returns an identity affine map (d0, ..., dn) -> (dp, ..., dn) on the most + /// minor dimensions. + static AffineMap getMinorIdentityMap(unsigned dims, unsigned results, + MLIRContext *context); + + /// Returns an identity affine map with `numDims` input dimensions and + /// filtered results using `keepDimFilter`. If `keepDimFilter` returns true + /// for a dimension, the dimension is kept in the affine map results. + /// Otherwise, the dimension is dropped from the results. + /// + /// Examples: + /// * getFilteredIdentityMap(4, [false, true, false, true]) + /// -> affine_map<(d0, d1, d2, d3) -> (d1, d3)> + /// * getFilteredIdentityMap(3, [false, false, true]) + /// -> affine_map<(d0, d1, d2) -> (d2)> + static AffineMap + getFilteredIdentityMap(MLIRContext *ctx, unsigned numDims, + llvm::function_ref keepDimFilter); + + /// Returns an AffineMap representing a permutation. + /// The permutation is expressed as a non-empty vector of integers. + /// E.g. the permutation `(i,j,k) -> (j,k,i)` will be expressed with + /// `permutation = [1,2,0]`. All values in `permutation` must be + /// integers, in the range 0..`permutation.size()-1` without duplications + /// (i.e. `[1,1,2]` is an invalid permutation). + static AffineMap getPermutationMap(ArrayRef permutation, + MLIRContext *context); + static AffineMap getPermutationMap(ArrayRef permutation, + MLIRContext *context); + + /// Returns an affine map with `numDims` input dimensions and results + /// specified by `targets`. + /// + /// Examples: + /// * getMultiDimMapWithTargets(3, [0, 2, 1]) + /// -> affine_map<(d0, d1, d2) -> (d0, d2, d1)> + /// * getMultiDimMapWithTargets(3, [2, 1]) + /// -> affine_map<(d0, d1, d2) -> (d2, d1)> + static AffineMap getMultiDimMapWithTargets(unsigned numDims, + ArrayRef targets, + MLIRContext *context); + + /// Returns a vector of AffineMaps; each with as many results as + /// `exprs.size()`, as many dims as the largest dim in `exprs` and as many + /// symbols as the largest symbol in `exprs`. + static SmallVector + inferFromExprList(ArrayRef> exprsList, + MLIRContext *context); + static SmallVector + inferFromExprList(ArrayRef> exprsList, + MLIRContext *context); + + MLIRContext *getContext() const; + + explicit operator bool() const { return map != nullptr; } + bool operator==(AffineMap other) const { return other.map == map; } + bool operator!=(AffineMap other) const { return !(other.map == map); } + + /// Returns true if this affine map is an identity affine map. + /// An identity affine map corresponds to an identity affine function on the + /// dimensional identifiers. + bool isIdentity() const; + + /// Returns true if this affine map is an identity affine map on the symbol + /// identifiers. + bool isSymbolIdentity() const; + + /// Returns true if this affine map is a minor identity, i.e. an identity + /// affine map (d0, ..., dn) -> (dp, ..., dn) on the most minor dimensions. + bool isMinorIdentity() const; + + /// Returns the list of broadcast dimensions (i.e. dims indicated by value 0 + /// in the result). + /// Ex: + /// * (d0, d1, d2) -> (0, d1) gives [0] + /// * (d0, d1, d2) -> (d2, d1) gives [] + /// * (d0, d1, d2, d4) -> (d0, 0, d1, 0) gives [1, 3] + SmallVector getBroadcastDims() const; + + /// Returns true if this affine map is a minor identity up to broadcasted + /// dimensions which are indicated by value 0 in the result. If + /// `broadcastedDims` is not null, it will be populated with the indices of + /// the broadcasted dimensions in the result array. + /// Example: affine_map<(d0, d1, d2, d3, d4) -> (0, d2, 0, d4)> + /// (`broadcastedDims` will contain [0, 2]) + bool isMinorIdentityWithBroadcasting( + SmallVectorImpl *broadcastedDims = nullptr) const; + + /// Return true if this affine map can be converted to a minor identity with + /// broadcast by doing a permute. Return a permutation (there may be + /// several) to apply to get to a minor identity with broadcasts. + /// Ex: + /// * (d0, d1, d2) -> (0, d1) maps to minor identity (d1, 0 = d2) with + /// perm = [1, 0] and broadcast d2 + /// * (d0, d1, d2) -> (d0, 0) cannot be mapped to a minor identity by + /// permutation + broadcast + /// * (d0, d1, d2, d3) -> (0, d1, d3) maps to minor identity (d1, 0 = d2, d3) + /// with perm = [1, 0, 2] and broadcast d2 + /// * (d0, d1) -> (d1, 0, 0, d0) maps to minor identity (d0, d1) with extra + /// leading broadcat dimensions. The map returned would be (0, 0, d0, d1) + /// with perm = [3, 0, 1, 2] + bool isPermutationOfMinorIdentityWithBroadcasting( + SmallVectorImpl &permutedDims) const; + + /// Returns true if this affine map is an empty map, i.e., () -> (). + bool isEmpty() const; + + /// Returns true if this affine map is a single result constant function. + bool isSingleConstant() const; + + /// Returns true if this affine map has only constant results. + bool isConstant() const; + + /// Returns the constant result of this map. This methods asserts that the map + /// has a single constant result. + int64_t getSingleConstantResult() const; + + /// Returns the constant results of this map. This method asserts that the map + /// has all constant results. + SmallVector getConstantResults() const; + + // Prints affine map to 'os'. + void print(raw_ostream &os) const; + void dump() const; + + unsigned getNumDims() const; + unsigned getNumSymbols() const; + unsigned getNumResults() const; + unsigned getNumInputs() const; + + ArrayRef getResults() const; + AffineExpr getResult(unsigned idx) const; + + /// Extracts the position of the dimensional expression at the given result, + /// when the caller knows it is safe to do so. + unsigned getDimPosition(unsigned idx) const; + + /// Extracts the first result position where `input` dimension resides. + /// Returns `std::nullopt` if `input` is not a dimension expression or cannot + /// be found in results. + std::optional getResultPosition(AffineExpr input) const; + + /// Return true if any affine expression involves AffineDimExpr `position`. + bool isFunctionOfDim(unsigned position) const { + return llvm::any_of(getResults(), [&](AffineExpr e) { + return e.isFunctionOfDim(position); + }); + } + + /// Return true if any affine expression involves AffineSymbolExpr `position`. + bool isFunctionOfSymbol(unsigned position) const { + return llvm::any_of(getResults(), [&](AffineExpr e) { + return e.isFunctionOfSymbol(position); + }); + } + + /// Walk all of the AffineExpr's in this mapping. Each node in an expression + /// tree is visited in postorder. + void walkExprs(llvm::function_ref callback) const; + + /// This method substitutes any uses of dimensions and symbols (e.g. + /// dim#0 with dimReplacements[0]) in subexpressions and returns the modified + /// expression mapping. Because this can be used to eliminate dims and + /// symbols, the client needs to specify the number of dims and symbols in + /// the result. The returned map always has the same number of results. + AffineMap replaceDimsAndSymbols(ArrayRef dimReplacements, + ArrayRef symReplacements, + unsigned numResultDims, + unsigned numResultSyms) const; + + /// Sparse replace method. Apply AffineExpr::replace(`expr`, `replacement`) to + /// each of the results and return a new AffineMap with the new results and + /// with the specified number of dims and symbols. + AffineMap replace(AffineExpr expr, AffineExpr replacement, + unsigned numResultDims, unsigned numResultSyms) const; + + /// Sparse replace method. Apply AffineExpr::replace(`map`) to each of the + /// results and return a new AffineMap with the new results and with inferred + /// number of dims and symbols. + AffineMap replace(const DenseMap &map) const; + + /// Sparse replace method. Apply AffineExpr::replace(`map`) to each of the + /// results and return a new AffineMap with the new results and with the + /// specified number of dims and symbols. + AffineMap replace(const DenseMap &map, + unsigned numResultDims, unsigned numResultSyms) const; + + /// Replace dims[offset ... numDims) + /// by dims[offset + shift ... shift + numDims). + AffineMap shiftDims(unsigned shift, unsigned offset = 0) const { + assert(offset <= getNumDims()); + return AffineMap::get(getNumDims() + shift, getNumSymbols(), + llvm::map_to_vector<4>( + getResults(), + [&](AffineExpr e) { + return e.shiftDims(getNumDims(), shift, offset); + }), + getContext()); + } + + /// Replace symbols[offset ... numSymbols) + /// by symbols[offset + shift ... shift + numSymbols). + AffineMap shiftSymbols(unsigned shift, unsigned offset = 0) const { + return AffineMap::get(getNumDims(), getNumSymbols() + shift, + llvm::map_to_vector<4>(getResults(), + [&](AffineExpr e) { + return e.shiftSymbols( + getNumSymbols(), shift, + offset); + }), + getContext()); + } + + /// Returns a new AffineMap with the same number of dims and symbols and one + /// less result at `pos`, dropped. + AffineMap dropResult(int64_t pos) const { + return dropResults(ArrayRef({pos})); + } + + // Returns a new AffineMap with the same number of dims and symbols, but all + // results in `positions` dropped. + AffineMap dropResults(ArrayRef positions) const { + SmallVector reverse_sorted_positions = llvm::to_vector(positions); + llvm::sort(reverse_sorted_positions, std::greater()); + + auto exprs = llvm::to_vector<4>(getResults()); + for (int64_t pos : reverse_sorted_positions) + exprs.erase(exprs.begin() + pos); + return AffineMap::get(getNumDims(), getNumSymbols(), exprs, getContext()); + } + + // Returns a new AffineMap with the same number of dims and symbols, but all + // results in `positions` dropped. + AffineMap dropResults(const llvm::SmallBitVector &positions) const; + + /// Returns a new AffineMap with the same number of dims and symbols and an + /// extra result inserted at `pos`. + AffineMap insertResult(AffineExpr expr, unsigned pos) const { + auto exprs = llvm::to_vector<4>(getResults()); + exprs.insert(exprs.begin() + pos, expr); + return AffineMap::get(getNumDims(), getNumSymbols(), exprs, getContext()); + } + + /// Folds the results of the application of an affine map on the provided + /// operands to a constant if possible. + LogicalResult constantFold(ArrayRef operandConstants, + SmallVectorImpl &results, + bool *hasPoison = nullptr) const; + + /// Propagates the constant operands into this affine map. Operands are + /// allowed to be null, at which point they are treated as non-constant. This + /// does not change the number of symbols and dimensions. Returns a new map, + /// which may be equal to the old map if no folding happened. If `results` is + /// provided and if all expressions in the map were folded to constants, + /// `results` will contain the values of these constants. + AffineMap partialConstantFold(ArrayRef operandConstants, + SmallVectorImpl *results = nullptr, + bool *hasPoison = nullptr) const; + + /// Returns the AffineMap resulting from composing `this` with `map`. + /// The resulting AffineMap has as many AffineDimExpr as `map` and as many + /// AffineSymbolExpr as the concatenation of `this` and `map` (in which case + /// the symbols of `this` map come first). + /// + /// Prerequisites: + /// The maps are composable, i.e. that the number of AffineDimExpr of `this` + /// matches the number of results of `map`. + /// + /// Example: + /// map1: `(d0, d1)[s0, s1] -> (d0 + 1 + s1, d1 - 1 - s0)` + /// map2: `(d0)[s0] -> (d0 + s0, d0 - s0)` + /// map1.compose(map2): + /// `(d0)[s0, s1, s2] -> (d0 + s1 + s2 + 1, d0 - s0 - s2 - 1)` + AffineMap compose(AffineMap map) const; + + /// Applies composition by the dims of `this` to the integer `values` and + /// returns the resulting values. `this` must be symbol-less. + SmallVector compose(ArrayRef values) const; + + /// Returns the number of "zero" results (constant values == 0) in this map. + /// + /// Example: + /// * For `(d0, d1) -> (d0, d1, 0)` returns 1 + /// * For `(d0, d1, d2) -> (d0, d1)` returns 0 + /// * For `(d0, d1, d2) -> (d0, 0, d1, 0, d2)` returns 2 + size_t getNumOfZeroResults() const; + + /// Returns the AffineMap resulting from removing "zero" results (constant + /// values == 0) from this map. + /// + /// Example: + /// * For `(d0, d1) -> (d0, d1, 0)` returns `(d0, d1) -> (d0, d1)` + /// * For `(d0, d1, d2) -> (d0, d1)` returns `(d0, d1, d2) -> (d0, d1)` + /// * For `(d0, d1, d2) -> (d0, 0, d1, 0, d2)` returns + /// `(d0, d1, d2) -> (d0, d1, d2)` + AffineMap dropZeroResults(); + + /// Returns true if the AffineMap represents a subset (i.e. a projection) of a + /// symbol-less permutation map. `allowZeroInResults` allows projected + /// permutation maps with constant zero result expressions. + /// TODO: Remove `allowZeroInResults` when constant zero result expressions + /// are broadly supported. + bool isProjectedPermutation(bool allowZeroInResults = false) const; + + /// Returns true if the AffineMap represents a symbol-less permutation map. + bool isPermutation() const; + + /// Returns the map consisting of the `resultPos` subset. + AffineMap getSubMap(ArrayRef resultPos) const; + + /// Returns the map consisting of `length` expressions starting from `start`. + AffineMap getSliceMap(unsigned start, unsigned length) const; + + /// Returns the map consisting of the most major `numResults` results. + /// Returns the null AffineMap if `numResults` == 0. + /// Returns `*this` if `numResults` >= `this->getNumResults()`. + AffineMap getMajorSubMap(unsigned numResults) const; + + /// Returns the map consisting of the most minor `numResults` results. + /// Returns the null AffineMap if `numResults` == 0. + /// Returns `*this` if `numResults` >= `this->getNumResults()`. + AffineMap getMinorSubMap(unsigned numResults) const; + + /// Get the largest known divisor of all map expressions. + /// For eg: for (d0, d1) -> (8*d0 + 4, 4*d1 + 2), the result is 2. + /// In the case of maps with no expressions or all zero constant expressions, + /// the largest known divisor is trivially the max uint64_t value. + uint64_t getLargestKnownDivisorOfMapExprs(); + + friend ::llvm::hash_code hash_value(AffineMap arg); + + /// Methods supporting C API. + const void *getAsOpaquePointer() const { + return static_cast(map); + } + static AffineMap getFromOpaquePointer(const void *pointer) { + return AffineMap(reinterpret_cast(const_cast(pointer))); + } + +private: + ImplType *map{nullptr}; + + static AffineMap getImpl(unsigned dimCount, unsigned symbolCount, + ArrayRef results, MLIRContext *context); +}; + +// Make AffineExpr hashable. +inline ::llvm::hash_code hash_value(AffineMap arg) { + return ::llvm::hash_value(arg.map); +} + +/// A mutable affine map. Its affine expressions are however unique. +struct MutableAffineMap { +public: + MutableAffineMap() = default; + MutableAffineMap(AffineMap map); + + ArrayRef getResults() const { return results; } + AffineExpr getResult(unsigned idx) const { return results[idx]; } + void setResult(unsigned idx, AffineExpr result) { results[idx] = result; } + unsigned getNumResults() const { return results.size(); } + unsigned getNumDims() const { return numDims; } + void setNumDims(unsigned d) { numDims = d; } + unsigned getNumSymbols() const { return numSymbols; } + void setNumSymbols(unsigned d) { numSymbols = d; } + MLIRContext *getContext() const { return context; } + + /// Returns true if the idx'th result expression is a multiple of factor. + bool isMultipleOf(unsigned idx, int64_t factor) const; + + /// Resets this MutableAffineMap with 'map'. + void reset(AffineMap map); + + /// Simplify the (result) expressions in this map using analysis (used by + //-simplify-affine-expr pass). + void simplify(); + /// Get the AffineMap corresponding to this MutableAffineMap. Note that an + /// AffineMap will be uniqued and stored in context, while a mutable one + /// isn't. + AffineMap getAffineMap() const; + +private: + // Same meaning as AffineMap's fields. + SmallVector results; + unsigned numDims = 0; + unsigned numSymbols = 0; + /// A pointer to the IR's context to store all newly created + /// AffineExprStorage's. + MLIRContext *context = nullptr; +}; + +/// Simplifies an affine map by simplifying its underlying AffineExpr results. +AffineMap simplifyAffineMap(AffineMap map); + +/// Drop the dims that are listed in `unusedDims`. +AffineMap compressDims(AffineMap map, const llvm::SmallBitVector &unusedDims); + +/// Drop the dims that are not used. +AffineMap compressUnusedDims(AffineMap map); + +/// Drop the dims that are not used by any of the individual maps in `maps`. +/// Asserts that all maps in `maps` are normalized to the same number of +/// dims and symbols. +SmallVector compressUnusedDims(ArrayRef maps); + +/// Drop the symbols that are listed in `unusedSymbols`. +AffineMap compressSymbols(AffineMap map, + const llvm::SmallBitVector &unusedSymbols); + +/// Drop the symbols that are not used. +AffineMap compressUnusedSymbols(AffineMap map); + +/// Drop the symbols that are not used by any of the individual maps in `maps`. +/// Asserts that all maps in `maps` are normalized to the same number of +/// dims and symbols. +SmallVector compressUnusedSymbols(ArrayRef maps); + +/// Fold all attributes among the given operands into the affine map. Return the +/// folded affine map. Return all remaining values via `remainingValues`. +AffineMap foldAttributesIntoMap(Builder &b, AffineMap map, + ArrayRef operands, + SmallVector &remainingValues); + +/// Returns a map with the same dimension and symbol count as `map`, but whose +/// results are the unique affine expressions of `map`. +AffineMap removeDuplicateExprs(AffineMap map); + +/// Returns a map of codomain to domain dimensions such that the first codomain +/// dimension for a particular domain dimension is selected. +/// Returns an empty map if the input map is empty. +/// Returns null map (not empty map) if `map` is not invertible (i.e. `map` does +/// not contain a subset that is a permutation of full domain rank). +/// +/// Prerequisites: +/// 1. `map` has no symbols. +/// +/// Example 1: +/// +/// ```mlir +/// (d0, d1, d2) -> (d1, d1, d0, d2, d1, d2, d1, d0) +/// 0 2 3 +/// ``` +/// +/// returns: +/// +/// ```mlir +/// (d0, d1, d2, d3, d4, d5, d6, d7) -> (d2, d0, d3) +/// ``` +/// +/// Example 2: +/// +/// ```mlir +/// (d0, d1, d2) -> (d1, d0 + d1, d0, d2, d1, d2, d1, d0) +/// 0 2 3 +/// ``` +/// +/// returns: +/// +/// ```mlir +/// (d0, d1, d2, d3, d4, d5, d6, d7) -> (d2, d0, d3) +/// ``` +AffineMap inversePermutation(AffineMap map); + +/// Return the reverse map of a projected permutation where the projected +/// dimensions are transformed into 0s. +/// +/// Prerequisites: `map` must be a projected permutation. +/// +/// Example 1: +/// +/// ```mlir +/// affine_map<(d0, d1, d2, d3) -> (d2, d0)> +/// ``` +/// +/// returns: +/// +/// ```mlir +/// affine_map<(d0, d1) -> (d1, 0, d0, 0)> +/// ``` +/// +/// Example 2: +/// +/// ```mlir +/// affine_map<(d0, d1, d2, d3) -> (d0, d3)> +/// ``` +/// +/// returns: +/// +/// ```mlir +/// affine_map<(d0, d1) -> (d0, 0, 0, d1)> +/// ``` +/// +/// Example 3: +/// +/// ```mlir +/// affine_map<(d0, d1, d2, d3) -> (d2)> +/// ``` +/// +/// returns: +/// +/// ```mlir +/// affine_map<(d0) -> (0, 0, d0, 0)> +/// ``` +/// Example 4: +/// +/// ```mlir +/// affine_map<(d0, d1, d2) -> (d0, 0)> +/// ``` +/// +/// returns: +/// +/// ```mlir +/// affine_map<(d0, d1) -> (d0, 0, 0)> +/// ``` +AffineMap inverseAndBroadcastProjectedPermutation(AffineMap map); + +/// Concatenates a list of `maps` into a single AffineMap, stepping over +/// potentially empty maps. Assumes each of the underlying map has 0 symbols. +/// The resulting map has a number of dims equal to the max of `maps`' dims and +/// the concatenated results as its results. +/// Returns an empty map if all input `maps` are empty. +/// +/// Example: +/// When applied to the following list of 3 affine maps, +/// +/// ```mlir +/// { +/// (i, j, k) -> (i, k), +/// (i, j, k) -> (k, j), +/// (i, j, k) -> (i, j) +/// } +/// ``` +/// +/// Returns the map: +/// +/// ```mlir +/// (i, j, k) -> (i, k, k, j, i, j) +/// ``` +AffineMap concatAffineMaps(ArrayRef maps, MLIRContext *context); + +/// Returns the map that results from projecting out the dimensions specified in +/// `projectedDimensions`. The projected dimensions are set to 0. +/// +/// Example: +/// 1) map : affine_map<(d0, d1, d2) -> (d0, d1)> +/// projected_dimensions : {2} +/// result : affine_map<(d0, d1) -> (d0, d1)> +/// +/// 2) map : affine_map<(d0, d1) -> (d0 + d1)> +/// projected_dimensions : {1} +/// result : affine_map<(d0) -> (d0)> +/// +/// 3) map : affine_map<(d0, d1, d2) -> (d0, d1)> +/// projected_dimensions : {1} +/// result : affine_map<(d0, d1) -> (d0, 0)> +/// +/// This function also compresses the dims when the boolean flag is true. +AffineMap projectDims(AffineMap map, + const llvm::SmallBitVector &projectedDimensions, + bool compressDimsFlag = false); +/// Symbol counterpart of `projectDims`. +/// This function also compresses the symbols when the boolean flag is true. +AffineMap projectSymbols(AffineMap map, + const llvm::SmallBitVector &projectedSymbols, + bool compressSymbolsFlag = false); +/// Calls `projectDims(map, projectedDimensions, compressDimsFlag)`. +/// If `compressSymbolsFlag` is true, additionally call `compressUnusedSymbols`. +AffineMap getProjectedMap(AffineMap map, + const llvm::SmallBitVector &projectedDimensions, + bool compressDimsFlag = true, + bool compressSymbolsFlag = true); + +// Return a bitvector where each bit set indicates a dimension that is not used +// by any of the maps in the input array `maps`. +llvm::SmallBitVector getUnusedDimsBitVector(ArrayRef maps); + +// Return a bitvector where each bit set indicates a symbol that is not used +// by any of the maps in the input array `maps`. +llvm::SmallBitVector getUnusedSymbolsBitVector(ArrayRef maps); + +/// Expand `map` to operate on `rank` dims while projecting out the dims in +/// `projectedDimensions`. This amounts to composing `map` with +/// `id(rank).dropResults(projectedDimensions)`. +AffineMap expandDimsToRank(AffineMap map, int64_t rank, + const llvm::SmallBitVector &projectedDimensions); + +inline raw_ostream &operator<<(raw_ostream &os, AffineMap map) { + map.print(os); + return os; +} + +//===----------------------------------------------------------------------===// +// Templated helper functions. +//===----------------------------------------------------------------------===// + +/// Apply a permutation from `map` to `source` and return the result. +template +SmallVector applyPermutationMap(AffineMap map, llvm::ArrayRef source) { + assert(map.isProjectedPermutation()); + assert(map.getNumInputs() == source.size()); + SmallVector result; + result.reserve(map.getNumResults()); + for (AffineExpr expr : map.getResults()) { + if (auto dimExpr = dyn_cast(expr)) { + result.push_back(source[dimExpr.getPosition()]); + } else if (auto constExpr = dyn_cast(expr)) { + assert(constExpr.getValue() == 0 && + "Unexpected constant in projected permutation map"); + result.push_back(0); + } else { + llvm_unreachable("Unexpected result in projected permutation map"); + } + } + return result; +} + +/// Calculates maximum dimension and symbol positions from the expressions +/// in `exprsLists` and stores them in `maxDim` and `maxSym` respectively. +template +static void getMaxDimAndSymbol(ArrayRef exprsList, + int64_t &maxDim, int64_t &maxSym) { + for (const auto &exprs : exprsList) { + for (auto expr : exprs) { + expr.walk([&maxDim, &maxSym](AffineExpr e) { + if (auto d = dyn_cast(e)) + maxDim = std::max(maxDim, static_cast(d.getPosition())); + if (auto s = dyn_cast(e)) + maxSym = std::max(maxSym, static_cast(s.getPosition())); + }); + } + } +} + +} // namespace mlir + +namespace llvm { + +// AffineExpr hash just like pointers +template <> +struct DenseMapInfo { + static mlir::AffineMap getEmptyKey() { + auto *pointer = llvm::DenseMapInfo::getEmptyKey(); + return mlir::AffineMap(static_cast(pointer)); + } + static mlir::AffineMap getTombstoneKey() { + auto *pointer = llvm::DenseMapInfo::getTombstoneKey(); + return mlir::AffineMap(static_cast(pointer)); + } + static unsigned getHashValue(mlir::AffineMap val) { + return mlir::hash_value(val); + } + static bool isEqual(mlir::AffineMap LHS, mlir::AffineMap RHS) { + return LHS == RHS; + } +}; + +} // namespace llvm + +#endif // MLIR_IR_AFFINEMAP_H diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/AsmState.h b/deps/exla/cache/xla_extension/include/mlir/IR/AsmState.h new file mode 100644 index 0000000000000000000000000000000000000000..5e9311742bd94a731174f066fceb915b68315598 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/AsmState.h @@ -0,0 +1,615 @@ +//===- AsmState.h - Assembly State Utilities --------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines various classes and utilites for interacting with the MLIR +// assembly formats. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_ASMSTATE_H_ +#define MLIR_IR_ASMSTATE_H_ + +#include "mlir/Bytecode/BytecodeReaderConfig.h" +#include "mlir/IR/OperationSupport.h" +#include "mlir/Support/LLVM.h" +#include "llvm/ADT/MapVector.h" +#include "llvm/ADT/StringMap.h" + +#include +#include + +namespace mlir { +class AsmResourcePrinter; +class AsmDialectResourceHandle; +class Operation; + +namespace detail { +class AsmStateImpl; +} // namespace detail + +//===----------------------------------------------------------------------===// +// Resources +//===----------------------------------------------------------------------===// + +/// The following classes enable support for parsing and printing resources +/// within MLIR assembly formats. Resources are a mechanism by which dialects, +/// and external clients, may attach additional information when parsing or +/// printing IR without that information being encoded in the IR itself. +/// Resources are not uniqued within the MLIR context, are not attached directly +/// to any operation, and are solely intended to live and be processed outside +/// of the immediate IR. +/// +/// Resources are encoded using a key-value pair nested within dictionaries +/// anchored either on a dialect, or an externally registered entity. +/// Dictionaries anchored on dialects use the dialect namespace directly, and +/// dictionaries anchored on external entities use a provided unique identifier. +/// The resource key is an identifier used to disambiguate the data. The +/// resource value may be stored in various limited forms, but general encodings +/// use a string (human readable) or blob format (binary). Within the textual +/// format, an example may be of the form: +/// +/// {-# +/// // The `dialect_resources` section within the file-level metadata +/// // dictionary is used to contain any dialect resource entries. +/// dialect_resources: { +/// // Here is a dictionary anchored on "foo_dialect", which is a dialect +/// // namespace. +/// foo_dialect: { +/// // `some_dialect_resource` is a key to be interpreted by the dialect, +/// // and used to initialize/configure/etc. +/// some_dialect_resource: "Some important resource value" +/// } +/// }, +/// // The `external_resources` section within the file-level metadata +/// // dictionary is used to contain any non-dialect resource entries. +/// external_resources: { +/// // Here is a dictionary anchored on "mlir_reproducer", which is an +/// // external entity representing MLIR's crash reproducer functionality. +/// mlir_reproducer: { +/// // `pipeline` is an entry that holds a crash reproducer pipeline +/// // resource. +/// pipeline: "func.func(canonicalize,cse)" +/// } +/// } +/// #-} +/// + +//===----------------------------------------------------------------------===// +// Resource Entry +//===----------------------------------------------------------------------===// + +class HeapAsmResourceBlob; + +/// This class represents a processed binary blob of data. A resource blob is +/// essentially a collection of data, potentially mutable, with an associated +/// deleter function (used if the data needs to be destroyed). +class AsmResourceBlob { +public: + /// A deleter function that frees a blob given the data, allocation size, and + /// allocation aligment. + using DeleterFn = + llvm::unique_function; + + //===--------------------------------------------------------------------===// + // Construction + //===--------------------------------------------------------------------===// + + AsmResourceBlob() = default; + AsmResourceBlob(ArrayRef data, size_t dataAlignment, DeleterFn deleter, + bool dataIsMutable) + : data(data), dataAlignment(dataAlignment), deleter(std::move(deleter)), + dataIsMutable(dataIsMutable) {} + /// Utility constructor that initializes a blob with a non-char type T. + template + AsmResourceBlob(ArrayRef data, DelT &&deleteFn, bool dataIsMutable) + : data((const char *)data.data(), data.size() * sizeof(T)), + dataAlignment(alignof(T)), + deleter([deleteFn = std::forward(deleteFn)]( + void *data, size_t size, size_t align) { + return deleteFn((T *)data, size, align); + }), + dataIsMutable(dataIsMutable) {} + AsmResourceBlob(AsmResourceBlob &&) = default; + AsmResourceBlob &operator=(AsmResourceBlob &&rhs) { + // Delete the current blob if necessary. + if (deleter) + deleter(const_cast(data.data()), data.size(), dataAlignment); + + // Take the data entries from rhs. + data = rhs.data; + dataAlignment = rhs.dataAlignment; + deleter = std::move(rhs.deleter); + dataIsMutable = rhs.dataIsMutable; + return *this; + } + AsmResourceBlob(const AsmResourceBlob &) = delete; + AsmResourceBlob &operator=(const AsmResourceBlob &) = delete; + ~AsmResourceBlob() { + if (deleter) + deleter(const_cast(data.data()), data.size(), dataAlignment); + } + + //===--------------------------------------------------------------------===// + // Data Access + //===--------------------------------------------------------------------===// + + /// Return the alignment of the underlying data. + size_t getDataAlignment() const { return dataAlignment; } + + /// Return the raw underlying data of this blob. + ArrayRef getData() const { return data; } + + /// Return the underlying data as an array of the given type. This is an + /// inherrently unsafe operation, and should only be used when the data is + /// known to be of the correct type. + template + ArrayRef getDataAs() const { + return llvm::ArrayRef((const T *)data.data(), data.size() / sizeof(T)); + } + + /// Return a mutable reference to the raw underlying data of this blob. + /// Asserts that the blob `isMutable`. + MutableArrayRef getMutableData() { + assert(isMutable() && + "cannot access mutable reference to non-mutable data"); + return MutableArrayRef(const_cast(data.data()), data.size()); + } + + /// Return if the data of this blob is mutable. + bool isMutable() const { return dataIsMutable; } + + /// Return the deleter function of this blob. + DeleterFn &getDeleter() { return deleter; } + const DeleterFn &getDeleter() const { return deleter; } + +private: + /// The raw, properly aligned, blob data. + ArrayRef data; + + /// The alignment of the data. + size_t dataAlignment = 0; + + /// An optional deleter function used to deallocate the underlying data when + /// necessary. + DeleterFn deleter; + + /// Whether the data is mutable. + bool dataIsMutable; + + friend class HeapAsmResourceBlob; +}; + +/// This class provides a simple utility wrapper for creating heap allocated +/// AsmResourceBlobs. +class HeapAsmResourceBlob { +public: + /// Create a new heap allocated blob with the given size and alignment. + /// `dataIsMutable` indicates if the allocated data can be mutated. By + /// default, we treat heap allocated blobs as mutable. + static AsmResourceBlob allocate(size_t size, size_t align, + bool dataIsMutable = true) { + return AsmResourceBlob( + ArrayRef((char *)llvm::allocate_buffer(size, align), size), align, + llvm::deallocate_buffer, dataIsMutable); + } + /// Create a new heap allocated blob and copy the provided data into it. + static AsmResourceBlob allocateAndCopyWithAlign(ArrayRef data, + size_t align, + bool dataIsMutable = true) { + // This sets the blob to be mutable initially to allow writing + // (getMutableData) below. + AsmResourceBlob blob = allocate(data.size(), align, /*dataIsMutable=*/true); + std::memcpy(blob.getMutableData().data(), data.data(), data.size()); + blob.dataIsMutable = dataIsMutable; + return blob; + } + template + static AsmResourceBlob allocateAndCopyInferAlign(ArrayRef data, + bool dataIsMutable = true) { + return allocateAndCopyWithAlign( + ArrayRef((const char *)data.data(), data.size() * sizeof(T)), + alignof(T), dataIsMutable); + } +}; +/// This class provides a simple utility wrapper for creating "unmanaged" +/// AsmResourceBlobs. The lifetime of the data provided to these blobs is +/// guaranteed to persist beyond the lifetime of this reference. +class UnmanagedAsmResourceBlob { +public: + /// Create a new unmanaged resource directly referencing the provided data. + /// `dataIsMutable` indicates if the allocated data can be mutated. By + /// default, we treat unmanaged blobs as immutable. + static AsmResourceBlob + allocateWithAlign(ArrayRef data, size_t align, + AsmResourceBlob::DeleterFn deleter = {}, + bool dataIsMutable = false) { + return AsmResourceBlob(data, align, std::move(deleter), dataIsMutable); + } + template + static AsmResourceBlob + allocateInferAlign(ArrayRef data, AsmResourceBlob::DeleterFn deleter = {}, + bool dataIsMutable = false) { + return allocateWithAlign( + ArrayRef((const char *)data.data(), data.size() * sizeof(T)), + alignof(T), std::move(deleter), dataIsMutable); + } +}; + +/// This class is used to build resource entries for use by the printer. Each +/// resource entry is represented using a key/value pair. The provided key must +/// be unique within the current context, which allows for a client to provide +/// resource entries without worrying about overlap with other clients. +class AsmResourceBuilder { +public: + virtual ~AsmResourceBuilder(); + + /// Build a resource entry represented by the given bool. + virtual void buildBool(StringRef key, bool data) = 0; + + /// Build a resource entry represented by the given human-readable string + /// value. + virtual void buildString(StringRef key, StringRef data) = 0; + + /// Build an resource entry represented by the given binary blob data. + virtual void buildBlob(StringRef key, ArrayRef data, + uint32_t dataAlignment) = 0; + /// Build an resource entry represented by the given binary blob data. This is + /// a useful overload if the data type is known. Note that this does not + /// support `char` element types to avoid accidentally not providing the + /// expected alignment of data in situations that treat blobs generically. + template + std::enable_if_t::value> buildBlob(StringRef key, + ArrayRef data) { + buildBlob( + key, ArrayRef((const char *)data.data(), data.size() * sizeof(T)), + alignof(T)); + } + /// Build an resource entry represented by the given resource blob. This is + /// a useful overload if a blob already exists in-memory. + void buildBlob(StringRef key, const AsmResourceBlob &blob) { + buildBlob(key, blob.getData(), blob.getDataAlignment()); + } +}; + +/// This enum represents the different kinds of resource values. +enum class AsmResourceEntryKind { + /// A blob of data with an accompanying alignment. + Blob, + /// A boolean value. + Bool, + /// A string value. + String, +}; +StringRef toString(AsmResourceEntryKind kind); + +/// This class represents a single parsed resource entry. +class AsmParsedResourceEntry { +public: + virtual ~AsmParsedResourceEntry(); + + /// Return the key of the resource entry. + virtual StringRef getKey() const = 0; + + /// Emit an error at the location of this entry. + virtual InFlightDiagnostic emitError() const = 0; + + /// Return the kind of this value. + virtual AsmResourceEntryKind getKind() const = 0; + + /// Parse the resource entry represented by a boolean. Returns failure if the + /// entry does not correspond to a bool. + virtual FailureOr parseAsBool() const = 0; + + /// Parse the resource entry represented by a human-readable string. Returns + /// failure if the entry does not correspond to a string. + virtual FailureOr parseAsString() const = 0; + + /// An allocator function used to allocate memory for a blob when required. + /// The function is provided a size and alignment, and should return an + /// aligned allocation buffer. + using BlobAllocatorFn = + function_ref; + + /// Parse the resource entry represented by a binary blob. Returns failure if + /// the entry does not correspond to a blob. If the blob needed to be + /// allocated, the given allocator function is invoked. + virtual FailureOr + parseAsBlob(BlobAllocatorFn allocator) const = 0; + /// Parse the resource entry represented by a binary blob using heap + /// allocation. + FailureOr parseAsBlob() const { + return parseAsBlob([](size_t size, size_t align) { + return HeapAsmResourceBlob::allocate(size, align); + }); + } +}; + +//===----------------------------------------------------------------------===// +// Resource Parser/Printer +//===----------------------------------------------------------------------===// + +/// This class represents an instance of a resource parser. This class should be +/// implemented by non-dialect clients that want to inject additional resources +/// into MLIR assembly formats. +class AsmResourceParser { +public: + /// Create a new parser with the given identifying name. This name uniquely + /// identifies the entries of this parser, and differentiates them from other + /// contexts. + AsmResourceParser(StringRef name) : name(name.str()) {} + virtual ~AsmResourceParser(); + + /// Return the name of this parser. + StringRef getName() const { return name; } + + /// Parse the given resource entry. Returns failure if the key/data were not + /// valid, or could otherwise not be processed correctly. Any necessary errors + /// should be emitted with the provided entry. + virtual LogicalResult parseResource(AsmParsedResourceEntry &entry) = 0; + + /// Return a resource parser implemented via the given callable, whose form + /// should match that of `parseResource` above. + template + static std::unique_ptr fromCallable(StringRef name, + CallableT &&parseFn) { + struct Processor : public AsmResourceParser { + Processor(StringRef name, CallableT &&parseFn) + : AsmResourceParser(name), parseFn(std::move(parseFn)) {} + LogicalResult parseResource(AsmParsedResourceEntry &entry) override { + return parseFn(entry); + } + + std::decay_t parseFn; + }; + return std::make_unique(name, std::forward(parseFn)); + } + +private: + std::string name; +}; + +/// This class represents an instance of a resource printer. This class should +/// be implemented by non-dialect clients that want to inject additional +/// resources into MLIR assembly formats. +class AsmResourcePrinter { +public: + /// Create a new printer with the given identifying name. This name uniquely + /// identifies the entries of this printer, and differentiates them from + /// other contexts. + AsmResourcePrinter(StringRef name) : name(name.str()) {} + virtual ~AsmResourcePrinter(); + + /// Return the name of this printer. + StringRef getName() const { return name; } + + /// Build any resources to include during printing, utilizing the given + /// top-level root operation to help determine what information to include. + /// Provided data should be registered in the form of a key/data pair, to the + /// given builder. + virtual void buildResources(Operation *op, + AsmResourceBuilder &builder) const = 0; + + /// Return a resource printer implemented via the given callable, whose form + /// should match that of `buildResources` above. + template + static std::unique_ptr fromCallable(StringRef name, + CallableT &&printFn) { + struct Printer : public AsmResourcePrinter { + Printer(StringRef name, CallableT &&printFn) + : AsmResourcePrinter(name), printFn(std::move(printFn)) {} + void buildResources(Operation *op, + AsmResourceBuilder &builder) const override { + printFn(op, builder); + } + + std::decay_t printFn; + }; + return std::make_unique(name, std::forward(printFn)); + } + +private: + std::string name; +}; + +/// A fallback map containing external resources not explicitly handled by +/// another parser/printer. +class FallbackAsmResourceMap { +public: + /// This class represents an opaque resource. + struct OpaqueAsmResource { + OpaqueAsmResource(StringRef key, + std::variant value) + : key(key.str()), value(std::move(value)) {} + + /// The key identifying the resource. + std::string key; + /// An opaque value for the resource, whose variant values align 1-1 with + /// the kinds defined in AsmResourceEntryKind. + std::variant value; + }; + + /// Return a parser than can be used for parsing entries for the given + /// identifier key. + AsmResourceParser &getParserFor(StringRef key); + + /// Build a set of resource printers to print the resources within this map. + std::vector> getPrinters(); + +private: + struct ResourceCollection : public AsmResourceParser { + ResourceCollection(StringRef name) : AsmResourceParser(name) {} + + /// Parse a resource into this collection. + LogicalResult parseResource(AsmParsedResourceEntry &entry) final; + + /// Build the resources held by this collection. + void buildResources(Operation *op, AsmResourceBuilder &builder) const; + + /// The set of resources parsed into this collection. + SmallVector resources; + }; + + /// The set of opaque resources. + llvm::MapVector, + llvm::StringMap> + keyToResources; +}; + +//===----------------------------------------------------------------------===// +// ParserConfig +//===----------------------------------------------------------------------===// + +/// This class represents a configuration for the MLIR assembly parser. It +/// contains all of the necessary state to parse a MLIR source file. +class ParserConfig { +public: + /// Construct a parser configuration with the given context. + /// `verifyAfterParse` indicates if the IR should be verified after parsing. + /// `fallbackResourceMap` is an optional fallback handler that can be used to + /// parse external resources not explicitly handled by another parser. + ParserConfig(MLIRContext *context, bool verifyAfterParse = true, + FallbackAsmResourceMap *fallbackResourceMap = nullptr) + : context(context), verifyAfterParse(verifyAfterParse), + fallbackResourceMap(fallbackResourceMap) { + assert(context && "expected valid MLIR context"); + } + + /// Return the MLIRContext to be used when parsing. + MLIRContext *getContext() const { return context; } + + /// Returns if the parser should verify the IR after parsing. + bool shouldVerifyAfterParse() const { return verifyAfterParse; } + + /// Returns the parsing configurations associated to the bytecode read. + BytecodeReaderConfig &getBytecodeReaderConfig() const { + return const_cast(bytecodeReaderConfig); + } + + /// Return the resource parser registered to the given name, or nullptr if no + /// parser with `name` is registered. + AsmResourceParser *getResourceParser(StringRef name) const { + auto it = resourceParsers.find(name); + if (it != resourceParsers.end()) + return it->second.get(); + if (fallbackResourceMap) + return &fallbackResourceMap->getParserFor(name); + return nullptr; + } + + /// Attach the given resource parser. + void attachResourceParser(std::unique_ptr parser) { + StringRef name = parser->getName(); + auto it = resourceParsers.try_emplace(name, std::move(parser)); + (void)it; + assert(it.second && + "resource parser already registered with the given name"); + } + + /// Attach the given callable resource parser with the given name. + template + std::enable_if_t>::value> + attachResourceParser(StringRef name, CallableT &&parserFn) { + attachResourceParser(AsmResourceParser::fromCallable( + name, std::forward(parserFn))); + } + +private: + MLIRContext *context; + bool verifyAfterParse; + DenseMap> resourceParsers; + FallbackAsmResourceMap *fallbackResourceMap; + BytecodeReaderConfig bytecodeReaderConfig; +}; + +//===----------------------------------------------------------------------===// +// AsmState +//===----------------------------------------------------------------------===// + +/// This class provides management for the lifetime of the state used when +/// printing the IR. It allows for alleviating the cost of recomputing the +/// internal state of the asm printer. +/// +/// The IR should not be mutated in-between invocations using this state, and +/// the IR being printed must not be an parent of the IR originally used to +/// initialize this state. This means that if a child operation is provided, a +/// parent operation cannot reuse this state. +class AsmState { +public: + /// This map represents the raw locations of operations within the output + /// stream. This maps the original pointer to the operation, to a pair of line + /// and column in the output stream. + using LocationMap = DenseMap>; + + /// Initialize the asm state at the level of the given operation. A location + /// map may optionally be provided to be populated when printing. `map` is an + /// optional fallback resource map, which when provided will attach resource + /// printers for the fallback resources within the map. + AsmState(Operation *op, + const OpPrintingFlags &printerFlags = OpPrintingFlags(), + LocationMap *locationMap = nullptr, + FallbackAsmResourceMap *map = nullptr); + AsmState(MLIRContext *ctx, + const OpPrintingFlags &printerFlags = OpPrintingFlags(), + LocationMap *locationMap = nullptr, + FallbackAsmResourceMap *map = nullptr); + ~AsmState(); + + /// Get the printer flags. + const OpPrintingFlags &getPrinterFlags() const; + + /// Return an instance of the internal implementation. Returns nullptr if the + /// state has not been initialized. + detail::AsmStateImpl &getImpl() { return *impl; } + + //===--------------------------------------------------------------------===// + // Resources + //===--------------------------------------------------------------------===// + + /// Attach the given resource printer to the AsmState. + void attachResourcePrinter(std::unique_ptr printer); + + /// Attach an resource printer, in the form of a callable, to the AsmState. + template + std::enable_if_t>::value> + attachResourcePrinter(StringRef name, CallableT &&printFn) { + attachResourcePrinter(AsmResourcePrinter::fromCallable( + name, std::forward(printFn))); + } + + /// Attach resource printers to the AsmState for the fallback resources + /// in the given map. + void attachFallbackResourcePrinter(FallbackAsmResourceMap &map) { + for (auto &printer : map.getPrinters()) + attachResourcePrinter(std::move(printer)); + } + + /// Returns a map of dialect resources that were referenced when using this + /// state to print IR. + DenseMap> & + getDialectResources() const; + +private: + AsmState() = delete; + + /// A pointer to allocated storage for the impl state. + std::unique_ptr impl; +}; + +//===----------------------------------------------------------------------===// +// AsmPrinter CommandLine Options +//===----------------------------------------------------------------------===// + +/// Register a set of useful command-line options that can be used to configure +/// various flags within the AsmPrinter. +void registerAsmPrinterCLOptions(); + +} // namespace mlir + +#endif // MLIR_IR_ASMSTATE_H_ diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/AttrTypeSubElements.h b/deps/exla/cache/xla_extension/include/mlir/IR/AttrTypeSubElements.h new file mode 100644 index 0000000000000000000000000000000000000000..234767deea00afd3921d45270786f637b39d74d7 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/AttrTypeSubElements.h @@ -0,0 +1,601 @@ +//===- AttrTypeSubElements.h - Attr and Type SubElements -------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file contains utilities for querying the sub elements of an attribute or +// type. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_ATTRTYPESUBELEMENTS_H +#define MLIR_IR_ATTRTYPESUBELEMENTS_H + +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/Visitors.h" +#include "mlir/Support/CyclicReplacerCache.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" +#include + +namespace mlir { +class Attribute; +class Type; + +//===----------------------------------------------------------------------===// +/// AttrTypeWalker +//===----------------------------------------------------------------------===// + +/// This class provides a utility for walking attributes/types, and their sub +/// elements. Multiple walk functions may be registered. +class AttrTypeWalker { +public: + //===--------------------------------------------------------------------===// + // Application + //===--------------------------------------------------------------------===// + + /// Walk the given attribute/type, and recursively walk any sub elements. + template + WalkResult walk(T element) { + return walkImpl(element, Order); + } + template + WalkResult walk(T element) { + return walk(element); + } + + //===--------------------------------------------------------------------===// + // Registration + //===--------------------------------------------------------------------===// + + template + using WalkFn = std::function; + + /// Register a walk function for a given attribute or type. A walk function + /// must be convertible to any of the following forms(where `T` is a class + /// derived from `Type` or `Attribute`: + /// + /// * WalkResult(T) + /// - Returns a walk result, which can be used to control the walk + /// + /// * void(T) + /// - Returns void, i.e. the walk always continues. + /// + /// Note: When walking, the mostly recently added walk functions will be + /// invoked first. + void addWalk(WalkFn &&fn) { + attrWalkFns.emplace_back(std::move(fn)); + } + void addWalk(WalkFn &&fn) { typeWalkFns.push_back(std::move(fn)); } + + /// Register a replacement function that doesn't match the default signature, + /// either because it uses a derived parameter type, or it uses a simplified + /// result type. + template >::template arg_t<0>, + typename BaseT = std::conditional_t, + Attribute, Type>, + typename ResultT = std::invoke_result_t> + std::enable_if_t || std::is_same_v> + addWalk(FnT &&callback) { + addWalk([callback = std::forward(callback)](BaseT base) -> WalkResult { + if (auto derived = dyn_cast(base)) { + if constexpr (std::is_convertible_v) + return callback(derived); + else + callback(derived); + } + return WalkResult::advance(); + }); + } + +private: + WalkResult walkImpl(Attribute attr, WalkOrder order); + WalkResult walkImpl(Type type, WalkOrder order); + + /// Internal implementation of the `walk` methods above. + template + WalkResult walkImpl(T element, WalkFns &walkFns, WalkOrder order); + + /// Walk the sub elements of the given interface. + template + WalkResult walkSubElements(T interface, WalkOrder order); + + /// The set of walk functions that map sub elements. + std::vector> attrWalkFns; + std::vector> typeWalkFns; + + /// The set of visited attributes/types. + DenseMap, WalkResult> visitedAttrTypes; +}; + +//===----------------------------------------------------------------------===// +/// AttrTypeReplacer +//===----------------------------------------------------------------------===// + +namespace detail { + +/// This class provides a base utility for replacing attributes/types, and their +/// sub elements. Multiple replacement functions may be registered. +/// +/// This base utility is uncached. Users can choose between two cached versions +/// of this replacer: +/// * For non-cyclic replacer logic, use `AttrTypeReplacer`. +/// * For cyclic replacer logic, use `CyclicAttrTypeReplacer`. +/// +/// Concrete implementations implement the following `replace` entry functions: +/// * Attribute replace(Attribute attr); +/// * Type replace(Type type); +template +class AttrTypeReplacerBase { +public: + //===--------------------------------------------------------------------===// + // Application + //===--------------------------------------------------------------------===// + + /// Replace the elements within the given operation. If `replaceAttrs` is + /// true, this updates the attribute dictionary of the operation. If + /// `replaceLocs` is true, this also updates its location, and the locations + /// of any nested block arguments. If `replaceTypes` is true, this also + /// updates the result types of the operation, and the types of any nested + /// block arguments. + void replaceElementsIn(Operation *op, bool replaceAttrs = true, + bool replaceLocs = false, bool replaceTypes = false); + + /// Replace the elements within the given operation, and all nested + /// operations. + void recursivelyReplaceElementsIn(Operation *op, bool replaceAttrs = true, + bool replaceLocs = false, + bool replaceTypes = false); + + //===--------------------------------------------------------------------===// + // Registration + //===--------------------------------------------------------------------===// + + /// A replacement mapping function, which returns either std::nullopt (to + /// signal the element wasn't handled), or a pair of the replacement element + /// and a WalkResult. + template + using ReplaceFnResult = std::optional>; + template + using ReplaceFn = std::function(T)>; + + /// Register a replacement function for mapping a given attribute or type. A + /// replacement function must be convertible to any of the following + /// forms(where `T` is a class derived from `Type` or `Attribute`, and `BaseT` + /// is either `Type` or `Attribute` respectively): + /// + /// * std::optional(T) + /// - This either returns a valid Attribute/Type in the case of success, + /// nullptr in the case of failure, or `std::nullopt` to signify that + /// additional replacement functions may be applied (i.e. this function + /// doesn't handle that instance). + /// + /// * std::optional>(T) + /// - Similar to the above, but also allows specifying a WalkResult to + /// control the replacement of sub elements of a given attribute or + /// type. Returning a `skip` result, for example, will not recursively + /// process the resultant attribute or type value. + /// + /// Note: When replacing, the mostly recently added replacement functions will + /// be invoked first. + void addReplacement(ReplaceFn fn); + void addReplacement(ReplaceFn fn); + + /// Register a replacement function that doesn't match the default signature, + /// either because it uses a derived parameter type, or it uses a simplified + /// result type. + template >::template arg_t<0>, + typename BaseT = std::conditional_t, + Attribute, Type>, + typename ResultT = std::invoke_result_t> + std::enable_if_t || + !std::is_convertible_v>> + addReplacement(FnT &&callback) { + addReplacement([callback = std::forward(callback)]( + BaseT base) -> ReplaceFnResult { + if (auto derived = dyn_cast(base)) { + if constexpr (std::is_convertible_v>) { + std::optional result = callback(derived); + return result ? std::make_pair(*result, WalkResult::advance()) + : ReplaceFnResult(); + } else { + return callback(derived); + } + } + return ReplaceFnResult(); + }); + } + +protected: + /// Invokes the registered replacement functions from most recently registered + /// to least recently registered until a successful replacement is returned. + /// Unless skipping is requested, invokes `replace` on sub-elements of the + /// current attr/type. + Attribute replaceBase(Attribute attr); + Type replaceBase(Type type); + +private: + /// The set of replacement functions that map sub elements. + std::vector> attrReplacementFns; + std::vector> typeReplacementFns; +}; + +} // namespace detail + +/// This is an attribute/type replacer that is naively cached. It is best used +/// when the replacer logic is guaranteed to not contain cycles. Otherwise, any +/// re-occurrence of an in-progress element will be skipped. +class AttrTypeReplacer : public detail::AttrTypeReplacerBase { +public: + Attribute replace(Attribute attr); + Type replace(Type type); + +private: + /// Shared concrete implementation of the public `replace` functions. Invokes + /// `replaceBase` with caching. + template + T cachedReplaceImpl(T element); + + // Stores the opaque pointer of an attribute or type. + DenseMap cache; +}; + +/// This is an attribute/type replacer that supports custom handling of cycles +/// in the replacer logic. In addition to registering replacer functions, it +/// allows registering cycle-breaking functions in the same style. +class CyclicAttrTypeReplacer + : public detail::AttrTypeReplacerBase { +public: + CyclicAttrTypeReplacer(); + + //===--------------------------------------------------------------------===// + // Application + //===--------------------------------------------------------------------===// + + Attribute replace(Attribute attr); + Type replace(Type type); + + //===--------------------------------------------------------------------===// + // Registration + //===--------------------------------------------------------------------===// + + /// A cycle-breaking function. This is invoked if the same element is asked to + /// be replaced again when the first instance of it is still being replaced. + /// This function must not perform any more recursive `replace` calls. + /// If it is able to break the cycle, it should return a replacement result. + /// Otherwise, it can return std::nullopt to defer cycle breaking to the next + /// repeated element. However, the user must guarantee that, in any possible + /// cycle, there always exists at least one element that can break the cycle. + template + using CycleBreakerFn = std::function(T)>; + + /// Register a cycle-breaking function. + /// When breaking cycles, the mostly recently added cycle-breaking functions + /// will be invoked first. + void addCycleBreaker(CycleBreakerFn fn); + void addCycleBreaker(CycleBreakerFn fn); + + /// Register a cycle-breaking function that doesn't match the default + /// signature. + template >::template arg_t<0>, + typename BaseT = std::conditional_t, + Attribute, Type>> + std::enable_if_t> addCycleBreaker(FnT &&callback) { + addCycleBreaker([callback = std::forward(callback)]( + BaseT base) -> std::optional { + if (auto derived = dyn_cast(base)) + return callback(derived); + return std::nullopt; + }); + } + +private: + /// Invokes the registered cycle-breaker functions from most recently + /// registered to least recently registered until a successful result is + /// returned. + std::optional breakCycleImpl(void *element); + + /// Shared concrete implementation of the public `replace` functions. + template + T cachedReplaceImpl(T element); + + /// The set of registered cycle-breaker functions. + std::vector> attrCycleBreakerFns; + std::vector> typeCycleBreakerFns; + + /// A cache of previously-replaced attr/types. + /// The key of the cache is the opaque value of an AttrOrType. Using + /// AttrOrType allows distinguishing between the two types when invoking + /// cycle-breakers. Using its opaque value avoids the cyclic dependency issue + /// of directly using `AttrOrType` to instantiate the cache. + /// The value of the cache is just the opaque value of the attr/type itself + /// (not the PointerUnion). + using AttrOrType = PointerUnion; + CyclicReplacerCache cache; +}; + +//===----------------------------------------------------------------------===// +/// AttrTypeSubElementHandler +//===----------------------------------------------------------------------===// + +/// This class is used by AttrTypeSubElementHandler instances to walking sub +/// attributes and types. +class AttrTypeImmediateSubElementWalker { +public: + AttrTypeImmediateSubElementWalker(function_ref walkAttrsFn, + function_ref walkTypesFn) + : walkAttrsFn(walkAttrsFn), walkTypesFn(walkTypesFn) {} + + /// Walk an attribute. + void walk(Attribute element); + /// Walk a type. + void walk(Type element); + /// Walk a range of attributes or types. + template + void walkRange(RangeT &&elements) { + for (auto element : elements) + walk(element); + } + +private: + function_ref walkAttrsFn; + function_ref walkTypesFn; +}; + +/// This class is used by AttrTypeSubElementHandler instances to process sub +/// element replacements. +template +class AttrTypeSubElementReplacements { +public: + AttrTypeSubElementReplacements(ArrayRef repls) : repls(repls) {} + + /// Take the first N replacements as an ArrayRef, dropping them from + /// this replacement list. + ArrayRef take_front(unsigned n) { + ArrayRef elements = repls.take_front(n); + repls = repls.drop_front(n); + return elements; + } + +private: + /// The current set of replacements. + ArrayRef repls; +}; +using AttrSubElementReplacements = AttrTypeSubElementReplacements; +using TypeSubElementReplacements = AttrTypeSubElementReplacements; + +/// This class provides support for interacting with the +/// SubElementInterfaces for different types of parameters. An +/// implementation of this class should be provided for any parameter class +/// that may contain an attribute or type. There are two main methods of +/// this class that need to be implemented: +/// +/// - walk +/// +/// This method should traverse into any sub elements of the parameter +/// using the provided walker, or by invoking handlers for sub-types. +/// +/// - replace +/// +/// This method should extract any necessary sub elements using the +/// provided replacer, or by invoking handlers for sub-types. The new +/// post-replacement parameter value should be returned. +/// +template +struct AttrTypeSubElementHandler { + /// Default walk implementation that does nothing. + static inline void walk(const T ¶m, + AttrTypeImmediateSubElementWalker &walker) {} + + /// Default replace implementation just forwards the parameter. + template + static inline decltype(auto) replace(ParamT &¶m, + AttrSubElementReplacements &attrRepls, + TypeSubElementReplacements &typeRepls) { + return std::forward(param); + } + + /// Tag indicating that this handler does not support sub-elements. + using DefaultHandlerTag = void; +}; + +/// Detect if any of the given parameter types has a sub-element handler. +namespace detail { +template +using has_default_sub_element_handler_t = decltype(T::DefaultHandlerTag); +} // namespace detail +template +inline constexpr bool has_sub_attr_or_type_v = + (!llvm::is_detected::value || + ...); + +/// Implementation for derived Attributes and Types. +template +struct AttrTypeSubElementHandler< + T, std::enable_if_t || + std::is_base_of_v>> { + static void walk(T param, AttrTypeImmediateSubElementWalker &walker) { + walker.walk(param); + } + static T replace(T param, AttrSubElementReplacements &attrRepls, + TypeSubElementReplacements &typeRepls) { + if (!param) + return T(); + if constexpr (std::is_base_of_v) { + return cast(attrRepls.take_front(1)[0]); + } else { + return cast(typeRepls.take_front(1)[0]); + } + } +}; +/// Implementation for derived ArrayRef. +template +struct AttrTypeSubElementHandler, + std::enable_if_t>> { + using EltHandler = AttrTypeSubElementHandler; + + static void walk(ArrayRef param, + AttrTypeImmediateSubElementWalker &walker) { + for (const T &subElement : param) + EltHandler::walk(subElement, walker); + } + static auto replace(ArrayRef param, AttrSubElementReplacements &attrRepls, + TypeSubElementReplacements &typeRepls) { + // Normal attributes/types can extract using the replacer directly. + if constexpr (std::is_base_of_v && + sizeof(T) == sizeof(void *)) { + ArrayRef attrs = attrRepls.take_front(param.size()); + return ArrayRef((const T *)attrs.data(), attrs.size()); + } else if constexpr (std::is_base_of_v && + sizeof(T) == sizeof(void *)) { + ArrayRef types = typeRepls.take_front(param.size()); + return ArrayRef((const T *)types.data(), types.size()); + } else { + // Otherwise, we need to allocate storage for the new elements. + SmallVector newElements; + for (const T &element : param) + newElements.emplace_back( + EltHandler::replace(element, attrRepls, typeRepls)); + return newElements; + } + } +}; +/// Implementation for Tuple. +template +struct AttrTypeSubElementHandler< + std::tuple, std::enable_if_t>> { + static void walk(const std::tuple ¶m, + AttrTypeImmediateSubElementWalker &walker) { + std::apply( + [&](const Ts &...params) { + (AttrTypeSubElementHandler::walk(params, walker), ...); + }, + param); + } + static auto replace(const std::tuple ¶m, + AttrSubElementReplacements &attrRepls, + TypeSubElementReplacements &typeRepls) { + return std::apply( + [&](const Ts &...params) + -> std::tuple::replace( + params, attrRepls, typeRepls))...> { + return {AttrTypeSubElementHandler::replace(params, attrRepls, + typeRepls)...}; + }, + param); + } +}; + +namespace detail { +template +struct is_tuple : public std::false_type {}; +template +struct is_tuple> : public std::true_type {}; + +template +struct is_pair : public std::false_type {}; +template +struct is_pair> : public std::true_type {}; + +template +using has_get_method = decltype(T::get(std::declval()...)); +template +using has_get_as_key = decltype(std::declval().getAsKey()); + +/// This function provides the underlying implementation for the +/// SubElementInterface walk method, using the key type of the derived +/// attribute/type to interact with the individual parameters. +template +void walkImmediateSubElementsImpl(T derived, + function_ref walkAttrsFn, + function_ref walkTypesFn) { + using ImplT = typename T::ImplType; + (void)derived; + (void)walkAttrsFn; + (void)walkTypesFn; + if constexpr (llvm::is_detected::value) { + auto key = static_cast(derived.getImpl())->getAsKey(); + + // If we don't have any sub-elements, there is nothing to do. + if constexpr (!has_sub_attr_or_type_v) + return; + AttrTypeImmediateSubElementWalker walker(walkAttrsFn, walkTypesFn); + AttrTypeSubElementHandler::walk(key, walker); + } +} + +/// This function invokes the proper `get` method for a type `T` with the given +/// values. +template +auto constructSubElementReplacement(MLIRContext *ctx, Ts &&...params) { + // Prefer a direct `get` method if one exists. + if constexpr (llvm::is_detected::value) { + (void)ctx; + return T::get(std::forward(params)...); + } else if constexpr (llvm::is_detected::value) { + return T::get(ctx, std::forward(params)...); + } else { + // Otherwise, pass to the base get. + return T::Base::get(ctx, std::forward(params)...); + } +} + +/// This function provides the underlying implementation for the +/// SubElementInterface replace method, using the key type of the derived +/// attribute/type to interact with the individual parameters. +template +auto replaceImmediateSubElementsImpl(T derived, ArrayRef &replAttrs, + ArrayRef &replTypes) { + using ImplT = typename T::ImplType; + if constexpr (llvm::is_detected::value) { + auto key = static_cast(derived.getImpl())->getAsKey(); + + // If we don't have any sub-elements, we can just return the original. + if constexpr (!has_sub_attr_or_type_v) { + return derived; + + // Otherwise, we need to replace any necessary sub-elements. + } else { + // Functor used to build the replacement on success. + auto buildReplacement = [&](auto newKey, MLIRContext *ctx) { + if constexpr (is_tuple::value || + is_pair::value) { + return std::apply( + [&](auto &&...params) { + return constructSubElementReplacement( + ctx, std::forward(params)...); + }, + newKey); + } else { + return constructSubElementReplacement(ctx, newKey); + } + }; + + AttrSubElementReplacements attrRepls(replAttrs); + TypeSubElementReplacements typeRepls(replTypes); + auto newKey = AttrTypeSubElementHandler::replace( + key, attrRepls, typeRepls); + MLIRContext *ctx = derived.getContext(); + if constexpr (std::is_convertible_v) + return succeeded(newKey) ? buildReplacement(*newKey, ctx) : nullptr; + else + return buildReplacement(newKey, ctx); + } + } else { + return derived; + } +} +} // namespace detail +} // namespace mlir + +#endif // MLIR_IR_ATTRTYPESUBELEMENTS_H diff --git a/deps/exla/cache/xla_extension/include/mlir/IR/AttributeSupport.h b/deps/exla/cache/xla_extension/include/mlir/IR/AttributeSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..9f36ee4aae2783a266ad5ace092510e4e493e516 --- /dev/null +++ b/deps/exla/cache/xla_extension/include/mlir/IR/AttributeSupport.h @@ -0,0 +1,327 @@ +//===- AttributeSupport.h ---------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines support types for registering dialect extended attributes. +// +//===----------------------------------------------------------------------===// + +#ifndef MLIR_IR_ATTRIBUTESUPPORT_H +#define MLIR_IR_ATTRIBUTESUPPORT_H + +#include "mlir/IR/MLIRContext.h" +#include "mlir/IR/StorageUniquerSupport.h" +#include "mlir/IR/Types.h" +#include "llvm/ADT/PointerIntPair.h" +#include "llvm/ADT/Twine.h" + +namespace mlir { +//===----------------------------------------------------------------------===// +// AbstractAttribute +//===----------------------------------------------------------------------===// + +/// This class contains all of the static information common to all instances of +/// a registered Attribute. +class AbstractAttribute { +public: + using HasTraitFn = llvm::unique_function; + using WalkImmediateSubElementsFn = function_ref, function_ref)>; + using ReplaceImmediateSubElementsFn = + function_ref, ArrayRef)>; + + /// Look up the specified abstract attribute in the MLIRContext and return a + /// reference to it. + static const AbstractAttribute &lookup(TypeID typeID, MLIRContext *context); + + /// Look up the specified abstract attribute in the MLIRContext and return a + /// reference to it if it exists. + static std::optional> + lookup(StringRef name, MLIRContext *context); + + /// This method is used by Dialect objects when they register the list of + /// attributes they contain. + template + static AbstractAttribute get(Dialect &dialect) { + return AbstractAttribute(dialect, T::getInterfaceMap(), T::getHasTraitFn(), + T::getWalkImmediateSubElementsFn(), + T::getReplaceImmediateSubElementsFn(), + T::getTypeID(), T::name); + } + + /// This method is used by Dialect objects to register attributes with + /// custom TypeIDs. + /// The use of this method is in general discouraged in favor of + /// 'get(dialect)'. + static AbstractAttribute + get(Dialect &dialect, detail::InterfaceMap &&interfaceMap, + HasTraitFn &&hasTrait, + WalkImmediateSubElementsFn walkImmediateSubElementsFn, + ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn, + TypeID typeID, StringRef name) { + return AbstractAttribute(dialect, std::move(interfaceMap), + std::move(hasTrait), walkImmediateSubElementsFn, + replaceImmediateSubElementsFn, typeID, name); + } + + /// Return the dialect this attribute was registered to. + Dialect &getDialect() const { return const_cast(dialect); } + + /// Returns an instance of the concept object for the given interface if it + /// was registered to this attribute, null otherwise. This should not be used + /// directly. + template + typename T::Concept *getInterface() const { + return interfaceMap.lookup(); + } + + /// Returns true if the attribute has the interface with the given ID + /// registered. + bool hasInterface(TypeID interfaceID) const { + return interfaceMap.contains(interfaceID); + } + + /// Returns true if the attribute has a particular trait. + template