give layout errors from `size_of_val` and `align_of_val` a span
`size_and_align_of_dst` used the spanless `layout_of` so a `SizeOverflow` from `size_of_val` or `align_of_val` came out as
```
error: values of the type `[u8; 9223372036854775807]` are too big for the target architecture
```
and now points at the call:
```
error: values of the type `[u8; 9223372036854775807]` are too big for the target architecture
--> src/lib.rs:5:53
|
5 | pub fn check(x: *const Example) -> usize { unsafe { std::intrinsics::size_of_val(x) } }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
with `-Cdebuginfo=2` the error is hit earlier while describing the signature of the function so `get_function_signature` and `build_pointer_or_reference_di_node` forward the span `dbg_scope_fn` already computes same as https://github.com/rust-lang/rust/pull/145967 and https://github.com/rust-lang/rust/pull/146025 did for arrays and enums. the two revisions of the new test cover both.
this doesnt close https://github.com/rust-lang/rust/issues/25116. the vtable case in `tests/ui/limits/vtable.stderr` is emitted from a query keyed only on the type and the other builders in `debuginfo/metadata.rs` still drop spans.
cc @estebank who pointed at these two gaps on the issue.
r? @oli-obk
x86_64-win: Enable f128 on LLVM 23+
LLVM23 includes the ABI fix to make f128 work [1]. That version isn't
yet stable, but at least the type will start getting picked up in
top-of-tree CI.
While addressing this, also update the comment regarding f16.
[1]: aa47e59245
LLVM23 includes the ABI fix to make f128 work [1]. That version isn't
yet stable, but at least the type will start getting picked up in
top-of-tree CI.
While addressing this, also update the comment regarding f16.
[1]: aa47e59245
`size_and_align_of_dst` asked for the pointee layout with the spanless `layout_of`, so a
`SizeOverflow` from these intrinsics printed a bare error with no location. it takes a span
now and both call sites pass the span of the
with `-Cdebuginfo=2` the same error comes froion signature,
which was spanless too. it now uses the span `dbg_scope_fn` already computes.
rustc_codegen_llvm: handle sm_101* features being an alias
LLVM 24 [moved sm_101{,a,f} features](https://github.com/llvm/llvm-project/pull/214335) to just be an alias for the matching sm_110 feature. Since the sm_110 feature already exists, we can do the remapping unconditionally rather than gating it on LLVM 24.
@rustbot label: +llvm-main
refactor handling of target features in Session
`Session` currently contains two lists of target features: `target_features`, which is also exposed in `cfg`, and `unstable_target_features`, which is used internally to communicate between various parts of the compiler which target features are *actually* available, including some that we don't have plans to put in `cfg`, namely "forbidden" target features. The `unstable_target_features` list is *not* equivalent to what nightly code sees in `cfg(target_features)` as the latter excludes "forbidden" target features. Both lists are computed by `fn cfg_target_features` even though one of them is never used for `cfg`. It's all kind of messy.
This PR refactors that: `fn cfg_target_features` is replaced by `fn internal_target_features` which computes all enabled Rust target features (including "forbidden" ones -- which are really more like "internal-only" ones so the 2nd commit renames them). We then compute `cfg(target_features)` from that. The session only stores one list, `internal_target_features`, which corresponds to the previous `unstable_target_features`.
To simplify computing `internal_target_features` I also refactored `parse_rust_feature_list` to better distinguish actual Rust target features from unknown target features that we are just grandfathering in. I also made `implied_target_features` not rebuild the same hash map over and over again. And I got rid of a bunch of silly temporary vectors and iterations over all Rust target features.
LLVM 24 moved sm_101{,a,f} features to just be an alias for the matching
sm_110 feature. Even though the breaking change in LLVM didn't introduce
the 110 flavors, they appear to not exist in older LLVMs so we just gate
on LLVM 24.
autodiff: Handle slice-tailed DSTs in type trees
Fixesrust-lang/rust#160327
References to `OsStr` reach a `[u8]` tail, but autodiff only recognized direct slices. TypeTree generation then recursed into `OsStr` and hit the slice arm that ICEd.
TypeTree generation and ABI activity handling now use `struct_tail_for_codegen`. Slice wrappers keep their element metadata, while prefixed DSTs retain their field offsets. IMO, reusing the existing rustc DST-tail query is cleaner than adding an `OsStr` special case. BTW, coverage includes the reduced `clap_lex` reproducer plus a prefixed slice-tail DST.
Split IncrCompSession out of Session
This will allow introducing a separate incr comp session dir for the post LTO artifacts in the future. In addition it statically encodes the lifetime of the incr comp session rather than requiring an enum behind a mutex stored in the Session.
Based on https://github.com/rust-lang/rust/pull/159000
Part of https://github.com/rust-lang/compiler-team/issues/908
Add -Zinstrument-mcount={fentry-nop-record,fentry-record}
The linux kernel still uses fentry for x86 and s390x arches. s390x depends entirely on the compiler to record and nop these sections.
This facilitates support for inserting nop's and/or recording the location of each mcount call in a special section named `__mcount_loc`.
These attributes are currently only supported with fentry on the s390x target, otherwise they are quietly ignored (except on s390x).
Bump thorin-dwp (0.10), gimli (0.33), and object (0.38.1)
Originally, the hope was that this would reduce duplication of `object` within the compiler.
In practice, it turns out that this merely bumps the object major-version-set from {0.36, 0.37} to {0.37, 0.38}.
(The holdout for object@0.37 is `ar_archive_writer`, which does have a newer release available. But that would end up pulling in object@0.39 instead.)
There is still an object@0.36 entry in Cargo.lock, but that comes via `ui_test` which is a dev-dependency for clippy and miri.
Use codegen tail discovery so wrappers such as OsStr keep slice element
metadata without losing offsets for prefixed DSTs. Keep recursion tracking
scoped to the current traversal path.
Structurally prevent zero-count `BackendRepr::SimdVector`s
This is already *supposed* to be impossible in layout, but this emphasizes that better. This PR makes no behaviour changes; just `BackendLaneCount` instead of `u64` in https://doc.rust-lang.org/nightly/nightly-rustc/rustc_abi/enum.BackendRepr.html
Ironically I was inspired to do this as part of [looking at making `Simd<T, 0>` *work*](https://rust-lang.zulipchat.com/#narrow/channel/257879-project-portable-simd/topic/Allow.20N.3D.3D0.3F/with/613345298), but importantly if that's going to happen I think it should be `BackendRepr::Memory` like other ZSTs, *not* a `BackendRepr::ScalarVector` that would need to carry around a useless LLVM value in `OperandValue::Immediate` (where it's not even clear what the LLVM type of that value would be).
This is already *supposed* to be impossible in layout, but this emphasizes that better.
Ironically I was inspired to do this as part of looking at making `Simd<T, 0>` *work*, but importantly if that's going to happen I think it should be `BackendRepr::Memory` like other ZSTs, *not* a `BackendRepr::ScalarVector` that would need to carry around a useless LLVM value in `OperandValue::Immediate` (where it's not even clear what the LLVM type of that value would be).
Fix Windows on Arm PAC default
Windows on Arm's branch protection only supports PAC Key B for return address signing. The CLI parsing sets it to Key A though, and it doesn't have access to the target information to fix it. This PR adds an accessor function where we can fix this possible discrepancy, and lints against using the `branch_protection` unstable option field directly.
I don't think we need to have a generic mechanism to allow targets to define the valid options themselves, at least not yet. So this is the rustc version of https://github.com/llvm/llvm-project/pull/203989 and uses basically the same idea to set the correct default.
This fixes the `pointer-auth-link-with-c` run-make [failure](https://triage.rust-lang.org/gha-logs/rust-lang/rust/90283463228) happening in the [LLVM23 update PR](https://github.com/rust-lang/rust/pull/158734).
It's probable people will want to add a `standard` value for branch protection, matching clang, and the current accessor will be a good place to do that, compared to e.g. only having an accessor for `PacRet::key`.
The linux kernel still uses fentry for x86 and s390x arches.
s390x depends entirely on the compiler to record and nop
these sections.
This facilitates support for inserting nop's and/or recording the
location of each mcount call in a special section named `__mcount_loc`.
These attributes are currently only supported with fentry on the s390x
target, otherwise they are quietly ignored (except on s390x).
Windows on Arm only supports PAC Key B for return address signing,
but we don't know the target when parsing the branch protection CLI
flag, and have to adjust this elsewhere.
Accessing the options field directly is now linted against, and the
accessor function `Session::branch_protection` handles the per-target
adjustment.
cfi: add diag mode support
Currently a Rust CFI failure only inserts a ud2. However, for clang we have the option for a helpful diagnostic message that explains the violation and is especially helpful for fixing it. This message works through hooking the UBSan runtime and calling into it with the necessary information for a helpful error message. In clang, this is enabled via `-fno-sanitize-trap=cfi`.
This change adds the same behavior to rustc's CFI. Instead of a `no-sanitize-trap` flag, we added `-Z cfi-mode={diag|trap}`, with trap as the default. The diag mode will print the following error message for a violation:
```
tests/ui/sanitizer/cfi/fn-ptr-type-mismatch.rs:1:1: runtime error: control flow integrity check for type fn(i32, i32) -> i32 failed during indirect function call
fn_ptr_type_mismatch.ecd806f409c5c1fc-cgu.0: note: fn_ptr_type_mismatch::add_one defined here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior tests/ui/sanitizer/cfi/fn-ptr-type-mismatch.rs:1:1
```
r? @rcvalle
Remove llvm_enzyme feature outside of bootstrap
r? bjorn3
I think you were the one who did the last refactoring on how we pass this feature.
We originally introduced and used this compile-time cfg since we were suspecting that some of the work we did for autodiff was causing a compile time regression even when no autodiff was used. It turned out later that we just did extra work due to a bug, which was fixed.
Thanks to the dlopen work our checks are now much simpler. We only do autodiff work if the -Zautodiff=Enable flag was set. If the flag is set we also just check if libEnzyme is in the sysroot, and if we can not find it, we error out.
I noticed it while fixing some related checks in https://github.com/rust-lang/rust/pull/158333
Currently a Rust CFI failure only inserts a ud2. However, for clang
we have the option for a helpful diagnostic message that explains the
violation and is especially helpful for fixing it. This message works
through hooking the UBSan runtime and calling into it with the
necessary information for a helpful error message. In clang, this is
enabled via -fno-sanitize-trap=cfi.
This change adds the same behavior to rustc's CFI. Instead of a
no-sanitize-trap flag, we added -Z cfi-mode={diag|trap}, with trap
as the default. The diag mode will print the following error message
for a violation:
```
tests/ui/sanitizer/cfi/fn-ptr-type-mismatch.rs:1:1: runtime error: control flow integrity check for type fn(i32, i32) -> i32 failed during indirect function call
fn_ptr_type_mismatch.ecd806f409c5c1fc-cgu.0: note: fn_ptr_type_mismatch::add_one defined here
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior tests/ui/sanitizer/cfi/fn-ptr-type-mismatch.rs:1:1
```
Support using const pointers in asm `const` operand
Implements [RFC#3848](https://github.com/rust-lang/rfcs/pull/3848) with tracking issue rust-lang/rust#128464
This adds support of const pointers for asm `const` in addition to plain integers.
The inline `asm!` support is implemented using `i` constraint, and the `global_asm!` and `naked_asm!` support is implemented by inserting `symbol + offset` and make `symbol` compiler-used. For unnamed consts, it will create additional internal & hidden symbols so that they can be referenced by global_asm.
~~The feature is also implemented for GCC backend but it's untested.~~ Tested now.
This will allow introducing a separate incr comp session dir for the
post LTO artifacts in the future. In addition it statically encodes the
lifetime of the incr comp session rather than requiring an enum behind a
mutex stored in the Session.
codegen: skip stores for entirely-uninit constant aggregate fields
MIR GVN (since rust-lang/rust#147827) propagates MaybeUninit::uninit() as `const <uninit>` in aggregate constructions. Without this fix, codegen would emit a memcpy from an `[N x i8] undef` global for each such field, which LLVM materializes as zero-initialization.
This mirrors the existing `all_bytes_uninit` skip already present for `Rvalue::Use` (added in rust-lang/rust#147827) into the `Rvalue::Aggregate` field loop.
Fixes: rust-lang/rust#157743
With the previous commit, now we can see there are some code duplication
for the handling of `GlobalAlloc` inside backends. Do some clean up to
unify them.
This gives the asm-const code the basic ability to deal wiht pointer and
provenances, which lays the ground work for asm_const_ptr.
Note that `SymStatic` is not fully removed, a specialized is kept and
renamed as `SymThreadLocalStatic`, for `#[thread_local]` statics where CTFE
does not support naming. The `#[thread_local]` is unstable feature and it's
not clear if we want to support this in `sym`, but removal of it should be
a separate PR.
MIR GVN propagates MaybeUninit::uninit() as `const <uninit>` in aggregate
constructions and codegen emits a memcpy from an `[N x i8] undef` global for
each such field, which LLVM materializes as zero-initialization.
Instead of special-casing `all_bytes_uninit` at each call site, add a new
`OperandValue::Uninit` variant that `eval_mir_constant_to_operand` returns for
any all-bytes-uninit constant. `store_with_flags` is a no-op for this variant,
so the fix applies uniformly across `Rvalue::Use`, `Rvalue::Repeat`, and
`Rvalue::Aggregate` without per-site checks. The variant propagates through
field extraction and transmutes, and is handled appropriately at the remaining
call sites (function arguments, discriminant reads, debug info, etc.).
Convert `-Ctarget-cpu` into a target-modifier for AVR, AMDGCN and NVPTX
Crates built for AVR, AMDGCN and NVPTX that specify different values for `-Ctarget-cpu` cannot be soundly linked together.
This PR attempts to make `rustc` ensure that no crates with disagreeing values for `-Ctarget-cpu` are linked together. This is achieved by converting `-Ctarget-cpu` into a target-modifier depending on `--target`.
To do this, the consistency check for `-Ctarget-cpu` considers mismatching values as inconsistent only for targets for which the new flag `requires_consistent_cpu` is set in their target spec.
**Why should `-Ctarget-cpu` be a target-modifier for `nvptx`?**
<details><summary>PTX is a single-module contract</summary>
<p>
PTX requires a binary to start with .version (`ptx$$`) then .target (`sm_$$`). If the ptx contains instructions that are not supported by either .version or .target, the binary is ill-formed and will be rejected by ptxas. The concept of features that can be mixed and matched in a binary does not exist for nvptx and is therefore not supported by LLVM.
</p>
</details>
<details><summary>It prevents the production of bitcode that cannot be codegen'd after linking</summary>
<p>
A target modifier should prevent configurations that are not composable across crates when those crates are linked together. The most prominent example is when enabling a target feature changes the ABI, making cross-crate calls inherently unsound.
In the case of nvptx, ABI mismatch is (at least for now) not the core problem motivating target modifiers. NVIDIA’s documented PTX calling convention has [remained stable since ptx20](https://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability/index.html#function-calling-sequence).
However, in the current state it is possible to produce bitcode that cannot be codegen'd after linking, because some operations are only lowerable for sufficiently new SM/PTX levels. In the best case this results in an LLVM error during the final llc step, but this is not something we should rely on for correctness.
nvptx has a special compilation pipeline where instead of linking the final PTX object, instead LLVM bitcode is linked. The resulting artifact is then compiled in one invocation.
Now consider crate A which is independently compiled into bitcode with the following rustc arguments:
```Rust
//@ compile-flags: --target nvptx64-nvidia-cuda -C target-cpu=sm_70 --crate-type=rlib
#[cfg(target_feature = "sm_70")]
fn foo() {
// cannot be lowered to ptx before "sm_70: so currently produces an LLVM error
}
#[cfg(not(target_feature = "sm_70"))]
fn foo() {
// can be lowered to ptx before "sm_70"
}
pub fn bar() {
foo()
}
```
Crate A is a dependency of crate B. In the *rustc* invocation of crate B
1. crate B is compiled into bitcode, too
2. both bitcode artifacts are bitcode-linked by *llvm-link*
3. the resulting bitcode artifact is compiled by *llc -mcpu=sm_60*
This should now ideally create an LLVM error, because the linked bitcode contains code paths that were selected under `sm_70` assumptions but the final NVPTX codegen is targeting `sm_60`, where those operations are not lowerable. An LLVM error here is better than silent miscompilation, but it’s not a promise we should rely on.
A real example where this could happen is the lowering of atomic loads and stores with non-relaxed orderings, which is known to depend on the selected SM level.
</p>
</details>
**Why should `-Ctarget-cpu` be a target-modifier for `amdgcn` and `avr`?**
- In case of AVR the target-cpu defines the ISA, which is encoded in the ELF header flags, amdgcn also encodes the cpu directly into those flags
- To not rely on *lld* which currently prevents it for both by looking at those flags [AVR](597ffbe09d/lld/test/ELF/avr-flags.s) and [amdgcn](597ffbe09d/lld/test/ELF/amdgpu-elf-flags-err.s)
Previous discussions about the topic can be found [here](https://github.com/rust-lang/rust/issues/131799#issuecomment-3390563329) and [here](https://github.com/rust-lang/rust/issues/141468).
I also created a [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Making.20-Ctarget-cpu.20a.20target-modifier.20on.20NVPTX/with/566622679).
I am unsure if a MCP is needed before proceeding. If you think so please let me know.
Creating *target-modifiers* for NVPTX *target-features* is to be done in a follow-up.
cc @kjetilkjeka as target maintainer for NVPTX
cc @flakebi as target maintainer for amdgcn
cc @Patryk27 as target maintainer for AVR
cc @RalfJung you were very involved in the discussions so far
Target modifier tracking issue: https://github.com/rust-lang/rust/issues/136966