Skip to content

add math.wideMul #2111

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

Merged
merged 1 commit into from
Mar 28, 2019
Merged
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
11 changes: 11 additions & 0 deletions std/math.zig
Original file line number Diff line number Diff line change
Expand Up @@ -806,3 +806,14 @@ test "max value type" {
const x: u32 = maxInt(i32);
testing.expect(x == 2147483647);
}

pub fn mulWide(comptime T: type, a: T, b: T) @IntType(T.is_signed, T.bit_count * 2) {
const ResultInt = @IntType(T.is_signed, T.bit_count * 2);
return ResultInt(a) * ResultInt(b);
}

test "math.wideMul" {
testing.expect(wideMul(u8, 5, 5) == 25);
testing.expect(wideMul(i8, 5, -5) == -25);
testing.expect(wideMul(u8, 100, 100) == 10000);
}
9 changes: 1 addition & 8 deletions std/math/big/int.zig
Original file line number Diff line number Diff line change
Expand Up @@ -705,14 +705,7 @@ pub const Int = struct {
const c1: Limb = @boolToInt(@addWithOverflow(Limb, a, carry.*, &r1));

// r2 = b * c
//
// We still use a DoubleLimb here since the @mulWithOverflow builtin does not
// return the carry and lower bits separately so we would need to perform this
// anyway to get the carry bits. The branch on the overflow case costs more than
// just computing them unconditionally and splitting.
//
// This could be a single x86 mul instruction, which stores the carry/lower in rdx:rax.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did this comment become incorrect?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is no longer relevant, because that is exactly what math.wideMul() does.

const bc = DoubleLimb(b) * DoubleLimb(c);
const bc = DoubleLimb(math.mulWide(Limb, b, c));
const r2 = @truncate(Limb, bc);
const c2 = @truncate(Limb, bc >> Limb.bit_count);

Expand Down