Use conditional synchronization for Lock
This changes `Lock` to use synchronization only if `mode::is_dyn_thread_safe` could be true. This reduces overhead for the parallel compiler running with 1 thread.
The emitters are changed to use `DynSend` instead of `Send` so they can still use `Lock`.
A Rayon thread pool is not used with 1 thread anymore, as session globals contains `Lock`s which are no longer `Sync`.
Performance improvement with 1 thread and `cfg(parallel_compiler)`:
<table><tr><td rowspan="2">Benchmark</td><td colspan="1"><b>Before</b></th><td colspan="2"><b>After</b></th></tr><tr><td align="right">Time</td><td align="right">Time</td><td align="right">%</th></tr><tr><td>🟣 <b>clap</b>:check</td><td align="right">1.7665s</td><td align="right">1.7336s</td><td align="right">💚 -1.86%</td></tr><tr><td>🟣 <b>hyper</b>:check</td><td align="right">0.2780s</td><td align="right">0.2736s</td><td align="right">💚 -1.61%</td></tr><tr><td>🟣 <b>regex</b>:check</td><td align="right">0.9994s</td><td align="right">0.9824s</td><td align="right">💚 -1.70%</td></tr><tr><td>🟣 <b>syn</b>:check</td><td align="right">1.5875s</td><td align="right">1.5656s</td><td align="right">💚 -1.38%</td></tr><tr><td>🟣 <b>syntex_syntax</b>:check</td><td align="right">6.0682s</td><td align="right">5.9532s</td><td align="right">💚 -1.90%</td></tr><tr><td>Total</td><td align="right">10.6997s</td><td align="right">10.5083s</td><td align="right">💚 -1.79%</td></tr><tr><td>Summary</td><td align="right">1.0000s</td><td align="right">0.9831s</td><td align="right">💚 -1.69%</td></tr></table>
cc `@SparrowLii`
Rollup of 7 pull requests
Successful merges:
- #113565 (Make SIGSEGV handler emit nicer backtraces)
- #114704 (parser: not insert dummy field in struct)
- #115272 (miri/diagnostics: don't forget to print_backtrace when ICEing on unexpected errors)
- #115313 (Make `get_return_block()` return `Some` only for HIR nodes in body)
- #115347 (suggest removing `impl` in generic trait bound position)
- #115355 (new solver: handle edge case of a recursion limit of 0)
- #115363 (Don't suggest adding parentheses to call an inaccessible method.)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't suggest adding parentheses to call an inaccessible method.
Previously, code of this form would emit E0615 (attempt to use a method as a field), thus emphasizing the existence of private methods that the programmer probably does not care about. Now it ignores their existence instead, producing error E0609 (no field). The motivating example is:
```rust
let x = std::rc::Rc::new(());
x.inner;
```
which would previously mention the private method `Rc::inner()`, even though `Rc<T>` intentionally has no public methods so that it can be a transparent smart pointer for any `T`.
```rust
error[E0615]: attempted to take value of method `inner` on type `Rc<()>`
--> src/main.rs:3:3
|
3 | x.inner;
| ^^^^^ method, not a field
|
help: use parentheses to call the method
|
3 | x.inner();
| ++
```
With this change, it emits E0609 and no suggestion.
new solver: handle edge case of a recursion limit of 0
Apparently a recursion limit of 0 is possible/valid/useful/used/cute, the more you know 🌟 .
(It's somewhat interesting to me that the old solver seemingly handles this, and that the new solver currently requires a recursion limit of 2 here)
r? `@compiler-errors.`
Fixes#115351.
suggest removing `impl` in generic trait bound position
rustc already does this recovery in type param position (`<T: impl Trait>` -> `<T: Trait>`).
This PR also adds that suggestion in trait bound position (e.g. `where T: impl Trait` or `trait Trait { type Assoc: impl Trait; }`)
Make `get_return_block()` return `Some` only for HIR nodes in body
Fixes#114918
The issue occurred while compiling the following input:
```rust
fn uwu() -> [(); { () }] {
loop {}
}
```
It was caused by the code below trying to suggest a missing return type which resulted in a const eval cycle: 1bd043098e/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs (L68-L75)
The root cause was `get_return_block()` returning an `Fn` node for a node in the return type (i.e. the second `()` in the return type `[(); { () }]` of the input) although it is supposed to do so only for nodes that lie in the body of the function and return `None` otherwise (at least as per my understanding).
The PR fixes the issue by fixing this behaviour of `get_return_block()`.
parser: not insert dummy field in struct
Fixes#114636
This PR eliminates the dummy field, initially introduced in #113999, thereby enabling unrestricted use of `ident.unwrap()`. A side effect of this action is that we can only report the error of the first macro invocation field within the struct node.
An alternative solution might be giving a virtual name to the macro, but it appears more complex.(https://github.com/rust-lang/rust/issues/114636#issuecomment-1670228715). Furthermore, if you think https://github.com/rust-lang/rust/issues/114636#issuecomment-1670228715 is a better solution, feel free to close this PR.
Make SIGSEGV handler emit nicer backtraces
This annotates the code heavily with comments to explain what is going on, for the benefit of other compiler contributors. The backtrace also emits appropriate comments to clarify, to a programmer who may not know why a bunch of file paths and hexadecimal blather was just dumped into stderr, what is going on. Finally, it detects cycles and uses their regularity to avoid repeating a bunch of text. The previous backtraces we were emitting was extremely unfriendly, potentially confusing, and often alarming, and this makes things almost "nice".
We can't necessarily make them much nicer than this, because a signal handler must use "signal-safe" functions. This precludes conveniences like dynamic allocations. Fortunately, Rust's stdlib has allocation-free formatting, but it may hinder integrating this error with our localization middleware, as I wasn't able to clearly ascertain, at a glance, whether there was a zero-alloc path through it.
r? `@Nilstrieb`
Adapt table sizes to the contents
This is an implementation of https://github.com/rust-lang/compiler-team/issues/666
The objective of this PR is to permit the rmeta format to accommodate larger crates that need offsets larger than a `u32` can store without compromising performance for crates that do not need such range. The second commit is a number of tiny optimization opportunities I noticed while looking at perf recordings of the first commit.
The rmeta tables need to have fixed-size elements to permit lazy random access. But the size only needs to be fixed _per table_, not per element type. This PR adds another `usize` to the table header which indicates the table element size. As each element of a table is set, we keep track of the widest encoded table value, then don't bother encoding all the unused trailing bytes on each value. When decoding table elements, we copy them to a full-width array if they are not already full-width.
`LazyArray` needs some special treatment. Most other values that are encoded in tables are indexes or offsets, and those tend to be small so we get to drop a lot of zero bytes off the end. But `LazyArray` encodes _two_ small values in a fixed-width table element: A position of the table and the length of the table. The treatment described above could trim zero bytes off the table length, but any nonzero length shields the position bytes from the optimization. To improve this, we interleave the bytes of position and length. This change is responsible for about half of the crate metadata win on many crates.
Fixes https://github.com/rust-lang/rust/issues/112934 (probably)
Fixes https://github.com/rust-lang/rust/issues/103607
Previously, the test code would emit E0615, thus revealing the existence
of private methods that the programmer probably does not care about.
Now it ignores their existence instead, producing error E0609 (no field).
The motivating example is:
```rust
let x = std::rc::Rc::new(());
x.inner;
```
which would previously mention the private method `Rc::inner()`, even
though `Rc<T>` intentionally has no public methods so that it can be a
transparent smart pointer for any `T`.
Always add LC_BUILD_VERSION for metadata object files
As of Xcode 15 Apple's linker has become a bit more strict about the warnings it produces. One of those new warnings requires all valid Mach-O object files in an archive to have a LC_BUILD_VERSION load command:
```
ld: warning: no platform load command found in 'ARCHIVE[arm64][2106](lib.rmeta)', assuming: iOS-simulator
```
This was already being done for Mac Catalyst so this change expands this logic to include it for all Apple platforms. I filed this behavior change as FB12546320 and was told it was the new intentional behavior.
Tweaks and improvements on SMIR around generics_of and predicates_of
r? `@oli-obk`
This allows an API like the following ...
```rust
let trait_decls = stable_mir::all_trait_decls().iter().map(|trait_def| {
let trait_decl = stable_mir::trait_decl(trait_def);
let generics = trait_decl.generics_of();
let predicates = trait_decl.predicates_of().predicates;
```
I didn't like that much `trait_def.trait_decl()` which is it possible but adding a method to a def_id that loads up a whole trait definition looks backwards to me.
Remove conditional use of `Sharded` from query state
`Sharded` is already a zero cost abstraction, so it shouldn't affect the performance of the single thread compiler if LLVM does its job.
r? `@cjgillot`
Use `preserve_mostcc` for `extern "rust-cold"`
As experimentation in #115242 has shown looks better than `coldcc`. Notably, clang exposes `preserve_most` (https://clang.llvm.org/docs/AttributeReference.html#preserve-most) but not `cold`, so this change should put us on a better-supported path.
And *don't* use a different convention for cold on Windows, because that actually ends up making things worse. (See comment in the code.)
cc tracking issue #97544
miri ABI compatibility check: accept u32 and i32
If only the sign differs, then surely these types are compatible. (We do still check that `arg_ext` is the same, just in case.)
Also I made it so that the ABI check must *imply* that size and alignment are the same, but it doesn't actively check that itself. With how crazy ABI constraints get, having equal size and align really shouldn't be used as a signal for anything I think...
Make RPITITs capture all in-scope lifetimes
Much like #114616, this implements the lang team decision from this T-lang meeting on [opaque captures strategy moving forward](https://hackmd.io/sFaSIMJOQcuwCdnUvCxtuQ?view). This will be RFC'd soon, but given that RPITITs are a nightly feature, this shouldn't necessarily be blocked on that.
We unconditionally capture all lifetimes in RPITITs -- impl is not as simple as #114616, since we still need to duplicate RPIT lifetimes to make sure we reify any late-bound lifetimes in scope.
Closes#112194
don't use SnapshotVec in Graph implementation, as it looks unused; use Vec instead
`Graph` don't use `SnapshotVec` methods, so use simple `Vec` instead?
More precisely detect cycle errors from type_of on opaque
Not sure if this still needs work. Just putting it up for initial impressions, since it seems that a few people are frustrated with the increased error verbosity due to #113320.
Essentially we introduce a new sub-query for `type_of` specifically for opaques which returns a value that is able to distinguish "has errors" from "due to cycle recovery".
Fixes#115188
r? `@oli-obk`
codegen_llvm/llvm_type: avoid matching on the Rust type
This `match` is highly suspicious. Looking at `scalar_llvm_type_at` I think it makes no difference. But if it were to make a difference that would be a huge problem, since it doesn't look through `repr(transparent)`!
Cc `@eddyb` `@bjorn3`
Avoid duplicate `large_assignments` lints
By checking for overlapping spans.
This PR does the "reduce noisiness" task in #83518.
r? `@oli-obk` who added E-mentor and E-help-wanted and wrote the initial code.
(The fix itself is in dc82736677. The two commits before that are just small refactorings.)
Rollup of 6 pull requests
Successful merges:
- #109660 (Document that SystemTime does not count leap seconds)
- #114238 (Fix implementation of `Duration::checked_div`)
- #114512 (std/tests: disable ancillary tests on freebsd since the feature itsel…)
- #114919 (style-guide: Add guidance for defining formatting for specific macros)
- #115278 (tell people what to do when removing an error code)
- #115280 (avoid triple-backtrace due to panic-during-cleanup)
r? `@ghost`
`@rustbot` modify labels: rollup
tell people what to do when removing an error code
Currently tidy and CI send developers on a wild goose chase:
- you edit the code
- CI/tidy tells you that an error code is gone, so you remove it from the list
- CI/tidy tells you that the markdown file is stale, so you remove that as well
- CI (but not tidy) tells you not to remove an error description and copy what E0001 does
Let's be nice to people and directly tell them what to do rather than making them follow misleading breadcrumbs.
r? ``@GuillaumeGomez``
Load include_bytes! directly into an Lrc
This PR deletes an innocent-looking `.into()` that was converting from a `Vec<u8>` to `Lrc<[u8]>`. This has significant runtime and memory overhead when using `include_bytes!` to pull in a large binary file.
Add a specialization for encoding byte arrays in rmeta
This specialization already exists for FileEncoder, but since EncodeContext is implemented by forwarding down to FileEncoder, using EncodeContext used to bypass the specialization.
Only inline functions that are considered eligible for inlining
by the reachability pass.
This constraint was previously indirectly enforced by only exporting MIR
of eligible functions, but that approach doesn't work with
-Zalways-encode-mir enabled.
Add an (perma-)unstable option to disable vtable vptr
This flag is intended for evaluation of trait upcasting space cost for embedded use cases.
Compared to the approach in #112355, this option provides a way to evaluate end-to-end cost of trait upcasting. Rationale: https://github.com/rust-lang/rust/issues/112355#issuecomment-1658207769
## How this flag should be used (after merge)
Build your project with and without `-Zno-trait-vptr` flag. If you are using cargo, set `RUSTFLAGS="-Zno-trait-vptr"` in the environment variable. You probably also want to use `-Zbuild-std` or the binary built may be broken. Save both binaries somewhere.
### Evaluate the space cost
The option has a direct and indirect impact on vtable space usage. Directly, it gets rid of the trait vptr entry needed to store a pointer to a vtable of a supertrait. (IMO) this is a small saving usually. The larger saving usually comes with the indirect saving by eliminating the vtable of the supertrait (and its parent).
Both impacts only affects vtables (notably the number of functions monomorphized should , however where vtable reside can depend on your relocation model. If the relocation model is static, then vtable is rodata (usually stored in Flash/ROM together with text in embedded scenario). If the binary is relocatable, however, the vtable will live in `.data` (more specifically, `.data.rel.ro`), and this will need to reside in RAM (which may be a more scarce resource in some cases), together with dynamic relocation info living in readonly segment.
For evaluation, you should run `size` on both binaries, with and without the flag. `size` would output three columns, `text`, `data`, `bss` and the sum `dec` (and it's hex version). As explained above, both `text` and `data` may change. `bss` shouldn't usually change. It'll be useful to see:
* Percentage change in text + data (indicating required flash/ROM size)
* Percentage change in data + bss (indicating required RAM size)
Move a local to the `#if` block where it is used
For other cases (LLVM < 17), this was complaining under `-Wall`:
```
warning: llvm-wrapper/PassWrapper.cpp: In function ‘void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef, const char*)’:
warning: llvm-wrapper/PassWrapper.cpp:311:26: warning: unused variable ‘MCInfo’ [-Wunused-variable]
warning: 311 | const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo();
warning: | ^~~~~~
```
This reverts commit 4410868798, reversing
changes made to 249595b752.
This causes linker failures with the binutils version used by
cross (#115239), as well as miscompilations when using the mold
linker.
As experimentation in 115242 has shown looks better than `coldcc`.
And *don't* use a different convention for cold on Windows, because that actually ends up making things worse.
cc tracking issue 97544
Point at type parameter that introduced unmet bound instead of full HIR node
```
error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
--> $DIR/issue-87199.rs:18:15
|
LL | ref_arg::<[i32]>(&[5]);
| ^^^^^ doesn't have a size known at compile-time
```
instead of
```
error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
--> $DIR/issue-87199.rs:18:22
|
LL | ref_arg::<[i32]>(&[5]);
| ---------------- ^^^^ doesn't have a size known at compile-time
| |
| required by a bound introduced by this call
```
------
```
error[E0277]: the trait bound `String: Copy` is not satisfied
--> $DIR/own-bound-span.rs:14:24
|
LL | let _: <S as D>::P<String>;
| ^^^^^^ the trait `Copy` is not implemented for `String`
|
note: required by a bound in `D::P`
--> $DIR/own-bound-span.rs:4:15
|
LL | type P<T: Copy>;
| ^^^^ required by this bound in `D::P`
```
instead of
```
error[E0277]: the trait bound `String: Copy` is not satisfied
--> $DIR/own-bound-span.rs:14:12
|
LL | let _: <S as D>::P<String>;
| ^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
|
note: required by a bound in `D::P`
--> $DIR/own-bound-span.rs:4:15
|
LL | type P<T: Copy>;
| ^^^^ required by this bound in `D::P`
```
Fix#105306.
Remove lub_empty from lexical region resolve
As of my understanding this method made sense when we had `ReEmpty`.
Removed `lub_empty` and made the calling site code equivalent.
r? `@lcnr` `@compiler-errors`
Fix waiting on a query that panicked
This fixes waiting on a query that panicked. The code now looks for `QueryResult::Poisoned` in the query state in addition to the query cache. This fixes https://github.com/rust-lang/rust/issues/111528.
r? `@cjgillot`
Revert "Use the same DISubprogram for each instance of the same inline function within the caller"
This reverts commit 687bffa493.
Reverting to resolve ICEs reported on nightly.
cc `@dpaoliello`
Fixes#115156
Stop emitting non-power-of-two vectors in (non-portable-SIMD) codegen
Fixes#115212
It's unclear what makes this not work sometimes, since it often *does* work, so for now just disable the unusual cases. A future PR can consider doing something smarter, but this is an easy and safe tweak that we can do to resolve the regressions for now.
On the following example, point at `String` instead of the whole type:
```
error[E0277]: the trait bound `String: Copy` is not satisfied
--> $DIR/own-bound-span.rs:14:24
|
LL | let _: <S as D>::P<String>;
| ^^^^^^ the trait `Copy` is not implemented for `String`
|
note: required by a bound in `D::P`
--> $DIR/own-bound-span.rs:4:15
|
LL | type P<T: Copy>;
| ^^^^ required by this bound in `D::P`
```
Add missing high-level stable_mir::generics_of fn
We forgot to add this function in https://github.com/rust-lang/rust/pull/115092, as we have done on https://github.com/rust-lang/rust/pull/115084 and other high level APIs.
At some point I think we should re-organize the structure of the code but this is what we have for now.
r? `@compiler-errors`
Would have assigned `@oli-obk` but he is still on vacations
Walk through full path in `point_at_path_if_possible`
We already had sufficient information to point at the `[u8]` in `Option::<[u8]>::None` (the `fallback_param_to_point_at` parameter), we just were neither using it nor walking through hir paths sufficiently to encounter it.
This should alleviate the need to add additional logic to extract params in a somewhat arbitrary manner of looking at the grandparent def path: https://github.com/rust-lang/rust/pull/115219#discussion_r1305946358
r? `@estebank`
Add stable for Constant in smir
Previously https://github.com/rust-lang/rust/pull/114587 we covered much of the groundwork needed to cover Const in smir, so there is no reason keep `Constant` as String.
r? `@spastorino`
Treat `StatementKind::Coverage` as completely opaque for SMIR purposes
Coverage statements in MIR are heavily tied to internal details of the coverage implementation that are likely to change, and are unlikely to be useful to third-party tools for the foreseeable future.
Add comment to the push_trailing function
## Add comment to the `push_trailing` function for clarity.
I improve the explanation by describing:
- how the code handles unicode and emoji characters using `char_indices`,
- how the code handles the absence of high indexes, and
- what the code's overall aim is.
Fix CFI: f32 and f64 are encoded incorrectly for cross-language CFI
Fix#115150 by encoding f32 and f64 correctly for cross-language CFI. I missed changing the encoding for f32 and f64 when I introduced the integer normalization option in #105452 as integer normalization does not include floating point. `f32` and `f64` should be always encoded as `f` and `d` since they are both FFI safe when their representation are the same (i.e., IEEE 754) for both the Rust compiler and Clang.
Fix#115150 by encoding f32 and f64 correctly for cross-language CFI. I
missed changing the encoding for f32 and f64 when I introduced the
integer normalization option in #105452 as integer normalization does
not include floating point. `f32` and `f64` should be always encoded as
`f` and `d` since they are both FFI safe when their representation are
the same (i.e., IEEE 754) for both the Rust compiler and Clang.
Allow explicit `#[repr(Rust)]`
This is identical to no `repr()` at all. For `Rust, packed` and `Rust, align(x)`, it should be the same as no `Rust` at all (as, afaik, `#[repr(align(16))]` uses the Rust ABI.)
The main use case for this is being able to explicitly say "I want to use the Rust ABI" in very very rare circumstances where the first obvious choice would be the C ABI yet is undesirable, which is already possible with functions as `extern "Rust"`. This would be useful for silencing https://github.com/rust-lang/rust-clippy/pull/11253. It's also more consistent with `extern`.
The lack of this also tripped me up a bit when I was new to Rust, as I expected this to be possible.
Add symbols for Clippy usage
The `arithmetic_side_effects` lint is always "interning" these non-existing symbols related to math operations causing a bit of a slowdown.
refactor(lint): translate `RenamedOrRemovedLint`
I was trying to address <https://github.com/rust-lang/cargo/issues/12495> and found that maybe I should refactor relevant lints a bit.
This PR translates `RenamedOrRemovedLint` into fluent file. To make diagnostic types clearer and easier to organize, this PR splits it into two structs.
The second commit adds lifetime annotations for removing unnecessary clones. If people feel too noisy, we can revert such change.
### Possibly relevant UI tests:
* `tests/ui/lint-removed*`
* `tests/ui/lint-renamed*`
* `tests/ui/rustdoc-renamed.rs`
* `tests/rustdoc-ui/lints/unknown-renamed-lints.rs`
elaborate a bit on the (lack of) safety in 'Mmap::map'
Sadly none of the callers of this function even consider it worth mentioning in their unsafe block that what they are doing is completely unsound.
resolve: Stop creating `NameBinding`s on every use, create them once per definition instead
`NameBinding` values are supposed to be unique, use referential equality, and be created once for every name declaration.
Before this PR many `NameBinding`s were created on name use, rather than on name declaration, because it's sufficiently cheap, and comparisons are not actually used in practice for some binding kinds.
This PR makes `NameBinding`s consistently unique and created on name declaration.
There are two special cases
- for extern prelude names creating `NameBinding` requires loading the corresponding crate, which is expensive, so such bindings are created lazily on first use, but they still keep the uniqueness by being reused on further uses.
- for legacy derive helpers (helper attributes written before derives that introduce them) the declaration and the use is basically the same thing (that's one of the reasons why they are deprecated), so they are still created on use, but we can still maybe do a bit better in a way that I described in FIXME in the last commit.
Fix races conditions with `SyntaxContext` decoding
This changes `SyntaxContext` decoding to work with concurrent decoding. The `remapped_ctxts` field now only stores `SyntaxContext` which have completed decoding, while the new `decoding` and `local_in_progress` keeps track of `SyntaxContext`s which are in process of being decoding and on which threads.
This fixes 2 issues with the current implementation. It can return an `SyntaxContext` which contains dummy data if another thread starts decoding before the first one has completely finished. Multiple threads could also allocate multiple `SyntaxContext`s for the same `raw_id`.
Suggest mutable borrow on read only for-loop that should be mutable
```
error[E0596]: cannot borrow `*test` as mutable, as it is behind a `&` reference
--> $DIR/suggest-mut-iterator.rs:22:9
|
LL | for test in &tests {
| ------ this iterator yields `&` references
LL | test.add(2);
| ^^^^ `test` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: use a mutable iterator instead
|
LL | for test in &mut tests {
| +++
```
Fix#114311.
Parse unnamed fields and anonymous structs or unions (no-recovery)
It is part of #114782 which implements #49804. Only parse anonymous structs or unions in struct field definition positions.
r? `@petrochenkov`
Anonymous structs or unions are only allowed in struct field
definitions.
Co-authored-by: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com>
Make `Sharded` an enum and specialize it for the single thread case
This changes `Sharded` to use a single shard by an enum, reducing the size of `Sharded` for greater cache efficiency.
Performance improvement with 1 thread and `cfg(parallel_compiler)`:
<table><tr><td rowspan="2">Benchmark</td><td colspan="1"><b>Before</b></th><td colspan="2"><b>After</b></th></tr><tr><td align="right">Time</td><td align="right">Time</td><td align="right">%</th></tr><tr><td>🟣 <b>clap</b>:check</td><td align="right">1.7009s</td><td align="right">1.6748s</td><td align="right">💚 -1.53%</td></tr><tr><td>🟣 <b>hyper</b>:check</td><td align="right">0.2525s</td><td align="right">0.2451s</td><td align="right">💚 -2.90%</td></tr><tr><td>🟣 <b>regex</b>:check</td><td align="right">0.9519s</td><td align="right">0.9353s</td><td align="right">💚 -1.74%</td></tr><tr><td>🟣 <b>syn</b>:check</td><td align="right">1.5504s</td><td align="right">1.5280s</td><td align="right">💚 -1.45%</td></tr><tr><td>🟣 <b>syntex_syntax</b>:check</td><td align="right">5.9536s</td><td align="right">5.8873s</td><td align="right">💚 -1.11%</td></tr><tr><td>Total</td><td align="right">10.4092s</td><td align="right">10.2706s</td><td align="right">💚 -1.33%</td></tr><tr><td>Summary</td><td align="right">1.0000s</td><td align="right">0.9825s</td><td align="right">💚 -1.75%</td></tr></table>
I did see an unexpected 0.23% change for the serial compiler, so this could use a perf run to see if that reproduces.
cc `@SparrowLii`
Ensure that THIR unsafety check is done before stealing it
This ensures that THIR unsafety check is done before stealing it by running it on the typeck root instead of on a closure, which does nothing.
Fixes https://github.com/rust-lang/rust/issues/111520
```
error[E0596]: cannot borrow `*test` as mutable, as it is behind a `&` reference
--> $DIR/suggest-mut-iterator.rs:22:9
|
LL | for test in &tests {
| ------ this iterator yields `&` references
LL | test.add(2);
| ^^^^ `test` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: use a mutable iterator instead
|
LL | for test in &mut tests {
| +++
```
Address #114311.
This option tells LLVM to emit relaxable relocation types
R_X86_64_GOTPCRELX/R_X86_64_REX_GOTPCRELX/R_386_GOT32X in applicable cases. True
matches Clang's CMake default since 2020-08 [1] and latest LLVM default[2].
This also works around a GNU ld<2.41 issue[3] when using
general-dynamic/local-dynamic TLS models in `-Z plt=no` mode with latest LLVM.
[1]: c41a18cf61
[2]: 2aedfdd9b8
[3]: https://sourceware.org/bugzilla/show_bug.cgi?id=24784
ArchiveWrapper: handle LLVM API update
In llvm/llvm-project@f740bcb370 a boolean parameter changed to an enum.
r? ``@nikic``
``@rustbot`` label: +llvm-main
Add support for `ptr::write`s for the `invalid_reference_casting` lint
This PR adds support for `ptr::write` and others for the `invalid_reference_casting` lint.
Detecting instances where instead of using the deref (`*`) operator to assign someone uses `ptr::write`, `ptr::write_unaligned` or `ptr::write_volatile`.
```rust
let data_len = 5u64;
std::ptr::write(
std::mem::transmute::<*const u64, *mut u64>(&data_len),
new_data_len,
);
```
r? ``@est31``
Don't do intra-pass validation on MIR shims
Fixes#114375
In the test that was committed, we end up generating the drop shim for `struct Foo` that looks like:
```
fn std::ptr::drop_in_place(_1: *mut Foo) -> () {
let mut _0: ();
bb0: {
goto -> bb5;
}
bb1: {
return;
}
bb2 (cleanup): {
resume;
}
bb3: {
goto -> bb1;
}
bb4 (cleanup): {
drop(((*_1).0: foo::WrapperWithDrop<()>)) -> [return: bb2, unwind terminate];
}
bb5: {
drop(((*_1).0: foo::WrapperWithDrop<()>)) -> [return: bb3, unwind: bb2];
}
}
```
In `bb4` and `bb5`, we assert that `(*_1).0` has type `WrapperWithDrop<()>`. However, In a user-facing param env, the type is actually `WrapperWithDrop<Tait>`. These types are not equal in a user-facing param-env (and can't be made equal even if we use `DefiningAnchor::Bubble`, since it's a non-local TAIT).
Use the same DISubprogram for each instance of the same inlined function within a caller
# Issue Details:
The call to `panic` within a function like `Option::unwrap` is translated to LLVM as a `tail call` (as it will never return), when multiple calls to the same function like this is inlined LLVM will notice the common `tail call` block (i.e., loading the same panic string + location info and then calling `panic`) and merge them together.
When merging these instructions together, LLVM will also attempt to merge the debug locations as well, but this fails (i.e., debug info is dropped) as Rust emits a new `DISubprogram` at each inline site thus LLVM doesn't recognize that these are actually the same function and so thinks that there isn't a common debug location.
As an example of this when building for x86_64 Windows (note the lack of `.cv_loc` before the call to `panic`, thus it will be attributed to the same line at the `addq` instruction):
```
.cv_loc 0 1 23 0 # src\lib.rs:23:0
addq $40, %rsp
retq
leaq .Lalloc_f570dea0a53168780ce9a91e67646421(%rip), %rcx
leaq .Lalloc_629ace53b7e5b76aaa810d549cc84ea3(%rip), %r8
movl $43, %edx
callq _ZN4core9panicking5panic17h12e60b9063f6dee8E
int3
```
# Fix Details:
Cache the `DISubprogram` emitted for each inlined function instance within a caller so that this can be reused if that instance is encountered again, this also requires caching the `DILexicalBlock` and `DIVariable` objects to avoid creating duplicates.
After this change the above assembly now looks like:
```
.cv_loc 0 1 23 0 # src\lib.rs:23:0
addq $40, %rsp
retq
.cv_inline_site_id 5 within 0 inlined_at 1 0 0
.cv_inline_site_id 6 within 5 inlined_at 1 12 0
.cv_loc 6 2 935 0 # library\core\src\option.rs:935:0
leaq .Lalloc_5f55955de67e57c79064b537689facea(%rip), %rcx
leaq .Lalloc_e741d4de8cb5801e1fd7a6c6795c1559(%rip), %r8
movl $43, %edx
callq _ZN4core9panicking5panic17hde1558f32d5b1c04E
int3
```
Add disclaimer on size assertion macro
Sometimes people are inspired by rustc to add size assertions to their code and copy the macro. This is bad because it causes hard build errors. rustc happens to be special where it makes this okay.
For example, see #115028 (not sure whether they were directly inspired by this function), but I think I've also seen other cases.
Warn on elided lifetimes in associated constants (`ELIDED_LIFETIMES_IN_ASSOCIATED_CONSTANT`)
Elided lifetimes in associated constants (in impls) erroneously resolve to fresh lifetime parameters on the impl since #97313. This is not correct behavior (see #38831).
I originally opened #114716 to fix this, but given the time that has passed, the crater results seem pretty bad: https://github.com/rust-lang/rust/pull/114716#issuecomment-1682091952
This PR alternatively implements a lint against this behavior, and I'm hoping to bump this to deny in a few versions.
Redefine the pluralize macro's arm
Redefine the unintuitive pluralize macro's arm because of the negation. The initial code starts with check if count is not 1, which is confusing and unintuitive.
The arm shoud start with checking,
- if "count" `is 1` then, append `""` (empty string) - indicate as singular
- Then check if "count" `is not 1` (more than 1), append `"s"` - indicate as plural
Before:
```rs
// This arm is abit confusing since it start with checking, if "count" is more than 1, append "s".
($x:expr) => {
if $x != 1 { "s" } else { "" }
};
```
After:
```rs
// Pluralize based on count (e.g., apples)
($x:expr) => {
if $x == 1 { "" } else { "s" }
};
```
Coverage statements in MIR are heavily tied to internal details of the coverage
implementation that are likely to change, and are unlikely to be useful to
third-party tools for the foreseeable future.
Sometimes people are inspired by rustc to add size assertions to their
code and copy the macro. This is bad because it causes hard build
errors. rustc happens to be special where it makes this okay.
As of Xcode 15 Apple's linker has become a bit more strict about the
warnings it produces. One of those new warnings requires all valid
Mach-O object files in an archive to have a LC_BUILD_VERSION load
command:
```
ld: warning: no platform load command found in 'ARCHIVE[arm64][2106](lib.rmeta)', assuming: iOS-simulator
```
This was already being done for Mac Catalyst so this change expands this
logic to include it for all Apple platforms. I filed this behavior
change as FB12546320 and was told it was the new intentional behavior.
coverage: Give the instrumentor its own counter type, separate from MIR
Within the MIR representation of coverage data, `CoverageKind` is an important part of `StatementKind::Coverage`, but the `InstrumentCoverage` pass also uses it heavily as an internal data structure. This means that any change to `CoverageKind` also needs to update all of the internal parts of `InstrumentCoverage` that manipulate it directly, making the MIR representation difficult to modify.
---
This change fixes that by giving the instrumentor its own `BcbCounter` type for internal use, which is then converted to a `CoverageKind` when injecting coverage information into MIR.
The main change is mostly mechanical, because the initial `BcbCounter` is drop-in compatible with `CoverageKind`, minus the unnecessary `CoverageKind::Unreachable` variant.
I've then removed the `function_source_hash` field from `BcbCounter::Counter`, as a small example of how the two types can now usefully differ from each other. Every counter in a MIR-level function should have the same source hash, so we can supply the hash during the conversion to `CoverageKind::Counter` instead.
---
*Background:* BCB stands for “basic coverage block”, which is a node in the simplified control-flow graph used by coverage instrumentation. The instrumentor pass uses the function's actual MIR control-flow graph to build a simplified BCB graph, then assigns coverage counters and counter expressions to various nodes/edges in that simplified graph, and then finally injects corresponding coverage information into the underlying MIR.
Fix a stack overflow with long else if chains
This fixes stack overflows when running the `issue-74564-if-expr-stack-overflow.rs` test with the parallel compiler.
Add MIR validation for unwind out from nounwind functions + fixes to make validation pass
`@Nilstrieb` This is the MIR validation you asked in https://github.com/rust-lang/rust/pull/112403#discussion_r1222739722.
Two passes need to be fixed to get the validation to pass:
* `RemoveNoopLandingPads` currently unconditionally introduce a resume block (even there is none to begin with!), changed to not do that
* Generator state transform introduces a `assert` which may unwind, and its drop elaboration also introduces many new `UnwindAction`s, so in this case run the AbortUnwindingCalls after the transformation.
I believe this PR should also fixRust-for-Linux/linux#1016, cc `@ojeda`
r? `@Nilstrieb`
custom_mir: change Call() terminator syntax to something more readable
I find our current syntax very hard to read -- I cannot even remember the order of arguments, and having the "next block" *before* the actual function call is very counter-intuitive IMO. So I suggest we use `Call(ret_val = function(v), next_block)` instead.
r? `@JakobDegen`
Ignore unexpected incr-comp session dirs
Clearly the code path can be hit without the presence of a compiler bug.
All it takes is mischief. See #71698.
Ignore problematic directories instead of ICE:ing. `continue`ing is
already done for problematic dirs in the code block above us.
Closes#71698.
With this fix, the output is this instead of ICE:
```
$ cargo +stage1 new gz-ice && cd gz-ice
$ cargo +stage1 build
$ find target -type f -exec gzip {} \;
$ cargo +stage1 run
Created binary (application) `gz-ice` package
Compiling gz-ice v0.1.0 (/tmp/gz-ice)
Finished dev [unoptimized + debuginfo] target(s) in 0.13s
gzip: target/debug/gz-ice has 1 other link -- unchanged
gzip: target/debug/deps/gz_ice-de919414dd9926b9 has 1 other link -- unchanged
Compiling gz-ice v0.1.0 (/tmp/gz-ice)
warning: failed to garbage collect invalid incremental compilation session directory `/tmp/gz-ice/target/debug/incremental/gz_ice-23qx9z9j9vghe/s-gnwd8daity-kp10sj.lock.gz`: Not a directory (os error 20)
warning: `gz-ice` (bin "gz-ice") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.13s
Running `target/debug/gz-ice`
Hello, world!
```
Avoid side-effects from `try_coerce` when suggesting borrowing LHS of cast
The name `try_coerce` is a bit misleading -- it has side-effects, so when it's used in diagnostics code, it sometimes causes spurious obligations to be registered which cause other errors to occur that really make no sense in context.
Addendum: let's just rename `try_coerce` to `coerce` -- the `try_` part doesn't really add much, imo.
Normalize return type of `deduce_future_output_from_obligations`
Fixes#114909
Also confirmed to fix#114727 manually
Now that we have weak/lazy type aliases, we need to normalize those in future signatures to ensure that `replace_opaque_types_with_inference_vars` actually sees TAITs behind them. This isn't needed in the new solver, but added a test to make sure it doesn't regress there either.
r? types cc `@oli-obk` (who's gone, worst case can delay this PR until he's back)
Fix ABI flags in RISC-V/LoongArch ELF file generated by rustc
Fix#114153
It turns out the current way to set these flags are completely wrong. In LLVM the target ABI is used instead of target features to determine these flags.
Not sure how to write a test though. Or maybe a test isn't necessary because this affects only those touching target json?
r? `@Nilstrieb`
This shows one small benefit of separating `BcbCounter` from `CoverageKind`.
The function source hash will be the same for all counters within a function,
so instead of passing it through `CoverageCounters` and storing it in every
counter, we can just supply it during the final conversion to `CoverageKind`.
rustdoc: Add lint `redundant_explicit_links`
Closes#87799.
- Lint warns by default
- Reworks link parser to cache original link's display text
r? `@jyn514`