2803 Commits

Author SHA1 Message Date
dianqk
90e0835004
mir: Mark Statement and BasicBlockData as #[non_exhaustive]
Ensure they are always created using constructors.
2025-07-01 07:14:13 +08:00
dianqk
24e553e6bc
mir: Use the new method for BasicBlockData 2025-06-29 20:39:13 +08:00
dianqk
9f9cd5e283
mir: Add a new method to statement
Avoid introducing a large number of changes when adding optional initialization fields.
2025-06-29 20:13:36 +08:00
bors
11ad40bb83 Auto merge of #142625 - cjgillot:inline-nocycle, r=oli-obk
Only compute recursive callees once.

Inlining MIR in a cyclic call graph may create query cycles, which are ICEs. The current implementation `mir_callgraph_reachable(inlining_candidate, being_optimized)` checks if calling `inlining_candidate` may cycle back to `being_optimized` that we are currently inlining into.

This PR replaces this device with query `mir_callgraph_cyclic(being_optimized)` which searches the call graph for all cycles going back to `being_optimized`, and returns the set of functions involved in those cycles.

This is a tradeoff:
- in the current implementation, we perform more walks, but shallower;
- in this new implementation, we perform fewer walks, but exhaust the graph.

I'd have liked to compute this using some kind of SCC, but generic parameters make resolution path-dependent, so usual graph algorithms do not apply.
2025-06-28 19:11:42 +00:00
bors
b63223c152 Auto merge of #141759 - 1c3t3a:discriminants-query, r=saethlin
Insert checks for enum discriminants when debug assertions are enabled

Similar to the existing null-pointer and alignment checks, this checks for valid enum discriminants on creation of enums through unsafe transmutes. Essentially this sanitizes patterns like the following:
```rust
let val: MyEnum = unsafe { std::mem::transmute<u32, MyEnum>(42) };
```

An extension of this check will be done in a follow-up that explicitly sanitizes for extern enum values that come into Rust from e.g. C/C++.

This check is similar to Miri's capabilities of checking for valid construction of enum values.

This PR is inspired by saethlin@'s PR
https://github.com/rust-lang/rust/pull/104862. Thank you so much for keeping this code up and the detailed comments!

I also pair-programmed large parts of this together with vabr-g@.

r? `@saethlin`
2025-06-28 10:25:00 +00:00
Matthias Krüger
2d59c4e0fe
Rollup merge of #143046 - RalfJung:zst-unsafe-cell, r=lcnr,oli-obk
const validation: properly ignore zero-sized UnsafeCell

Fixes https://github.com/rust-lang/rust/issues/142948
r? `@oli-obk`
2025-06-27 22:13:05 +02:00
Stypox
708dc15cf1
Add InterpCx::layout_of with tracing, shadowing LayoutOf 2025-06-27 11:49:22 +02:00
Bastian Kersting
1087042e22 Insert checks for enum discriminants when debug assertions are enabled
Similar to the existing nullpointer and alignment checks, this checks
for valid enum discriminants on creation of enums through unsafe
transmutes. Essentially this sanitizes patterns like the following:
```rust
let val: MyEnum = unsafe { std::mem::transmute<u32, MyEnum>(42) };
```
An extension of this check will be done in a follow-up that explicitly
sanitizes for extern enum values that come into Rust from e.g. C/C++.

This check is similar to Miri's capabilities of checking for valid
construction of enum values.

This PR is inspired by saethlin@'s PR
https://github.com/rust-lang/rust/pull/104862. Thank you so much for
keeping this code up and the detailed comments!

I also pair-programmed large parts of this together with vabr-g@.
2025-06-27 09:37:36 +00:00
Ralf Jung
7de39f55dd make size_and_align_of_mplace work on all projectable 2025-06-26 10:28:15 +02:00
Jana Dönszelmann
63c5a84b74
Rollup merge of #142724 - xizheyin:avoid_overwrite_args, r=oli-obk
Add runtime check to avoid overwrite arg in `Diag`

## Origin PR description
At first, I set up a `debug_assert` check for the arg method to make sure that `args` in `Diag` aren't easily overwritten, and I added the `remove_arg()` method, so that if you do need to overwrite an arg, then you can explicitly call `remove_arg()` to remove it first, then call `arg()` to overwrite it.

For the code before the rust-lang/rust#142015 change, it won't compile because it will report an error
```
arg `instance`already exists.
```

This PR also modifies all diagnostics that fail the check to pass the check. There are two cases of check failure:

1. ~~Between *the parent diagnostic and the subdiagnostic*, or *between the subdiagnostics* have the same field between them. In this case, I renamed the conflicting fields.~~
2. ~~For subdiagnostics stored in `Vec`, the rendering may iteratively write the same arg over and over again. In this case, I changed the auto-generation with `derive(SubDiagnostic)` to manually implementing `SubDiagnostic` and manually rendered it with `eagerly_translate()`, similar to https://github.com/rust-lang/rust/issues/142031#issuecomment-2984812090, and after rendering it I manually deleted useless arg with the newly added `remove_arg` method.~~

## Final Decision

After trying and discussing, we made a final decision.

For `#[derive(Subdiagnostic)]`, This PR made two changes:

1. After the subdiagnostic is rendered, remove all args of this subdiagnostic, which allows for usage like `Vec<Subdiag>`.
2. Store `diag.args` before setting arguments, so that you can restore the contents of the main diagnostic after deleting the arguments after subdiagnostic is rendered, to avoid deleting the main diagnostic's arg when they have the same name args.
2025-06-25 22:14:55 +02:00
xizheyin
d2d17c60bd
Add runtime check to avoid overwrite arg easily in diag and store and restore snapshot when set subdiag arg
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-06-25 21:07:16 +08:00
Camille GILLOT
2074013f44 Only store the LocalDefId instead of the whole instance. 2025-06-23 08:44:31 +00:00
Camille GILLOT
09aab29ebf Only compute recursive callees once. 2025-06-22 20:08:49 +00:00
Tomasz Miąsko
c353539109 Leave from CopyProp early when there are no replacements 2025-06-22 14:30:23 +02:00
bors
9972ebfcc2 Auto merge of #142675 - tmiasko:preserve-cache, r=oli-obk
Preserve caches in a call to shrink_to_fit

A small follow up to rust-lang/rust#142542.
2025-06-22 06:49:02 +00:00
bors
d4e1159b8c Auto merge of #142546 - cjgillot:reachable-jump, r=compiler-errors
Only traverse reachable blocks in JumpThreading.

Fixes https://github.com/rust-lang/rust/issues/131451

We only compute loop headers for reachable blocks. We shouldn't try to perform an opt on unreachable blocks anyway.
2025-06-21 18:54:29 +00:00
Trevor Gross
4455d1e57b
Rollup merge of #142571 - cjgillot:borrowed-classes, r=oli-obk
Reason about borrowed classes in CopyProp.

Fixes https://github.com/rust-lang/rust/issues/141122

The current implementation of `CopyProp` avoids unifying two borrowed locals, as this would change the result of address comparison.

However, the implementation was inconsistent with the general algorithm, which identifies equivalence classes of locals and then replaces all locals by a single representative of their equivalence class.

This PR fixes it by forbidding the unification of two *classes* if any of those contain a borrowed local.
2025-06-20 23:25:55 -04:00
Urgau
33185d3fd9
Rollup merge of #135656 - joshtriplett:hint-mostly-unused, r=saethlin
Add `-Z hint-mostly-unused` to tell rustc that most of a crate will go unused

This hint allows the compiler to optimize its operation based on this assumption, in order to compile faster. This is a hint, and does not guarantee any particular behavior.

This option can substantially speed up compilation if applied to a large dependency where the majority of the dependency does not get used. This flag may slow down compilation in other cases.

Currently, this option makes the compiler defer as much code generation as possible from functions in the crate, until later crates invoke those functions. Functions that never get invoked will never have code generated for them. For instance, if a crate provides thousands of functions, but only a few of them will get called, this flag will result in the compiler only doing code generation for the called functions. (This uses the same mechanisms as cross-crate inlining of functions.) This does not affect `extern` functions, or functions marked as `#[inline(never)]`.

This option has already existed in nightly as `-Zcross-crate-inline-threshold=always` for some time, and has gotten testing in that form. However, this option is still unstable, to give an opportunity for wider testing in this form.

Some performance numbers, based on a crate with many dependencies having just *one* large dependency set to `-Z hint-mostly-unused` (using Cargo's `profile-rustflags` option):

A release build went from 4m07s to 2m04s.

A non-release build went from 2m26s to 1m28s.
2025-06-18 19:40:30 +02:00
Tomasz Miąsko
8e266d999d Preserve caches in a call to shrink_to_fit 2025-06-18 16:16:45 +02:00
Jubilee
725d8291ab
Rollup merge of #142542 - cjgillot:invalidate-simplify-cfg, r=SparrowLii
Manually invalidate caches in SimplifyCfg.

The current `SimplifyCfg` pass unconditionally invalidates CFG caches. This is unfortunate if there are no modifications that require this invalidation.
2025-06-17 00:28:16 -07:00
Camille GILLOT
c4b67c6d87 Reason about borrowed classes in CopyProp. 2025-06-16 14:17:13 +00:00
Camille GILLOT
a2d96875a5 Add comment. 2025-06-16 12:31:36 +00:00
León Orell Valerian Liehr
e06196da5b
Rollup merge of #142347 - azhogin:azhogin/async-drop-storage-live-dead-fix, r=oli-obk
Async drop - fix for StorageLive/StorageDead codegen for pinned future

Fixes: rust-lang/rust#140429, Fixes: rust-lang/rust#140531, Fixes: rust-lang/rust#141761, Fixes: rust-lang/rust#141409.

StorageLive/StorageDead codegen is corrected for pinned async drop future.
2025-06-15 23:51:56 +02:00
Camille GILLOT
89b079d844 Only traverse reachable blocks in JumpThreading. 2025-06-15 21:12:17 +00:00
Camille GILLOT
a16b49bb93 Manually invalidate caches in SimplifyCfg. 2025-06-15 15:30:14 +00:00
Matthias Krüger
db23a76217
Rollup merge of #141811 - mejrs:bye_locals, r=compiler-errors
Unimplement unsized_locals

Implements https://github.com/rust-lang/compiler-team/issues/630

Tracking issue here: https://github.com/rust-lang/rust/issues/111942

Note that this just removes the feature, not the implementation, and does not touch `unsized_fn_params`. This is because it is required to support `Box<dyn FnOnce()>: FnOnce()`.

There may be more that should be removed (possibly in follow up prs)
- the `forget_unsized` function and `forget` intrinsic.
- the `unsized_locals` test directory; I've just fixed up the tests for now
- various codegen support for unsized values and allocas

cc ``@JakobDegen`` ``@oli-obk`` ``@Noratrieb`` ``@programmerjake`` ``@bjorn3``

``@rustbot`` label F-unsized_locals

Fixes rust-lang/rust#79409
2025-06-14 11:27:10 +02:00
Andrew Zhogin
d6a9081612 Async drop - fix for StorageLive/StorageDead codegen for pinned async drop future 2025-06-14 15:10:08 +07:00
mejrs
c0e02e26b3 Unimplement unsized_locals 2025-06-13 01:16:36 +02:00
Ralf Jung
62418f4c56 intrinsics: rename min_align_of to align_of 2025-06-12 17:50:25 +02:00
bors
bdb04d6c4f Auto merge of #141763 - lcnr:fixme-gamer, r=BoxyUwU
`FIXME(-Znext-solver)` triage

r? `@BoxyUwU`
2025-06-11 11:47:05 +00:00
bors
8ce2287586 Auto merge of #142299 - fmease:rollup-u86s80a, r=fmease
Rollup of 16 pull requests

Successful merges:

 - rust-lang/rust#134442 (Specify the behavior of `file!`)
 - rust-lang/rust#140372 (Exhaustively handle parsed attributes in CheckAttr)
 - rust-lang/rust#140766 (Stabilize keylocker)
 - rust-lang/rust#141642 (Note the version and PR of removed features when using it)
 - rust-lang/rust#141818 (Don't create .msi installer for gnullvm hosts)
 - rust-lang/rust#141909 (Add central execution context to bootstrap)
 - rust-lang/rust#141992 (use `#[naked]` for `__rust_probestack`)
 - rust-lang/rust#142101 (core::ptr: deduplicate more method docs)
 - rust-lang/rust#142102 (docs: Small clarification on the usage of read_to_string and read_to_end trait methods)
 - rust-lang/rust#142124 (Allow transmute casts in pre-runtime-MIR)
 - rust-lang/rust#142240 (deduplicate the rest of AST walker functions)
 - rust-lang/rust#142258 (platform-support.md: Mention specific Linux kernel version or later)
 - rust-lang/rust#142262 (Mark `core::slice::memchr` as `#[doc(hidden)]`)
 - rust-lang/rust#142271 (compiler: fn ptrs should hit different lints based on ABI)
 - rust-lang/rust#142275 (rustdoc: Refractor `clean_ty_generics`)
 - rust-lang/rust#142288 (const_eval: fix some outdated comments)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-06-10 17:51:43 +00:00
León Orell Valerian Liehr
e8be230f1f
Rollup merge of #142124 - oli-obk:transmute-cast, r=scottmcm
Allow transmute casts in pre-runtime-MIR

r? ``@scottmcm``

cc ``@BoxyUwU``

turns out in https://github.com/rust-lang/rust/pull/138393 I erroneously used transmute casts in fd3da4bebd/compiler/rustc_mir_build/src/builder/matches/test.rs (L209)

I don't think they have any issues using them before runtime, we just checked for them because we didn't have code exercising those code paths
2025-06-10 16:54:50 +02:00
bors
c6a955468b Auto merge of #141485 - dianqk:early_otherwise_branch_loop, r=oli-obk
mir-opt: Do not create storage marks in EarlyOtherwiseBranch

Fixes #141212.

The first commit add `StorageDead` by creating new indirect BB that makes CFG more complicated, but I think it's better to just not create storage marks.

r? mir-opt
2025-06-10 14:50:54 +00:00
bjorn3
9223704f4b Remove all unused feature gates from the compiler 2025-06-08 14:50:42 +00:00
Josh Triplett
1b23b64be4 Add -Z hint-mostly-unused to tell rustc that most of a crate will go unused
This hint allows the compiler to optimize its operation based on this
assumption, in order to compile faster. This is a hint, and does not
guarantee any particular behavior.

This option can substantially speed up compilation if applied to a large
dependency where the majority of the dependency does not get used. This flag
may slow down compilation in other cases.

Currently, this option makes the compiler defer as much code generation as
possible from functions in the crate, until later crates invoke those
functions. Functions that never get invoked will never have code generated for
them. For instance, if a crate provides thousands of functions, but only a few
of them will get called, this flag will result in the compiler only doing code
generation for the called functions. (This uses the same mechanisms as
cross-crate inlining of functions.) This does not affect `extern` functions, or
functions marked as `#[inline(never)]`.

Some performance numbers, based on a crate with many dependencies having
just *one* large dependency set to `-Z hint-mostly-unused` (using
Cargo's `profile-rustflags` option):

A release build went from 4m07s to 2m04s.

A non-release build went from 2m26s to 1m28s.
2025-06-06 19:12:00 -07:00
Guillaume Gomez
3a6f1b0375
Rollup merge of #142103 - scottmcm:fieldidx-in-interp, r=oli-obk
Update `InterpCx::project_field` to take `FieldIdx`

As suggested by Ralf in https://github.com/rust-lang/rust/pull/142005#discussion_r2125839015
2025-06-06 23:53:18 +02:00
Oli Scherer
c677dc26b4 Allow transmute casts in pre-runtime-MIR 2025-06-06 16:19:38 +00:00
Scott McMurray
8bce2255e8 Update InterpCx::project_field to take FieldIdx
As suggested by Ralf in 142005.
2025-06-05 19:15:56 -07:00
Oli Scherer
fd3da4bebd Replace some Option<Span> with Span and use DUMMY_SP instead of None 2025-06-05 14:14:59 +00:00
Matthias Krüger
9ec41bcf72
Rollup merge of #141932 - azhogin:azhogin/async-drop-inside-asyncgen-fix, r=oli-obk
Fix for async drop inside async gen fn

Return value (for yield) is corrected for async drop inside async gen function.
In CFG, when internal async drop future is polled and returned `Poll<()>::Pending`, then async gen resume function returns `Poll<(OptRet)>::Pending`.

Fixes rust-lang/rust#140530
2025-06-04 19:50:21 +02:00
Andrew Zhogin
d5a9a00518 Fix for async drop inside async gen fn 2025-06-04 18:45:34 +07:00
lcnr
7dac755be8 FIXME(-Znext-solver) triage
Co-authored-by: Michael Goulet <michael@errs.io>
2025-06-03 14:23:56 +02:00
Matthias Krüger
aed1171c66
Rollup merge of #141677 - azhogin:azhogin/async-drop-unexpected-type-instead-of-drop-fn-fix, r=oli-obk
Async drop - type instead of async drop fn, fixes #140484

Fixes: rust-lang/rust#140484
Fixes: rust-lang/rust#140500

Fixes ICE, when type is provided in AsyncDrop trait instead of `async fn drop()`.
Fixes ICE, when async drop fn has wrong signature.
2025-06-03 07:03:43 +02:00
Andrew Zhogin
f023a69f32 Async drop - type instead of async drop fn and incorrect drop signature don't ICE now 2025-06-01 15:22:29 +07:00
bors
f0999ffdc4 Auto merge of #139118 - scottmcm:slice-get-unchecked-intrinsic, r=workingjubilee
`slice.get(i)` should use a slice projection in MIR, like `slice[i]` does

`slice[i]` is built-in magic, so ends up being quite different from `slice.get(i)` in MIR, even though they're both doing nearly identical operations -- checking the length of the slice then getting a ref/ptr to the element if it's in-bounds.

This PR adds a `slice_get_unchecked` intrinsic for `impl SliceIndex for usize` to use to fix that, so it no longer needs to do a bunch of lines of pointer math and instead just gets the obvious single statement.  (This is *not* used for the range versions, since `slice[i..]` and `slice[..k]` can't use the mir Slice projection as they're using fenceposts, not indices.)

I originally tried to do this with some kind of GVN pattern, but realized that I'm pretty sure it's not legal to optimize `BinOp::Offset` to `PlaceElem::Index` without an extremely complicated condition.  Basically, the problem is that the `Index` projection on a dereferenced slice pointer *cares about the metadata*, since it's UB to `PlaceElem::Index` outside the range described by the metadata.  But then you cast the fat pointer to a thin pointer then offset it, that *ignores* the slice length metadata, so it's possible to write things that are legal with `Offset` but would be UB if translated in the obvious way to `Index`.  Checking (or even determining) the necessary conditions for that would be complicated and error-prone, whereas this intrinsic-based approach is quite straight-forward.

Zero backend changes, because it just lowers to MIR, so it's already supported naturally by CTFE/Miri/cg_llvm/cg_clif.
2025-05-31 21:38:21 +00:00
Jubilee
3846f2f08f
Rollup merge of #141494 - dianqk:match-br-non-int, r=wesleywiser
mir-opt: Do not transform non-int type in match_branches

Fixes #141378.

r? mir-opt
2025-05-30 13:52:26 -07:00
Scott McMurray
4668124cc7 slice.get(i) should use a slice projection in MIR, like slice[i] does 2025-05-30 12:04:41 -07:00
Trevor Gross
e0278ed5af
Rollup merge of #141551 - compiler-errors:hir-lints, r=BoxyUwU
Make two transmute-related MIR lints into HIR lint

Make `PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS` (rust-lang/rust#130540) and `UNNECESSARY_TRANSMUTES` (rust-lang/rust#136083) into "normal" HIR-based lints.

Funny enough this came up in the review of the latter (https://github.com/rust-lang/rust/pull/136083#issuecomment-2614301413), but I guess it just was overlooked.

But anywyas, there's no reason for these to be MIR lints; in fact, it makes the suggestions for them a bit more complicated than necessary.

Note that there's probably a few more simplifications and improvements to be done here. Follow-ups can be done in a separate PR, especially if they're about the messaging and suggestions themselves, which I didn't write.
2025-05-27 20:28:32 -04:00
Trevor Gross
ee4efa1f86
Rollup merge of #141252 - dianqk:gvn-repeat-index, r=saethlin
gvn: bail out unavoidable non-ssa locals in repeat

Fixes #141251.

We cannot transform `*elem` to `array[idx1]` in the following code, as `idx1` has already been modified.

```rust
    mir! {
        let array;
        let elem;
        {
            array = [*val; 5];
            elem = &array[idx1];
            idx1 = idx2;
            RET = *elem;
            Return()
        }
    }
```

Perhaps I could transform it to `array[0]`, but I prefer the conservative approach.

r? mir-opt
2025-05-27 20:28:31 -04:00
Zalathar
3f526eeec4 coverage: Revert "unused local file IDs" due to empty function names
This reverts commit 3b22c21dd8c30f499051fe7a758ca0e5d81eb638, reversing
changes made to 5f292eea6d63abbd26f1e6e00a0b8cf21d828d7d.
2025-05-27 23:33:29 +10:00