Skip to content

core::num::f16b Rust's 16bit Brain Float - #160859

Open
Jamesbarford wants to merge 6 commits into
rust-lang:mainfrom
Jamesbarford:feat/fb16-pt1
Open

core::num::f16b Rust's 16bit Brain Float#160859
Jamesbarford wants to merge 6 commits into
rust-lang:mainfrom
Jamesbarford:feat/fb16-pt1

Conversation

@Jamesbarford

@Jamesbarford Jamesbarford commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

View all comments

Implements the RFC: f16b type. Best reviewed commit by commit, happy to split into separate PRs if that is deemed easier to review. However the line count and surface area is, in my opinion, reasonably small.

Adds;

  • ABI plumbing for the f16b along with bfloat lang item to work with LLVM, GCC is explicitly unimplemented!(...)
  • f16b feature gate, page for f16b on libruscdoc and a struct bf16 in core::num
  • Tests
  • Treat f16b as a scalar primitive for scalable vectors

Issues;

@rustbot

rustbot commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred in compiler/rustc_attr_ir

cc @jdonszelmann, @JonathanBrouwer

This PR changes rustc_public

cc @oli-obk, @celinval, @ouz-a, @makai410

rustc_codegen_gcc is developed in its own repository. If possible, consider making this change to rust-lang/rustc_codegen_gcc instead.

cc @antoyo, @GuillaumeGomez

@rustbot rustbot added A-attributes Area: Attributes (`#[…]`, `#![…]`) A-LLVM Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Aug 10, 2026
@rustbot rustbot added T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Aug 10, 2026
@rustbot

rustbot commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

r? @jieyouxu

rustbot has assigned @jieyouxu.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 75 candidates
  • Random selection from 18 candidates

@rust-log-analyzer

This comment has been minimized.

… and backend handling. GCC and Cranelift explicitly unsupported
@jieyouxu

Copy link
Copy Markdown
Member

@rustbot reroll

@rustbot rustbot assigned mati865 and unassigned jieyouxu Aug 10, 2026
}

fn type_f16b(&self) -> Type<'gcc> {
bug!("f16b is not supported by the GCC codegen backend")

@antoyo antoyo Aug 10, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks 😄, I will aim to add it in a follow up PR 👍

@rustbot

rustbot commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

rustc_codegen_cranelift is developed in its own repository. If possible, consider making this change to rust-lang/rustc_codegen_cranelift instead.

cc @bjorn3

let bfloat = scalar_unit(Primitive::Float(abi::Float::F16B));
assert_eq!(layout.size, abi::Float::F16B.size());
assert_eq!(layout.align, abi::Float::F16B.align(cx));
layout.backend_repr = BackendRepr::Scalar(bfloat);

@bjorn3 bjorn3 Aug 10, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You probably also want to add a check that you can't take a reference to the inner field just like for #[repr(simd)].

View changes since the review

@bjorn3 bjorn3 Aug 10, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What is the calling convention of other targets?

View changes since the review

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I believe only these files were changed because they have an exhaustive match on Float.

However, my version of abi-cafe found two interesting failures: GCC and Clang are inconsistent on aarch64 and armv7

// callee, compiled with GCC 12
#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct Many1 {
    __bf16 f0;
} Many1;

void struct_in_1(Many1 arg0) {
    printf("%d", arg0.f0);
}
// caller, compiled with clang 23
#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct Many1 {
    __bf16 f0;
} Many1;

void struct_in_1(Many1 arg0);

void do_test(void) {
    {
        Many1 arg0 = { .f0 = (((union { uint16_t bits; __bf16 value; }){ .bits = 49600 }).value) };

        printf("%d", arg0.f0);
        struct_in_1(arg0);

    }
}

hits

    func struct_in_1's values differed
      values (native-endian hex bytes):
        expect: C0 C1
        caller: C0 C1
        callee: 04 00
      the value was arg0.f0: rustarithmeticty(f16b)
      whose arg was arg0: Many1

The current Rust implementation matches clang, and is hence incompatible with GCC


armv7 with hardware floats also runs into incompatibilities

[target.armv7-unknown-linux-gnueabihf."f16::conv_c::repr_c::clang-nightly_calls_distro-gcc"]
busted = "check"

