Skip to content

Add fallback implementation for fixed_(u)int #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/typed-geometry/detail/intrinsics.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#pragma once

#include <clean-core/macros.hh>

#ifdef _MSC_VER
#include <intrin.h>
#elif __has_include("x86intrin.h")
#include <x86intrin.h>
#include <cstring>
#endif


namespace tg::detail
{
CC_FORCE_INLINE char add_with_carry(char carry, unsigned long long a, unsigned long long b, unsigned long long* out)
{
#if defined(__x86_64__) || defined(_M_X64)
return _addcarry_u64(carry, a, b, out);
#else
#pragma message("[typed-geometry] Using fallback for add_with_carry(...). This may be slow!")
unsigned long long tmp = b + carry;
a += tmp;
*out = a;
return (tmp < carry) + (a < tmp);
#endif
}

CC_FORCE_INLINE unsigned long long mul128(unsigned long long a, unsigned long long b, unsigned long long* high)
{
#if defined(_MSC_VER)
return _umul128(a, b, high);
#elif __has_include("x86intrin.h")
return _mulx_u64(a, b, high);
#elif defined(__SIZEOF_INT128__)
__uint128_t res = __uint128_t(a) * __uint128_t(b);
*high = res >> 64;
return static_cast<unsigned long long>(res);
#else
#pragma message("[typed-geometry] Using fallback for mul128(...). This may be slow!")
using u64 = unsigned long long;
using u32 = unsigned int;
static_assert(sizeof(u64) == 8, "u64 must be exactly 64 bits");
static_assert(sizeof(u32) == 4, "u32 must be exactly 32 bits");

u64 a_lo = u64(u32(a));
u64 a_hi = a >> 32;
u64 b_lo = u64(u32(b));
u64 b_hi = b >> 32;

u64 p0 = a_lo * b_lo;
u64 p1 = a_lo * b_hi;
u64 p2 = a_hi * b_lo;
u64 p3 = a_hi * b_hi;

u32 cy = u32(((p0 >> 32) + u32(p1) + u32(p2)) >> 32);

*high = p3 + (p1 >> 32) + (p2 >> 32) + cy;
return p0 + (p1 << 32) + (p2 << 32);
#endif
}
}
6 changes: 0 additions & 6 deletions src/typed-geometry/feature/fixed_int.hh
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@

#include <clean-core/macros.hh>

#ifdef CC_COMPILER_MSVC
#define TG_MUL_U128 _umul128
#else
#define TG_MUL_U128 _mulx_u64
#endif

#include <typed-geometry/functions/fixed_int/conversions.hh>
#include <typed-geometry/functions/fixed_int/fixed_int.hh>
#include <typed-geometry/functions/fixed_int/fixed_int_gen.hh>
Expand Down
Loading