/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910#ifndef ZSTD_COMPILER_H11#define ZSTD_COMPILER_H1213#include <stddef.h>1415#include "portability_macros.h"1617/*-*******************************************************18* Compiler specifics19*********************************************************/20/* force inlining */2122#if !defined(ZSTD_NO_INLINE)23#if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */24# define INLINE_KEYWORD inline25#else26# define INLINE_KEYWORD27#endif2829#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)30# define FORCE_INLINE_ATTR __attribute__((always_inline))31#elif defined(_MSC_VER)32# define FORCE_INLINE_ATTR __forceinline33#else34# define FORCE_INLINE_ATTR35#endif3637#else3839#define INLINE_KEYWORD40#define FORCE_INLINE_ATTR4142#endif4344/**45On MSVC qsort requires that functions passed into it use the __cdecl calling conversion(CC).46This explicitly marks such functions as __cdecl so that the code will still compile47if a CC other than __cdecl has been made the default.48*/49#if defined(_MSC_VER)50# define WIN_CDECL __cdecl51#else52# define WIN_CDECL53#endif5455/* UNUSED_ATTR tells the compiler it is okay if the function is unused. */56#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)57# define UNUSED_ATTR __attribute__((unused))58#else59# define UNUSED_ATTR60#endif6162/**63* FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant64* parameters. They must be inlined for the compiler to eliminate the constant65* branches.66*/67#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR UNUSED_ATTR68/**69* HINT_INLINE is used to help the compiler generate better code. It is *not*70* used for "templates", so it can be tweaked based on the compilers71* performance.72*73* gcc-4.8 and gcc-4.9 have been shown to benefit from leaving off the74* always_inline attribute.75*76* clang up to 5.0.0 (trunk) benefit tremendously from the always_inline77* attribute.78*/79#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 580# define HINT_INLINE static INLINE_KEYWORD81#else82# define HINT_INLINE FORCE_INLINE_TEMPLATE83#endif8485/* "soft" inline :86* The compiler is free to select if it's a good idea to inline or not.87* The main objective is to silence compiler warnings88* when a defined function in included but not used.89*90* Note : this macro is prefixed `MEM_` because it used to be provided by `mem.h` unit.91* Updating the prefix is probably preferable, but requires a fairly large codemod,92* since this name is used everywhere.93*/94#ifndef MEM_STATIC /* already defined in Linux Kernel mem.h */95#if defined(__GNUC__)96# define MEM_STATIC static __inline UNUSED_ATTR97#elif defined(__IAR_SYSTEMS_ICC__)98# define MEM_STATIC static inline UNUSED_ATTR99#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)100# define MEM_STATIC static inline101#elif defined(_MSC_VER)102# define MEM_STATIC static __inline103#else104# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */105#endif106#endif107108/* force no inlining */109#ifdef _MSC_VER110# define FORCE_NOINLINE static __declspec(noinline)111#else112# if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)113# define FORCE_NOINLINE static __attribute__((__noinline__))114# else115# define FORCE_NOINLINE static116# endif117#endif118119120/* target attribute */121#if defined(__GNUC__) || defined(__IAR_SYSTEMS_ICC__)122# define TARGET_ATTRIBUTE(target) __attribute__((__target__(target)))123#else124# define TARGET_ATTRIBUTE(target)125#endif126127/* Target attribute for BMI2 dynamic dispatch.128* Enable lzcnt, bmi, and bmi2.129* We test for bmi1 & bmi2. lzcnt is included in bmi1.130*/131#define BMI2_TARGET_ATTRIBUTE TARGET_ATTRIBUTE("lzcnt,bmi,bmi2")132133/* prefetch134* can be disabled, by declaring NO_PREFETCH build macro */135#if defined(NO_PREFETCH)136# define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */137# define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */138#else139# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) && !defined(_M_ARM64EC) /* _mm_prefetch() is not defined outside of x86/x64 */140# include <mmintrin.h> /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */141# define PREFETCH_L1(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0)142# define PREFETCH_L2(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T1)143# elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) )144# define PREFETCH_L1(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)145# define PREFETCH_L2(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */)146# elif defined(__aarch64__)147# define PREFETCH_L1(ptr) do { __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr))); } while (0)148# define PREFETCH_L2(ptr) do { __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr))); } while (0)149# else150# define PREFETCH_L1(ptr) do { (void)(ptr); } while (0) /* disabled */151# define PREFETCH_L2(ptr) do { (void)(ptr); } while (0) /* disabled */152# endif153#endif /* NO_PREFETCH */154155#define CACHELINE_SIZE 64156157#define PREFETCH_AREA(p, s) \158do { \159const char* const _ptr = (const char*)(p); \160size_t const _size = (size_t)(s); \161size_t _pos; \162for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) { \163PREFETCH_L2(_ptr + _pos); \164} \165} while (0)166167/* vectorization168* older GCC (pre gcc-4.3 picked as the cutoff) uses a different syntax,169* and some compilers, like Intel ICC and MCST LCC, do not support it at all. */170#if !defined(__INTEL_COMPILER) && !defined(__clang__) && defined(__GNUC__) && !defined(__LCC__)171# if (__GNUC__ == 4 && __GNUC_MINOR__ > 3) || (__GNUC__ >= 5)172# define DONT_VECTORIZE __attribute__((optimize("no-tree-vectorize")))173# else174# define DONT_VECTORIZE _Pragma("GCC optimize(\"no-tree-vectorize\")")175# endif176#else177# define DONT_VECTORIZE178#endif179180/* Tell the compiler that a branch is likely or unlikely.181* Only use these macros if it causes the compiler to generate better code.182* If you can remove a LIKELY/UNLIKELY annotation without speed changes in gcc183* and clang, please do.184*/185#if defined(__GNUC__)186#define LIKELY(x) (__builtin_expect((x), 1))187#define UNLIKELY(x) (__builtin_expect((x), 0))188#else189#define LIKELY(x) (x)190#define UNLIKELY(x) (x)191#endif192193#if __has_builtin(__builtin_unreachable) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)))194# define ZSTD_UNREACHABLE do { assert(0), __builtin_unreachable(); } while (0)195#else196# define ZSTD_UNREACHABLE do { assert(0); } while (0)197#endif198199/* disable warnings */200#ifdef _MSC_VER /* Visual Studio */201# include <intrin.h> /* For Visual 2005 */202# pragma warning(disable : 4100) /* disable: C4100: unreferenced formal parameter */203# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */204# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */205# pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */206# pragma warning(disable : 4324) /* disable: C4324: padded structure */207#endif208209/* compile time determination of SIMD support */210#if !defined(ZSTD_NO_INTRINSICS)211# if defined(__AVX2__)212# define ZSTD_ARCH_X86_AVX2213# endif214# if defined(__SSE2__) || defined(_M_X64) || (defined (_M_IX86) && defined(_M_IX86_FP) && (_M_IX86_FP >= 2))215# define ZSTD_ARCH_X86_SSE2216# endif217# if defined(__ARM_NEON) || defined(_M_ARM64)218# define ZSTD_ARCH_ARM_NEON219# endif220#221# if defined(ZSTD_ARCH_X86_AVX2)222# include <immintrin.h>223# endif224# if defined(ZSTD_ARCH_X86_SSE2)225# include <emmintrin.h>226# elif defined(ZSTD_ARCH_ARM_NEON)227# include <arm_neon.h>228# endif229#endif230231/* C-language Attributes are added in C23. */232#if defined(__STDC_VERSION__) && (__STDC_VERSION__ > 201710L) && defined(__has_c_attribute)233# define ZSTD_HAS_C_ATTRIBUTE(x) __has_c_attribute(x)234#else235# define ZSTD_HAS_C_ATTRIBUTE(x) 0236#endif237238/* Only use C++ attributes in C++. Some compilers report support for C++239* attributes when compiling with C.240*/241#if defined(__cplusplus) && defined(__has_cpp_attribute)242# define ZSTD_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)243#else244# define ZSTD_HAS_CPP_ATTRIBUTE(x) 0245#endif246247/* Define ZSTD_FALLTHROUGH macro for annotating switch case with the 'fallthrough' attribute.248* - C23: https://en.cppreference.com/w/c/language/attributes/fallthrough249* - CPP17: https://en.cppreference.com/w/cpp/language/attributes/fallthrough250* - Else: __attribute__((__fallthrough__))251*/252#ifndef ZSTD_FALLTHROUGH253# if ZSTD_HAS_C_ATTRIBUTE(fallthrough)254# define ZSTD_FALLTHROUGH [[fallthrough]]255# elif ZSTD_HAS_CPP_ATTRIBUTE(fallthrough)256# define ZSTD_FALLTHROUGH [[fallthrough]]257# elif __has_attribute(__fallthrough__)258/* Leading semicolon is to satisfy gcc-11 with -pedantic. Without the semicolon259* gcc complains about: a label can only be part of a statement and a declaration is not a statement.260*/261# define ZSTD_FALLTHROUGH ; __attribute__((__fallthrough__))262# else263# define ZSTD_FALLTHROUGH264# endif265#endif266267/*-**************************************************************268* Alignment269*****************************************************************/270271/* @return 1 if @u is a 2^n value, 0 otherwise272* useful to check a value is valid for alignment restrictions */273MEM_STATIC int ZSTD_isPower2(size_t u) {274return (u & (u-1)) == 0;275}276277/* this test was initially positioned in mem.h,278* but this file is removed (or replaced) for linux kernel279* so it's now hosted in compiler.h,280* which remains valid for both user & kernel spaces.281*/282283#ifndef ZSTD_ALIGNOF284# if defined(__GNUC__) || defined(_MSC_VER)285/* covers gcc, clang & MSVC */286/* note : this section must come first, before C11,287* due to a limitation in the kernel source generator */288# define ZSTD_ALIGNOF(T) __alignof(T)289290# elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)291/* Oracle Studio */292# define ZSTD_ALIGNOF(T) _Alignof(T)293294# elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)295/* C11 support */296# include <stdalign.h>297# define ZSTD_ALIGNOF(T) alignof(T)298299# else300/* No known support for alignof() - imperfect backup */301# define ZSTD_ALIGNOF(T) (sizeof(void*) < sizeof(T) ? sizeof(void*) : sizeof(T))302303# endif304#endif /* ZSTD_ALIGNOF */305306#ifndef ZSTD_ALIGNED307/* C90-compatible alignment macro (GCC/Clang). Adjust for other compilers if needed. */308# if defined(__GNUC__) || defined(__clang__)309# define ZSTD_ALIGNED(a) __attribute__((aligned(a)))310# elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */311# define ZSTD_ALIGNED(a) _Alignas(a)312#elif defined(_MSC_VER)313# define ZSTD_ALIGNED(n) __declspec(align(n))314# else315/* this compiler will require its own alignment instruction */316# define ZSTD_ALIGNED(...)317# endif318#endif /* ZSTD_ALIGNED */319320321/*-**************************************************************322* Sanitizer323*****************************************************************/324325/**326* Zstd relies on pointer overflow in its decompressor.327* We add this attribute to functions that rely on pointer overflow.328*/329#ifndef ZSTD_ALLOW_POINTER_OVERFLOW_ATTR330# if __has_attribute(no_sanitize)331# if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 8332/* gcc < 8 only has signed-integer-overlow which triggers on pointer overflow */333# define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("signed-integer-overflow")))334# else335/* older versions of clang [3.7, 5.0) will warn that pointer-overflow is ignored. */336# define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR __attribute__((no_sanitize("pointer-overflow")))337# endif338# else339# define ZSTD_ALLOW_POINTER_OVERFLOW_ATTR340# endif341#endif342343/**344* Helper function to perform a wrapped pointer difference without triggering345* UBSAN.346*347* @returns lhs - rhs with wrapping348*/349MEM_STATIC350ZSTD_ALLOW_POINTER_OVERFLOW_ATTR351ptrdiff_t ZSTD_wrappedPtrDiff(unsigned char const* lhs, unsigned char const* rhs)352{353return lhs - rhs;354}355356/**357* Helper function to perform a wrapped pointer add without triggering UBSAN.358*359* @return ptr + add with wrapping360*/361MEM_STATIC362ZSTD_ALLOW_POINTER_OVERFLOW_ATTR363unsigned char const* ZSTD_wrappedPtrAdd(unsigned char const* ptr, ptrdiff_t add)364{365return ptr + add;366}367368/**369* Helper function to perform a wrapped pointer subtraction without triggering370* UBSAN.371*372* @return ptr - sub with wrapping373*/374MEM_STATIC375ZSTD_ALLOW_POINTER_OVERFLOW_ATTR376unsigned char const* ZSTD_wrappedPtrSub(unsigned char const* ptr, ptrdiff_t sub)377{378return ptr - sub;379}380381/**382* Helper function to add to a pointer that works around C's undefined behavior383* of adding 0 to NULL.384*385* @returns `ptr + add` except it defines `NULL + 0 == NULL`.386*/387MEM_STATIC388unsigned char* ZSTD_maybeNullPtrAdd(unsigned char* ptr, ptrdiff_t add)389{390return add > 0 ? ptr + add : ptr;391}392393/* Issue #3240 reports an ASAN failure on an llvm-mingw build. Out of an394* abundance of caution, disable our custom poisoning on mingw. */395#ifdef __MINGW32__396#ifndef ZSTD_ASAN_DONT_POISON_WORKSPACE397#define ZSTD_ASAN_DONT_POISON_WORKSPACE 1398#endif399#ifndef ZSTD_MSAN_DONT_POISON_WORKSPACE400#define ZSTD_MSAN_DONT_POISON_WORKSPACE 1401#endif402#endif403404#if ZSTD_MEMORY_SANITIZER && !defined(ZSTD_MSAN_DONT_POISON_WORKSPACE)405/* Not all platforms that support msan provide sanitizers/msan_interface.h.406* We therefore declare the functions we need ourselves, rather than trying to407* include the header file... */408#include <stddef.h> /* size_t */409#define ZSTD_DEPS_NEED_STDINT410#include "zstd_deps.h" /* intptr_t */411412/* Make memory region fully initialized (without changing its contents). */413void __msan_unpoison(const volatile void *a, size_t size);414415/* Make memory region fully uninitialized (without changing its contents).416This is a legacy interface that does not update origin information. Use417__msan_allocated_memory() instead. */418void __msan_poison(const volatile void *a, size_t size);419420/* Returns the offset of the first (at least partially) poisoned byte in the421memory range, or -1 if the whole range is good. */422intptr_t __msan_test_shadow(const volatile void *x, size_t size);423424/* Print shadow and origin for the memory range to stderr in a human-readable425format. */426void __msan_print_shadow(const volatile void *x, size_t size);427#endif428429#if ZSTD_ADDRESS_SANITIZER && !defined(ZSTD_ASAN_DONT_POISON_WORKSPACE)430/* Not all platforms that support asan provide sanitizers/asan_interface.h.431* We therefore declare the functions we need ourselves, rather than trying to432* include the header file... */433#include <stddef.h> /* size_t */434435/**436* Marks a memory region (<c>[addr, addr+size)</c>) as unaddressable.437*438* This memory must be previously allocated by your program. Instrumented439* code is forbidden from accessing addresses in this region until it is440* unpoisoned. This function is not guaranteed to poison the entire region -441* it could poison only a subregion of <c>[addr, addr+size)</c> due to ASan442* alignment restrictions.443*444* \note This function is not thread-safe because no two threads can poison or445* unpoison memory in the same memory region simultaneously.446*447* \param addr Start of memory region.448* \param size Size of memory region. */449void __asan_poison_memory_region(void const volatile *addr, size_t size);450451/**452* Marks a memory region (<c>[addr, addr+size)</c>) as addressable.453*454* This memory must be previously allocated by your program. Accessing455* addresses in this region is allowed until this region is poisoned again.456* This function could unpoison a super-region of <c>[addr, addr+size)</c> due457* to ASan alignment restrictions.458*459* \note This function is not thread-safe because no two threads can460* poison or unpoison memory in the same memory region simultaneously.461*462* \param addr Start of memory region.463* \param size Size of memory region. */464void __asan_unpoison_memory_region(void const volatile *addr, size_t size);465#endif466467#endif /* ZSTD_COMPILER_H */468469470