[target.armv7-unknown-linux-gnueabihf."f16::conv_c::repr_c::distro-gcc_calls_clang-nightly"]
busted = "check"

[target.armv7-unknown-linux-gnueabihf."f16b::conv_c::repr_c::clang-nightly_calls_distro-gcc"]
busted = "check"

[target.armv7-unknown-linux-gnueabihf."f16b::conv_c::repr_c::distro-gcc_calls_clang-nightly"]
busted = "check"

Finally, you can let this ICE on many targets, e.g. mips, powerpc, s390x, sparc

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You can also (e.g. on loongarch64 https://godbolt.org/z/Y3hdhG4e6) emit a __truncsfbf2 libcall that is not provided (probably needs to be added to compiler-builtins).


I think the ICEs are probably a blocker? That needs a mechanism similar to has_reliable_f128.

@Jamesbarford Jamesbarford Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes I added it because of the exhaustive match statement in mips64.rs and sparc64.rs I've removed it; 40d3f6e and put in a panic!(...).

With regard to has_reliable_f128, are you envisaging a has_reliable_f16b entry on TargetConfig?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With regard to has_reliable_f128, are you envisaging a has_reliable_f16b entry on TargetConfig?

Exactly

@rust-log-analyzer

This comment has been minimized.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I believe only these files were changed because they have an exhaustive match on Float.

However, my version of abi-cafe found two interesting failures: GCC and Clang are inconsistent on aarch64 and armv7

// callee, compiled with GCC 12
#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct Many1 {
    __bf16 f0;
} Many1;

void struct_in_1(Many1 arg0) {
    printf("%d", arg0.f0);
}
// caller, compiled with clang 23
#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct Many1 {
    __bf16 f0;
} Many1;

void struct_in_1(Many1 arg0);

void do_test(void) {
    {
        Many1 arg0 = { .f0 = (((union { uint16_t bits; __bf16 value; }){ .bits = 49600 }).value) };

        printf("%d", arg0.f0);
        struct_in_1(arg0);

    }
}

hits

    func struct_in_1's values differed
      values (native-endian hex bytes):
        expect: C0 C1
        caller: C0 C1
        callee: 04 00
      the value was arg0.f0: rustarithmeticty(f16b)
      whose arg was arg0: Many1

The current Rust implementation matches clang, and is hence incompatible with GCC


armv7 with hardware floats also runs into incompatibilities

[target.armv7-unknown-linux-gnueabihf."f16::conv_c::repr_c::clang-nightly_calls_distro-gcc"]
busted = "check"

[target.armv7-unknown-linux-gnueabihf."f16::conv_c::repr_c::distro-gcc_calls_clang-nightly"]
busted = "check"

[target.armv7-unknown-linux-gnueabihf."f16b::conv_c::repr_c::clang-nightly_calls_distro-gcc"]
busted = "check"

[target.armv7-unknown-linux-gnueabihf."f16b::conv_c::repr_c::distro-gcc_calls_clang-nightly"]
busted = "check"

Finally, you can let this ICE on many targets, e.g. mips, powerpc, s390x, sparc

Comment on lines +12 to +16
#[lang = "bfloat"]
#[allow(non_camel_case_types)]
#[repr(transparent)]
#[unstable(feature = "f16b", issue = "160630")]
pub struct f16b(u16);

@folkertdev folkertdev Aug 11, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can you also add this to minicore.rs?

View changes since the review

},
Primitive::Float(float) => match float {
Float::F16 | Float::F32 => "f32",
Float::F16 | Float::F16B | Float::F32 => "f32",

@folkertdev folkertdev Aug 11, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is that right? LLVM just crashes on bf16 right now, so it's probably at least untested?

View changes since the review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I could be mistaken, however I don't think WASM supports bf16? I've made it panic!(...) for now; 40d3f6e

Comment thread library/core/src/num/f16b.rs
Comment thread library/core/src/num/f16b.rs
Comment thread tests/codegen-llvm/float/f16b.rs Outdated
- Add documentation aliases to `f16b`
- Add Wikipedia link to `bfloat16`
- Remove `@ only-x86_64` flag from test
- ICE on `sparc64`, `mips64` & WASM
@rust-log-analyzer

Copy link
Copy Markdown
Collaborator

The job aarch64-gnu-llvm-21-1 failed! Check out the build log: (web) (plain enhanced) (plain)

Click to see the possible cause of the failure (guessed by this bot)
diff of stdout:

15     /*
16     0#0
17     */ {
-     ($f /* 0#0 */:ident /* 0#0 */<$a /* 0#0 */:lifetime /* 0#0 */>)
-     =>
+     ($f /* 0#0 */:ident /* 0#0 */<$a /* 0#0 */:lifetime /* 0#0
+     */>) =>
20     { fn /* 0#0 */ $f /* 0#0 */<$a /* 0#0 */, 'a /* 0#0 */>() {} }
21 }
22 fn f /* 0#0 */<'a /* 0#0 */, 'a /* 0#1 */>() {}

Note: some mismatched output was normalized before being compared
-     ($f /* 2355#0 */:ident /* 1001#0 */<$a /* 2350#0 */:lifetime /* 1098#0
+     ($f /* 0#0 */:ident /* 0#0 */<$a /* 0#0 */:lifetime /* 0#0
+     */>) =>


The actual stdout differed from the expected stdout
To update references, rerun the tests and pass the `--bless` flag
To only update this specific test, also pass `--test-args hygiene/unpretty-debug-lifetimes.rs`

error: 1 errors occurred comparing output.
status: exit status: 0
command: env -u RUSTC_LOG_COLOR RUSTC_ICE="0" RUST_BACKTRACE="short" "/checkout/obj/build/aarch64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/ui/hygiene/unpretty-debug-lifetimes.rs" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "-Z" "ignore-directory-in-diagnostics-source-blocks=/checkout/vendor" "--sysroot" "/checkout/obj/build/aarch64-unknown-linux-gnu/stage2" "--target=aarch64-unknown-linux-gnu" "--check-cfg" "cfg(test,FALSE)" "--error-format" "json" "--json" "future-incompat" "-Ccodegen-units=1" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zwrite-long-types-to-disk=no" "-Cstrip=debuginfo" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/aarch64-unknown-linux-gnu/test/ui/hygiene/unpretty-debug-lifetimes" "-A" "unused" "-W" "unused_attributes" "-A" "internal_features" "-A" "incomplete_features" "-A" "unused_parens" "-A" "unused_braces" "-Crpath" "-Cdebuginfo=0" "-Lnative=/checkout/obj/build/aarch64-unknown-linux-gnu/native/rust-test-helpers" "-Zunpretty=expanded,hygiene"
--- stdout -------------------------------
//@ check-pass
//@ compile-flags: -Zunpretty=expanded,hygiene

// Regression test for lifetime hygiene annotations in -Zunpretty=expanded,hygiene
// Previously, lifetimes were missing the #N syntax context suffix.

// Don't break whenever Symbol numbering changes
//@ normalize-stdout: "\d+#" -> "0#"

#![feature /* 861#0 */(decl_macro /* 695#0 */)]
#![feature /* 861#0 */(no_core /* 1334#0 */)]
#![no_core /* 1334#0 */]

macro lifetime_hygiene
    /*
    2942#0
    */ {
    ($f /* 2355#0 */:ident /* 1001#0 */<$a /* 2350#0 */:lifetime /* 1098#0
    */>) =>
    { fn /* 12#0 */ $f /* 2355#0 */<$a /* 2350#0 */, 'a /* 2943#0 */>() {} }
}
fn f /* 2355#0 */<'a /* 2943#0 */, 'a /* 2943#1 */>() {}


/*
Expansions:
crate0::{{expn0}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Root
crate0::{{expn1}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Bang, "lifetime_hygiene")

SyntaxContexts:
#0: parent: #0, outer_mark: (crate0::{{expn0}}, Opaque)
#1: parent: #0, outer_mark: (crate0::{{expn1}}, Opaque)
*/
------------------------------------------
stderr: none

---- [ui] tests/ui/hygiene/unpretty-debug-lifetimes.rs stdout end ----

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-attributes Area: Attributes (`#[…]`, `#![…]`) A-LLVM Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants