Set target-abi module flag for LoongArch targets
Like the earlier RISC-V fix (rust-lang/rust#123612), emit the "target-abi" module flag for LoongArch so that LTO correctly picks up the ABI.
This follows the recent LLVM change (llvm/llvm-project#223647) that relies on the module flag for proper TargetMachine / data-layout handling during LTO on LoongArch.
`core::num::f16b` Rust's 16bit Brain Float
Implements the [RFC: f16b type](https://github.com/rust-lang/rfcs/pull/3983). 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;
- [Tracking Issue](https://github.com/rust-lang/rust/issues/160630)
- [RFC](https://github.com/rust-lang/rfcs/pull/3983)
It encodes the `emit` behaviour, one of:
- `BugAbort`: Abort as a bug.
- `FatalAbort`: Abort as a fatal error.
- `ErrorGuaranteed`: Return an `ErrorGuaranteed` (the default).
- `()`: return `()`.
This is useful but `Diag` is very widely used and it's arguably not
useful enough to be worth the generic parameter. This commit removes it.
Benefits:
- Many fewer generic parameters, including many functions where the
genericity is entirely uninteresting. This includes every
`Diagnostic::into_diag` and `Subdiagnostic::add_to_diag`. Removes the
need for the comment about `<G>` on `trait Diagnostic`.
- No `PhantomData` in `Diag`.
- Makes bootstrapping a bit faster.
The downside is there is no longer a single `emit` method.
- Getting a `!` return type requires calling `emit_bug` or `emit_fatal`.
This only affects a few call sites.
- Getting an `ErrorGuaranteed` return type requires calling `emit_err`.
This affects a lot of call sites. (It arguably makes call sites more
self-documenting.)
- Using the wrong `emit_*` on a diagnostic causes a runtime abort, which
previously couldn't occur. Seems unlikely, but it's not impossible.
- Note: If no particular return type is needed, `emit` can be used for
any diagnostic. (Bug/fatal diagnostics will still trigger abort.)
don't mark `f128` as reliable on AIX
In fact the type is really not supported at all there.
In https://github.com/rust-lang/rust/pull/162979 we made `f128` reliable on powerpc64 when the `vsx` feature is enabled. Apparently this is the case on AIX, but it just does not implement `f128` at all.
r? tgross35
cg_llvm: Move all code out of the crate root
Having non-trivial code in the crate root causes a few problems, most of which stem from every item being effectively `pub(crate)`:
- Fields/methods can't be private, so enforcing abstractions is impossible
- Every `use` becomes a de-facto re-export, leading to messy imports
- Moving items out of the root requires visibility adjustment
This PR therefore moves all non-trivial code out of the crate root, and into `rustc_codegen_llvm:🔙:llvm_backend`.
---
Deciding where to move the code *to* was a bit tricky. But the code being moved delegates a lot of its methods to other submodules in `back`, so creating another submodule in `back` seemed reasonable. I certainly like it more than the status-quo.
The main commit doesn't modify any of the code being moved, other than updating imports, as verified manually by:
```shell
git diff --color-moved --color-moved-ws=allow-indentation-change head^ head
```
There should be no change to compiler behaviour.
mark `f128` as reliable on `powerpc64` with `+vsx`
This feature is only enabled by default for powerpc64le, and not enabled on the big-endian targets. Even with vsx, the default long double is ppcf128 on the big-endian targets, so LLVM calls the incorrect libcall. Also some libcalls just don't exist.
I tested this with and without `rustflags = ["-C", "target-feature=+vsx"]` in the `bootstrap.toml`:
```
./x.py test library/core --target powerpc64-unknown-linux-gnu
./x.py test library/core --target powerpc64le-unknown-linux-gnu
```
These all hit one failure, in the docs test for `library/core/src/keyword_docs.rs` where `become` is used: powerpc does not support guaranteed tail calls. Anyway, that is not relevant for f128 support.
Sadly `powerpc-unknown-linux-gnu` with `+vsx` hits the issue fixed in https://github.com/llvm/llvm-project/pull/216613, I've requested a backport for the fix.
r? beetrees or @tgross35
cc @Gelbpunkt
Remove applying inline attributes at the callsite
Following from our discussion and the currently open PR; https://github.com/rust-lang/rust/pull/162460, removing the blanket addition of inline attributes at the callsite, even without the `#[inline(always)]` changes, looks to now have negligible impact.
Add Natvis visualiser and debuginfo tests for `f128`
To render f128s in debuggers on MSVC targets, this PR changes the compiler to output `f128`s as `struct f128 { low_bits: u64, high_bits: u64 }`, and includes a Natvis visualiser that displays the float in hexdecimal format (similar to the `LowerHex` impl in rust-lang/rust#160626), as unlike `f16` there's no larger supported float format to convert to and trying to write a float to decimal string converter in Natvis didn't seem practical. gdb, lldb and cdb tests are also included for `f128`, although gdb does not yet correctly identify the float format.
I did consider also displaying a `double` approximation of the `f128` (as the debugger will convert that to a decimal string) but decided against it as `f64` has a significantly smaller exponent range too (meaning very large or small `f128`s couldn't have an approximation anyway) and `cdb` and `WinDbg` both seem to round all floating-point numbers to 6 decimal places, meaning the displayed number is (double) rounded even further than `f64` precision and is useless for tiny values.
Closesrust-lang/rust#121837
Tracking issue: rust-lang/rust#116909
Having non-trivial code in the crate root causes a few problems, most
of which stem from every item being effectively `pub(crate)`:
- Fields/methods can't be private, so enforcing abstractions is impossible
- Every `use` becomes a de-facto re-export, leading to messy imports
- Moving items out of the root requires visibility adjustment
This feature is only enabled by default for powerpc64le, and not enabled on the big-endian targets. Even with vsx, the default long double is ppcf128 on the big-endian targets, so LLVM calls the incorrect libcall. Also some libcalls just don't exist
rustc_{codegen_,}llvm: adapt to new ThreadModel API
LLVM 24 [has moved](e733cebdf7) from TargetOptions::ThreadModel to specifying thread-model as a module flag. This catches us up.
@rustbot label: +llvm-main
fix `is_single_fp_element` for `s390x` and `x86`
In https://github.com/rust-lang/rust/pull/161950#discussion_r3886952310 we discovered that the old `is_single_fp_element` is incorrect in a number of ways.
- it did not consider `f16` or `f128`
- it did not consider transparent wrappers
- on x86, it incorrectly accepted over-aligned types
- on s390x, it incorrectly accepted single-element unions and arrays
So, in practice each target does something slightly different here, and I've split the function into two.
cc @beetrees
Stabilize `feature(trim_prefix_suffix)` (`{str, [T], Path}::trim_prefix` and `{str, [T]}::trim_suffix`)
Closesrust-lang/rust#142312 (tracking issue)
FCP completed [here](https://github.com/rust-lang/rust/issues/142312#issuecomment-4920020056). There was discussion during FCP about a possibly adding `strip_circumfix`, but that wasn't mentioned as blocking.
r? libs-api
It's now possible to get the backend features (a `Vec<String>`) when the
codegen backend is started, pass it back through `CodegenBackendInit`,
and just store it in the `Session`. This removes the need for the query.
Also:
- `WriteBackendMethods::target_machine_factory` no longer needs the
`target_features` parameter, because it's now available through the
`sess` parameter.
- `CodegenContext` no longer needs the `backend_features` field because
we can use `sess.global_backend_features` instead.
- `CodegenBackend::provide` is now a no-op for all the in-tree backends.
I haven't removed it because out-of-tree backends still rely on it.
It currently takes `&self`, which is a bit strange for an `init` method.
As a result, the Cranelift and GCC backends have to use types with
interior mutability.
This commit changes it to `&mut self`. Benefits:
- The Cranelift backend can use `Option` instead of `OnceCell` to
indicate uninit vs. init.
- The GCC backend can avoid `Mutex`, and use `bool` instead of
`AtomicBool`, which makes things much simpler. The commit also
restructures `GccCodegenBackend` to mirror `CraneliftCodegenBackend`:
just contain an `Option<BackendConfig>`, which makes the uninit vs.
init distinction foolproof. (E.g. no need to set `lto_supported` to
false and then later overwrite it with the real value.) As part of
this the `LockedTargetInfo` type is renamed `SharedTargetInfo` because
that better matches its new internals. (All this compiles both with
and without the "master" feature set.)
Session creation is currently awkward: we build a mostly-initialized
session, then use it to initialize a codegen backend, and then use the
codegen backend to finish initializing the session.
And it's not just awkward: within the Cranelift backend's `init` method
`sess.lto()` is called, which consults `sess.thin_lto_supported`,
*before* that field has been properly set! In practice it had no effect
but it's worth fixing.
This commit cleans up this mess. It introduces `EarlySession`, which
contains just four `Session` fields, the ones that are needed for
codegen backend initialization. It is now a field within `Session`, and
`Session` derefs to `EarlySession` to avoid changing a zillion
`sess.target`/`sess.opts`/etc. occurrences. `EarlySession` is passed to
`init`, which returns a `CodegenBackendInit` that contains the
backend-specific information needed to build a `Session`. (It replaces
the `replaced_intrinsics`, `fallback_intrinsics`, and
`thin_lto_supported` methods.) The `Session` can then be built in a
single step. No more `Session`/`CodegenBackend` initialization
intermingling.
A few functions that previously took a `Session` now take something
else, e.g. a `Target`. Some `Session` methods are now `EarlySession`
methods. And a new `early_lto` method is used for Cranelift's LTO check.
Simplify the `G` in `Diag<'a, G>`
The `EmissionGuarantee` trait isn't necessary, and just complicates things. Details in individual commits.
r? @oli-obk
Fix initialization cycle in `target_config`
There is an initialization cycle in `target_config`. Details in the final commit. The previous commits are precursors that support the changes in the final commit.
r? @nikic
cc @cuviper @RalfJung @Zalathar @Patryk27
cg_llvm: Make the LLVM version-check bindings safe
- Follow-up to https://github.com/rust-lang/rust/pull/161788
---
These version-check functions should always be safe to call, so marking them `safe` avoids some unsafe blocks at call sites.
There should be no change to compiler behaviour.
Fix the remaining `tests/debuginfo` failures on `msvc`
Fixes the remainder of the failing tests from https://github.com/rust-lang/rust/issues/161657
I used lldb 22.1 to individually check each of the `S_DEFRANGE_REGISTER_REL_INDIR` node (using e.g. `llvm-pdbutil dump --symbols ".\build\x86_64-pc-windows-gnu\test\debuginfo\<test_name>.lldb\a.pdb" | rg "unknown \(4471\)"`)
Any tests with an `unknown (4471)` node (4471/0x1177 being the enum value for `S_DEFRANGE_REGISTER_REL_INDIR`) got an `[msvc]` revision to disable on LLDB older than 23.1.0.
I then updated to LLDB 23.1.0 and disabled any remaining test failures that ocurred due to the variable shadowing behavior (so that they do not instantly break when we eventually run 23 in CI). Technically we could have avoided disabling those tests by using the python API to inspect individual slots of the frame, or by printing the whole frame at each step and matching against that, but the amount of effort seems not worth it until [we determine whether or not LLDB can/will improve its behavior here.](https://github.com/llvm/llvm-project/issues/221696).
One note, LLDB 23 seems to like it even less when we use the parent debugger instance for the test harness. I'll fix that in a followup PR since it requires a little bit of fiddling to get it to work with LLDB <23 (the short version is it's much harder to exit with a non-0 status code when using a nested debugger instance. We should be able to run something like `os.kill(os.getpid(), signal.SIGTERM)` from the internal python to kill the parent LLDB process to work around that)
There were a few fixes that required special handling
### `borrowed-basic.rs`, `basic-types-globals.rs`, `reference-debuginfo.rs`
LLDB appears to have changed their default formatting for chars again in v23.1.0 (`U+0x00000061 U'a'` -> `U+0061 U'a'`) luckily these are similar enough that we can use a wildcard to pass in both cases
### `dummy-span.rs`
There was a conditional to prevent using the (0,0) default dummy span on MSVC with a comment explaining why (it would default to the first line of the file instead). I removed the `is_msvc` check and this test worked and didn't break anything else so, best guess this got fixed at some point and the comment was outdated?
In any case, with this PR, the entirety of `tests/debuginfo` passes on `linux-gnu`, `windows-gnu`, and `windows-msvc` 🎉🎉
<img width="847" height="444" alt="image" src="https://github.com/user-attachments/assets/4c0f14d1-5ad4-4234-8380-59ad18ad6309" />
<img width="817" height="208" alt="image" src="https://github.com/user-attachments/assets/87819fcd-cdbb-4fd4-b2f8-c6cf2ecf5db3" />
r? @Kobzol, @jieyouxu
It's a trait that is used to give `Diag::emit` different return types
depending on the `G` in `Diag<'_, G>`. It works, but it's overkill.
There are only four different `G` types in practice (`BugAbort`,
`FatalAbort`, `ErrorGuaranteed`, and `()`) and having inherent `emit`
methods for each of those four concrete `Diag<'_, G>` types is good
enough.
This commit makes that change. This removes `EmissionGuarantee`
trait bounds from many places, which is nice.
Refactor the way cg_ssa handles indirect returns (returns via `sret`) — Take 2
This continues the work that @FractalFir done in rust-lang/rust#144976.
**I managed to make this work, so this confirms the original approach works and is ready to merge.**
r? workingjubilee
(assigning the same reviewer as the original PR)
# The problem
The current way `cg_ssa` handles `PassMode::Indirect` is fundamentally incompatible with the requirements of the GCC backend. This is currently worked around in a very brittle way, that breaks on ARM.
In order to function correctly, `cg_gcc` requires the `sret`(indirect return) pointer to be treated in a special way.
# The solution
This PR separates the `sret` pointer from all the other arguments, allowing each backend to decide how it wants to handle that pointer. This will allow GCC to do it's own thing, while changing nothing on the LLVM side. Currently, the PR just makes both backends preappend the sret arg, mimicking the previous behaviour.
The PR is based on this [zulip suggestion](https://rust-lang.zulipchat.com/#narrow/channel/421156-gsoc/topic/Project.3A.20Bootstrap.20of.20rustc.20with.20rustc_codegen_gcc/near/526487725).
# Assumptions I made.
The PR makes certain assumptions about the ABI handling.
1. No LLVM intrinsic returns via sret. [According to my sources](https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/Can.20LLVM.20intrinsics.20return.20via.20PassMode.3A.3AIndirect.3F), this is always true.
2. Tail calls don't currently return via `sret`. From [asking about](https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/Can.20tail.20calls.20return.20indirectly.28via.20a.20pointer.29.3F/near/532984507), it seems like the tail call handling does not currently support indirect returns. So, I did not add support for that.
3. TLS shims don't perform indirect returns, and asserts and drops also don't perform indirect returns(since they return nothing) - those assumptions seemed reasonable.
4. Inline assembly calls don't use indirect returns. I *assumed* functions like `inline_asm_call` will not need the `sret` handling code. I am not 100% sure about this, tough.