Commit Graph

8402 Commits

Author SHA1 Message Date
bors
aaa8614934 Auto merge of #137162 - nnethercote:remove-Map-2, r=Zalathar
Move methods from `Map` to `TyCtxt`, part 2.

Continuing the work started in #136466.

Every method gains a `hir_` prefix, though for the ones that already have a `par_` or `try_par_` prefix I added the `hir_` after that.

r? Zalathar
2025-02-18 04:26:30 +00:00
Nicholas Nethercote
04eeda47ab Inline and replace Statement::replace_nop.
It has a single call site, and doesn't seem worth having as an API
function.
2025-02-18 13:43:43 +11:00
Nicholas Nethercote
69f5e342bf Inline and remove BasicBlockData::retain_statements.
It has a single call site, and the code is clearer this way.
2025-02-18 13:31:08 +11:00
Nicholas Nethercote
627e08c909 Remove BasicBlockData::expand_statements.
The previous commit removed its single use. `MirPatch` is a more
flexible alternative.
2025-02-18 13:13:32 +11:00
Nicholas Nethercote
fd7b4bf4e1 Move methods from Map to TyCtxt, part 2.
Continuing the work started in #136466.

Every method gains a `hir_` prefix, though for the ones that already
have a `par_` or `try_par_` prefix I added the `hir_` after that.
2025-02-18 10:17:44 +11:00
Matthias Krüger
7808784f01
Rollup merge of #137168 - klensy:rc--, r=lcnr
correct comment

Rc was removed in #113573, so
r? `@lcnr`
2025-02-17 17:06:12 +01:00
Matthias Krüger
005de3877d
Rollup merge of #136959 - nnethercote:simplify-SwitchSources, r=tmiasko
Simplify switch sources

`SwitchSources` and the code around it can be simplified.

r? `@tmiasko`
2025-02-17 17:06:08 +01:00
Matthew Jasper
49cf00c7c0 Clean up dropck code a bit
- Remove `Result` that couldn't be Err on valid compilation.
- Always compute errors on failure.
2025-02-17 11:33:07 +00:00
bors
2162e9d4b1 Auto merge of #137164 - matthiaskrgr:rollup-dj5826k, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #137095 (Replace some u64 hashes with Hash64)
 - #137100 (HIR analysis: Remove unnecessary abstraction over list of clauses)
 - #137105 (Restrict DerefPure for Cow<T> impl to T = impl Clone, [impl Clone], str.)
 - #137120 (Enable `relative-path-include-bytes-132203` rustdoc-ui test on Windows)
 - #137125 (Re-add missing empty lines in the releases notes)
 - #137145 (use add-core-stubs / minicore for a few more tests)
 - #137149 (Remove SSE ABI from i586-pc-windows-msvc)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-17 11:18:33 +00:00
klensy
6fa3ad1e5e correct comment 2025-02-17 12:32:26 +03:00
Matthias Krüger
2a25a16c57
Rollup merge of #137100 - fmease:hirtylow-rm-clauses-wrapper, r=compiler-errors
HIR analysis: Remove unnecessary abstraction over list of clauses

`rustc_hir_analysis::bounds::Bounds` with its methods is nowadays a paper-thin wrapper around `Vec<(Clause, Span)>`s and `Vec::push` essentially.

Its existence slightly annoyed me (and I keep opening its corresp. file instead of the identically named `bounds.rs` in `hir_ty_lowering/` that I actually want most of the time :P).

Opening to check if you agree with inlining it.
r? compiler-errors or reassign
2025-02-17 06:38:14 +01:00
Matthias Krüger
fab38375bc
Rollup merge of #137095 - saethlin:use-hash64-for-hashes, r=workingjubilee
Replace some u64 hashes with Hash64

I introduced the Hash64 and Hash128 types in https://github.com/rust-lang/rust/pull/110083, essentially as a mechanism to prevent hashes from landing in our leb128 encoding paths. If you just have a u64 or u128 field in a struct then derive Encodable/Decodable, that number gets leb128 encoding. So if you need to store a hash or some other value which behaves very close to a hash, don't store it as a u64.

This reverts part of https://github.com/rust-lang/rust/pull/117603, which turned an encoded Hash64 into a u64.

Based on https://github.com/rust-lang/rust/pull/110083, I don't expect this to be perf-sensitive on its own, though I expect that it may help stabilize some of the small rmeta size fluctuations we currently see in perf reports.
2025-02-17 06:38:14 +01:00
Matthias Krüger
0c051c8196
Rollup merge of #136671 - nnethercote:middle-limits, r=Nadrieril
Overhaul `rustc_middle::limits`

In particular, to make `pattern_complexity` work more like other limits, which then enables some other simplifications.

r? ``@Nadrieril``
2025-02-17 06:37:35 +01:00
Matthias Krüger
f3a4f1a02a
Rollup merge of #136466 - nnethercote:start-removing-Map, r=cjgillot
Start removing `rustc_middle::hir::map::Map`

`rustc_middle::hir::map::Map` is now just a low-value wrapper around `TyCtxt`. This PR starts removing it.

r? `@cjgillot`
2025-02-17 06:37:35 +01:00
Nicholas Nethercote
f666361caa Remove TyCtxt::hir_krate.
It's a trivial wrapper around the `hir_crate` query with a small number
of uses.
2025-02-17 13:24:40 +11:00
Nicholas Nethercote
661f99ba03 Overhaul the intravisit::Map trait.
First of all, note that `Map` has three different relevant meanings.
- The `intravisit::Map` trait.
- The `map::Map` struct.
- The `NestedFilter::Map` associated type.

The `intravisit::Map` trait is impl'd twice.
- For `!`, where the methods are all unreachable.
- For `map::Map`, which gets HIR stuff from the `TyCtxt`.

As part of getting rid of `map::Map`, this commit changes `impl
intravisit::Map for map::Map` to `impl intravisit::Map for TyCtxt`. It's
fairly straightforward except various things are renamed, because the
existing names would no longer have made sense.

- `trait intravisit::Map` becomes `trait intravisit::HirTyCtxt`, so named
  because it gets some HIR stuff from a `TyCtxt`.
- `NestedFilter::Map` assoc type becomes `NestedFilter::MaybeTyCtxt`,
  because it's always `!` or `TyCtxt`.
- `Visitor::nested_visit_map` becomes `Visitor::maybe_tcx`.

I deliberately made the new trait and associated type names different to
avoid the old `type Map: Map` situation, which I found confusing. We now
have `type MaybeTyCtxt: HirTyCtxt`.
2025-02-17 13:21:35 +11:00
Nicholas Nethercote
f86f7ad5f2 Move some Map methods onto TyCtxt.
The end goal is to eliminate `Map` altogether.

I added a `hir_` prefix to all of them, that seemed simplest. The
exceptions are `module_items` which became `hir_module_free_items` because
there was already a `hir_module_items`, and `items` which became
`hir_free_items` for consistency with `hir_module_free_items`.
2025-02-17 13:21:02 +11:00
Nicholas Nethercote
cd1d84cdf7 Remove unused Map::hir_node_by_def_id method. 2025-02-17 09:53:27 +11:00
Nicholas Nethercote
6021ba0668 Rename rustc_middle/src/hir/map/mod.rs as map.rs.
There is no need for the extra subdirectory, and this makes the `map`
module consistent with its sibling modules `nested_filter` and `place`.
2025-02-17 09:53:27 +11:00
Nicholas Nethercote
db1ca60470 Update and clarify the comment on SwitchTargets. 2025-02-17 09:51:37 +11:00
Nicholas Nethercote
8403d39dce Add SwitchTargetValue.
This is much clearer than `Option<u128>`.
2025-02-17 09:51:37 +11:00
Nicholas Nethercote
23dbff88f6 Add a useful comment. 2025-02-17 09:51:34 +11:00
Nicholas Nethercote
223c95fd59 Move rustc_middle::limits to rustc_interface.
It's always good to make `rustc_middle` smaller. `rustc_interface` is
the best destination, because it's the only crate that calls
`get_recursive_limit`.
2025-02-17 09:30:39 +11:00
Nicholas Nethercote
13280eed6a Improve comments about limits. 2025-02-17 09:30:37 +11:00
Nicholas Nethercote
30b8c84de6 Merge get_limit and get_limit_size.
Thanks to the previous commit, they no longer need to be separate.
2025-02-17 09:30:35 +11:00
Nicholas Nethercote
b023671ce2 Add pattern_complexity_limit to Limits.
It's similar to the other limits, e.g. obtained via `get_limit`. So it
makes sense to handle it consistently with the other limits. We now use
`Limit`/`usize` in most places instead of `Option<usize>`, so we use
`Limit::new(usize::MAX)`/`usize::MAX` to emulate how `None` used to work.

The commit also adds `Limit::unlimited`.
2025-02-17 09:30:33 +11:00
Ben Kimock
4cf21866e8 Move hashes from rustc_data_structure to rustc_hashes so they can be shared with rust-analyzer 2025-02-16 16:18:30 -05:00
Scott McMurray
7e35729bfc Don't project into NonNull when dropping a Box 2025-02-15 23:20:52 -08:00
León Orell Valerian Liehr
84bdc5de6e
HIR analysis: Remove unnecessary abstraction over list of clauses 2025-02-15 23:54:53 +01:00
Ben Kimock
1d7cf0ff40 Replace some u64 hashes with Hash64 2025-02-15 13:59:09 -05:00
Jubilee
181458bc1c
Rollup merge of #137002 - chenyukang:fix-early-lint-check-desc, r=compiler-errors
Fix early lint check desc in query

When I debugging this issue: https://github.com/rust-lang/rust/pull/136906#discussion_r1954151036

I found early lint checking is performed after [macro expansion](37520e6d89/compiler/rustc_interface/src/passes.rs (L267)), but [prior to AST lowering](37520e6d89/compiler/rustc_ast_lowering/src/lib.rs (L427)).

r? ``@cjgillot``
2025-02-14 14:05:25 -08:00
Nicholas Nethercote
28b75a384e Move MirPatch from rustc_middle to rustc_mir_transform.
Because it's only used in `rustc_mir_transform`. (Presumably it is
currently in `rustc_middle` because lots of other MIR-related stuff is,
but that's not a hard requirement.) And because `rustc_middle` is huge
and it's always good to make it smaller.
2025-02-14 16:15:57 +11:00
yukang
37520e6d89 Fix early lint check desc in query 2025-02-14 09:49:57 +08:00
bors
c241e14650 Auto merge of #136593 - lukas-code:ty-value-perf, r=oli-obk
valtree performance tuning

Summary: This PR makes type checking of code with many type-level constants faster.

After https://github.com/rust-lang/rust/pull/136180 was merged, we observed a small perf regression (https://github.com/rust-lang/rust/pull/136318#issuecomment-2635562821). This happened because that PR introduced additional copies in the fast reject code path for consts, which is very hot for certain crates: 6c1d960d88/compiler/rustc_type_ir/src/fast_reject.rs (L486-L487)

This PR improves the performance again by properly interning the valtrees so that copying and comparing them becomes faster. This will become especially useful with `feature(adt_const_params)`, so the fast reject code doesn't have to do a deep compare of the valtrees.

Note that we can't just compare the interned consts themselves in the fast reject, because sometimes `'static` lifetimes in the type are be replaced with inference variables (due to canonicalization) on one side but not the other.

A less invasive alternative that I considered is simply avoiding copies introduced by https://github.com/rust-lang/rust/pull/136180 and comparing the valtrees it in-place (see commit: 9e91e50ac5 / perf results: https://github.com/rust-lang/rust/pull/136593#issuecomment-2642303245), however that was still measurably slower than interning.

There are some minor regressions in secondary benchmarks: These happen due to changes in memory allocations and seem acceptable to me. The crates that make heavy use of valtrees show no significant changes in memory usage.
2025-02-13 15:27:30 +00:00
Michael Goulet
516afd557c Implement and use BikeshedGuaranteedNoDrop for union/unsafe field validity 2025-02-13 03:45:04 +00:00
Lukas Markeffsky
885e0f1b96 intern valtrees 2025-02-13 00:38:17 +01:00
bors
6dce9f8c2d Auto merge of #135994 - 1c3t3a:rename-unsafe-ptr, r=oli-obk
Rename rustc_middle::Ty::is_unsafe_ptr to is_raw_ptr

The wording unsafe pointer is less common and not mentioned in a lot of places, instead this is usually called a "raw pointer". For the sake of uniformity, we rename this method.
This came up during the review of
https://github.com/rust-lang/rust/pull/134424.

r? `@Noratrieb`
2025-02-12 23:18:14 +00:00
Guillaume Gomez
54b4b1c902
Rollup merge of #136907 - workingjubilee:middle-errors-cleanup, r=compiler-errors
compiler: Make middle errors `pub(crate)` and bury the dead code
2025-02-12 20:30:55 +01:00
bors
33d92df3e6 Auto merge of #136905 - matthiaskrgr:rollup-8zwcgta, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #135549 (Document some safety constraints and use more safe wrappers)
 - #135965 (In "specify type" suggestion, skip type params that are already known)
 - #136193 (Implement pattern type ffi checks)
 - #136646 (Add a TyPat in the AST to reuse the generic arg lowering logic)
 - #136874 (Change the issue number for `likely_unlikely` and `cold_path`)
 - #136884 (Lower fn items as ZST valtrees and delay a bug)
 - #136885 (i686-linux-android: increase CPU baseline to Pentium 4 (without an actual change)
 - #136891 (Check sig for errors before checking for unconstrained anonymous lifetime)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-12 06:54:18 +00:00
Jubilee Young
7564f3c8e6 compiler: Make middle errors pub(crate) and bury some dead code 2025-02-11 21:57:05 -08:00
Matthias Krüger
febb367a04
Rollup merge of #136884 - compiler-errors:fn-zst, r=BoxyUwU
Lower fn items as ZST valtrees and delay a bug

Lower it as a ZST instead of a const error, which we can handle mostly fine. Delay a bug so we don't accidentally support it tho.

r? BoxyUwU

Fixes #136855
Fixes #136853
Fixes #136854
Fixes #136337

Only added one test bc that's really the crux of the issue (fn item in array length position).
2025-02-12 06:07:39 +01:00
bors
672e3aaf28 Auto merge of #136074 - compiler-errors:deeply-normalize-next-solver, r=lcnr
Properly deeply normalize in the next solver

Turn deep normalization into a `TypeOp`. In the old solver, just dispatch to the `Normalize` type op, but in the new solver call `deeply_normalize`. I chose to separate it into a different type op b/c some normalization is a no-op in the new solver, so this distinguishes just the normalization we need for correctness.

Then use `DeeplyNormalize` in the callsites we used to be using a `CustomTypeOp` (for normalizing known type outlives obligations), and also use it to normalize function args and impl headers in the new solver.

Finally, use it to normalize signatures for WF checks in the new solver as well. This addresses https://github.com/rust-lang/trait-system-refactor-initiative/issues/146.
2025-02-12 04:04:32 +00:00
Michael Goulet
d5be3bae51 Deeply normalize signature in new solver 2025-02-11 19:24:07 +00:00
Michael Goulet
a02a982ffc Make DeeplyNormalize a real type op 2025-02-11 19:24:07 +00:00
Michael Goulet
f0cb746480 Lower fn items as ZST valtrees and delay a bug 2025-02-11 19:16:12 +00:00
Matthias Krüger
89ee41cc4c
Rollup merge of #136847 - nnethercote:simplify-intra-crate-quals, r=oli-obk
Simplify intra-crate qualifiers.

The following is a weird pattern for a file within `rustc_middle`:
```
use rustc_middle::aaa;
use crate::bbb;
```
More sensible and standard would be this:
```
use crate::{aaa, bbb};
```
I.e. we generally prefer using `crate::` to using a crate's own name. (Exceptions are things like in macros where `crate::` doesn't work because the macro is used in multiple crates.)

This commit fixes a bunch of these weird qualifiers.

r? `@jieyouxu`
2025-02-11 18:04:49 +01:00
Matthias Krüger
8ade6baa12
Rollup merge of #136833 - workingjubilee:let-the-impossible-be-impossible, r=compiler-errors
compiler: die immediately instead of handling unknown target codegen

We cannot produce anything useful if asked to compile unknown targets. We should handle the error immediately at the point of discovery instead of propagating it upward, and preferably in the simplest way: Die.

This allows cleaning up our "error-handling" spread across 5 crates.
2025-02-11 18:04:44 +01:00
Nicholas Nethercote
af6020320d Simplify intra-crate qualifiers.
The following is a weird pattern for a file within `rustc_middle`:
```
use rustc_middle::aaa;
use crate::bbb;
```
More sensible and standard would be this:
```
use crate::{aaa, bbb};
```
I.e. we generally prefer using `crate::` to using a crate's own name.
(Exceptions are things like in macros where `crate::` doesn't work
because the macro is used in multiple crates.)

This commit fixes a bunch of these weird qualifiers.
2025-02-11 14:59:13 +11:00
Jubilee Young
17716be86e compiler: die immediately instead of handling unknown target codegen
We cannot produce anything useful if asked to compile unknown targets.
We should handle the error immediately at the point of discovery instead
of propagating it upward, and preferably in the simplest way: Die.

This allows cleaning up our "error-handling" spread across 5 crates.
2025-02-10 11:04:31 -08:00
Matthias Krüger
277dda4ed3
Rollup merge of #136731 - safinaskar:parallel-2025-02-08-07-22, r=SparrowLii
rustc_middle: parallel: TyCtxt: remove "unsafe impl DynSend/DynSync"

rustc_middle: parallel: TyCtxt: remove "unsafe impl DynSend/DynSync"

We don't need to "short circuit trait resolution", because DynSend and DynSync are auto traits and thus coinductive

cc "Parallel Rustc Front-end" https://github.com/rust-lang/rust/issues/113349

r? SparrowLii

``@rustbot`` label: +WG-compiler-parallel

(rustbot sometimes ignores me and doesn't attach labels on my behalf. rustbot banned me?)
2025-02-10 16:38:27 +01:00
Bastian Kersting
432ff5e559 Extend the renaming to coerce_unsafe_ptr 2025-02-10 13:01:55 +00:00
Bastian Kersting
f842ee8245 Rename rustc_middle::Ty::is_unsafe_ptr to is_raw_ptr
The wording unsafe pointer is less common and not mentioned in a lot of
places, instead this is usually called a "raw pointer". For the sake of
uniformity, we rename this method.
This came up during the review of
https://github.com/rust-lang/rust/pull/134424.
2025-02-10 12:49:18 +00:00
Jubilee
ae732f3f65
Rollup merge of #136201 - davidv1992:eliminate-field-offset-alt, r=Mark-Simulacrum
Removed dependency on the field-offset crate, alternate approach

This is an alternate approach to reach the same goals as #136003. As it touches the core of the query system, this too probably should be evaluated for performance.

r? ``@Mark-Simulacrum``
2025-02-10 00:51:50 -08:00
Jubilee
7f8108afc8
Rollup merge of #136053 - Zalathar:defer-counters, r=saethlin
coverage: Defer part of counter-creation until codegen

Follow-up to #135481 and #135873.

One of the pleasant properties of the new counter-assignment algorithm is that we can stop partway through the process, store the intermediate state in MIR, and then resume the rest of the algorithm during codegen. This lets it take into account which parts of the control-flow graph were eliminated by MIR opts, resulting in fewer physical counters and simpler counter expressions.

Those improvements end up completely obsoleting much larger chunks of code that were previously responsible for cleaning up the coverage metadata after MIR opts, while also doing a more thorough cleanup job.

(That change also unlocks some further simplifications that I've kept out of this PR to limit its scope.)
2025-02-10 00:51:49 -08:00
Matthias Krüger
d64bd3bedd
Rollup merge of #136722 - kornelski:visit-spans, r=chenyukang
Visit all debug info in MIR Visitor

I've been experimenting with simplifying debug info in MIR inliner, and discovered that MIR Visitor doesn't reliably visit all spans. This PR adds the missing visitor calls.
2025-02-09 19:44:52 +01:00
bors
124cc92199 Auto merge of #136751 - bjorn3:update_rustfmt, r=Mark-Simulacrum
Update bootstrap compiler and rustfmt

The rustfmt version we previously used formats things differently from what the latest nightly rustfmt does. This causes issues for subtrees that get formatted both in-tree and in their own repo. Updating the rustfmt used in-tree solves those issues. Also bumped the bootstrap compiler as the stage0 update command always updates both at the same
time.
2025-02-09 15:44:16 +00:00
Michael Goulet
a61537f6c0 occured -> occurred 2025-02-08 22:28:21 +00:00
bjorn3
1fcae03369 Rustfmt 2025-02-08 22:12:13 +00:00
bors
8ad2c9724d Auto merge of #136728 - matthiaskrgr:rollup-x2qh9yt, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #136640 (Debuginfo for function ZSTs should have alignment of 8 bits, not 1 bit)
 - #136648 (Add a missing `//@ needs-symlink` to `tests/run-make/libs-through-symlinks`)
 - #136651 (Label mismatched parameters at the def site for foreign functions)
 - #136691 (Remove Linkage::Private and Linkage::Appending)
 - #136692 (add module level doc for bootstrap:utils:exec)
 - #136700 (i686-unknown-hurd-gnu: bump baseline CPU to Pentium 4)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-08 12:57:59 +00:00
Askar Safin
8eba29ac10 rustc_middle: parallel: TyCtxt: remove "unsafe impl DynSend/DynSync"
We don't need to "short circuit trait resolution", because DynSend and DynSync are auto traits and thus coinductive
2025-02-08 07:40:52 +03:00
Matthias Krüger
c9771e9590
Rollup merge of #136691 - bjorn3:linkage_cleanup, r=jieyouxu
Remove Linkage::Private and Linkage::Appending

Neither of them has any use case. Neither known nor theoretical.
2025-02-08 03:58:48 +01:00
bors
0148a2be13 Auto merge of #136713 - matthiaskrgr:rollup-sy6py39, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #135179 (Make sure to use `Receiver` trait when extracting object method candidate)
 - #136554 (Add `opt_alias_variances` and use it in outlives code)
 - #136556 ([AIX] Update tests/ui/wait-forked-but-failed-child.rs to accomodate exiting and idle processes.)
 - #136589 (Enable "jump to def" feature on rustc docs)
 - #136615 (sys: net: Add UEFI stubs)
 - #136635 (Remove outdated `base_port` calculation in std net test)
 - #136682 (Move two windows process tests to tests/ui)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-08 02:57:14 +00:00
Kornel
da4cf03f82
Visit fn_span of calls in MIR Visitor 2025-02-08 00:23:07 +00:00
Kornel
6573b6259b
super_local_decl should visit source_info before copying it
Visiting source_info first makes it consistent with other visitors
2025-02-08 00:23:05 +00:00
Matthias Krüger
7ca0fd18f6
Rollup merge of #136554 - compiler-errors:opt-alias-variances, r=lcnr
Add `opt_alias_variances` and use it in outlives code

...so to fix some subtle outlives bugs with precise capturing in traits, and eventually make it easier to compute variances for "forced unconstrained" trait lifetimes.

r? lcnr
2025-02-07 21:31:00 +01:00
Matthias Krüger
20f9e973d9
Rollup merge of #136577 - dianne:simple-pat-migration-simplification, r=Nadrieril
Pattern Migration 2024: try to suggest eliding redundant binding modifiers

This is based on #136475. Only the last commit is new.

This is a simpler, more restrictive alternative to #136496, meant to partially address #136047. If a pattern can be migrated to Rust 2024 solely by removing redundant binding modifiers, this will make that suggestion; otherwise, it uses the old suggestion of making the pattern fully explicit.

Relevant tracking issue: #131414

``@rustbot`` label A-diagnostics A-patterns A-edition-2024

r? ``@Nadrieril``
2025-02-07 18:26:27 +01:00
bjorn3
f68cd90412 Remove Linkage::Appending
It can only be used for certain LLVM internal variables like
llvm.global_ctors which users are not allowed to define.
2025-02-07 16:02:19 +00:00
bjorn3
382e4031c2 Remove Linkage::Private
This is the same as Linkage::Internal except that it doesn't emit any
symbol. Some backends may not support it and it isn't all that useful
anyway.
2025-02-07 16:02:19 +00:00
Waffle Lapkin
da9a85a1a6
stabilize feature(trait_upcasting) 2025-02-06 23:30:23 +01:00
bors
942db6782f Auto merge of #136641 - matthiaskrgr:rollup-lajwje5, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #136073 (Always compute coroutine layout for eagerly emitting recursive layout errors)
 - #136235 (Pretty print pattern type values with transmute if they don't satisfy their pattern)
 - #136311 (Ensure that we never try to monomorphize the upcasting or vtable calls of impossible dyn types)
 - #136315 (Use short ty string for binop and unop errors)
 - #136393 (Fix accidentally not emitting overflowing literals lints anymore in patterns)
 - #136435 (Simplify some code for lowering THIR patterns)
 - #136630 (Change two std process tests to not output to std{out,err}, and fix test suite stat reset in bootstrap CI test rendering)

r? `@ghost`
`@rustbot` modify labels: rollup

try-job: aarch64-gnu-debug
2025-02-06 17:08:45 +00:00
Michael Goulet
d17a4a7f9a Add opt_alias_variances and use it in outlives code 2025-02-06 15:16:27 +00:00
Matthias Krüger
c9635e51b5
Rollup merge of #136435 - Zalathar:thir-pat-stuff, r=Nadrieril
Simplify some code for lowering THIR patterns

I've been playing around with some radically different ways of storing THIR patterns, and while those experiments haven't yet produced a clear win, I have noticed various smaller things in the existing code that can be made a bit nicer.

Some of the more significant changes:
- With a little bit of extra effort (and thoughtful use of Arc), we can completely remove an entire layer of `'pat` lifetimes from the intermediate data structures used for match lowering.
- In several places, lists of THIR patterns were being double-boxed for no apparent reason.
2025-02-06 13:10:00 +01:00
Matthias Krüger
62cad970e8
Rollup merge of #136235 - oli-obk:transmuty-pat-tys, r=RalfJung
Pretty print pattern type values with transmute if they don't satisfy their pattern

Instead of printing `0_u32 is 1..`, we now print the default fallback rendering that we also use for invalid bools, chars, ...: `{transmute(0x00000000): (u32) is 1..=}`.

These cases can occur in mir dumps when const prop propagates a constant across a safety check that would prevent the actually UB value from existing. That's fine though, as it's dead code and we always need to allow UB in dead code.

follow-up to https://github.com/rust-lang/rust/pull/136176

cc ``@compiler-errors`` ``@scottmcm``

r? ``@RalfJung`` because of the interpreter changes
2025-02-06 13:09:58 +01:00
Matthias Krüger
7ca29360a7
Rollup merge of #136073 - compiler-errors:recursive-coro-always, r=oli-obk
Always compute coroutine layout for eagerly emitting recursive layout errors

Detect recursive coroutine layouts even if we don't detect opaque type recursion in the new solver. This is for two reasons:
1. It helps us detect (bad) recursive async function calls in the new solver, which due to its approach to normalization causes us to not detect this via a recursive RPIT (since the opaques are more eagerly revealed in the opaque body).
    * Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/137.
2. It helps us detect (bad) recursive async functions behind AFITs. See the AFIT test that changed for the old solver too.
3. It also greatly simplifies the recursive impl trait check, since I can remove some jankness around how it handles coroutines.
2025-02-06 13:09:57 +01:00
bors
2f92f050e8 Auto merge of #136471 - safinaskar:parallel, r=SparrowLii
tree-wide: parallel: Fully removed all `Lrc`, replaced with `Arc`

tree-wide: parallel: Fully removed all `Lrc`, replaced with `Arc`

This is continuation of https://github.com/rust-lang/rust/pull/132282 .

I'm pretty sure I did everything right. In particular, I searched all occurrences of `Lrc` in submodules and made sure that they don't need replacement.

There are other possibilities, through.

We can define `enum Lrc<T> { Rc(Rc<T>), Arc(Arc<T>) }`. Or we can make `Lrc` a union and on every clone we can read from special thread-local variable. Or we can add a generic parameter to `Lrc` and, yes, this parameter will be everywhere across all codebase.

So, if you think we should take some alternative approach, then don't merge this PR. But if it is decided to stick with `Arc`, then, please, merge.

cc "Parallel Rustc Front-end" ( https://github.com/rust-lang/rust/issues/113349 )

r? SparrowLii

`@rustbot` label WG-compiler-parallel
2025-02-06 10:50:05 +00:00
Zalathar
bd855b6c9e coverage: Remove the old code for simplifying counters after MIR opts 2025-02-06 21:44:31 +11:00
Zalathar
20d051ec87 coverage: Defer part of counter-creation until codegen 2025-02-06 21:44:31 +11:00
Zalathar
ee7dc06cf1 coverage: Store BCB node IDs in mappings, and resolve them in codegen
Even though the coverage graph itself is no longer available during codegen,
its nodes can still be used as opaque IDs.
2025-02-06 21:44:29 +11:00
Jubilee
854a710fca
Rollup merge of #136563 - nnethercote:clean-up-Trivials, r=lcnr
Clean up `Trivial*Impls` macros

They're currently quite messy. Details in the individual commit logs.

r? `@lcnr`
2025-02-05 19:53:48 -08:00
Nicholas Nethercote
d282a67d58 Fix whitespace in lift macros.
This has been bugging me for some time.
2025-02-06 13:35:01 +11:00
Nicholas Nethercote
d28678e621 Clean up trivial traversal/lift impl generator macro calls.
We have four macros for generating trivial traversal (fold/visit) and
lift impls.
- `rustc_ir::TrivialTypeTraversalImpls`
- `rustc_middle::TrivialTypeTraversalImpls`
- `rustc_middle::TrivialLiftImpls`
- `rustc_middle::TrivialTypeTraversalAndLiftImpls`

The first two are very similar. The last one just combines the second
and third one.

The macros themselves are ok, but their use is a mess. This commit does
the following.
- Removes types that no longer need a lift and/or traversal impl from
  the macro calls.
- Consolidates the macro calls into the smallest number of calls
  possible, with each one mentioning as many types as possible.
- Orders the types within those macro calls alphabetically, and makes
  the module qualification more consistent.
- Eliminates `rustc_middle::mir::type_foldable`, because the macro calls
  were merged and the manual `TypeFoldable` impls are better placed in
  `structural_impls.rs`, alongside all the other ones.

This makes the code more concise. Moving forward, it also makes it more
obvious where new types should be added.
2025-02-06 13:31:43 +11:00
Michael Goulet
d0b0b028a6 Eagerly detect coroutine recursion pre-mono when possible 2025-02-05 18:36:17 +00:00
dianne
b32a5331dc try to suggest eliding redundant binding modifiers 2025-02-05 09:17:25 -08:00
David Venhoek
62bbaa8091 Removed dependency on the field-offset crate. 2025-02-05 17:56:06 +01:00
Oli Scherer
ab3115990d Pretty print pattern type values with transmute if they don't satisfy their pattern 2025-02-05 14:56:41 +00:00
León Orell Valerian Liehr
d81701b610
Rollup merge of #128045 - pnkfelix:rustc-contracts, r=oli-obk
#[contracts::requires(...)]  + #[contracts::ensures(...)]

cc https://github.com/rust-lang/rust/issues/128044

Updated contract support: attribute syntax for preconditions and postconditions, implemented via a series of desugarings  that culminates in:
1. a compile-time flag (`-Z contract-checks`) that, similar to `-Z ub-checks`, attempts to ensure that the decision of enabling/disabling contract checks is delayed until the end user program is compiled,
2. invocations of lang-items that handle invoking the precondition,  building a checker for the post-condition, and invoking that post-condition checker at the return sites for the function, and
3. intrinsics for the actual evaluation of pre- and post-condition predicates that third-party verification tools can intercept and reinterpret for their own purposes (e.g. creating shims of behavior that abstract away the function body and replace it solely with the pre- and post-conditions).

Known issues:

 * My original intent, as described in the MCP (https://github.com/rust-lang/compiler-team/issues/759) was   to have a rustc-prefixed attribute namespace (like   rustc_contracts::requires). But I could not get things working when I tried   to do rewriting via a rustc-prefixed builtin attribute-macro. So for now it  is called `contracts::requires`.

 * Our attribute macro machinery does not provide direct support for attribute arguments that are parsed like rust expressions. I spent some time trying to add that (e.g. something that would parse the attribute arguments as an AST while treating the remainder of the items as a token-tree), but its too big a lift for me to undertake. So instead I hacked in something approximating that goal, by semi-trivially desugaring the token-tree attribute contents into internal AST constucts. This may be too fragile for the long-term.
   * (In particular, it *definitely* breaks when you try to add a contract to a function like this: `fn foo1(x: i32) -> S<{ 23 }> { ... }`, because its token-tree based search for where to inject the internal AST constructs cannot immediately see that the `{ 23 }` is within a generics list. I think we can live for this for the short-term, i.e. land the work, and continue working on it while in parallel adding a new attribute variant that takes a token-tree attribute alongside an AST annotation, which would completely resolve the issue here.)

* the *intent* of `-Z contract-checks` is that it behaves like `-Z ub-checks`, in that we do not prematurely commit to including or excluding the contract evaluation in upstream crates (most notably, `core` and `std`). But the current test suite does not actually *check* that this is the case. Ideally the test suite would be extended with a multi-crate test that explores the matrix of enabling/disabling contracts on both the upstream lib and final ("leaf") bin crates.
2025-02-05 05:03:01 +01:00
bors
e5f11af042 Auto merge of #136115 - Mark-Simulacrum:shard-alloc-id, r=RalfJung
Shard AllocMap Lock

This improves performance on many-seed parallel (-Zthreads=32) miri executions from managing to use ~8 cores to using 27-28 cores, which is about the same as what I see with the data structure proposed in https://github.com/rust-lang/rust/pull/136105 - I haven't analyzed but I suspect the sharding might actually work out better if we commonly insert "densely" since sharding would split the cache lines and the OnceVec packs locks close together. Of course, we could do something similar with the bitset lock too.

Either way, this seems like a very reasonable starting point that solves the problem ~equally well on what I can test locally.

r? `@RalfJung`
2025-02-04 23:47:45 +00:00
Matthias Krüger
b07fa7696b
Rollup merge of #136284 - oli-obk:push-zsxuwnzmonnl, r=lcnr
Allow using named consts in pattern types

This required a refactoring first: I had to stop using `hir::Pat`in `hir::TyKind::Pat` and instead create a separate `TyPat` that has `ConstArg` for range ends instead of `PatExpr`. Within the type system we should be using `ConstArg` for all constants, as otherwise we'd be maintaining two separate const systems that could diverge. The big advantage of this PR is that we now inherit all the rules from const generics and don't have a separate system. While this makes things harder for users (const generic rules wrt what is allowed in those consts), it also means we don't accidentally allow some things like referring to assoc consts or doing math on generic consts.
2025-02-04 18:49:37 +01:00
dianne
203d3109d8 experimentally label the spans for default binding modes 2025-02-04 03:18:10 -08:00
Jacob Pratt
87af17c978
Rollup merge of #136465 - nnethercote:rustc_middle-MORE, r=jieyouxu
Some `rustc_middle` cleanups

Small cleanups I found while looking closely at this code.

r? `@jieyouxu`
2025-02-04 05:38:03 -05:00
dianne
4331f55b72 highlight the whole problem subpattern when pointing out the default binding mode 2025-02-03 22:23:35 -08:00
Nicholas Nethercote
d8d6128026 Two minor use fixups.
I *think* this addresses what the `FIXME` comments are asking for.
2025-02-04 08:34:11 +11:00
Nicholas Nethercote
6606bb35a9 Fix an inconsistent import. 2025-02-04 08:34:11 +11:00
Nicholas Nethercote
bd6eb05ccd Update top-level rustc_middle comment.
- Mention THIR.
- Removed mentions of non-existent READMEs.
2025-02-04 08:34:11 +11:00
Nicholas Nethercote
0be280e52f Simplify thir_with_elements macro.
The `field_name`/`field_ty` don't need to be parameters, they can be
hardcoded.
2025-02-04 08:34:11 +11:00
Nicholas Nethercote
6d03fa7519 Remove impl_for_typed_def_id macro.
It has a single call site and removing it makes the code simpler.
Perhaps there were more uses at some point in the past?
2025-02-04 08:34:11 +11:00
Nicholas Nethercote
f89d509eb1 Remove comment duplication.
The same comments are on the `DepNodeExt` trait and the single impl of
that trait, immediately below. This commit eliminates the duplication.
2025-02-04 08:34:10 +11:00
Nicholas Nethercote
1fa9200475 Remove dep_node comment duplication.
`rustc_middle` and `rustc_query_system` both have a file called
`dep_node.rs` with a big comment at the top, and the comments are very
similar. The one in `rustc_query_system` looks like the original, and
the one in `rustc_middle` is a copy with some improvements.

This commit removes the comment from `rustc_middle` and updates the one
in `rustc_query_system` to include the improvements. I did it this way
because `rustc_query_system` is the crate that defines `DepNode`, and so
seems like the right place for the comment.
2025-02-04 08:34:10 +11:00
Nicholas Nethercote
0825202cf2 Remove unused features from rustc_middle. 2025-02-04 08:34:08 +11:00
Felix S. Klock II
bcb8565f30 Contracts core intrinsics.
These are hooks to:

  1. control whether contract checks are run
  2. allow 3rd party tools to intercept and reintepret the results of running contracts.
2025-02-03 12:53:57 -08:00
Matthias Krüger
d6f94a683c
Rollup merge of #136484 - Zalathar:query-cache-notes, r=jieyouxu
Notes on types/traits used for in-memory query caching

When the word "cache" appears in the context of the query system, it often isn't obvious whether that is referring to the in-memory query cache or the on-disk incremental cache.

For these types, we can assure the reader that they are for in-memory caching.
2025-02-03 21:11:36 +01:00
Matthias Krüger
7e0118cdd2
Rollup merge of #136430 - FedericoBruzzone:follow-up-136180, r=oli-obk
Use the type-level constant value `ty::Value` where needed

**Follow-up to #136180**

### Summary

This PR refactors functions to accept a single type-level constant value `ty::Value` instead of separate `ty::ValTree` and `ty::Ty` parameters:

- `valtree_to_const_value`: now takes `ty::Value`
- `pretty_print_const_valtree`: now takes `ty::Value`
- Uses `pretty_print_const_valtree` for formatting valtrees  when `visit_const_operand`
- Moves `try_to_raw_bytes` from `ty::Valtree` to `ty::Value`

---

r? ``@lukas-code`` ``@oli-obk``
2025-02-03 21:11:35 +01:00
FedericoBruzzone
00c61a81a0 Move try_to_raw_bytes from ty::Valtree to ty::Value
Signed-off-by: FedericoBruzzone <federico.bruzzone.i@gmail.com>
2025-02-03 18:33:27 +01:00
FedericoBruzzone
6e0dfc813c Refactor using the type-level constant value ty::Value
Signed-off-by: FedericoBruzzone <federico.bruzzone.i@gmail.com>
2025-02-03 14:19:43 +01:00
Zalathar
623d6e8ca4 Notes on types/traits used for in-memory query caching
When the word "cache" appears in the context of the query system, it often
isn't obvious whether that is referring to the in-memory query cache or the
on-disk incremental cache.

For these types, we can assure the reader that they are for in-memory caching.
2025-02-03 22:36:01 +11:00
许杰友 Jieyou Xu (Joe)
5bd0f32378
Rollup merge of #136464 - nnethercote:rm-TyCtxtAt-for-hooks, r=oli-obk
Remove hook calling via `TyCtxtAt`.

All hooks receive a `TyCtxtAt` argument.

Currently hooks can be called through `TyCtxtAt` or `TyCtxt`. In the latter case, a `TyCtxtAt` is constructed with a dummy span and passed to the hook.

However, in practice hooks are never called through `TyCtxtAt`, and always receive a dummy span. (I confirmed this via code inspection, and double-checked it by temporarily making the `TyCtxtAt` code path panic and running all the tests.)

This commit removes all the `TyCtxtAt` machinery for hooks. All hooks now receive `TyCtxt` instead of `TyCtxtAt`. There are two existing hooks that use `TyCtxtAt::span`: `const_caller_location_provider` and `try_destructure_mir_constant_for_user_output`. For both hooks the span is always a dummy span, probably unintentionally. This dummy span use is now explicit. If a non-dummy span is needed for these two hooks it would be easy to add it as an extra argument because hooks are less constrained than queries.

r? `@oli-obk`
2025-02-03 19:13:29 +08:00
许杰友 Jieyou Xu (Joe)
40d1cb406d
Rollup merge of #136455 - nnethercote:less-Clone, r=compiler-errors
Remove some `Clone` bounds and derives.

r? `@cjgillot`
2025-02-03 19:13:28 +08:00
Askar Safin
0a21f1d0a2 tree-wide: parallel: Fully removed all Lrc, replaced with Arc 2025-02-03 13:25:57 +03:00
dianne
bdc6c4d07b reword pattern migration diagnostic to make sense in all editions
This aligns the main error message a bit more with the phrasing in the
Edition Guide and provides a bit more information on the labels to
(hopefully!) aid in understanding.
2025-02-03 01:50:14 -08:00
Oli Scherer
f0308938ba Use a different hir type for patterns in pattern types than we use in match patterns 2025-02-03 08:18:30 +00:00
bors
7daf4cf911 Auto merge of #133138 - azhogin:azhogin/target-modifiers, r=davidtwco,saethlin
Target modifiers (special marked options) are recorded in metainfo

Target modifiers (special marked options) are recorded in metainfo and compared to be equal in different linked crates.

PR for this RFC: https://github.com/rust-lang/rfcs/pull/3716

Option may be marked as `TARGET_MODIFIER`, example: `regparm: Option<u32> = (None, parse_opt_number, [TRACKED TARGET_MODIFIER]`.
If an TARGET_MODIFIER-marked option has non-default value, it will be recorded in crate metainfo as a `Vec<TargetModifier>`:
```
pub struct TargetModifier {
    pub opt: OptionsTargetModifiers,
    pub value_name: String,
}
```

OptionsTargetModifiers is a macro-generated enum.

Option value code (for comparison) is generated using `Debug` trait.

Error example:
```
error: mixing `-Zregparm` will cause an ABI mismatch in crate `incompatible_regparm`
  --> $DIR/incompatible_regparm.rs:10:1
   |
LL | #![crate_type = "lib"]
   | ^
   |
   = help: the `-Zregparm` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely
   = note: `-Zregparm=1` in this crate is incompatible with `-Zregparm=2` in dependency `wrong_regparm`
   = help: set `-Zregparm=2` in this crate or `-Zregparm=1` in `wrong_regparm`
   = help: if you are sure this will not cause problems, use `-Cunsafe-allow-abi-mismatch=regparm` to silence this error

error: aborting due to 1 previous error
```

`-Cunsafe-allow-abi-mismatch=regparm,reg-struct-return` to disable list of flags.
2025-02-03 07:16:57 +00:00
Nicholas Nethercote
e661514bda Remove hook calling via TyCtxtAt.
All hooks receive a `TyCtxtAt` argument.

Currently hooks can be called through `TyCtxtAt` or `TyCtxt`. In the
latter case, a `TyCtxtAt` is constructed with a dummy span and passed to
the hook.

However, in practice hooks are never called through `TyCtxtAt`, and
always receive a dummy span. (I confirmed this via code inspection, and
double-checked it by temporarily making the `TyCtxtAt` code path panic
and running all the tests.)

This commit removes all the `TyCtxtAt` machinery for hooks. All hooks
now receive `TyCtxt` instead of `TyCtxtAt`. There are two existing hooks
that use `TyCtxtAt::span`: `const_caller_location_provider` and
`try_destructure_mir_constant_for_user_output`. For both hooks the span
is always a dummy span, probably unintentionally. This dummy span use is
now explicit. If a non-dummy span is needed for these two hooks it would
be easy to add it as an extra argument because hooks are less
constrained than queries.
2025-02-03 17:02:33 +11:00
Zalathar
869c7b766e Avoid double-boxing lists of THIR subpatterns 2025-02-03 16:20:53 +11:00
Zalathar
849e0364c1 Remove 'pat lifetime from some match-lowering data structures
By storing `PatRange` in an Arc, and copying a few fields out of `Pat`, we can
greatly simplify the lifetimes involved in match lowering.
2025-02-03 16:20:53 +11:00
Nicholas Nethercote
f0b6d660c9 Derive Clone on fewer THIR types.
Some of these were never necessary, and some were facilitated by the
previous commit.
2025-02-03 10:12:40 +11:00
Matthias Krüger
0429945476
Rollup merge of #136425 - nnethercote:mv-rustc_middle-infer, r=lcnr
Move `rustc_middle::infer::unify_key`

`rustc_infer` is a much better place for it.

r? `@lcnr`
2025-02-02 23:06:56 +01:00
Matthias Krüger
5bc5827636
Rollup merge of #136422 - nnethercote:convert-lint-functions, r=Noratrieb
Convert two `rustc_middle::lint` functions to `Span` methods.

`rustc_middle` is a huge crate and it's always good to move stuff out of it. There are lots of similar methods already on `Span`, so these two functions, `in_external_macro` and `is_from_async_await`, fit right in. The diff is big because `in_external_macro` is used a lot by clippy lints.

r? ``@Noratrieb``
2025-02-02 18:05:24 +01:00
Matthias Krüger
453c32d614
Rollup merge of #136394 - saethlin:clean-up-instantiation-mode, r=compiler-errors
Clean up MonoItem::instantiation_mode

More progress on cleaning up and documenting instantiation mode selection.

This should have no behavior changes at all, it just rearranges the code inside `MonoItem::instantiation_mode` to a more logical flow and I've tried to explain every choice the implementation is making.
2025-02-02 18:05:23 +01:00
Andrew Zhogin
05c88a31e7 Target modifiers (special marked options) are recorded in metainfo and compared to be equal in different crates 2025-02-02 22:12:49 +07:00
Matthias Krüger
3559a48b8e
Rollup merge of #136368 - estebank:listify, r=fee1-dead
Make comma separated lists of anything easier to make for errors

Provide a new function `listify`, meant to be used in cases similar to `pluralize!`. When you have a slice of arbitrary elements that need to be presented to the user, `listify` allows you to turn that into a list of comma separated strings.

This reduces a lot of redundant logic that happens often in diagnostics.
2025-02-02 12:31:57 +01:00
Matthias Krüger
39efaa09d6
Rollup merge of #136328 - estebank:long-ty-path, r=jieyouxu,lqd
Rework "long type names" printing logic

Make it so more type-system types can be printed in a shortened version (like `Predicate`s).

Centralize printing the information about the "full type name path".

Make the "long type path" for the file where long types are written part of `Diag`, so that it becomes easier to keep track of it, and ensure it will always will be printed out last in the diagnostic by making its addition to the output implicit.

Tweak the shortening of types in "expected/found" labels.

Remove dead file `note.rs`.
2025-02-02 12:31:56 +01:00
Matthias Krüger
58a5f891f9
Rollup merge of #136279 - Zalathar:ensure-ok, r=oli-obk
Rename `tcx.ensure()` to `tcx.ensure_ok()`, and improve the associated docs

This is all based on my archaeology for https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/.60TyCtxtEnsure.60.

The main renamings are:
- `tcx.ensure()` → `tcx.ensure_ok()`
- `tcx.ensure_with_value()` → `tcx.ensure_done()`
- Query modifier `ensure_forwards_result_if_red` → `return_result_from_ensure_ok`

Hopefully these new names are a better fit for the *actual* function and purpose of these query call modes.
2025-02-02 12:31:55 +01:00
Nicholas Nethercote
000f8c4e82 Move unify_key module.
From `rustc_middle::infer` to `rustc_infer::infer`. Because everything
in it is only used within `rustc_infer`, and no longer needs to be
`pub`. Plus it's always good to make the huge `rustc_middle` crate
smaller.
2025-02-02 17:38:19 +11:00
Nicholas Nethercote
44482a5290 Remove unused ToType trait. 2025-02-02 17:36:19 +11:00
Nicholas Nethercote
06090e89d3 Convert two rustc_middle::lint functions to Span methods.
`rustc_middle` is a huge crate and it's always good to move stuff out of
it. There are lots of similar methods already on `Span`, so these two
functions, `in_external_macro` and `is_from_async_await`, fit right in.
The diff is big because `in_external_macro` is used a lot by clippy
lints.
2025-02-02 13:57:34 +11:00
Mark Rousskov
7f1231c986 Shard AllocMap Lock
This improves performance on many-seed parallel (-Zthreads=32) miri
executions from managing to use ~8 cores to using 27-28 cores. That's
pretty reasonable scaling for the simplicity of this solution.
2025-02-01 18:24:54 -05:00
Ben Kimock
eea88f5dcb Clean up MonoItem::instantiation_mode 2025-02-01 12:57:04 -05:00
Matthias Krüger
2fd3007cbc
Rollup merge of #130514 - compiler-errors:unsafe-binders, r=oli-obk
Implement MIR lowering for unsafe binders

This is the final bit of the unsafe binders puzzle. It implements MIR, CTFE, and codegen for unsafe binders, and enforces that (for now) they are `Copy`. Later on, I'll introduce a new trait that relaxes this requirement to being "is `Copy` or `ManuallyDrop<T>`" which more closely models how we treat union fields.

Namely, wrapping unsafe binders is now `Rvalue::WrapUnsafeBinder`, which acts much like an `Rvalue::Aggregate`. Unwrapping unsafe binders are implemented as a MIR projection `ProjectionElem::UnwrapUnsafeBinder`, which acts much like `ProjectionElem::Field`.

Tracking:
- https://github.com/rust-lang/rust/issues/130516
2025-02-01 16:41:03 +01:00
Zalathar
3ae0239f85 Mark the tcx-ensure wrapper types with #[must_use] 2025-02-01 12:42:41 +11:00
Zalathar
fef46f4e07 Rename ensure_forwards_result_if_red to return_result_from_ensure_ok 2025-02-01 12:42:41 +11:00
Zalathar
9e4f10db65 Rename tcx.ensure_with_value() to tcx.ensure_done() 2025-02-01 12:42:39 +11:00
Zalathar
24cdaa146a Rename tcx.ensure() to tcx.ensure_ok() 2025-02-01 12:38:54 +11:00
Esteban Küber
0751e9036a Rework "long type names" printing logic
Make it so more type-system types can be printed in a shortened version (like `Predicate`s).

Centralize printing the information about the "full type name path".

Make the "long type path" for the file where long types are written part of `Diag`, so that it becomes easier to keep track of it, and ensure it will always will be printed out last in the diagnostic by making its addition to the output implicit.

Tweak the shortening of types in "expected/found" labels.

Remove dead file `note.rs`.
2025-01-31 20:39:01 +00:00
Esteban Küber
8e9422f94e Make comma separated lists of anything easier to make for errors
Provide a new function `listify`, meant to be used in cases similar to `pluralize!`. When you have a slice of arbitrary elements that need to be presented to the user, `listify` allows you to turn that into a list of comma separated strings.

This reduces a lot of redundant logic that happens often in diagnostics.
2025-01-31 20:36:44 +00:00
bors
854f22563c Auto merge of #136350 - matthiaskrgr:rollup-6eqfyvh, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #134531 ([rustdoc] Add `--extract-doctests` command-line flag)
 - #135860 (Compiler: Finalize dyn compatibility renaming)
 - #135992 (Improve documentation when adding a new target)
 - #136194 (Support clobber_abi in BPF inline assembly)
 - #136325 (Delay a bug when indexing unsized slices)
 - #136326 (Replace our `LLVMRustDIBuilderRef` with LLVM-C's `LLVMDIBuilderRef`)
 - #136330 (Remove unnecessary hooks)
 - #136336 (Overhaul `rustc_middle::util`)
 - #136341 (Remove myself from vacation)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 20:16:46 +00:00
Michael Goulet
fc1a9186dc Implement MIR, CTFE, and codegen for unsafe binders 2025-01-31 17:19:53 +00:00
bors
aa4cfd0809 Auto merge of #134424 - 1c3t3a:null-checks, r=saethlin
Insert null checks for pointer dereferences when debug assertions are enabled

Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a `MirPass`.

This inserts checks in the same places as the `CheckAlignment` pass and additionally
also inserts checks for `Borrows`, so code like
```rust
let ptr: *const u32 = std::ptr::null();
let val: &u32 = unsafe { &*ptr };
```
will have a check inserted on dereference. This is done because null references
are UB. The alignment check doesn't cover these places, because in `&(*ptr).field`,
the exact requirement is that the final reference must be aligned. This is something to
consider further enhancements of the alignment check.

For now this is implemented as a separate `MirPass`, to make it easy to disable
this check if necessary.

This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.

r? `@saethlin`
2025-01-31 15:56:53 +00:00
Matthias Krüger
95f746d2ef
Rollup merge of #136336 - nnethercote:overhaul-rustc_middle-util, r=jieyouxu
Overhaul `rustc_middle::util`

It's an odd module with some odd stuff in it.

r? `@Noratrieb`
2025-01-31 12:28:20 +01:00
Matthias Krüger
417aa6c1f6
Rollup merge of #136330 - nnethercote:rm-unnecessary-hooks, r=oli-obk
Remove unnecessary hooks

Some hooks can be downgraded to vanilla functions.

r? `@oli-obk`
2025-01-31 12:28:19 +01:00
Matthias Krüger
308ea7120b
Rollup merge of #135860 - fmease:compiler-mv-obj-save-dyn-compat-ii, r=jieyouxu
Compiler: Finalize dyn compatibility renaming

Update the Reference link to use the new URL fragment from https://github.com/rust-lang/reference/pull/1666 (this change has finally hit stable). Fixes a FIXME.

Follow-up to #130826.
Part of #130852.

~~Blocking it on #133372.~~ (merged)

r? ghost
2025-01-31 12:28:15 +01:00
Bastian Kersting
b151b513ba Insert null checks for pointer dereferences when debug assertions are enabled
Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a MirPass.

This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.
2025-01-31 11:13:34 +00:00
bors
7f36543a48 Auto merge of #136332 - jhpratt:rollup-aa69d0e, r=jhpratt
Rollup of 9 pull requests

Successful merges:

 - #132156 (When encountering unexpected closure return type, point at return type/expression)
 - #133429 (Autodiff Upstreaming - rustc_codegen_ssa, rustc_middle)
 - #136281 (`rustc_hir_analysis` cleanups)
 - #136297 (Fix a typo in profile-guided-optimization.md)
 - #136300 (atomic: extend compare_and_swap migration docs)
 - #136310 (normalize `*.long-type.txt` paths for compare-mode tests)
 - #136312 (Disable `overflow_delimited_expr` in edition 2024)
 - #136313 (Filter out RPITITs when suggesting unconstrained assoc type on too many generics)
 - #136323 (Fix a typo in conventions.md)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 09:42:28 +00:00
bors
25a16572a3 Auto merge of #136331 - jhpratt:rollup-curo1f4, r=jhpratt
Rollup of 8 pull requests

Successful merges:

 - #135414 (Stabilize `const_black_box`)
 - #136150 (ci: use windows 2025 for i686-mingw)
 - #136258 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 11))
 - #136270 (Remove `NamedVarMap`.)
 - #136278 (add constraint graph to polonius MIR dump)
 - #136287 (LLVM changed the nocapture attribute to captures(none))
 - #136291 (some test suite cleanups)
 - #136296 (float::min/max: mention the non-determinism around signed 0)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 06:55:04 +00:00
Jacob Pratt
c19c4b91f5
Rollup merge of #133429 - EnzymeAD:autodiff-middle, r=oli-obk
Autodiff Upstreaming - rustc_codegen_ssa, rustc_middle

This PR should not be merged until the rustc_codegen_llvm part is merged.
I will also alter it a little based on what get's shaved off from the cg_llvm PR,
and address some of the feedback I received in the other PR (including cleanups).

I am putting it already up to
1) Discuss with `@jieyouxu` if there is more work needed to add tests to this and
2) Pray that there is someone reviewing who can tell me why some of my autodiff invocations get lost.

Re 1: My test require fat-lto. I also modify the compilation pipeline. So if there are any other llvm-ir tests in the same compilation unit then I will likely break them. Luckily there are two groups who currently have the same fat-lto requirement for their GPU code which I have for my autodiff code and both groups have some plans to enable support for thin-lto. Once either that work pans out, I'll copy it over for this feature. I will also work on not changing the optimization pipeline for functions not differentiated, but that will require some thoughts and engineering, so I think it would be good to be able to run the autodiff tests isolated from the rest for now. Can you guide me here please?
For context, here are some of my tests in the samples folder: https://github.com/EnzymeAD/rustbook

Re 2: This is a pretty serious issue, since it effectively prevents publishing libraries making use of autodiff: https://github.com/EnzymeAD/rust/issues/173. For some reason my dummy code persists till the end, so the code which calls autodiff, deletes the dummy, and inserts the code to compute the derivative never gets executed. To me it looks like the rustc_autodiff attribute just get's dropped, but I don't know WHY? Any help would be super appreciated, as rustc queries look a bit voodoo to me.

Tracking:

- https://github.com/rust-lang/rust/issues/124509

r? `@jieyouxu`
2025-01-31 00:26:30 -05:00
Jacob Pratt
dcf1134386
Rollup merge of #136270 - nnethercote:rm-NamedVarMap, r=jackh726
Remove `NamedVarMap`.

`NamedVarMap` is extremely similar to `ResolveBoundVars`. The former contains two `UnordMap<ItemLocalId, T>` fields (obscured behind `ItemLocalMap` typedefs). The latter contains two
`SortedMap<ItemLocalId, T>` fields. We construct a `NamedVarMap` and then convert it into a `ResolveBoundVars` by sorting the `UnordMap`s, which is unnecessary busywork.

This commit removes `NamedVarMap` and constructs a `ResolveBoundVars` directly. `SortedMap` and `NamedVarMap` have slightly different perf characteristics during construction (e.g. speed of insertion) but this code isn't hot enough for that to matter.

A few details to note.
- A `FIXME` comment is removed.
- The detailed comments on the fields of `NamedVarMap` are copied to `ResolveBoundVars` (which has a single, incorrect comment).
- `BoundVarContext::map` is renamed.
- `ResolveBoundVars` gets a derived `Default` impl.

r? `@jackh726`
2025-01-31 00:25:36 -05:00
Nicholas Nethercote
0c47091006 Overhaul to_readable_str.
It's a function that prints numbers with underscores inserted for
readability (e.g. "1_234_567"), used by `-Zmeta-stats` and
`-Zinput-stats`. It's the only thing in `rustc_middle::util::common`,
which is a bizarre location for it.

This commit:
- moves it to `rustc_data_structures`, a more logical crate for it;
- puts it in a module `thousands`, like the similar crates.io crate;
- renames it `format_with_underscores`, which is a clearer name;
- rewrites it to be more concise;
- slightly improves the testing.
2025-01-31 16:04:13 +11:00
Nicholas Nethercote
4ced93ed35 Don't export the Trivial* macros.
They're only used within the crate.
2025-01-31 16:04:13 +11:00
Nicholas Nethercote
140817380c Move find_self_call.
It's a function that does stuff with MIR and yet it weirdly has its own
module in `rustc_middle::util`. This commit moves it into
`rustc_middle::mir`, a more sensible home.
2025-01-31 16:04:13 +11:00
Nicholas Nethercote
3f5e218581 Give a better explanation for having bug_fmt and span_bug_fmt. 2025-01-31 16:04:07 +11:00
Nicholas Nethercote
1d2cb611f7 Remove the mir_build hook.
It was downgraded from a query in #122721 but it can just be a vanilla
function because it's not called in `rustc_middle`.
2025-01-31 15:15:01 +11:00
Nicholas Nethercote
4b025ca083 Remove the thir_{tree,flat} hooks.
They were downgraded from queries in #123995 but they can just be
vanilla functions because they are not called in `rustc_middle`.
2025-01-31 15:13:51 +11:00
Nicholas Nethercote
be1aa7bb2a Add/clarify comments about hooks.
Explaining things that weren't clear to me at first.
2025-01-31 15:11:09 +11:00
bors
c37fbd873a Auto merge of #135318 - compiler-errors:vtable-fixes, r=lcnr
Fix deduplication mismatches in vtables leading to upcasting unsoundness

We currently have two cases where subtleties in supertraits can trigger disagreements in the vtable layout, e.g. leading to a different vtable layout being accessed at a callsite compared to what was prepared during unsizing. Namely:

### #135315

In this example, we were not normalizing supertraits when preparing vtables. In the example,

```
trait Supertrait<T> {
    fn _print_numbers(&self, mem: &[usize; 100]) {
        println!("{mem:?}");
    }
}
impl<T> Supertrait<T> for () {}

trait Identity {
    type Selff;
}
impl<Selff> Identity for Selff {
    type Selff = Selff;
}

trait Middle<T>: Supertrait<()> + Supertrait<T> {
    fn say_hello(&self, _: &usize) {
        println!("Hello!");
    }
}
impl<T> Middle<T> for () {}

trait Trait: Middle<<() as Identity>::Selff> {}
impl Trait for () {}

fn main() {
    (&() as &dyn Trait as &dyn Middle<()>).say_hello(&0);
}
```

When we prepare `dyn Trait`, we see a supertrait of `Middle<<() as Identity>::Selff>`, which itself has two supertraits `Supertrait<()>` and `Supertrait<<() as Identity>::Selff>`. These two supertraits are identical, but they are not duplicated because we were using structural equality and *not* considering normalization. This leads to a vtable layout with two trait pointers.

When we upcast to `dyn Middle<()>`, those two supertraits are now the same, leading to a vtable layout with only one trait pointer. This leads to an offset error, and we call the wrong method.

### #135316

This one is a bit more interesting, and is the bulk of the changes in this PR. It's a bit similar, except it uses binder equality instead of normalization to make the compiler get confused about two vtable layouts. In the example,

```
trait Supertrait<T> {
    fn _print_numbers(&self, mem: &[usize; 100]) {
        println!("{mem:?}");
    }
}
impl<T> Supertrait<T> for () {}

trait Trait<T, U>: Supertrait<T> + Supertrait<U> {
    fn say_hello(&self, _: &usize) {
        println!("Hello!");
    }
}
impl<T, U> Trait<T, U> for () {}

fn main() {
    (&() as &'static dyn for<'a> Trait<&'static (), &'a ()>
        as &'static dyn Trait<&'static (), &'static ()>)
        .say_hello(&0);
}
```

When we prepare the vtable for `dyn for<'a> Trait<&'static (), &'a ()>`, we currently consider the PolyTraitRef of the vtable as the key for a supertrait. This leads two two supertraits -- `Supertrait<&'static ()>` and `for<'a> Supertrait<&'a ()>`.

However, we can upcast[^up] without offsetting the vtable from `dyn for<'a> Trait<&'static (), &'a ()>` to `dyn Trait<&'static (), &'static ()>`. This is just instantiating the principal trait ref for a specific `'a = 'static`. However, when considering those supertraits, we now have only one distinct supertrait -- `Supertrait<&'static ()>` (which is deduplicated since there are two supertraits with the same substitutions). This leads to similar offsetting issues, leading to the wrong method being called.

[^up]: I say upcast but this is a cast that is allowed on stable, since it's not changing the vtable at all, just instantiating the binder of the principal trait ref for some lifetime.

The solution here is to recognize that a vtable isn't really meaningfully higher ranked, and to just treat a vtable as corresponding to a `TraitRef` so we can do this deduplication more faithfully. That is to say, the vtable for `dyn for<'a> Tr<'a>` and `dyn Tr<'x>` are always identical, since they both would correspond to a set of free regions on an impl... Do note that `Tr<for<'a> fn(&'a ())>` and `Tr<fn(&'static ())>` are still distinct.

----

There's a bit more that can be cleaned up. In codegen, we can stop using `PolyExistentialTraitRef` basically everywhere. We can also fix SMIR to stop storing `PolyExistentialTraitRef` in its vtable allocations.

As for testing, it's difficult to actually turn this into something that can be tested with `rustc_dump_vtable`, since having multiple supertraits that are identical is a recipe for ambiguity errors. Maybe someone else is more creative with getting that attr to work, since the tests I added being run-pass tests is a bit unsatisfying. Miri also doesn't help here, since it doesn't really generate vtables that are offset by an index in the same way as codegen.

r? `@lcnr` for the vibe check? Or reassign, idk. Maybe let's talk about whether this makes sense.

<sup>(I guess an alternative would also be to not do any deduplication of vtable supertraits (or only a really conservative subset) rather than trying to normalize and deduplicate more faithfully here. Not sure if that works and is sufficient tho.)</sup>

cc `@steffahn` -- ty for the minimizations
cc `@WaffleLapkin` -- since you're overseeing the feature stabilization :3

Fixes #135315
Fixes #135316
2025-01-31 04:09:11 +00:00
bors
6c1d960d88 Auto merge of #136318 - matthiaskrgr:rollup-a159mzo, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #135026 (Cast global variables to default address space)
 - #135475 (uefi: Implement path)
 - #135852 (Add `AsyncFn*` to `core` prelude)
 - #136004 (tests: Skip const OOM tests on aarch64-unknown-linux-gnu)
 - #136157 (override build profile for bootstrap tests)
 - #136180 (Introduce a wrapper for "typed valtrees" and properly check the type before extracting the value)
 - #136256 (Add release notes for 1.84.1)
 - #136271 (Remove minor future footgun in `impl Debug for MaybeUninit`)
 - #136288 (Improve documentation for file locking)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-30 23:11:38 +00:00
Nicholas Nethercote
635c6d0eac Simplify bug! and span_bug!.
Three rules can be combined into one. I based this change on the
definition of `print!`.
2025-01-31 09:01:40 +11:00
Lukas Markeffsky
ca3ff832e3 add comments 2025-01-30 18:13:16 +01:00
Lukas Markeffsky
0055fb92db check the types in ty::Value to value conversion
and remove `ty::Const::try_to_scalar` because it becomes redundant
2025-01-30 18:13:16 +01:00
Lukas Markeffsky
10fc0b159e introduce ty::Value
Co-authored-by: FedericoBruzzone <federico.bruzzone.i@gmail.com>
2025-01-30 17:47:44 +01:00
Michael Goulet
fdc4bd22b7 Do not treat vtable supertraits as distinct when bound with different bound vars 2025-01-30 15:33:58 +00:00
Matthias Krüger
aab61ad663
Rollup merge of #136179 - oli-obk:push-vxvyttorquxw, r=BoxyUwU
Allow transmuting generic pattern types to and from their base

Pattern types always have the same size as their base type, so we can just ignore the pattern and look at the base type for figuring out whether transmuting is possible.
2025-01-30 12:45:32 +01:00
Manuel Drehwald
1f30517d40 upstream rustc_codegen_ssa/rustc_middle changes for enzyme/autodiff 2025-01-29 21:31:13 -05:00
bors
5e5567993d Auto merge of #136035 - SpecificProtagonist:miri-zeroed-alloc, r=oli-obk
miri: optimize zeroed alloc

When allocating zero-initialized memory in MIR interpretation, rustc allocates zeroed memory, marks it as initialized and then re-zeroes it. Remove the last step.

I don't expect this to have much of an effect on performance normally, but in my case in which I'm creating a large allocation via mmap it gets in the way.
2025-01-30 01:27:21 +00:00
Nicholas Nethercote
022c0ce947 Remove NamedVarMap.
`NamedVarMap` is extremely similar to `ResolveBoundVars`. The former
contains two `UnordMap<ItemLocalId, T>` fields (obscured behind
`ItemLocalMap` typedefs). The latter contains two
`SortedMap<ItemLocalId, T>` fields. We construct a `NamedVarMap` and
then convert it into a `ResolveBoundVars` by sorting the `UnordMap`s,
which is unnecessary busywork.

This commit removes `NamedVarMap` and constructs a `ResolveBoundVars`
directly. `SortedMap` and `NamedVarMap` have slightly different
perf characteristics during construction (e.g. speed of insertion) but
this code isn't hot enough for that to matter.

A few details to note.
- A `FIXME` comment is removed.
- The detailed comments on the fields of `NamedVarMap` are copied to
  `ResolveBoundVars` (which has a single, incorrect comment).
- `BoundVarContext::map` is renamed.
- `ResolveBoundVars` gets a derived `Default` impl.
2025-01-30 09:39:52 +11:00
bors
0cc4f4f7b8 Auto merge of #136248 - matthiaskrgr:rollup-leaxgfd, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #133382 (Suggest considering casting fn item as fn pointer in more cases)
 - #136092 (Test pipes also when not running on Windows and Linux simultaneously)
 - #136190 (Remove duplicated code in RISC-V asm bad-reg test)
 - #136192 (ci: remove unused windows runner)
 - #136205 (Properly check that array length is valid type during built-in unsizing in index)
 - #136211 (Update mdbook to 0.4.44)
 - #136212 (Tweak `&mut self` suggestion span)
 - #136214 (Make crate AST mutation accessible for driver callback)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-29 16:18:29 +00:00
Matthias Krüger
e8289d801c
Rollup merge of #136205 - compiler-errors:len-3, r=BoxyUwU
Properly check that array length is valid type during built-in unsizing in index

This results in duplicated errors, but this class of errors is not new; in general, we aren't really equipped to detect cases where a WF error due to a field type would be shadowed by the parent struct of that field also not being WF.

This also adds a note for these types of mismatches to make it clear that this is due to an array type.

Fixes #134352

r? boxyuwu
2025-01-29 15:29:41 +01:00
bors
a1d7676d6a Auto merge of #136227 - fmease:rollup-ewpvznh, r=fmease
Rollup of 9 pull requests

Successful merges:

 - #136121 (Deduplicate operand creation between scalars, non-scalars and string patterns)
 - #136134 (Fix SIMD codegen tests on LLVM 20)
 - #136153 (Locate asan-odr-win with other sanitizer tests)
 - #136161 (rustdoc: add nobuild typescript checking to our JS)
 - #136166 (interpret: is_alloc_live: check global allocs last)
 - #136168 (GCI: Don't try to eval / collect mono items inside overly generic free const items)
 - #136170 (Reject unsound toggling of Arm atomics-32 target feature)
 - #136176 (Render pattern types nicely in mir dumps)
 - #136186 (uefi: process: Fix args)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-29 11:27:18 +00:00
Oli Scherer
a639e276f3 Allow transmuting generic pattern types to and from their base 2025-01-29 10:25:55 +00:00
León Orell Valerian Liehr
f49ad60fee
Rollup merge of #136176 - oli-obk:pattern-type-mir-opts, r=compiler-errors
Render pattern types nicely in mir dumps

avoid falling through to the fallback rendering that just does a hex dump

r? ``@scottmcm``

best reviewed commit by commit
2025-01-29 06:03:24 +01:00
Michael Goulet
009d68740f Make item self/non-self bound naming less whack 2025-01-28 19:08:50 +00:00
Michael Goulet
3f8ce7c973 Do not assume child bound assumptions for rigid alias 2025-01-28 19:08:50 +00:00
Michael Goulet
7e68422859 Properly check that array length is valid type during built-in unsizing in index 2025-01-28 17:52:28 +00:00
Matthias Krüger
21ddd7ab89
Rollup merge of #135748 - compiler-errors:len-2, r=RalfJung,oli-obk
Lower index bounds checking to `PtrMetadata`, this time with the right fake borrow semantics 😸

Change `Rvalue::RawRef` to take a `RawRefKind` instead of just a `Mutability`. Then introduce `RawRefKind::FakeForPtrMetadata` and use that for lowering index bounds checking to a `PtrMetadata`. This new `RawRefKind::FakeForPtrMetadata` acts like a shallow fake borrow in borrowck, which mimics the semantics of the old `Rvalue::Len` operation we're replacing.

We can then use this `RawRefKind` instead of using a span desugaring hack in CTFE.

cc ``@scottmcm`` ``@RalfJung``
2025-01-28 14:23:22 +01:00
SpecificProtagonist
eee9df43e6
miri: optimize zeroed alloc
Co-authored-by: Ralf Jung <post@ralfj.de>
2025-01-28 12:50:02 +01:00
bors
aa6f5ab18e Auto merge of #133929 - saethlin:remove-inline-in-all-cgus, r=nnethercote
Remove -Zinline-in-all-cgus and clean up tests/codegen-units/

Implementation of https://github.com/rust-lang/compiler-team/issues/814

I've taken some liberties with cleaning up the CGU partitioning tests, because that's the only place this flag was used and also mattered. I've often fought a lot with the contents of `tests/codegen-units` and it has never been clear to me when a test failure indicates a problem with my changes as opposed to a test just needing to be manually blessed. Hopefully the combination of the new README, new comments, and using `-Zprint-mono-items=lazy` in the partitioning tests improves that.

I've also deleted some of the `tests/run-make/sepcomp` tests. I think all the "sepcomp" tests have been obviated for years by better-designed (less flaky, clearer failures) test suites, but here I'm just deleting the ones I'm confident in.
2025-01-28 09:43:03 +00:00
Oli Scherer
fd6713fce1 Make mir dumps more readable 2025-01-28 08:19:31 +00:00
Ben Kimock
bf9df97660 Remove -Zinline-in-all-cgus and clean up CGU partitioning tests 2025-01-27 23:48:47 -05:00
Michael Goulet
eeecb56b73 Represent the raw pointer for a array length check as a new kind of fake borrow 2025-01-28 00:00:33 +00:00
Guillaume Gomez
3d02ce7d6b
Rollup merge of #136118 - oli-obk:push-qsslxsopnrmr, r=Zalathar
Change `collect_and_partition_mono_items` tuple return type to a struct

https://github.com/rust-lang/rust/pull/133429 will add a new field to this tuple, so it seems prudent to turn it into a struct first to avoid confusion about what the tuple elements mean.
2025-01-27 15:38:31 +01:00
Guillaume Gomez
03fdcffa1e
Rollup merge of #136114 - compiler-errors:more-idents, r=jieyouxu
Use identifiers more in diagnostics code

This should make the diagnostics code slightly more correct when rendering idents in mixed crate edition situations. Kinda a no-op, but a cleanup regardless.

r? oli-obk or reassign
2025-01-27 15:38:30 +01:00
Guillaume Gomez
a02e78871d
Rollup merge of #135988 - bjorn3:workaround_parallel_rustc_crash, r=lqd
Add a workaround for parallel rustc crashing when there are delayed bugs

This doesn't fix the root cause of this crash, but at least stops it from happening for the time being.

Workaround for https://github.com/rust-lang/rust/issues/135870
2025-01-27 15:38:25 +01:00
Oli Scherer
b24f674520 Change collect_and_partition_mono_items tuple return type to a struct 2025-01-27 09:38:12 +00:00
Michael Goulet
ac1c6c50f4 Use identifiers in diagnostics more often 2025-01-27 01:23:34 +00:00
FedericoBruzzone
cef97bce7b Add TooGeneric variant to LayoutError and emit Unknown one
- `check-pass` test for a MRE of #135020
- fail test for #135138
- switch to `TooGeneric` for checking CMSE fn signatures
- switch to `TooGeneric` for compute `SizeSkeleton` (for transmute)
- fix broken tests
2025-01-27 00:37:34 +01:00
León Orell Valerian Liehr
57b5d3af62
Compiler: Finalize dyn compatibility renaming 2025-01-26 21:20:31 +01:00
bors
d9b4598d7e Auto merge of #135753 - compiler-errors:from-ty-const, r=oli-obk
Get rid of `mir::Const::from_ty_const`

This function is strange, because it turns valtrees into `mir::Const::Value`, but the rest of the const variants stay as type system consts.

All of the callsites except for one in `instsimplify` (array length simplification of `ptr_metadata` call) just go through the valtree arm of the function, so it's easier to just create a `mir::Const` directly for those.

For the instsimplify case, if we have a type system const we should *keep* having a type system const, rather than turning it into a `mir::Const::Value`; it doesn't really matter in practice, though, bc `usize` has no padding, but it feels more principled.
2025-01-26 09:26:34 +00:00
Jacob Pratt
182ccfa11f
Rollup merge of #136031 - lqd:polonius-debugger-episode-1, r=compiler-errors
Expand polonius MIR dump

This PR starts expanding the polonius MIR:
- switches to an HTML file, to show graphs in the same document as the MIR dump, share them more easily since it's a single file that can be hosted as a gist, and also to allow for interactivity in the near future.
- adds the regular NLL MIR + polonius constraints
- embeds a mermaid version of the CFG, similar to the graphviz one, but that needs a smaller js than `dot`'s emscripten js from graphvizonline

[Here's an example](https://gistpreview.github.io/?0c18f2a59b5e24ac0f96447aa34ffe00) of how it looks.

---
In future PRs: mermaid graphs of the NLL region graph, of the NLL SCCs, of the polonius localized outlives constraints, and the interactive polonius MIR dump.

r? ```@matthewjasper```
2025-01-25 23:27:01 -05:00
Jacob Pratt
6cf4204790
Rollup merge of #135951 - yotamofek:use-debug-helpers, r=SparrowLii
Use `fmt::from_fn` in more places in the compiler

Use the unstable functions from #117729 in more places in the compiler, follow up to #135494
2025-01-25 23:27:00 -05:00
bors
f7cc13af82 Auto merge of #119286 - jyn514:linker-output, r=bjorn3
show linker output even if the linker succeeds

Show stderr and stderr by default, controlled by a new `linker_messages` lint.

fixes https://github.com/rust-lang/rust/issues/83436. fixes https://github.com/rust-lang/rust/issues/38206. cc https://rust-lang.zulipchat.com/#narrow/stream/233931-t-compiler.2Fmajor-changes/topic/uplift.20some.20-Zverbose.20calls.20and.20rename.20to.E2.80.A6.20compiler-team.23706/near/408986134

<!-- try-job: dist-x86_64-msvc -->
try-job: aarch64-apple

r? `@bjorn3`
2025-01-25 17:16:33 +00:00
Rémy Rakic
82c016846e fix terminator edges comments 2025-01-25 07:32:20 +00:00
Rémy Rakic
492d98564e extract principal MIR dump function
for cases where we want to dump the MIR to a given writer instead of a
new file as the default does.

this will be used when dumping the MIR to a buffer to process
differently, e.g. post-process to escape for an HTML dump.
2025-01-25 07:32:20 +00:00
bors
6365178a6b Auto merge of #128657 - clubby789:optimize-none, r=fee1-dead,WaffleLapkin
Add `#[optimize(none)]`

cc #54882

This extends the `optimize` attribute to add `none`, which corresponds to the LLVM `OptimizeNone` attribute.

Not sure if an MCP is required for this, happy to file one if so.
2025-01-25 05:50:36 +00:00
clubby789
5ac95a5c47 Rename OptimizeAttr::None to Default 2025-01-24 19:34:01 +00:00
Matthias Krüger
135cd69b57
Rollup merge of #135873 - Zalathar:be-prepared, r=oli-obk
coverage: Prepare for upcoming changes to counter creation

This is a collection of smaller changes to coverage instrumentation code that have been extracted from a larger PR that I'm still working on, in order to hopefully make review easier.

Each individual change should hopefully be mostly self-explanatory. One of the big goals of the upcoming PR will be to defer certain parts of counter-creation until codegen, via the query system, so that ends up being a recurring theme in these changes. Several of the changes are follow-ups to #135481.

There should be no observable change in compiler output.
2025-01-24 16:25:42 +01:00
Yotam Ofek
8b57fd9e43 use fmt::from_fn in more places, instead of using structs that impl formatting traits 2025-01-24 14:45:56 +00:00
bjorn3
bc0170a43b Add a workaround for parallel rustc crashing when there are delayed bugs
This doesn't fix the root cause of this crash, but at least stops it
from happening for the time being.
2025-01-24 12:15:11 +00:00
bors
8231e8599e Auto merge of #135272 - BoxyUwU:generic_arg_infer_reliability_2, r=compiler-errors
Forbid usage of `hir` `Infer` const/ty variants in ambiguous contexts

The feature `generic_arg_infer` allows providing `_` as an argument to const generics in order to infer them. This introduces a syntactic ambiguity as to whether generic arguments are type or const arguments. In order to get around this we introduced a fourth `GenericArg` variant, `Infer` used to represent `_` as an argument to generic parameters when we don't know if its a type or a const argument.

This made hir visitors that care about `TyKind::Infer` or `ConstArgKind::Infer` very error prone as checking for `TyKind::Infer`s in  `visit_ty` would find *some* type infer arguments but not *all* of them as they would sometimes be lowered to `GenericArg::Infer` instead.

Additionally the `visit_infer` method would previously only visit `GenericArg::Infer` not *all* infers (e.g. `TyKind::Infer`), this made it very easy to override `visit_infer` and expect it to visit all infers when in reality it would only visit *some* infers.

---

This PR aims to fix those issues by making the `TyKind` and `ConstArgKind` types generic over whether the infer types/consts are represented by `Ty/ConstArgKind::Infer` or out of line (e.g. by a `GenericArg::Infer` or accessible by overiding `visit_infer`). We then make HIR Visitors convert all const args and types to the versions where infer vars are stored out of line and call `visit_infer` in cases where a `Ty`/`Const` would previously have had a `Ty/ConstArgKind::Infer` variant:

API Summary
```rust
enum AmbigArg {}

enum Ty/ConstArgKind<Unambig = ()> {
   ...
   Infer(Unambig),
}

impl Ty/ConstArg {
  fn try_as_ambig_ty/ct(self) -> Option<Ty/ConstArg<AmbigArg>>;
}
impl Ty/ConstArg<AmbigArg> {
  fn as_unambig_ty/ct(self) -> Ty/ConstArg;
}

enum InferKind {
  Ty(Ty),
  Const(ConstArg),
  Ambig(InferArg),
}

trait Visitor {
  ...
  fn visit_ty/const_arg(&mut self, Ty/ConstArg<AmbigArg>) -> Self::Result;
  fn visit_infer(&mut self, id: HirId, sp: Span, kind: InferKind) -> Self::Result;
}

// blanket impl'd, not meant to be overriden
trait VisitorExt {
  fn visit_ty/const_arg_unambig(&mut self, Ty/ConstArg) -> Self::Result;
}

fn walk_unambig_ty/const_arg(&mut V, Ty/ConstArg) -> Self::Result;
fn walk_ty/const_arg(&mut V, Ty/ConstArg<AmbigArg>) -> Self::Result;
```

The end result is that `visit_infer` visits *all* infer args and is also the *only* way to visit an infer arg, `visit_ty` and `visit_const_arg` can now no longer encounter a `Ty/ConstArgKind::Infer`. Representing this in the type system means that it is now very difficult to mess things up, either accessing `TyKind::Infer` "just works" and you won't miss *some* type infers- or it doesn't work and you have to look at `visit_infer` or some `GenericArg::Infer` which forces you to think about the full complexity involved.

Unfortunately there is no lint right now about explicitly matching on uninhabited variants, I can't find the context for why this is the case 🤷‍♀️

I'm not convinced the framing of un/ambig ty/consts is necessarily the right one but I'm not sure what would be better. I somewhat like calling them full/partial types based on the fact that `Ty<Partial>`/`Ty<Full>` directly specifies how many of the type kinds are actually represented compared to `Ty<Ambig>` which which leaves that to the reader to figure out based on the logical consequences of it the type being in an ambiguous position.

---

tool changes have been modified in their own commits for easier reviewing by anyone getting cc'd from subtree changes. I also attempted to split out "bug fixes arising from the refactoring" into their own commit so they arent lumped in with a big general refactor commit

Fixes #112110
2025-01-24 11:12:01 +00:00
Zalathar
ff48331588 coverage: Make query coverage_ids_info return an Option
This reflects the fact that we can't compute meaningful info for a function
that wasn't instrumented and therefore doesn't have `function_coverage_info`.
2025-01-24 16:13:11 +11:00
Zalathar
8a6e06fecb Exclude mir::coverage types from TypeFoldable/TypeVisitable
These types are unlikely to ever contain type information in the foreseeable
future, so excluding them from TypeFoldable/TypeVisitable avoids some unhelpful
derive boilerplate.
2025-01-24 16:06:18 +11:00
Boxy
2bdeff2fb8 visit_x_unambig 2025-01-23 06:01:36 +00:00
Boxy
98d80e22d0 Split hir TyKind and ConstArgKind in two and update hir::Visitor 2025-01-23 06:01:36 +00:00
Boxy
0f10ba60ff Make hir::TyKind::TraitObject use tagged ptr 2025-01-23 06:01:36 +00:00
Zalathar
4c448d5163 Allow arena_cache queries to return Option<&'tcx T> 2025-01-23 13:25:37 +11:00
bors
dee7d0e730 Auto merge of #134478 - compiler-errors:attr-span, r=oli-obk
Properly record metavar spans for other expansions other than TT

This properly records metavar spans for nonterminals other than tokentree. This means that we operations like `span.to(other_span)` work correctly for macros. As you can see, other diagnostics involving metavars have improved as a result.

Fixes #132908
Alternative to #133270

cc `@ehuss`
cc `@petrochenkov`
2025-01-22 14:46:41 +00:00
Matthias Krüger
4af3ff8cd1
Rollup merge of #135706 - compiler-errors:elaborate, r=lcnr
Move `supertrait_def_ids` into the elaborate module like all other fns

It's strange that this is the only elaborate-like fn on tcx.

r? lcnr
2025-01-21 23:30:18 +01:00
bors
ed43cbcb88 Auto merge of #134299 - RalfJung:remove-start, r=compiler-errors
remove support for the (unstable) #[start] attribute

As explained by `@Noratrieb:`
`#[start]` should be deleted. It's nothing but an accidentally leaked implementation detail that's a not very useful mix between "portable" entrypoint logic and bad abstraction.

I think the way the stable user-facing entrypoint should work (and works today on stable) is pretty simple:
- `std`-using cross-platform programs should use `fn main()`. the compiler, together with `std`, will then ensure that code ends up at `main` (by having a platform-specific entrypoint that gets directed through `lang_start` in `std` to `main` - but that's just an implementation detail)
- `no_std` platform-specific programs should use `#![no_main]` and define their own platform-specific entrypoint symbol with `#[no_mangle]`, like `main`, `_start`, `WinMain` or `my_embedded_platform_wants_to_start_here`. most of them only support a single platform anyways, and need cfg for the different platform's ways of passing arguments or other things *anyways*

`#[start]` is in a super weird position of being neither of those two. It tries to pretend that it's cross-platform, but its signature is  a total lie. Those arguments are just stubbed out to zero on ~~Windows~~ wasm, for example. It also only handles the platform-specific entrypoints for a few platforms that are supported by `std`, like Windows or Unix-likes. `my_embedded_platform_wants_to_start_here` can't use it, and neither could a libc-less Linux program.
So we have an attribute that only works in some cases anyways, that has a signature that's a total lie (and a signature that, as I might want to add, has changed recently, and that I definitely would not be comfortable giving *any* stability guarantees on), and where there's a pretty easy way to get things working without it in the first place.

Note that this feature has **not** been RFCed in the first place.

*This comment was posted [in May](https://github.com/rust-lang/rust/issues/29633#issuecomment-2088596042) and so far nobody spoke up in that issue with a usecase that would require keeping the attribute.*

Closes https://github.com/rust-lang/rust/issues/29633

try-job: x86_64-gnu-nopt
try-job: x86_64-msvc-1
try-job: x86_64-msvc-2
try-job: test-various
2025-01-21 19:46:20 +00:00
Michael Goulet
45929a8f46 Move supertrait_def_ids into the elaborate module like all other fns 2025-01-21 17:36:57 +00:00
Ralf Jung
56c90dc31e remove support for the #[start] attribute 2025-01-21 06:59:15 -07:00
Oli Scherer
8876cf7181 Also generate undef scalars and scalar pairs 2025-01-21 08:22:15 +00:00
jyn
537218afb2 make it possible to silence linker warnings with a crate-level attribute
this was slightly complicated because codegen_ssa doesn't have access to a tcx.
2025-01-20 16:46:00 -05:00
Michael Goulet
e9a566002d Get rid of mir::Const::from_ty_const 2025-01-20 04:26:44 +00:00
Yotam Ofek
1951d86a35 Manual cleanup of some is_{or_none|some_and} usages 2025-01-19 20:50:43 +00:00
Yotam Ofek
264fa0fc54 Run clippy --fix for unnecessary_map_or lint 2025-01-19 19:15:00 +00:00
bors
c62b732724 Auto merge of #135709 - lqd:bring-back-len, r=compiler-errors
Temporarily bring back `Rvalue::Len`

r? `@compiler-errors` as requested in https://github.com/rust-lang/rust/issues/135671#issuecomment-2599580364

> However, in the mean time, I'd rather we not crunch trying to find and more importantly validate the soundness of a solution 🤔

Agreed. To fix the IMO P-critical #135671 for which we somehow didn't have test coverage, this PR temporarily reverts:
- https://github.com/rust-lang/rust/pull/133734
- its bugfix https://github.com/rust-lang/rust/pull/134371
- https://github.com/rust-lang/rust/pull/134330

cc `@scottmcm`

I added the few samples from that issue as a test, but we can add more in the future, in particular it seems `@steffahn` [will work on that](https://github.com/rust-lang/rust/issues/135671#issuecomment-2599714354).

Fixes #135671. And if we want to land this, it should also be nominated for beta backport.
2025-01-19 06:09:51 +00:00
bors
98572840b6 Auto merge of #135715 - matthiaskrgr:rollup-9a18sxj, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #135641 ([rustdoc] Replace module list items `ul`/`li` with `dl`/`dd`/`dt` elements)
 - #135703 (Disallow `A { .. }` if `A` has no fields)
 - #135705 (Consolidate ad-hoc MIR lints into real pass-manager-based MIR lints)
 - #135708 (Some random compiler nits)

Failed merges:

 - #135685 (Remove unused `item-row` CSS class)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-19 03:23:56 +00:00
Matthias Krüger
d810c13b92
Rollup merge of #135697 - compiler-errors:poly-trait-ref, r=lqd
Get rid of `ToPolyTraitRef`

It's generally a footgun, since it throws away `PredicatePolarity`.

This PR doesn't attempt to fix any related bugs having to do with binders or polarity; it just tries to pass through `TraitPredicate`s around instead of `TraitRef`s. There should be basically no functional changes.
2025-01-19 01:18:57 +01:00
Rémy Rakic
122a55bb44 Revert "Auto merge of #133734 - scottmcm:lower-indexing-to-ptrmetadata, r=davidtwco,RalfJung"
This reverts commit b57d93d8b9, reversing
changes made to 0aeaa5eb22.
2025-01-18 22:09:35 +00:00
Rémy Rakic
ca1c17c88d Revert "Auto merge of #134330 - scottmcm:no-more-rvalue-len, r=matthewjasper"
This reverts commit e108481f74, reversing
changes made to 303e8bd768.
2025-01-18 22:09:34 +00:00
Michael Goulet
0e98d9a3f7 Fix comment 2025-01-18 22:03:04 +00:00
Michael Goulet
2a180a93a1 Get rid of ToPolyTraitRef 2025-01-18 18:47:17 +00:00
Zalathar
6000d5c462 coverage: Remove BcbCounter and BcbExpression
Making these separate types from `CovTerm` and `Expression` was historically
very helpful, but now that most of the counter-creation work is handled by
`node_flow` they are no longer needed.
2025-01-18 22:14:16 +11:00
bors
0c2c096e1a Auto merge of #135047 - Flakebi:amdgpu-kernel-cc, r=workingjubilee
Add gpu-kernel calling convention

The amdgpu-kernel calling convention was reverted in commit f6b21e90d1 (#120495 and https://github.com/rust-lang/rust-analyzer/pull/16463) due to inactivity in the amdgpu target.

Introduce a `gpu-kernel` calling convention that translates to `ptx_kernel` or `amdgpu_kernel`, depending on the target that rust compiles for.

Tracking issue: #135467
amdgpu target tracking issue: #135024
2025-01-17 04:36:09 +00:00
bors
76a030a6c2 Auto merge of #135592 - matthiaskrgr:rollup-4t69l7i, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #134754 (Implement `use` associated items of traits)
 - #135481 (coverage: Completely overhaul counter assignment, using node-flow graphs)
 - #135504 (Allow coercing safe-to-call target_feature functions to safe fn pointers)
 - #135561 (Update docs for `-Clink-dead-code` to discourage its use)
 - #135574 (ci: mirror ubuntu:22.04 to ghcr.io)
 - #135585 (resolve symlinks of LLVM tool binaries before copying them)
 - #135588 (Add license-metadata.json to rustc-src tarball.)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-16 21:31:19 +00:00
bors
99db2737c9 Auto merge of #134504 - oli-obk:push-rltsvnyttwll, r=compiler-errors
Use trait definition cycle detection for trait alias definitions, too

fixes #133901

In general doing this for `All` is not right, but this code path is specifically for traits and trait aliases, and there we only ever use `All` for trait aliases.
2025-01-16 18:46:28 +00:00
Matthias Krüger
bbc6d16ad6
Rollup merge of #135504 - veluca93:target-feature-cast-to-fn-ptr, r=oli-obk
Allow coercing safe-to-call target_feature functions to safe fn pointers

r? oli-obk

`@oli-obk:` this is based on your PR #134353 :-)

See https://github.com/rust-lang/rust/pull/134090#issuecomment-2539422624 for the motivation behind this change.
2025-01-16 18:46:09 +01:00
Luca Versari
8fee6a7739 Coerce safe-to-call target_feature functions to fn pointers. 2025-01-16 10:54:33 +01:00
Flakebi
e7e5202978
Add gpu-kernel calling convention
The amdgpu-kernel calling convention was reverted in commit
f6b21e90d1 due to inactivity in the amdgpu
target.

Introduce a `gpu-kernel` calling convention that translates to
`ptx_kernel` or `amdgpu_kernel`, depending on the target that rust
compiles for.
2025-01-16 00:26:55 +01:00
Guillaume Gomez
369d135733
Rollup merge of #135003 - RalfJung:deprecate-allowed-through-unstable, r=davidtwco
deprecate `std::intrinsics::transmute` etc, use `std::mem::*` instead

The `rustc_allowed_through_unstable_modules` attribute lets users call `std::mem::transmute` as `std::intrinsics::transmute`. The former is a reexport of the latter, and for a long time we didn't properly check stability for reexports, so making this a hard error now would be a breaking change for little gain. But at the same time, `std::intrinsics::transmute` is not the intended path for this function, so I think it is a good idea to show a deprecation warning when that path is used. This PR implements that, for all the functions in `std::intrinsics` that carry the attribute.

I assume this will need ``@rust-lang/libs-api`` FCP.
2025-01-15 16:30:11 +01:00
bors
341f60327f Auto merge of #134353 - oli-obk:safe-target-feature-unsafe-by-default, r=wesleywiser
Treat safe target_feature functions as unsafe by default [less invasive variant]

This unblocks
* #134090

As I stated in https://github.com/rust-lang/rust/pull/134090#issuecomment-2541332415 I think the previous impl was too easy to get wrong, as by default it treated safe target feature functions as safe and had to add additional checks for when they weren't. Now the logic is inverted. By default they are unsafe and you have to explicitly handle safe target feature functions.

This is the less (imo) invasive variant of #134317, as it doesn't require changing the Safety enum, so it only affects FnDefs and nothing else, as it should.
2025-01-15 12:06:56 +00:00
Oli Scherer
50654e5384 Render fn defs with target_features attrs with the attribute 2025-01-15 08:58:17 +00:00
Ralf Jung
561a097b65 late_report_deprecation: move fast-path closer to the core logic 2025-01-15 09:36:17 +01:00
Michael Goulet
2743df848b Enforce syntactical stability of const traits in HIR 2025-01-14 19:12:08 +00:00
bors
8c39ce5b4f Auto merge of #135278 - tgross35:ignore-std-dep-crates, r=SparrowLii
Exclude dependencies of `std` for diagnostics

Currently crates in the sysroot can show up in diagnostic suggestions, such as in https://github.com/rust-lang/rust/issues/135232. To prevent this, duplicate `all_traits` into `visible_traits` which only shows traits in non-private crates.

Setting `#![feature(rustc_private)]` overrides this and makes items in private crates visible as well, since `rustc_private` enables use of `std`'s private dependencies.

This may be reviewed per-commit.

Fixes: https://github.com/rust-lang/rust/issues/135232
2025-01-14 14:15:39 +00:00
Oli Scherer
a907c56a77 Add hir::HeaderSafety to make follow up commits simpler 2025-01-14 10:54:11 +00:00
Trevor Gross
2da9accab9 Add tcx.visible_traits() and use it for producing diagnostics
Add an alternative to `tcx.all_traits()` that only shows traits that the
user might be able to use, for diagnostic purposes. With this available,
make use of it for diagnostics including associated type errors, which
is part of the problem with [1].

Includes a few comment updates for related API.

[1]: https://github.com/rust-lang/rust/issues/135232
2025-01-14 08:51:19 +00:00
Trevor Gross
9c34253762 Make #[rustc_private] override dependency visibility
Really this is always-visible override only needs to happen when the
crate is a dependency of itself. However, this is a very internal
feature, so it doesn't seem worth doing any additional filtering here.
2025-01-14 08:51:19 +00:00
Matthias Krüger
62f2c3c75c
Rollup merge of #135451 - mzacho:code-duplication, r=oli-obk
Remove code duplication when hashing query result and interning node

Refactored the duplicated code into a function.

`with_feed_task` currently passes the query key to `debug_assert!`. I believe that's a mistake, since `with_task` prints the `DepNode` which is more sensible, so this commit changes that, so it debug prints the `DepNode`.
2025-01-14 07:56:24 +01:00
bors
35c2908177 Auto merge of #135465 - jhpratt:rollup-7p93bct, r=jhpratt
Rollup of 10 pull requests

Successful merges:

 - #134498 (Fix cycle error only occurring with -Zdump-mir)
 - #134977 (Detect `mut arg: &Ty` meant to be `arg: &mut Ty` and provide structured suggestion)
 - #135390 (Re-added regression test for #122638)
 - #135393 (uefi: helpers: Introduce OwnedDevicePath)
 - #135440 (rm unnecessary `OpaqueTypeDecl` wrapper)
 - #135441 (Make sure to mark `IMPL_TRAIT_REDUNDANT_CAPTURES` as `Allow` in edition 2024)
 - #135444 (Update books)
 - #135450 (Fix emscripten-wasm-eh with unwind=abort)
 - #135452 (bootstrap: fix outdated feature name in comment)
 - #135454 (llvm: Allow sized-word rather than ymmword in tests)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-14 03:08:59 +00:00
Jacob Pratt
81f742954a
Rollup merge of #134498 - oli-obk:push-wmxynprsyxvr, r=compiler-errors
Fix cycle error only occurring with -Zdump-mir

fixes #134205

During mir dumping, we evaluate static items to render their allocations. If a static item refers to itself, its own MIR will have a reference to itself, so during mir dumping we end up evaluating the static again, causing us to try to build MIR again (mir dumping happens during MIR building).

Thus I disabled evaluation of statics during MIR dumps in case the MIR body isn't far enough along yet to be able to be guaranteed cycle free.
2025-01-13 20:43:44 -05:00
Martin Zacho
abe603212e remove code duplication when hashing query result and interning node
Refactored the duplicated code into a function.

`with_feed_task` currently passes the query key to `debug_assert!`.
This commit changes that, so it debug prints the `DepNode`, as in
`with_task`.
2025-01-13 20:25:46 +01:00
Matthias Krüger
40f5861de9
Rollup merge of #135426 - compiler-errors:no-resolve-assoc-ty, r=lcnr
Assert that `Instance::try_resolve` is only used on body-like things

`Instance::resolve` is not set up to resolve items that are not body-like things. The logic in `resolve_associated_item` very much encodes this assumption:

e7ad3ae331/compiler/rustc_ty_utils/src/instance.rs (L96-L386)

However, some diagnostics were using `Instance::resolve` on an associated type, and it was simply a lucky coicidence that nothing went wrong.

This PR adds an assertion to make sure we won't do this again in the future, and fixes two callsites:
1. `call_kind` which returns a `CallKind` enum to categorize what a call in MIR comes from, and was using `Instance::resolve` to point at the associated type `Deref::Target` for a specific self ty.
2. `MirBorrowckCtxt::explain_deref_coercion`, which was doing the same thing.

The logic was replaced with `specialization_graph::assoc_def`, which is the proper way of fetching the right `AssocItem` for a given impl.

r? `@lcnr` or re-roll :)
2025-01-13 15:57:14 +01:00
bors
3ff1b6410e Auto merge of #135167 - mzacho:depth-limit-const-eval-query, r=oli-obk
Depth limit const eval query

Currently the const-eval query doesn't have a recursion limit or timeout, causing the complier to freeze in an infinite loop, see #125718. This PR depth limits the `eval_to_const_value_raw` query (with the [`recursion_limit`](https://doc.rust-lang.org/reference/attributes/limits.html) attribute) and improves the diagnostics for query overflow errors, so spans are reported for other dep kinds than `layout_of` (e.g. `eval_to_const_value_raw`).

fixes #125718
fixes #114192
2025-01-13 10:18:26 +00:00
Michael Goulet
9bf9f5db9b Assert that Instance::try_resolve is only used on body-like things 2025-01-13 02:20:08 +00:00
Guillaume Gomez
fad3039124
Rollup merge of #135383 - BoxyUwU:cov_tag_ptr, r=compiler-errors
De-abstract tagged ptr and make it covariant

In #135272 I needed to use a tagged ptr in `hir::TyKind` in order to not regress hir type sizes. Unfortunately the existing `CopyTaggedPtr` abstraction is insufficient as it makes the `'hir` lifetime invariant.

I spent some time trying to keep existing functionality while making it covariant but in the end I realised that actually we dont use *any* of this code *anywhere* in rustc, so I've just removed everything and replaced it with a much less general abstraction that is suitable for what I need in #135272.

Idk if anyone has a preference for just keeping all the abstractions here in case anyone needs them in the future 🤷‍♀️
2025-01-12 23:08:58 +01:00
Boxy
4de8cefbdf De-abstract tagged pointer abstraction 2025-01-12 14:56:10 +00:00
Matthias Krüger
b53239668a
Rollup merge of #135378 - compiler-errors:unnecessary-stashing, r=chenyukang
Remove a bunch of diagnostic stashing that doesn't do anything

#121669 removed a bunch of conditional diagnostic stashing/canceling, but left around the `steal` calls which just emitted the error eagerly instead of canceling the diagnostic. I think that these no-op `steal` calls don't do much and are confusing to encounter, so let's remove them.

The net effect is:
1. We emit more duplicated errors, since stashing has the side effect of duplicating diagnostics. This is not a big deal, since outside of `-Zdeduplicate-diagnostics=no`, the errors are already being deduplicated by the compiler.
2. It changes the order of diagnostics, since we're no longer stashing and then later stealing the errors. I don't think this matters much for the changes that the UI test suite manifests, and it makes these errors less order dependent.
2025-01-12 12:07:58 +01:00
Michael Goulet
85c9ce6d79 Remove a bunch of diagnostic stashing that doesn't do anything 2025-01-11 19:22:06 +00:00
Matthias Krüger
076c047fe1
Rollup merge of #135314 - compiler-errors:eagerly-mono-closures, r=wesleywiser
Eagerly collect mono items for non-generic closures

This allows users to use `-Zprint-mono-items=eager` to eagerly monomorphize closures and coroutine bodies, in case they want to inspect the LLVM or ASM for those items.

`-Zprint-mono-items`, which used to be called `-Zprint-trans-items`, was originally added in https://github.com/rust-lang/rust/pull/30900:

> Eager mode is meant to be used in conjunction with incremental compilation
> where a stable set of translation items is more important than a minimal
> one. Thus, eager mode will instantiate drop-glue for every drop-able type
> in the crate, even of no drop call for that type exists (yet). It will
> also instantiate default implementations of trait methods, something that
> otherwise is only done on demand.

Although it remains an unstable option, its purpose has somewhat expanded since then, and as far as I can tell it's generally useful for cases when you want to monomorphize as many items as possible, even if they're unreachable. Specifically, it's useful for debugging since you can look at the codegen'd body of a function, since we don't emit items that are not reachable in monomorphization.

And even more specifically, it would be very to monomorphize the coroutine body of an async fn, since those you can't easily call those without a runtime. This PR enables this usecase since we now monomorphize `DefKind::Closure`.
2025-01-11 18:13:47 +01:00
Rémy Rakic
a13354bea0 rename BitSet to DenseBitSet
This should make it clearer that this bitset is dense, with the
advantages and disadvantages that it entails.
2025-01-11 11:34:01 +00:00
David Wood
f86169a58f
mir_transform: implement forced inlining
Adds `#[rustc_force_inline]` which is similar to always inlining but
reports an error if the inlining was not possible, and which always
attempts to inline annotated items, regardless of optimisation levels.
It can only be applied to free functions to guarantee that the MIR
inliner will be able to resolve calls.
2025-01-10 18:37:54 +00:00
Oli Scherer
15c01eb22c Fix cycle error only occurring with -Zdump-mir 2025-01-10 08:57:54 +00:00