Skip to content

Commit 969bcb6

Browse files
rainbowbismuthandrewrk
authored andcommitted
C backend: implement signed trunc
1 parent 1de6f9a commit 969bcb6

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

src/codegen/c.zig

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1390,7 +1390,14 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
13901390
return local;
13911391
},
13921392
.signed => {
1393-
return f.fail("TODO: C backend: implement trunc for signed integers", .{});
1393+
const operand_ty = f.air.typeOf(ty_op.operand);
1394+
const c_bits = toCIntBits(operand_ty.intInfo(target).bits) orelse
1395+
return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});
1396+
const shift_rhs = c_bits - dest_bits;
1397+
try writer.print("(int{d}_t)((uint{d}_t)", .{ c_bits, c_bits });
1398+
try f.writeCValue(writer, operand);
1399+
try writer.print(" << {d}) >> {d};\n", .{ shift_rhs, shift_rhs });
1400+
return local;
13941401
},
13951402
}
13961403
}

test/behavior.zig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ test {
55
_ = @import("behavior/basic.zig");
66
_ = @import("behavior/bool.zig");
77
_ = @import("behavior/if.zig");
8+
_ = @import("behavior/truncate.zig");
89

910
if (builtin.object_format != .c) {
1011
// Tests that pass for stage1 and stage2 but not the C backend.
@@ -60,7 +61,6 @@ test {
6061
_ = @import("behavior/switch.zig");
6162
_ = @import("behavior/this.zig");
6263
_ = @import("behavior/translate_c_macros.zig");
63-
_ = @import("behavior/truncate.zig");
6464
_ = @import("behavior/underscore.zig");
6565
_ = @import("behavior/union.zig");
6666
_ = @import("behavior/usingnamespace.zig");

test/behavior/basic.zig

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,11 @@ test "truncate to non-power-of-two integers" {
2727
try testTrunc(u32, u1, 0b10110, 0b0);
2828
try testTrunc(u32, u2, 0b10101, 0b01);
2929
try testTrunc(u32, u2, 0b10110, 0b10);
30-
// TODO add test coverage for this!
31-
// try testTrunc(i32, i3, -4, -4);
30+
try testTrunc(i32, i5, -4, -4);
31+
try testTrunc(i32, i5, 4, 4);
32+
try testTrunc(i32, i5, -28, 4);
33+
try testTrunc(i32, i5, 28, -4);
34+
try testTrunc(i32, i5, std.math.maxInt(i32), -1);
3235
}
3336

3437
fn testTrunc(comptime Big: type, comptime Little: type, big: Big, little: Little) !void {

0 commit comments

Comments
 (0)