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
Add support for generics in `offload`and remove `no_mangle` attribute
implements a 3rd pass where we collect kernel instantiations required by offload to work
also enforces consistent mangling for offload functions between host and device
closes: https://github.com/rust-lang/rust/issues/150985
r? @ZuseZ4
`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.
split up `rustc_session`
Followup on https://github.com/rust-lang/rust/pull/160336 cc @JonathanBrouwer (feel free to review if you want)
The first commit splits out the `cstore` module from `rustc_session` into its own crate.
`rustc_session` actually never used it anywhere internally, and there are also several crates that only depend on `rustc_session` for it. So it is a natural candidate to split off.
The second commit is similar; `rustc_hir::definitions` is moved to `rustc_hir_id`; it is used nowhere in `rustc_hir`, except to implement an inherent method:
```rust
impl DefKind {
pub fn def_path_data(self, name: Option<Symbol>) -> DefPathData { }
}
```
which is used (once) in rustc_middle, so the items in `rustc_hir::definitions` and this conversion function could be in many places. `rustc_hir_id` is the earliest and the easiest, so that's what I went with.
Together these allow `rustc_crate_store`, `rustc_hir` and `rustc_session` to compile in parallel.
Current graph:
<img width="825" height="617" alt="image" src="https://github.com/user-attachments/assets/aa954265-0057-4596-a7c4-38290937fb74" />
Graph after this pr:
<img width="853" height="572" alt="image" src="https://github.com/user-attachments/assets/9bcd16f8-897c-4990-920b-249500b2e78e" />
Do not pass `-no-pie` on Windows
The warning can be seen with a simple example:
```
❯ cargo new /tmp/hello -q
❯ cargo rustc --target x86_64-pc-windows-gnullvm -q -- -C target-feature=+crt-static
warning: linker stderr: clang: argument unused during compilation: '-no-pie' [-Wunused-command-line-argument]
|
= note: `#[warn(linker_messages)]` on by default
```
codegen: classify localized MSVC linker progress as linker_info
Fixesrust-lang/rust#159133.
`report_linker_output` currently recognizes only a small set of English `link.exe` progress messages as informational. When the linker output is localized, equivalent progress messages are instead emitted through the `linker_messages` lint.
Instead of matching specific English strings, classify MSVC linker output based on locale-independent `LNK####` diagnostic codes.Lines without an `LNK####` code are routed to `linker_info`, while diagnostics continue to be emitted through `linker_messages`. The existing `LNK6004` incremental-link exception is preserved.
Testing
- Added a run-make regression test for localized `link.exe` progress output.
- Verified the existing MSVC linker-info tests continue to pass.
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.
Revive L4Re target
This revives the target for the L4Re OS. It changes the way, linking is done and adds aarch64 support and documentation including a maintainer for the target.
The update of the libc crate is necessary since only in 0.2.179 and higher is the fixed support for L4Re on uclibc.
Optimize handling of solver errors
- Check for the empty case in `collect_remaining_errors()`.
- Instead of representing trait errors as `Vec<Error>`, use a special type
This has multiple advantages:
- Performance. The new type is 1/3 the size of `Vec` (being equivalent in layout to `Option<ThinVec>`) and can be kept in a register.
- Type safety. We mark the type `#[must_use]`, and thinks requiring errors take `ThinVec`, which requires unwrapping the type and verifying there is indeed an error. We still provide conversions to slices, `ThinVec`, and iteration, because some code needs this and I saw no benefit in changing it, but we deliberately do not provide `Deref<Target = [E]>` or things like that.
link.exe progress messages (e.g. "Creating library ...") are detected
by matching their English text, which fails when the English language
pack is not installed and the output is localized despite VSLANG=1033.
Since all actual warnings and errors carry a locale-independent LNK####
code, classify every line without one as linker_info instead of
linker_messages.
Diagnostics are recognized by their structured form, `LINK : warning
LNK####:`: the code must be followed by a `:` that is the second colon
in the line, so the matcher cannot accidentally hit file names.
The one code-bearing informational line, LNK6004 ("performing full
link"), keeps the exception that was previously handled by matching its
English text.
Fixes the builds of rustc and library/std for the L4Re target OS.
A major change was done in linking binaries: The need for the L4Bender
tool was removed and linking parameters are now fully configured in the
rustc target config.
rustc_abi: Add `LayoutData::is_variant_uninhabited` method
This is a cheaper alternative to `TyAndLayout::for_variant(_, idx).is_uninhabited()`, which avoids the extra work done by `TyAndLayout::for_variant`.
EDIT: Let me expand on the motivation from this [comment](https://github.com/rust-lang/rust/pull/160398#issuecomment-5167761369):
`TyAndLayout::for_variant` is a curious API: the resulting layout doesn't represent a Rust type in the strict sense (not even `pattern_type!(Enum is Variant { .. })`; instead, it only describes the "variant-specific" fields, and fields shared between variants (e.g. the enum tag or coroutine captures) are entirely missing.
As such, I believe alternative APIs should be used instead to clarify intent, when possible. This PR deals with the simplest cases, and a future PR will add `TyAndLayout::variant_field(self, cx, variant_idx, field_idx)` to deal with the next-most common case of only needing a variant layout for field lookups.
This has multiple advantages:
- Performance. The new type is 1/3 the size of `Vec` (being equivalent in layout to `Option<ThinVec>`) and can be kept in a register.
- Type safety. We mark the type `#[must_use]`, and thinks requiring errors take `ThinVec`, which requires unwrapping the type and verifying there is indeed an error. We still provide conversions to slices, `ThinVec`, and iteration, because some code needs this and I saw no benefit in changing it, but we deliberately do not provide `Deref<Target = [E]>` or things like that.
Revert "codegen_ssa: no dbginfo for scalable vec local w/ `-O0`"
This partially reverts commit ebe72104f0 (it keeps the tests), from rust-lang/rust#158088. The workaround in that patch is no longer necessary with the upgrade to LLVM 23 in rust-lang/rust#158734. I've confirmed that the stdarch tests also continue passing with this patch applied.
r? @lqd
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
Fix mono reachability with no-op landing pads
the landing pad filtering used regular MIR successors when the initial traversal used monomorphized one
fixesrust-lang/rust#159980
This allows implementing EIIs that don't have a default impl without the
involvement of symbol aliases by simply changing the mangled symbol name
of the implementation, which would make them trivially compatible with
all backends and targets. This change will be left to a followup PR.
Don't use exported generics from conditional dependencies (panic runtimes and profiler-builtins)
This is a fix for https://github.com/rust-lang/rust/issues/159682.
This seems like a generalized footgun for writing FFI plugins? But at least right now, a very specific change to the crates we often swap around seems prudent.
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.
miri: ensure validity of references and pointers we dereference and cast
Conceptually, when we evaluate the place expression `*place`, there are two steps that happen:
- perform a (typed) load from `place`, which yields a value of pointer/ref type
- construct a new place from that value
Since this is a typed load, we have to ensure that the value satisfies the validity invariant. We forgot to do that, which led to Miri missing a bunch of UB. This PR fixes that by adding the missing checks.
Triggering this UB is a bit non-trivial: you cannot just store an invalid value into `place` using regular assignment (that would already be caught as part of the assignment). However, you can take a raw pointer to `place` and then use that to mutate the contents of `place` in a way that its validity invariant no longer holds. For example:
```rust
fn main() {
let mut x = &();
// Overwrite `x` with null.
unsafe { (&raw mut x).cast::<usize>().write(0) };
let _val = *x; //~ERROR: null reference
}
```
This program clearly (IMO) should have UB, and has UB in MiniRust, but Miri accepted that program before this PR. The same applies to references that are invalid because they are unaligned (even if we end up only accessing a 1-aligned field, i.e. the rest of the place expression evaluates just fine), and to references that are invalid because they are not dereferenceable (even if we end up projecting to a zero-sized field, i.e., the rest of the place expression evaluates just fine).
Even raw pointers have this problem: a raw pointer can be invalid if its vtable pointer is wrong, and we did not check that.
And finally, this also affects `Box`, and this is where things get tricky. `Box` derefs are not even present any more in the MIR Miri sees; they have been replaced by derefs of the underlying raw pointer. But that means we have no way to know that we should check all those things. So to fix that I adjusted the ElaborateBoxDerefs to emit a new special kind of cast that's almost a transmute but also checks `Box` validity.
Fixes https://github.com/rust-lang/miri/issues/5226
Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/617
Cc @rust-lang/opsem
Emit retags in codegen to support BorrowSanitizer (part 5)
Tracking issue: rust-lang/rust#154760
[Zulip Thread](https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Staging.20for.20emitting.20retags.20in.20codegen/with/592364811)
This is one of several PRs that add experimental support for emitting retags as function calls in codegen.
This PR adds support for emitting global arrays that specify the ranges of interior mutable and pinned data. For example,
```rust
fn cell(x: &(i32, Cell<i32>)) { ... }
```
This program will have IR similar to the following:
```llvm
@anon.0 = unnamed_addr constant [16 x i8] c"\04...\04..."
define void @cell(ptr %0) {
start:
%x = call ptr @__rust_retag_reg(ptr %0, i64 8, i8 1, ptr @anon.0, ptr null)
...
}
```
The last four bytes at offset four are interior mutable.
Users can disable this behavior by passing `no-precise-im` or `no-precise-pin` as options to `-Zcodegen-emit-retag`. In that case, the last two parameters to the retag intrinsic will always be null pointers.
BorrowSanitizer will be able to switch to using nightly once this is merged. Thank you @saethlin for reviewing these PRs!
Note: we still do not support retagging SIMD types, since cg-ssa does not support `insertelement`.
Related: rust-lang/rust#158100
Cc: @RalfJung
r? @saethlin
Flatten all -L search paths into a single list of files
This is an optimization that mostly targets the new [Cargo build dir layout](https://rust-lang.github.io/rust-project-goals/2025h2/cargo-build-dir-layout.html).
Before, Cargo usually used to pass rustc a single `-L` path to a directory containing potentially a large number of `.rlib` or other dependency paths. Rustc is optimized for this, and does a preprocessing step, where it preloads all files from this directory into a sorted vector, in which it then performs binary search to look for files having a given prefix and postfix.
With the new build dir layout, this changes, and Cargo will pass potentially many (even hundreds, if your crate has many dependencies) `-L` directories, where each directory will usually have only 1-2 files. This is not ideal for the current rustc search implementation, because the old preprocessing isn't really worth it when the `-L` directory typically only has a single file, and because rustc will do a lot of work per each `-L` directory in the lookup phase, including some quadratic (O(n^2)) work.
With the `large-workspace` stress test from rustc-perf, where the final binary has ~1000 total and ~500 direct dependencies:
- With the old build dir layout, rustc does 4274 calls to `FilesIndex::query`
- With the new build dir layout, it does `1938314` calls to `FilesIndex::query`. Not ideal :)
This PR modifies the logic so that instead of going through all `-L` directories one by one when we are looking for a specific dependency, we pre-gather all files from all passed `-L` directories at the start, and sort them all together. Then, in the lookup phase, instead of performing <number of -L dirs> * 4 (.rmeta, .rlib, etc.) searched, we only perform the 4 searches across all files. This gets rid of the O(n^2) behavior.
Further improvements could be made, e.g. sort the files just once and then filter it for for both host and target filesearchs. I alsothought about pre-filtering the files further, e.g. based on their `kind`, but that is not worth it in usual situations, where ~all of the deps will be `.rlib`s or `.rmeta`s anyway. What might work is pre-filtering based on their actual names (we strip known prefixes from them and then search based on the names alone, in a hashmap or something?), but that can be a follow-up.
Diff vs parent. of https://github.com/rust-lang/rust/pull/159857: https://perf.rust-lang.org/compare.html?start=1a833e16546c2eb012758ddd499964fd8afee29e&end=6514e2707b7e90fecbc570eeaa36f3780a9b02b4&stat=instructions%3Au
rustc: Support `--jobs` options for limiting parallelism in various parts of the compiler
`--jobs-frontend` for the frontend, `--jobs-backend` for the backend, `--jobs-linker` for the linker, and `-j`/`--jobs` for the overall limit.
See the added docs for more details.
Part of https://github.com/rust-lang/compiler-team/issues/1005.
Any suspicious option combinations are prohibited for now.
r? @bjorn3 @Zoxc