Re: [PATCH v2 2/3] kbuild: rust: provide an option to inline C helpers into Rust
From: Andreas Hindborg
Date: Tue Jan 07 2025 - 06:32:19 EST
"Gary Guo" <gary@xxxxxxxxxxx> writes:
> A new Kconfig option, `RUST_INLINE_HELPERS` is added to allow C helpers
> (which was created to allow Rust to call into inline/macro C functions
> without having to re-implement the logic in Rust) to be inlined into
> Rust crates without performing a global LTO.
>
> If the option is enabled, the following is performed:
> * For helpers, instead of compiling them to object file to be linked
> into vmlinux, we compile them to LLVM IR.
> * The LLVM IR is patched to add `linkonce_odr` linkage. This linkage
> means that the function is inlineable (effect of `_odr`), and the
> symbols generated will have weak linkage if emitted into object file
> (important since as later described, we might have multiple copies of
> the same symbol) and it will may be discarded if it is not invoked or
> all invocations are inlined.
> * The LLVM IR is compiled to bitcode (This is step is not necessary, but
> is a performance optimisation to prevent LLVM from always have to
> reparse the same IR).
> * When a Rust crate is compiled, instead of generating object file, we
> ask LLVM bitcode to be generated.
> * llvm-link is invoked to combine the helper bitcode with the crate
> bitcode. This step is similar to LTO, but this is much faster since it
> only needs to inline the helpers.
> * clang is invoked to turn the combined bitcode into object file.
>
> Some caveats with the option:
> * clang and Rust doesn't have the exact target string. Manual inspection
> shows that they should be compatible, but since they are not exactly
> the same LLVM seems to prefer not inlining them. This is bypassed with
> `--ignore-tti-inline-compatible`.
> * LLVM doesn't want to inline functions combined with
> `-fno-delete-null-pointer-checks` with code compiled without. So we
> remove this command when compiling helpers. I think this should be
> okay since this is one of the hardening features and we shouldn't have
> null pointer dereferences in these helpers.
>
> The checks can also be bypassed with force inlining (`__always_inline`)
> but the behaviour is the same with extra options.
>
> Co-developed-by: Boqun Feng <boqun.feng@xxxxxxxxx>
> Signed-off-by: Boqun Feng <boqun.feng@xxxxxxxxx>
> Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
Reviewed-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
Tested-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
Tested with downstream rnull tree, works as expected.
Best regards,
Andreas Hindborg