Skip to content

Change codegen of LLVM intrinsics to be name-based, and add llvm linkage support for bf16(xN), i1xN and x86amx #140763

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

Open
wants to merge 10 commits into
base: master
Choose a base branch
from

Conversation

sayantn
Copy link
Contributor

@sayantn sayantn commented May 7, 2025

This PR changes how LLVM intrinsics are codegen

Explanation of the changes

Current procedure

This is the same for all functions, LLVM intrinsics are not treated specially

  • We get the LLVM Type of a function simply using the argument types. For example, the following function
    #[link_name = "llvm.sqrt.f32"]
    fn sqrtf32(a: f32) -> f32;
    will have LLVM type simply f32 (f32) due to the Rust signature

Pros

  • Simpler to implement, no extra complexity involved due to LLVM intrinsics

Cons

  • LLVM intrinsics have a well-defined signature, completely defined by their name (and if it is overloaded, the type parameters). So, this process of converting Rust signatures to LLVM signatures may not work, for example the following code generates LLVM IR without any problem
    #[link_name = "llvm.sqrt.f32"]
    fn sqrtf32(a: i32) -> f32;
    but the generated LLVM IR is invalid, because it has wrong signature for the intrinsic (Godbolt, adding -Zverify-llvm-ir to it will fail compilation). I would expect this code to not compile at all instead of generating invalid IR.
  • LLVM intrinsics that have types in their signature that can't be accessed from Rust (notable examples are the AMX intrinsics that have the x86amx type, and (almost) all intrinsics that have vectors of i1 types) can't be linked to at all. This is a (major?) roadblock in the AMX and AVX512 support in stdarch.
  • If code uses an non-existing LLVM intrinsic, even -Zverify-llvm-ir won't complain. Eventually it will error out due to the non-existing function (courtesy of the linker). I don't think this is a behavior we want.

What this PR does

  • When linking to non-overloaded intrinsics, we use the function LLVMIntrinsicGetType to directly get the function type of the intrinsic from LLVM.
  • We then use this LLVM definition to verify the Rust signature, and emit a proper error if it doesn't match, instead of silently emitting invalid IR.

Note

This PR only focuses on non-overloaded intrinsics, overloaded can be done in a future PR

Regardless, the undermentioned functionalities work for all intrinsics

  • If we can't find the intrinsic, we check if it has been AutoUpgraded by LLVM. If not, that means it is an invalid intrinsic, and we error out.
  • Don't allow intrinsics from other archs to be declared, e.g. error out if an AArch64 intrinsic is declared when we are compiling for x86

Pros

  • It is now not possible (or at least, it would require significantly more leaps and bounds) to introduce invalid IR using non-overloaded LLVM intrinsics.
  • As we are now doing the matching of Rust signatures to LLVM intrinsics ourselves, we can now add bypasses to enable linking to such non-Rust types (e.g. matching 8192-bit vectors to x86amx and injecting llvm.x86.cast.vector.to.tile and llvm.x86.cast.tile.to.vectors in callsite)

Note

I don't intend for these bypasses to be permanent (at least the bf16 and i1 ones, the x86amx bypass seems inevitable). A better approach will be introducing a bf16 type in Rust, and allowing repr(simd) with bools to get Rust-native i1xNs. These are meant to be short-time, as I mentioned, "bypass"es. They shouldn't cause any major breakage even if removed, as link_llvm_intrinsics is perma-unstable.

This PR adds bypasses for bf16 (via i16), bf16xN (via i16xN), i1xN (via iM, where M is the smallest power of 2 s.t. M >= N, unless N <= 4, where we use M = 8), and x86amx (via 8192-bit vectors). This will unblock AVX512-VP2INTERSECT, AMX and a lot of bf16 intrinsics in stdarch. This PR also automatically destructures structs if the types don't exactly match (this is required for us to start emitting hard errors on mismmatches).

Cons

  • This only works for non-overloaded intrinsics (at least for now). Improving this to work with overloaded intrinsics too will involve significantly more work.

Possible ways to extend this to overloaded intrinsics (future)

Parse the mangled intrinsic name to get the type parameters

LLVM has a stable mangling of intrinsic names with type parameters (in LLVMIntrinsicCopyOverloadedName2), so we can parse the name to get the type parameters, and then just do the same thing.

Pros

  • For most intrinsics, this will work perfectly, and is a easy way to do this.

Cons

  • The LLVM mangling is not perfectly reversible. When we have TargetExt types or identified structs, their name is a part of the mangling, making it impossible to reverse. Even more complexities arise when there are unnamed identified structs, as LLVM adds more mangling to the names.

Use the IITDescriptor table and the Rust function signature

We can use the base name to get the IITDescriptors of the corresponding intrinsic, and then manually implement the matching logic based on the Rust signature.

Pros

  • Doesn't have the above mentioned limitation of the parsing approach, has correct behavior even when there are identified structs and TargetExt types. Also, fun fact, Rust exports all struct types as literal structs (unless it is emitting LLVM IR, then it always uses named identified structs, with mangled names)

Cons

  • Doesn't actually use the type parameters in the name, only uses the base name and the Rust signature to get the llvm signature (although we can check that it is the correct name). It means there would be no way to (for example) link against llvm.sqrt.bf16 until we have bf16 types in Rust. Because if we are using u16s (or any other type) as bf16s, then the matcher will deduce that the signature is u16 (u16) not bf16 (bf16) (which would lead to an error because u16 is not a valid type parameter for llvm.sqrt), even though the intended type parameter is specified in the name.
  • Much more complex, and hard to maintain as LLVM gets new IITDescriptorKinds

These 2 approaches might give different results for same function. Let's take

#[link_name = "llvm.is.constant.bf16"]
fn foo(a: u16) -> bool

The name-based approach will decide that the type parameter is bf16, and the LLVM signature is i1 (bf16) and will inject some bitcasts at callsite.
The IITDescriptor-based approach will decide that the LLVM signature is i1 (u16), and will see that the name given doesn't match the expected name (llvm.is.constant.u16), and will error out.

Other things that this PR does

  • Disables all ABI checks only for the unadjusted ABI to facilitate the implementation of AMX (otherwise passing 8192-bit vectors to the intrinsic won't be allowed). This is "safe" because this ABI is only used to link to LLVM intrinsics, and passing vectors of any lengths to LLVM intrinsics is fine, because they don't exist in machine level.
  • Removes unnecessary bitcasts in cg_llvm/builder::check_call (now renamed as cast_arguments due to its new counterpart cast_return). This was old code from when Rust used to pass non-erased lifetimes to LLVM.

Reviews are welcome, as this is my first time actually contributing to rustc

After CI is green, we would need a try build and a rustc-perf run.

@rustbot label T-compiler A-codegen A-LLVM
r? codegen

@rustbot rustbot added 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. O-x86_64 Target: x86-64 processors (like x86_64-*) (also known as amd64 and x64) labels May 7, 2025
@rustbot
Copy link
Collaborator

rustbot commented May 8, 2025

Some changes occurred in compiler/rustc_codegen_ssa

cc @WaffleLapkin

@sayantn

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rustbot
Copy link
Collaborator

rustbot commented May 8, 2025

Some changes occurred in compiler/rustc_codegen_gcc

cc @antoyo, @GuillaumeGomez

@rust-log-analyzer

This comment has been minimized.

@sayantn sayantn changed the title Add auto-bitcasts from/to x86amx and i32x256 for AMX intrinsics Add auto-bitcasts from/to x86amx for i32x256 for AMX intrinsics May 8, 2025
@sayantn sayantn changed the title Add auto-bitcasts from/to x86amx for i32x256 for AMX intrinsics Add auto-bitcasts between x86amx and i32x256 for AMX intrinsics May 8, 2025
@sayantn

This comment has been minimized.

@dianqk
Copy link
Member

dianqk commented May 9, 2025

I think you can use LLVMGetIntrinsicDeclaration, LLVMGetIntrinsicDeclaration or some functions in Intrinsic.h in declare_raw_fn, as a reference: https://github.com/llvm/llvm-project/blob/d35ad58859c97521edab7b2eddfa9fe6838b9a5e/llvm/lib/AsmParser/LLParser.cpp#L330-L335.

@sayantn
Copy link
Contributor Author

sayantn commented May 9, 2025

That can be used to improve performance, I am not really focusing on performance in this PR. I want to currently emphasize the correctness of the codegen.

@sayantn
Copy link
Contributor Author

sayantn commented May 9, 2025

Oh wait, I probably misunderstood your comment, you meant using the llvm declaration by itself. Yeah, that would be better, thanks for the info. I will update the impl when I get the chance

@dianqk
Copy link
Member

dianqk commented May 15, 2025

Oh wait, I probably misunderstood your comment, you meant using the llvm declaration by itself. Yeah, that would be better, thanks for the info. I will update the impl when I get the chance

I think you can just focus on non-overloaded functions for this PR. Overloaded functions and type checking that checking Rust function signatures using LLVM defined can be subsequent PRs.

@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels May 15, 2025
@rustbot
Copy link
Collaborator

rustbot commented May 15, 2025

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@sayantn

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@sayantn sayantn marked this pull request as draft May 19, 2025 07:23
@nikic
Copy link
Contributor

nikic commented May 19, 2025

@sayantn Taking the address of an intrinsic is invalid LLVM IR.

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

bors added a commit that referenced this pull request Jun 14, 2025
Simplify implementation of Rust intrinsics by using type parameters in the cache

The current implementation of intrinsics have a lot of duplication to handle different overloads of overloaded LLVM intrinsic. This PR uses the **base name and the type parameters** in the cache instead of the full, overloaded name. This has the benefit that `call_intrinsic` doesn't need to provide the full name, rather the type parameters (which is most of the time more available). This uses `LLVMIntrinsicCopyOverloadedName2` to get the overloaded name from the base name and the type parameters, and only uses it to declare the function.

(originally was part of #140763, split off later)

`@rustbot` label A-codegen A-LLVM
r? codegen
@bors
Copy link
Collaborator

bors commented Jun 14, 2025

☔ The latest upstream changes (presumably #142259) made this pull request unmergeable. Please resolve the merge conflicts.

RalfJung pushed a commit to RalfJung/miri that referenced this pull request Jun 15, 2025
Simplify implementation of Rust intrinsics by using type parameters in the cache

The current implementation of intrinsics have a lot of duplication to handle different overloads of overloaded LLVM intrinsic. This PR uses the **base name and the type parameters** in the cache instead of the full, overloaded name. This has the benefit that `call_intrinsic` doesn't need to provide the full name, rather the type parameters (which is most of the time more available). This uses `LLVMIntrinsicCopyOverloadedName2` to get the overloaded name from the base name and the type parameters, and only uses it to declare the function.

(originally was part of rust-lang/rust#140763, split off later)

`@rustbot` label A-codegen A-LLVM
r? codegen
github-actions bot pushed a commit to rust-lang/rustc-dev-guide that referenced this pull request Jun 16, 2025
Simplify implementation of Rust intrinsics by using type parameters in the cache

The current implementation of intrinsics have a lot of duplication to handle different overloads of overloaded LLVM intrinsic. This PR uses the **base name and the type parameters** in the cache instead of the full, overloaded name. This has the benefit that `call_intrinsic` doesn't need to provide the full name, rather the type parameters (which is most of the time more available). This uses `LLVMIntrinsicCopyOverloadedName2` to get the overloaded name from the base name and the type parameters, and only uses it to declare the function.

(originally was part of rust-lang/rust#140763, split off later)

`@rustbot` label A-codegen A-LLVM
r? codegen
@bors
Copy link
Collaborator

bors commented Jun 16, 2025

☔ The latest upstream changes (presumably #142521) made this pull request unmergeable. Please resolve the merge conflicts.

lnicola pushed a commit to lnicola/rust-analyzer that referenced this pull request Jun 18, 2025
Simplify implementation of Rust intrinsics by using type parameters in the cache

The current implementation of intrinsics have a lot of duplication to handle different overloads of overloaded LLVM intrinsic. This PR uses the **base name and the type parameters** in the cache instead of the full, overloaded name. This has the benefit that `call_intrinsic` doesn't need to provide the full name, rather the type parameters (which is most of the time more available). This uses `LLVMIntrinsicCopyOverloadedName2` to get the overloaded name from the base name and the type parameters, and only uses it to declare the function.

(originally was part of rust-lang/rust#140763, split off later)

`@rustbot` label A-codegen A-LLVM
r? codegen
@nikic
Copy link
Contributor

nikic commented Jun 25, 2025

Here are my high level thoughts on what this PR does:

  • Checking whether the function signature is correct for the intrinsic is a great idea. We should indeed check this in rustc instead of producing invalid LLVM IR.
  • Emitting a warning when auto-upgrade occurs sounds useful, but I think this needs to be a controllable lint. The problem is that we support multiple LLVM versions, so e.g. stdarch may be required to use the representation of the oldest supported version. Knowing that it's outdated is helpful, but we need to be able to suppress it.
  • I don't think that automagically inserting casts for differences between the LLVM and Rust signatures is a good idea. I know you have some ideas on how you can get this to work on overloaded intrinsics, but I'm going to give you some bad news here: I have an ongoing experiment to completely remove intrinsic mangling from LLVM. Intrinsics will be identified only by their ID / base name, but you will no longer have the property that you can reconstruct the signature from just the intrinsic name. So what you want to do may become fundamentally impossible.

I think to handle something like x86amx properly, we actually need to teach rustc that this is a type that has a special ABI when passed to LLVM intrinsics (i.e. driven by information in Rust code, not in LLVM). Probably the proper way is something like #[repr(x86_amx)], but for this specific case maybe just adding a #[lang = "x86_amx"] for a single type would be sufficient? Other people can probably give better advice on the proper way to do this, but I think that's the general direction this should take.

I also think that this can be split into multiple changes. I think that the intrinsic validation can be implemented independently of the auto-casting bits.

@sayantn
Copy link
Contributor Author

sayantn commented Jun 25, 2025

Yeah, it would be better with a toggle-able warning (I was also facing problems with too many warnings, that's why I put it behind --verbose, but a dedicated lint will be better). I will have to look up on it, haven't worked on lints yet.

Could you link to some refs on what the redesign will look like, from an API perspective?

I can see your reasoning for not adding autocasts, but to actually error on signature mismatches, we need autocasts for structs at least (https://github.com/rust-lang/rust/pull/140763/files#r2128418128). If this issue was resolved, and we don't care about other autocasts, we can probably use Intrinsic::matchIntrinsicSignature.

Nonetheless, I will open another PR for the AMX, i1xN and bf16(xN) autocasts, and we can discuss the semantics there.

@nikic
Copy link
Contributor

nikic commented Jun 25, 2025

Could you link to some refs on what the redesign will look like, from an API perspective?

Mostly the same, with the caveat that intrinsic have to be constructed from intrinsic ID and either the function type or type overloads. From a string name only via auto-upgrade. It's possible to verify whether a function type is valid for an intrinsic ID, but it's no longer associated with a unique name.

I can see your reasoning for not adding autocasts, but to actually error on signature mismatches, we need autocasts for structs at least (https://github.com/rust-lang/rust/pull/140763/files#r2128418128). If this issue was resolved, and we don't care about other autocasts, we can probably use Intrinsic::matchIntrinsicSignature.

Do you have an example of an intrinsic currently using struct return? But generally, doing the struct auto-cast is fine, as long as it's approach from an angle of "the intrinsic ABI always requires literal structs". So the signature we would be generating on the Rust side would be the correct one in the first place, and the re-packing into a different type is part of the ABI adjustments.

@sayantn
Copy link
Contributor Author

sayantn commented Jun 25, 2025

Do you have an example of an intrinsic currently using struct return?

There are actually quite a few of them in stdarch. One example otoh will be llvm.x86.encodekey128, used in the x86 intrinsic _mm_encodekey128_u8. The return type is {i8,i64x2,i64x2,i64x2,i64x2,i64x2,i64x2}, and due to alignment mismatch of i8 and i64x2, this cannot be a Rust struct type without #[repr(packed)]

Mostly the same, with the caveat that intrinsic have to be constructed from intrinsic ID and either the function type or type overloads. From a string name only via auto-upgrade. It's possible to verify whether a function type is valid for an intrinsic ID, but it's no longer associated with a unique name.

Will the intrinsic names still be mangled in IR with the overload types? Or is it a more fundamental change so that LLVM will automatically pull out the correct overloading when it sees an intrinsic call?

@nikic
Copy link
Contributor

nikic commented Jun 25, 2025

Mostly the same, with the caveat that intrinsic have to be constructed from intrinsic ID and either the function type or type overloads. From a string name only via auto-upgrade. It's possible to verify whether a function type is valid for an intrinsic ID, but it's no longer associated with a unique name.

Will the intrinsic names still be mangled in IR with the overload types? Or is it a more fundamental change so that LLVM will automatically pull out the correct overloading when it sees an intrinsic call?

The intrinsic names will not be mangled in IR. It will be printed using the intrinsic base name without the mangling suffix (internally it's just an entirely unnamed function, only identified by the intrinsic ID).

@sayantn
Copy link
Contributor Author

sayantn commented Jun 25, 2025

Ah, so all the overloads will be printed with just the base name in IR. This certainly complicates my work, and makes it a lot harder to add autocasts for overloaded intrinsics without going through the IITDesc table, which is a lot of effort.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-codegen Area: Code generation A-LLVM Area: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues. A-run-make Area: port run-make Makefiles to rmake.rs 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.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants