Skip to content
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

Tracking Issue for bigint helper methods #85532

Open
4 of 8 tasks
clarfonthey opened this issue May 21, 2021 · 85 comments
Open
4 of 8 tasks

Tracking Issue for bigint helper methods #85532

clarfonthey opened this issue May 21, 2021 · 85 comments
Labels
C-tracking-issue Category: An issue tracking the progress of sth. like the implementation of an RFC T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.

Comments

@clarfonthey
Copy link
Contributor

clarfonthey commented May 21, 2021

Feature gate: #![feature(bigint_helper_methods)]

This is a tracking issue for the following methods on integers:

  • carrying_add
  • borrowing_sub
  • carrying_mul
  • widening_mul

These methods are intended to help centralise the effort required for creating efficient big integer implementations, by offering a few methods which would otherwise require special compiler intrinsics or custom assembly code in order to do efficiently. They do not alone constitute big integer implementations themselves, but are necessary building blocks for a larger implementation.

Public API

// On unsigned integers:

/// `self + rhs + carry` (full adder)
const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool);

/// `self - rhs - carry` (full "subtractor")
const fn borrowing_sub(self, rhs: Self, carry: bool) -> (Self, bool);

/// `self * rhs + carry` (multiply-accumulate)
const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self);

/// `self * rhs` (wide multiplication, same as `self.carrying_mul(rhs, 0)`)
const fn widening_mul(self, rhs: Self) -> (Self, Self);


// On signed integers:

/// `self + rhs + carry` (full adder)
const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool);

/// `self - rhs - carry` (full "subtractor")
const fn borrowing_sub(self, rhs: Self, carry: bool) -> (Self, bool);

Steps / History

Unresolved Questions

  • Should these be implemented using compiler intrinsics? LLVM currently has no equivalents, so, we'd have to custom-build some.
  • Should an alternative API be provided for widening_mul that simply returns the next-larger type? What would we do for u128/i128?
  • What should the behaviour be for signed integers? Should there be implementations for signed integers at all?
  • Is the "borrowing" terminology worth it for subtraction, or should we simply call that "carrying" as well for consistency?
  • Are there other methods that should be added in addition to the existing ones?
@clarfonthey clarfonthey added C-tracking-issue Category: An issue tracking the progress of sth. like the implementation of an RFC T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. labels May 21, 2021
@leonardo-m
Copy link

Are there other methods that should be added in addition to the existing ones?

I'd like a mul_mod, as shown in #85017, because I think you can't implement it efficiently without asm and it's a basic block for power_mod and other things.

@clarfonthey
Copy link
Contributor Author

clarfonthey commented May 21, 2021

Another set of methods that could be useful that I'll probably offer implementations for at some point:

/// `(self << rhs) | carry`
fn carrying_shl(self, rhs: u32, carry: Self) -> (Self, Self); 

/// `(self >> rhs) | carry`
fn borrowing_shr(self, rhs: u32, carry: Self) -> (Self, Self);

/// `self << rhs`
fn widening_shl(self, rhs: u32) -> (Self, Self);

/// `self >> rhs`
fn widening_shr(self, rhs: u32) -> (Self, Self);

Essentially, return the two halves of a rotation, i.e. x.widening_shl(y) is the same as (x << y, x >> (BITS - y)) and similarly for widening_shr. Not sure whether they should allow rhs == BITS or not, but presumably they wouldn't for consistency with existing shift methods.

@clarfonthey
Copy link
Contributor Author

From @scottmcm in the original PR:

Some prior art I happened upon: https://docs.rs/cranelift-codegen/0.74.0/cranelift_codegen/ir/trait.InstBuilder.html#method.isub_bin

Same as isub with an additional borrow flag input. Computes:

   a = x - (y + b_{in}) \pmod 2^B

@photino
Copy link

photino commented Sep 7, 2021

Why don't we add carrying_mul and widening_mul for i128/u128 as well?

@clarfonthey
Copy link
Contributor Author

Mostly effort implementing them efficiently. In the meantime, you can do it with four calls to the u64 version. Or three if you want to be fancy.

@RalfJung
Copy link
Member

RalfJung commented Sep 9, 2021

fn borrowing_sub(self, rhs: Self, carry: bool) -> (Self, bool);

I was very confused by this function name at first, since borrowing in Rust usually refers to references. I am not a native speaker, but I do formal mathematical work in English professionally, and yet I never before heard the term "borrowing" in the context of subtraction. So I think this, at least, needs some explanation in the docs. (I would have expected something like carrying_sub, but maybe that is nonsense for a native speaker.)

The current docs for some of the other methods could probably also be improved: they talk about not having the "ability to overflow", which makes it sound like not overflowing is a bad thing.

@AaronKutch
Copy link
Contributor

The word borrow here comes from the terminology for a full subtractor. I am thinking that maybe the borrowing_sub function could be removed altogether. The same effect that borrowing_sub has can be obtained from carrying_add by making the first carrying_add in the chain have a set carry bit, and then bitnot every rhs. This fact could be put in the documentation of carrying_add.

@clarfonthey
Copy link
Contributor Author

The word borrow here comes from the terminology for a full subtractor. I am thinking that maybe the borrowing_sub function could be removed altogether. The same effect that borrowing_sub has can be obtained from carrying_add by making the first carrying_add in the chain have a set carry bit, and then bitnot every rhs. This fact could be put in the documentation of carrying_add.

Considering how the primary goal of these methods is to be as efficient as possible, usually optimising down to a single instruction, I don't think it'd be reasonable to just get rid of subtraction in favour of telling everyone to use addition instead. Definitely open to changing the name, though.

@AaronKutch
Copy link
Contributor

AaronKutch commented Sep 9, 2021

These helper methods will not be very useful to me unless they are implemented for every kind of integer. Here is an implementation for a widening multiplication-addition for u128:

/// Extended multiply-addition of `(lhs * rhs) + add`. The result is returned as a tuple of the wrapping part and the
/// overflow part. No numerical overflow is possible even if all three arguments are set to their max values.
pub const fn widen_mul_add(lhs: u128, rhs: u128, add: u128) -> (u128, u128) {
    //                       [rhs_hi]  [rhs_lo]
    //                       [lhs_hi]  [lhs_lo]
    //                     X___________________
    //                       [------tmp0------]
    //             [------tmp1------]
    //             [------tmp2------]
    //     [------tmp3------]
    //                       [-------add------]
    // +_______________________________________
    //                       [------sum0------]
    //     [------sum1------]

    let lhs_lo = lhs as u64;
    let rhs_lo = rhs as u64;
    let lhs_hi = (lhs.wrapping_shr(64)) as u64;
    let rhs_hi = (rhs.wrapping_shr(64)) as u64;
    let tmp0 = (lhs_lo as u128).wrapping_mul(rhs_lo as u128);
    let tmp1 = (lhs_lo as u128).wrapping_mul(rhs_hi as u128);
    let tmp2 = (lhs_hi as u128).wrapping_mul(rhs_lo as u128);
    let tmp3 = (lhs_hi as u128).wrapping_mul(rhs_hi as u128);
    // tmp1 and tmp2 straddle the boundary. We have to handle three carries
    let (sum0, carry0) = tmp0.overflowing_add(tmp1.wrapping_shl(64));
    let (sum0, carry1) = sum0.overflowing_add(tmp2.wrapping_shl(64));
    let (sum0, carry2) = sum0.overflowing_add(add as u128);
    let sum1 = tmp3
        .wrapping_add(tmp1.wrapping_shr(64))
        .wrapping_add(tmp2.wrapping_shr(64))
        .wrapping_add(carry0 as u128)
        .wrapping_add(carry1 as u128)
        .wrapping_add(carry2 as u128);
    (sum0, sum1)
}

I have tested this with my crate awint.

edit: There is a version of this that uses the Karatsuba trick to use 3 multiplications instead of 4, but it incurs extra summations, branches, and is not as parallel. For typical desktop processors the above should be the fastest.

@clarfonthey
Copy link
Contributor Author

I would make a PR for that.

@AaronKutch
Copy link
Contributor

Some alternative signatures include u128::widen_mul_add(lhs, rhs, add), lhs.widen_mul_add(rhs, add), or add.widen_mul_add(lhs, rhs). In awint my general purpose mul-add function is mul_add_triop which uses the third signature but takes self mutably and add-assigns lhs * rhs. I'm not sure which is best.

@AaronKutch
Copy link
Contributor

I would also change up the documentation headers for the carrying_add function to say

Extended addition of `self + rhs + carry`. The booleans are interpreted as a single bit
integer of value 0 or 1. If unsigned overflow occurs, then the boolean in the tuple
returns 1. The output carry can be chained into the input carry of another carrying add,
which allows for arbitrarily large additions to be calculated.

I specifically note unsigned overflow, because that happens for both signed and unsigned
integers because of how two's complement works.

@AaronKutch
Copy link
Contributor

borrowing_sub should be left in with its naming, but its documentation could be

Extended subtraction of `self - rhs - borrow`. The "borrowing" here refers to borrowing in the full subtractor sense.
The booleans are interpreted as a single bit integer of value 0 or 1. If unsigned overflow occurs, then the boolean
in the tuple returns 1. The output carry can be chained into the input carry of another borrowing subtract,
which allows for arbitrarily large subtraction to be calculated.

@tspiteri
Copy link
Contributor

tspiteri commented Sep 10, 2021

I specifically note unsigned overflow, because that happens for both signed and unsigned
integers because of how two's complement works.

But unsigned overflow and signed overflow are different. For example, on x86_64, while unsigned and signed integers share addition and subtraction instructions, unsigned overflow is detected using the carry flag while signed overflow is detected using the overflow flag.

As a concrete example: 127i8 + 1 causes signed overflow but not unsigned overflow. So the carry flag should be false/0.

Edit: I think I had misread your comment and thought the middle part of your comment was the current doc, not your suggestion, so it looks like I completely misinterpreted your final comment.

@AaronKutch
Copy link
Contributor

Yes signed and unsigned overflow are different, but the carrying_add as implemented for unsigned and signed integers both use unsigned overflow because of how two's complement carrying works. Someone using i64::carrying_add might think that the carry out bit follows the bit of i64::overflowing_add when in actuality it is following u64::overflowing_add. So in the documentation I would put emphasis on _unsigned_ overflow.

@clarfonthey
Copy link
Contributor Author

clarfonthey commented Sep 14, 2021

I think all of these are good suggestions, and like mentioned earlier, these changes definitely should go in a PR if you have the time. I think one important thing to note is that so far the APIs here seem good, but the documentation definitely could use some work. Although if there's a bigger case for changing the subtraction behaviour to be more in line with what's expected (the existing behaviour is mostly modelled after the x86 instructions adc and sbb), then I'm for that.

That said, the main goal is to make it relatively painless to write correct code that compiles down to the right instructions in release mode, so, I would say we should make sure that happens regardless of what's done. I would have added an explicit test for that but I honestly don't know how.

matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Nov 4, 2021
…riplett

Add more text and examples to `carrying_{add|mul}`

`feature(bigint_helper_methods)` tracking issue rust-lang#85532

cc `@clarfonthey`
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Nov 4, 2021
…riplett

Add more text and examples to `carrying_{add|mul}`

`feature(bigint_helper_methods)` tracking issue rust-lang#85532

cc ``@clarfonthey``
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Nov 4, 2021
…riplett

Add more text and examples to `carrying_{add|mul}`

`feature(bigint_helper_methods)` tracking issue rust-lang#85532

cc ```@clarfonthey```
matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Nov 4, 2021
…riplett

Add more text and examples to `carrying_{add|mul}`

`feature(bigint_helper_methods)` tracking issue rust-lang#85532

cc ````@clarfonthey````
JohnTitor added a commit to JohnTitor/rust that referenced this issue Nov 5, 2021
…riplett

Add more text and examples to `carrying_{add|mul}`

`feature(bigint_helper_methods)` tracking issue rust-lang#85532

cc `````@clarfonthey`````
geky added a commit to geky/gf256 that referenced this issue Nov 8, 2021
Multiplication, and carry-less multiplication, are inherently a widening
operation. Unfortunately, at the time of writing, the types in Rust
don't capture this well, being built around fixed-width wrapping
multiplication.

Rust's stdlib can rely on compiler-level optimizations to clean up
performance issues from unnecessarily-wide multiplications, but this
becomes a bit of an issue for our library, especially for u64 types,
since we rely on intrinsics, which may be hard for compilers to
optimize around.

This commit adds widening_mul, based on a proposal to add widening_mul
to Rust's primitive types:
rust-lang/rust#85532

As well as several other tweaks to how xmul is provided, moving more
arch-level details into xmul, but still limiting when it is emitted.
@AaronKutch
Copy link
Contributor

I've seen before that you can fit a second carry, but usually in bigint libraries we just have a single carry to deal with in multiply-add chains. For long multiplication there are additions in two directions, but a loop can only handle one chain at at time and is usually adding to a temporary and handling that carry separately with carrying_add

@scottmcm
Copy link
Member

@typetetris I don't know whether this will resonate, but I've been thinking of carrying_add like a Full Adder as opposed to the existing overflowing_add that's just a Half Adder. When you're combining multiple for a larger-width operation, the full one is what you want.

So the goal here to to provide that primitive as the obvious way to write it in math libraries, without needing to know about the best way to represent it in the backend in use. For example, LLVM represents wide multiplication by casting to a larger type and doing multiplication on that, but cranelift has mul and mulhi instructions, and there's no way for a library to know its codegen backend. Much better for core to have this essential piece that does the right thing. Having biginteger math in core is probably not the right choice -- there's too many options for how to do it -- but it should make easy for other crates to make a u256 or BigInteger.

So unless there's a particular use for the extra carry, I don't think it makes sense here, even though it's certainly a nice observation that another carry can fit. Like if the extra carry solved the slightly-wider intermediate result problem in Karatsuba then we should absolutely offer it (after all, it's easy to optimize out a + 0 for people that don't need it), but at least from a quick look I don't see a way for the extra carry to handle that.

@scottmcm
Copy link
Member

Also I find the order of return values a bit confusing. Why was it chosen this way around?

Because it fits with overflowing_* in that .0 is the wrapping_* result, then the extra information is in .1.

@kennytm
Copy link
Member

kennytm commented Apr 25, 2024

The return type of .overflowing_*(), .carrying_add() and .borrowing_sub() are (integer, bool) and there's no way to confuse the meaning of the two fields because they have different types.

This is entirely different for the .widening_mul() and .carrying_mul() operations which currently returns (integer, integer) and it's hard to tell which one is the low and high part. The name .widening_mul() does not even contain the word "overflowing" to relate it to other .overflowing_*() functions to make sense of the ordering.

The two multiplication functions should really return a named struct.

@typetetris
Copy link

typetetris commented Apr 26, 2024

@AaronKutch and @scottmcm Thanks for your explanations. I just had something like

// result = result + lhs * rhs
pub fn classic_mul_add_in_place(result: &mut [u64], lhs: &[u64], rhs: &[u64]) {
    debug_assert!(
        result.len() > lhs.len() + rhs.len(),
        "{} <= {} + {}",
        result.len(),
        lhs.len(),
        rhs.len()
    );
    debug_assert!(result[lhs.len() + rhs.len()] < u64::MAX);

    for (rhs_pos, rhs_leg) in rhs.iter().copied().enumerate() {
        let mut carry = 0u64;
        for (lhs_leg, result_place) in lhs
            .iter()
            .copied()
            .chain(std::iter::repeat(0u64))
            .zip(result[rhs_pos..].iter_mut())
        {
            let (new_digit, new_carry) = carrying_mul(rhs_leg, lhs_leg, *result_place, carry);
            *result_place = new_digit;
            carry = new_carry;
        }
        debug_assert_eq!(carry, 0u64);
    }
}

