aboutsummaryrefslogtreecommitdiff
path: root/lib/compiler_rt/negv.zig
blob: 6a2e717db1505f7a7b98be11116e6fdade939703 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//! negv - negate oVerflow
//! * @panic, if result can not be represented
//! - negvXi4_generic for unoptimized version
const std = @import("std");
const builtin = @import("builtin");
const common = @import("common.zig");

pub const panic = common.panic;

comptime {
    @export(&__negvsi2, .{ .name = "__negvsi2", .linkage = common.linkage, .visibility = common.visibility });
    @export(&__negvdi2, .{ .name = "__negvdi2", .linkage = common.linkage, .visibility = common.visibility });
    @export(&__negvti2, .{ .name = "__negvti2", .linkage = common.linkage, .visibility = common.visibility });
}

pub fn __negvsi2(a: i32) callconv(.c) i32 {
    return negvXi(i32, a);
}

pub fn __negvdi2(a: i64) callconv(.c) i64 {
    return negvXi(i64, a);
}

pub fn __negvti2(a: i128) callconv(.c) i128 {
    return negvXi(i128, a);
}

inline fn negvXi(comptime ST: type, a: ST) ST {
    const UT = switch (ST) {
        i32 => u32,
        i64 => u64,
        i128 => u128,
        else => unreachable,
    };
    const N: UT = @bitSizeOf(ST);
    const min: ST = @as(ST, @bitCast((@as(UT, 1) << (N - 1))));
    if (a == min)
        @panic("compiler_rt negv: overflow");
    return -a;
}

test {
    _ = @import("negvsi2_test.zig");
    _ = @import("negvdi2_test.zig");
    _ = @import("negvti2_test.zig");
}