Skip to content
This repository was archived by the owner on Nov 26, 2025. It is now read-only.

Commit 052fcbe

Browse files
committed
convert bf16 to u16
1 parent e883d95 commit 052fcbe

3 files changed

Lines changed: 24 additions & 2 deletions

File tree

src/MacroTranslator.zig

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -355,8 +355,17 @@ fn parseCNumLit(mt: *MacroTranslator) ParseError!ZigNode {
355355
.L => "c_longdouble",
356356
.W, .F64x => "f80",
357357
.Q, .F128 => "f128",
358-
.BF16 => "u16",
359-
358+
.BF16 => {
359+
// Zig doesn't support BFloat16, so the best thing we can do is convert it to u16,
360+
// so that the value is bit-to-bit identic between the emitted Zig and original C code.
361+
// https://github.com/ziglang/zig/issues/3148
362+
const value_u16 = parseBfloat16AsU16(bytes.items);
363+
std.debug.assert(bytes.capacity >= 6); // guaranteed since we allocated literal len + 3
364+
const bf16_hex = std.fmt.bufPrint(bytes.allocatedSlice(), "0x{x}", .{value_u16}) catch unreachable;
365+
const rhs = try ZigTag.integer_literal.create(arena, bf16_hex);
366+
const type_node = try ZigTag.type.create(arena, "u16");
367+
return ZigTag.as.create(arena, .{ .lhs = type_node, .rhs = rhs });
368+
},
360369
else => {
361370
try mt.fail("TODO: float literal suffix: '{s}'", .{suffix_str});
362371
return error.ParseError;
@@ -1359,3 +1368,11 @@ fn parseCUnaryExpr(mt: *MacroTranslator, scope: *Scope) ParseError!ZigNode {
13591368

13601369
return try mt.parseCPostfixExpr(scope, null);
13611370
}
1371+
1372+
fn parseBfloat16AsU16(bytes: []const u8) u16 {
1373+
const value_f32 = std.fmt.parseFloat(f32, bytes) catch math.nan(f32);
1374+
var int: u32 = @bitCast(value_f32);
1375+
// Round up if needed.
1376+
int += 0x8000;
1377+
return @truncate(int >> 16);
1378+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#define EXACT_BF16 0.007873535BF16
2+
3+
// translate
4+
//
5+
// pub const EXACT_BF16 = @as(u16, 0x3c01);

test/cases/translate/f64_integer_suffix_after_float_literal.c renamed to test/cases/translate/f64_suffix_after_float_literal.c

File renamed without changes.

0 commit comments

Comments
 (0)