in a toy project of mine (certainly buggy, slow and not idiomatic or something!). The carrying_mul here simply does the "widening" trick of calculating in u128 and then there isn't some additional carrying_add needed. Didn't measure though, if it would make a difference on my machine.

If you ever find a way to handle the slightly wider intermediate multiplication in Karatsuba, let me know, please. At the moment I just handle the carries from the additions of high and low part separately leading to some code bloat.

Edit1: std::iter::repeat instead of std::iter::once
Edit2: The slices in the function are least significant "digit" first.

@nickkuk
Copy link
Contributor

nickkuk commented May 20, 2024

Thank you @typetetris!

I found carrying2_mul function with two carries very useful even for long multiplication.

E.g., here is adapted @kennytm's function that uses carrying2_mul:

pub fn u64_widening_mul2(x: u64, y: u64) -> u128 {
    let a = (x >> u32::BITS) as u32;
    let b = x as u32;
    let c = (y >> u32::BITS) as u32;
    let d = y as u32;
    let (p1, p2) = widening_mul(b, d);
    let (p2, p31) = carrying_mul(b, c, p2);
    let (p2, p32) = carrying_mul(a, d, p2);
    let (p3, p4) = carrying2_mul(a, c, p31, p32);
    u128::from(p1) | u128::from(p2) << 32 | u128::from(p3) << 64 | u128::from(p4) << 96
}

Ever assembly seems to be better than for initial version with explicit overflowing_add: https://godbolt.org/z/aaqzYxsd3

@scottmcm @AaronKutch I'm not sure if this affects the addition of this method to std.

@Lohann
Copy link

Lohann commented Jul 11, 2024

Btw I didn't find a way to generate optimal code for u128 widening multiplication for aarch64 targets.

Tool: https://godbolt.org/
Target: aarch64-unknown-linux-gnu
compiler options: -Copt-level=3 -Clto=fat -Ccodegen-units=1 -Cpanic=abort -Cstrip=symbols -Zlocation-detail=none

Rust code:

#![feature(const_bigint_helper_methods)]
#![feature(bigint_helper_methods)]

#[no_mangle]
pub fn u128_widening_mul(x: u128, y: u128, result: &mut [u128; 2]) {
    let a = (x >> 64) as u64;
    let b = x as u64;
    let c = (y >> 64) as u64;
    let d = y as u64;
    let (p1, p2) = b.widening_mul(d);
    let (p2, p31) = b.carrying_mul(c, p2);
    let (p2, p32) = a.carrying_mul(d, p2);
    let (p3, p4o) = p31.overflowing_add(p32);
    let (p3, p4) = a.carrying_mul(c, p3);
    let p4 = p4.wrapping_add(p4o.into());
    result[0] = u128::from(p1) | u128::from(p2) << 64;
    result[1] = u128::from(p3) | u128::from(p4) << 64;
}

output:

u128_widening_mul:
        umulh   x8, x2, x0
        mul     x10, x3, x0
        umulh   x9, x3, x0
        mul     x12, x2, x1
        adds    x8, x8, x10
        umulh   x11, x2, x1
        cinc    x9, x9, hs
        mul     x14, x3, x1
        adds    x8, x8, x12
        umulh   x10, x3, x1
        cinc    x11, x11, hs
        mul     x13, x2, x0
        adds    x12, x9, x11
        adds    x12, x14, x12
        cinc    x10, x10, hs
        cmn     x9, x11
        stp     x13, x8, [x4]
        cinc    x8, x10, hs
        stp     x12, x8, [x4, #16]
        ret

But using Zig 0.12.0 it was able to generate optimal code:
compiler options: -target aarch64-linux -O ReleaseFast -dead_strip -dead_strip_dylibs

export fn u128_widening_mul(a: u128, b: u128, result: *[2]u128) void {
    const value: u256 = @mulWithOverflow(@as(u256, a), @as(u256, b))[0];
    result[0] = @intCast(value);
    result[1] = @intCast(@shlWithOverflow(value, 128)[0]);
}

output:

u128_widening_mul:
        umulh   x8, x2, x0
        stp     xzr, xzr, [x4, #16]
        mul     x9, x2, x0
        madd    x8, x2, x1, x8
        madd    x8, x3, x0, x8
        stp     x9, x8, [x4]
        ret

@clarfonthey
Copy link
Contributor Author

This is kind of an aside to the discussion, but I greatly appreciate everyone discussing ways of optimising these functions for various targets, and ways of optimising using them for said targets. Very much reaffirms my assumption from the beginning that getting these right is very complicated and generally depends a lot on compiler internals, which is why they should exist in the standard library IMHO.

@tgross35
Copy link
Contributor

tgross35 commented Jul 11, 2024

@Lohann fyi you can share the link to your exact godbolt setup in the top right corner, here: https://godbolt.org/z/r19nKaGh5.

But thanks for mentioning this. Zig supports arbitrary width integers so it just emits much better LLVM IR in your example, compared to Rust where it seems like LLVM can't optimize through the math. nope it's just doing a standard 128-bit multiply and dropping the wide part, see a few comments down. Looks like it isn't even telling LLVM to use i256.

I think the above point still stands, that we would like to figure out the best API before adding methods that may require intrinsics (for i128/u128).

@Lohann
Copy link

Lohann commented Jul 11, 2024

@clarfonthey @tgross35 Makes sense.

About the api, I also think that u128 must implement the same widening_mul primitive, otherwise it can make difficult for using macros that works for all primitives, for example I'm working in a PR for num-traits for supporting the widening multiplication, the trait looks like this so far:

/// Calculates the complete product self * rhs without the possibility to overflow.
pub trait WideningMul<Rhs = Self> {
    type Output;

    #[must_use]
    fn widening_mul(self, rhs: Rhs) -> (Self::Output, Self::Output);
}

I implemented this trait for all primitives, except u128 which I can't find a way to generate optimal code.
rust-num/num-traits#331

@kennytm
Copy link
Member

kennytm commented Jul 11, 2024

@Lohann are you sure the result of Zig make sense?
u128_widening_mul:

; export fn u128_widening_mul(a: u128, b: u128, result: *[2]u128) void
;
; - x0 = lower 64-bit of `a`
; - x1 = upper 64-bit of `a`
; - x2 = lower 64-bit of `b`
; - x3 = upper 64-bit of `b`
; - x4 = pointer to `result`

        umulh   x8, x2, x0

; x8 := upper64(x2 * x0)

        stp     xzr, xzr, [x4, #16]

; x4[1] = 0

        mul     x9, x2, x0

; x9 := lower64(x2 * x0)

        madd    x8, x2, x1, x8

; x8 += lower64(x2 * x1)

        madd    x8, x3, x0, x8

; x8 += lower64(x3 * x0)

        stp     x9, x8, [x4]

; x4[0] = x8 << 64 | x9

        ret

it looks like it is simply computing

result[0] = a * b
result[1] = 0

I think any compiler targeting aarch64 that generated code for u128*u128 significantly less than 18 instructions (which is the output of directly using LLVM-IR from #85532 (comment)) should be considered their bug.

@Lohann
Copy link

Lohann commented Jul 11, 2024

@kennytm good catch, you are right there was a bug in my zig code, I was doing shift left instead of shift right, fixed 🤦 .

export fn u128_widening_mul(a: u128, b: u128, result: *[2]u128) void {
    const x: u256 = @intCast(a);
    const y: u256 = @intCast(b);
    const value: u256 = @mulWithOverflow(x, y)[0];
    result[0] = @truncate(value);
    result[1] = @truncate(value >> 128);
}

The rust code only generates one instruction more than the zig code, which is weird because zig also uses llvm, but that's not bad I can go forward with this implementation, thank you sir!
https://godbolt.org/z/39Mq5serc

@clarfonthey
Copy link
Contributor Author

One potential (weird) solution might be implementing an internal 256-bit integer which isn't exposed publicly and doesn't have all the operations implemented, but could be used oh LLVM's side to generate better code here.

Or just going all out and doing generic integers like zig has, and keeping them internal until a public API is settled on.

Both probably require an MCP.

@cuviper
Copy link
Member

cuviper commented Jul 11, 2024

I think we don't need full-blown types -- an intrinsic can lower to LLVM i256 internally, and hopefully similar on other backends.

@scottmcm
Copy link
Member

@typetetris @nickkuk Your messages made me realize something: the way to justify carrying2_mul is not to talk about it as two carries, but that it's mul_add_carry. Basically, it's what you need for the wide version of z += a * b;. And, conveniently, LLVM already knows that both adds in the wider type can't overflow https://llvm.godbolt.org/z/6r7bxc39E.

If you want to send a PR adding it to nightly, I'm willing to approve it, though it'll need naming feedback from libs-api at some before before it would have a chance at stabilizing. (I could see carrying_mul_add, mul_add_carry, mul_add_with_carry, or more, so pick whatever you think is best justified.)

@clarfonthey We have intrinsics with fallback bodies now, so we can add a poor version in rust in a way that it can be overridden by LLVM (to emit i256 operations like https://llvm.godbolt.org/z/qjfEajb7Y) to let LLVM see it as well as possible but without forcing all the other backends to implement it too.

@clarfonthey
Copy link
Contributor Author

clarfonthey commented Oct 9, 2024

So, I was looking into this again and wanted to summarise some of the stuff folks have discussed so far, to see what common ground has been established.

Addition methods

So far, we're totally okay with the signatures of the two methods, where T is any integer type:

  • addition: (T + T + bool) -> (T, bool)
  • subtraction: (T - T - bool) -> (T, bool)

The main issue is naming these methods, and there doesn't seem to be a consensus so far. A few of the options for addition:

  • carrying_add (current)
  • extending_add
  • overflowing_add_carry
  • carrying_add_carry
  • add_with_carry

And for subtraction:

  • borrowing_add (current)
  • extending_sub
  • overflowing_sub_borrow
  • sub_with_carry

One option I particularly like is using the carry terminology for unsigned integers only, and using overflowing instead for signed integers, to indicate that they have different usages. So:

  • uN::carrying_add_carry
  • uN::carrying_sub_carry
  • iN::overflowing_add_carry
  • iN::overflowing_sub_carry

Although we definitely need to come up with a name consensus before stabilisation. The shed awaits…

Multiplication methods

These ones have undergone a lot of different discussion. A few notes that folks have added:

  1. Less-significant words should always be unsigned. This also helps a bit with return value order since regardless of order, you'll know based upon the type.
  2. In addition to unsigned-unsigned and signed-signed multiplication, there should be signed-unsigned as well.
  3. There can be up to two carries for multiplication, and people have expressed desire for all combinations (zero carries, one carry, and two carries).
  4. There are also requests for mul_mod, which would only have one return value. No one mentioned signed versions, but presumably these would exist.

So, just to fully cover the signatures of these, using not-Rust syntax. Going to use a period for concatenation, and give a temporary name to them to hopefully make sense.

Shorthand Input Signature Input Meaning Output Signature Output Meaning
unsigned (x: uN, y: uN) x * y (z: uN, w: uN) (z . w)
unsigned-carry (x: uN, y: uN, a: uN) x * y + a (z: uN, w: uN) (z . w)
unsigned-carry2 (x: uN, y: uN, a: uN, b: uN) x * y + a + b (z: uN, w: uN) (z . w)
mixed (x: iN, y: uN) x * y (z: iN, w: uN) (z . w)
mixed-carry (x: iN, y: uN, a: iN) x * y + a (z: iN, w: uN) (z . w)
mixed-carry2 (x: iN, y: uN, a: iN, b: iN) x * y + a + b (z: iN, w: uN) (z . w)
signed (x: iN, y: iN) x * y (z: iN, w: uN) (z . w)
signed-carry (x: iN, y: iN, a: iN) x * y + a (z: iN, w: uN) (z . w)
signed-carry2 (x: iN, y: iN, a: iN, b: iN) x * y + a + b (z: iN, w: uN) (z . w)
unsigned-mod (x: uN, y: uN, n: uN) (x * y) % n z: uN z
mixed-mod (x: iN, y: uN, n: iN) (x * y) % n z: iN z
signed-mod (x: iN, y: iN, n: iN) (x * y) % n z: iN z

Not a whole lot has been done for names. Generally, people think of the two-word versions of multiplication as a "wide mul" or "widening mul" and that's okay. Probably the names carry and carry2 will be what we use for the carrying + double-carrying versions.

Right now, it's unclear whether signed-mod and mixed-mod should have an unsigned or signed modulo, which would affect the final result. It feels reasonable to potentially offer this for greater precision.

Finally, there's the subject of the return value. It seems reasonable to create a struct for this, since otherwise it won't be clear what word is which in most cases.

Right now, only the unsigned is implemented as widening_mul (excluding u128) and unsigned-carry is implemented as carrying_mul (excluding u128 again).

Bit-shift methods

People seemed pretty amenable to adding these, although again, the carry/borrow name is a bit weird. Particularly, (T shift u32) | T -> (T . T) (carrying) and (T shift u32) -> (T . T) (not carrying), where they represent shifts potentially with an or-ed carry.

These aren't on nightly yet.

Conclusions

It seems definitely reasonable to add intrinsics for some of these methods as a good next step, since it's unlikely we'll get the right result without help.

@kennytm
Copy link
Member

kennytm commented Oct 10, 2024

It seems definitely reasonable to add intrinsics for some of these methods as a good next step, since it's unlikely we'll get the right result without help.

I don't think it's unlikely to get the right result for all of these without intrinsics. The intrinsics are needed to get them right and fast (easy to optimizable).

@clarfonthey
Copy link
Contributor Author

clarfonthey commented Oct 11, 2024

So, I attempted to start writing some intrinsics for these, but I have not done this before and may have run into the most cursed compiler bug I've ever encountered, and I've also never done this before.

But uh, we'll see what this ends up as later. Figured I'd mention in case anyone else was thinking of trying.


In case you're wondering, it's me finding out that LLVM doesn't document any of its methods and secretly makes them all have unknown preconditions that can trigger UB if not properly met. I was getting illegal instructions just randomly in the middle of building my code.

@Rudxain
Copy link
Contributor

Rudxain commented Oct 12, 2024

Is there a link pointing to some Internals-Forum or Zulip thread for bike-shedding the names?

I'm aware that tracking-issues aren't meant for discussion, that's why I'm asking 😅

@clarfonthey
Copy link
Contributor Author

No, but you're more than welcome to make one and link it here!

@Rudxain
Copy link
Contributor

Rudxain commented Oct 12, 2024

Done!

@leb-kuchen
Copy link

After looking at the assembly, I say that carrying_add and borrowing_sub are desperately needed. the optimal assembly has an add instruction with a constant of -1, an addc instruction, one of which is a constant, and a set instruction, while the current assembly has two add instructions, two set instructions, and an or instruction.
Then for example, dashu could also use optimal assembly for targets other than x86-64 without much effort.

example::add_with_carry_arch::h46794524507ae557:
        mov     rax, rdi
        add     dl, -1
        adc     rax, rsi
        setb    dl
        ret

example::add_with_carry_helper::h2bc1fa2da7e86911:
        add     rdi, rsi
        setb    cl
        mov     eax, edx
        add     rax, rdi
        setb    dl
        or      dl, cl
        ret

https://godbolt.org/z/roejrjjzz

@TDecking
Copy link
Contributor

It turns out that rustc was able to optimize the current implementation of carrying_add/borrowing_sub perfectly in previous versions,
but it has regressed since. Rust 1.82 added another regression in which the use of these functions inside a standard bignum addition loop
is now worse when compared to a version using architecture instrinsics.

https://godbolt.org/z/hK7M37Y85

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-tracking-issue Category: An issue tracking the progress of sth. like the implementation of an RFC T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests