Various cleanups to dest prop
This makes fixing the issues identified in #105577 easier. A couple changes
- Use an enum with names instead of a bool
- Only call `remove_candidates_if` from one place instead of two. Doing it from two places is far too fragile, since any divergence in the behavior between those callsites is likely to be unsound.
- Remove `is_constant`. Right now we only merge locals, so this doesn't do anything, and the logic would be wrong if it did.
r? `@tmiasko`
Auto traits in `dyn Trait + Auto` are suggestable
Not sure why I had made the `IsSuggestableVisitor` have that rule to not consider `dyn Trait + Auto` to be suggestable.
It's possible that this was done because of the fact that we don't print the right parentheses for `&(dyn Trait + Auto)`, but that's a problem with printing these types in general that we probably have tracked somewhere else...
Ensure async trait impls are async (or otherwise return an opaque type)
As a workaround for the full `#[refine]` semantics not being implemented
yet, forbit returning a concrete future type like `Box<dyn Future>` or a
manually implemented Future.
`-> impl Future` is still permitted; while that can also cause
accidental refinement, that's behind a different feature gate
(`return_position_impl_trait_in_trait`) and that problem exists
regardless of whether the trait method is async, so will have to be
solved more generally.
Fixes https://github.com/rust-lang/rust/issues/102745
Highlight conflicting param-env candidates, again
Un-reverts #98794 (i.e. reverts #99290).
The previous time I attempted to land this PR, it was because of an incremental issue (#99233). The repro instructions in the issue is no longer manifest the ICE -- I think it's because this ambiguity code was refactored (I think by `@lcnr)` to no longer store the ambiguities in the fulfillment error, but instead recompute them on the fly.
The main motivation for trying to re-land this is that it fixes#105131 by highlighting the root-cause of the issue, which is conflicting param-env candidates:
```
error[E0283]: type annotations needed: cannot satisfy `Self: Gen<'source>`
|
note: multiple `impl`s or `where` clauses satisfying `Self: Gen<'source>` found
--> $DIR/conflicting-bounds.rs:3:1
|
LL | pub trait Gen<'source> {
| ^^^^^^^^^^^^^^^^^^^^^^
...
LL | Self: for<'s> Gen<'s, Output = T>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0283`.
```
Fixes#105131.
Fixes (again) #98786
Sync rustc_codegen_cranelift
This time there are a bunch of bugfixes, some new llvm intrinsic implementations and refactorings to the build system in preparation for running cg_clif tests as part of `./x.py test`.
r? `@ghost`
`@rustbot` label +A-codegen +A-cranelift +T-compiler
As a workaround for the full `#[refine]` semantics not being implemented
yet, forbit returning a concrete future type like `Box<dyn Future>` or a
manually implemented Future.
`-> impl Future` is still permitted; while that can also cause
accidental refinement, that's behind a different feature gate
(`return_position_impl_trait_in_trait`) and that problem exists
regardless of whether the trait method is async, so will have to be
solved more generally.
Fixes#102745
fold instead of obliterating args
Fixes#105608
we call `const_eval_resolve` on the following constant:
```
def: playground::{impl#0}::and::{constant#0},
substs: [
ConstKind::Unevaluated {
def: playground::{impl#0}::and::{constant#0},
substs: [
ConstKind::Value(0x0),
_,
]
}
_,
],
```
when expanded out to `ConstKind::Expr` there are no infer vars so we attempt to evaluate it after replacing infer vars with garbage, however the current logic for replacing with garbage replaces _the whole arg containing the infer var_ rather than just the infer var. This means that after garbage replacement has occured we attempt to evaluate:
```
def: playground::{impl#0}::and::{constant#0},
substs: [
PLACEHOLDER,
PLACEHOLDER,
],
```
Which then leads to ctfe being unable to evaluate the const. With this PR we attempt to evaluate:
```
def: playground::{impl#0}::and::{constant#0},
substs: [
ConstKind::Unevaluated {
def: playground::{impl#0}::and::{constant#0},
substs: [
ConstKind::Value(0x0),
PLACEHOLDER,
]
}
PLACEHOLDER,
],
```
which ctfe _can_ handle.
I am not entirely sure why this function is supposed to replace params with placeholders rather than just inference vars 🤔
Illegal sized bounds: only suggest mutability change if needed
In a scenario like
```rust
struct Type;
pub trait Trait {
fn function(&mut self)
where
Self: Sized;
}
impl Trait for Type {
fn function(&mut self) {}
}
fn main() {
(&mut Type as &mut dyn Trait).function();
}
```
the problem is Sized, not the mutability of self. Thus don't emit the "you need &T instead of &mut T" note, or the other way around, as all it does is just invert the mutability of whatever was supplied.
Fixes#103622.
Refine when invalid prefix case error arises
Fix cases where the "invalid base prefix for number literal" error arises with suffixes that look erroneously capitalized but which are actually invalid.
Combine `ty::Projection` and `ty::Opaque` into `ty::Alias`
Implements https://github.com/rust-lang/types-team/issues/79.
This PR consolidates `ty::Projection` and `ty::Opaque` into a single `ty::Alias`, with an `AliasKind` and `AliasTy` type (renamed from `ty::ProjectionTy`, which is the inner data of `ty::Projection`) defined as so:
```
enum AliasKind {
Projection,
Opaque,
}
struct AliasTy<'tcx> {
def_id: DefId,
substs: SubstsRef<'tcx>,
}
```
Since we don't have access to `TyCtxt` in type flags computation, and because repeatedly calling `DefKind` on the def-id is expensive, these two types are distinguished with `ty::AliasKind`, conveniently glob-imported into `ty::{Projection, Opaque}`. For example:
```diff
match ty.kind() {
- ty::Opaque(..) =>
+ ty::Alias(ty::Opaque, ..) => {}
_ => {}
}
```
This PR also consolidates match arms that treated `ty::Opaque` and `ty::Projection` identically.
r? `@ghost`
Rollup of 7 pull requests
Successful merges:
- #105147 (Allow unsafe through inline const)
- #105438 (Move some codegen-y methods from `rustc_hir_analysis::collect` -> `rustc_codegen_ssa`)
- #105464 (Support #[track_caller] on async closures)
- #105476 (Change pattern borrowing suggestions to be verbose and remove invalid suggestion)
- #105500 (Make some diagnostics not depend on the source of what they reference being available)
- #105628 (Small doc fixes)
- #105659 (Don't require owned data in `MaybeStorageLive`)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Don't require owned data in `MaybeStorageLive`
Small improvement that avoids a clone. I don't expect this to have any noticeable perf effects, but better to have it than not to.
r? ``@tmiasko``
Change pattern borrowing suggestions to be verbose and remove invalid suggestion
Synthesize a more accurate span and use verbose suggestion output to
make the message clearer.
Do not suggest borrowing binding in pattern in let else. Fix#104838.
Move some codegen-y methods from `rustc_hir_analysis::collect` -> `rustc_codegen_ssa`
Unclear if they should live here, but they seem codegen-y enough, and `rustc_hir_analysis::collect` is extremely long, so it should probably lose some methods.
Allow unsafe through inline const
Handle similar to closures.
Address https://github.com/rust-lang/rust/pull/104087#issuecomment-1324173328
Note that this PR does not fix the issue for `unsafe { [0; function_requiring_unsafe()] }`. This is fundamentally unfixable for MIR unsafeck IMO.
This PR also does not fix unsafety checking for inline const in pattern position. It actually breaks it, allowing unsafe functions to be used in inline const in pattern position without unsafe blocks. Inline const in pattern position is not visible in MIR so ignored by MIR unsafety checking (currently it is also not checked by borrow checker, which is the reason why it's considered an incomplete feature).
`@rustbot` label: +T-lang +F-inline_const
Simpler diagnostic when passing arg to closure and missing borrow
fixes#64915
I followed roughly the instructions and the older PR #76362.
The number of references for the expected and the found types will be compared and depending on which has more the diagnostic will be emitted.
I'm not quite sure if my approach with the many `span_bug!`s is good, it could lead to some ICEs. Would it be better if those errors are ignored?
As far as I know the following code works similarly but in a different context. Is this probably reusable since it looks like it would emit better diagnostics?
a688a0305f/compiler/rustc_hir_analysis/src/check/demand.rs (L713-L1061)
When running the tests locally, a codegen test failed. Is there something I can/ should do about that?
If you have some improvements/ corrections please say so and I will happily include them.
r? `@estebank` (as you added the mentoring instructions to the issue)
Remove previously existing fallback that tried to give a good turbofish
suggestion, `need_type_info` is already good enough.
Special case `::<Vec<_>` suggestion for `Iterator::collect`.
use ty::Binder in rustdoc instead of `skip_binder`
r? `@GuillaumeGomez`
this is a preliminary cleanup required to be able to normalize correctly/conveniently in rustdoc
Fix cases where the "invalid base prefix for number literal" error arises with
suffixes that look erroneously capitalized but which are in fact invalid.
Inline and remove `place_contents_drop_state_cannot_differ`.
It has a single call site and is hot enough to be worth inlining. And make sure `is_terminal_path` is inlined, too.
r? `@ghost`
Point out the type of associated types in every method call of iterator chains
Partially address #105184 by pointing out the type of associated types in every method call of iterator chains:
```
note: the expression is of type `Map<std::slice::Iter<'_, {integer}>, [closure@src/test/ui/iterators/invalid-iterator-chain.rs:12:18: 12:21]>`
--> src/test/ui/iterators/invalid-iterator-chain.rs:12:14
|
10 | vec![0, 1]
| ---------- this expression has type `Vec<{integer}>`
11 | .iter()
| ------ associated type `std::iter::Iterator::Item` is `&{integer}` here
12 | .map(|x| { x; })
| ^^^^^^^^^^^^^^^ associated type `std::iter::Iterator::Item` is `()` here
```
We also reduce the number of impls we mention when any of the candidates is an "exact match". This benefits the output of cases with numerics greatly.
Outstanding work would be to provide a structured suggestion for appropriate changes, like in this case detecting the spurious `;` in the closure.
Use struct types during codegen in less places
This makes it easier to use cg_ssa from a backend like Cranelift that doesn't have any struct types at all. After this PR struct types are still used for function arguments and return values. Removing those usages is harder but should still be doable.
Remove `token::Lit` from `ast::MetaItemLit`.
Currently `ast::MetaItemLit` represents the literal kind twice. This PR removes that redundancy. Best reviewed one commit at a time.
r? `@petrochenkov`
Fix lint perf regressions
#104863 caused small but widespread regressions in lint performance. I tried to improve things in #105291 and #105416 with minimal success, before fully understanding what caused the regression. This PR effectively reverts all of #105291 and part of #104863 to fix the perf regression.
r? `@cjgillot`
Make encode_info_for_trait_item use queries instead of accessing the HIR
This change avoids accessing the HIR on `encode_info_for_trait_item` and uses queries. We will need to execute this function for elements that have no HIR and by using queries we will be able to feed for definitions that have no HIR.
r? ``@oli-obk``
This commit partly undoes #104863, which combined the builtin lints pass
with other lints. This caused a slowdown, because often there are no
other lints, and it's faster to do a pass with a single lint directly
than it is to do a combined pass with a `passes` vector containing a
single lint.
I removed these in #105291, and subsequently learned they are necessary
for performance.
This commit reinstates them with the new and more descriptive names
`RuntimeCombined{Early,Late}LintPass`, similar to the existing passes
like `BuiltinCombinedEarlyLintPass`. It also adds some comments,
particularly emphasising how we have ways to combine passes at both
compile-time and runtime. And it moves some comments around.
When encountering an unmet obligation that affects a method chain, like
in iterator chains where one of the links has the wrong associated
type, we point at every method call and mention their evaluated
associated type at that point to give context to the user of where
expectations diverged from the code as written.
```
note: the expression is of type `Map<std::slice::Iter<'_, {integer}>, [closure@$DIR/invalid-iterator-chain.rs:12:18: 12:21]>`
--> $DIR/invalid-iterator-chain.rs:12:14
|
LL | vec![0, 1]
| ---------- this expression has type `Vec<{integer}>`
LL | .iter()
| ------ associated type `std::iter::Iterator::Item` is `&{integer}` here
LL | .map(|x| { x; })
| ^^^^^^^^^^^^^^^ associated type `std::iter::Iterator::Item` is `()` here
```
Don't internalize __llvm_profile_counter_bias
Currently, LLVM profiling runtime counter relocation cannot be used by rust during LTO because symbols are being internalized before all symbol information is known.
This mode makes LLVM emit a __llvm_profile_counter_bias symbol which is referenced by the profiling initialization, which itself is pulled in by the rust driver here [1].
It is enabled with -Cllvm-args=-runtime-counter-relocation for platforms which are opt-in to this mode like Linux. On these platforms there will be no link error, rather just surprising behavior for a user which request runtime counter relocation. The profiling runtime will not see that symbol go on as if it were never there. On Fuchsia, the profiling runtime must have this symbol which will cause a hard link error.
As an aside, I don't have enough context as to why rust's LTO model is how it is. AFAICT, the internalize pass is only safe to run at link time when all symbol information is actually known, this being an example as to why. I think special casing this symbol as a known one that LLVM can emit which should not have it's visbility de-escalated should be fine given how seldom this pattern of defining an undefined symbol to get initilization code pulled in is. From a quick grep, __llvm_profile_runtime is the only symbol that rustc does this for.
[1] 0265a3e93b/compiler/rustc_codegen_ssa/src/back/linker.rs (L598)
compiler: remove unnecessary imports and qualified paths
Some of these imports were necessary before Edition 2021, others were already in the prelude.
I hope it's fine that this PR is so spread-out across files :/
Some method confirmation code nits
1. Make some pick methods take `&self` instead of `&mut` to avoid some cloning
2. Pass some values by reference to avoid some cloning
3. Rename a few variables here and there
Fix invalid codegen during debuginfo lowering
In order for LLVM to correctly generate debuginfo for msvc, we sometimes need to spill arguments to the stack and perform some direct & indirect offsets into the value. Previously, this code always performed those actions, even when not required as LLVM would clean it up during optimization.
However, when MIR inlining is enabled, this can cause problems as the operations occur prior to the spilled value being initialized. To solve this, we first calculate the necessary offsets using just the type which is side-effect free and does not alter the LLVM IR. Then, if we are in a situation which requires us to generate the LLVM IR (and this situation only occurs for arguments, not local variables) then we perform the same calculation again, this time generating the appropriate LLVM IR as we go.
r? `@tmiasko` but feel free to reassign if you want 🙂Fixes#105386
Migrate parts of `rustc_expand` to session diagnostics
This migrates everything but the `mbe` and `proc_macro` modules. It also contains a few cleanups and drive-by/accidental diagnostic improvements which can be seen in the diff for the UI tests.
Rollup of 10 pull requests
Successful merges:
- #98391 (Reimplement std's thread parker on top of events on SGX)
- #104019 (Compute generator sizes with `-Zprint_type_sizes`)
- #104512 (Set `download-ci-llvm = "if-available"` by default when `channel = dev`)
- #104901 (Implement masking in FileType comparison on Unix)
- #105082 (Fix Async Generator ABI)
- #105109 (Add LLVM KCFI support to the Rust compiler)
- #105505 (Don't warn about unused parens when they are used by yeet expr)
- #105514 (Introduce `Span::is_visible`)
- #105516 (Update cargo)
- #105522 (Remove wrong note for short circuiting operators)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
This migrates everything but the `mbe` and `proc_macro` modules. It also
contains a few cleanups and drive-by/accidental diagnostic improvements
which can be seen in the diff for the UI tests.
Add LLVM KCFI support to the Rust compiler
This PR adds LLVM Kernel Control Flow Integrity (KCFI) support to the Rust compiler. It initially provides forward-edge control flow protection for operating systems kernels for Rust-compiled code only by aggregating function pointers in groups identified by their return and parameter types. (See llvm/llvm-project@cff5bef.)
Forward-edge control flow protection for C or C++ and Rust -compiled code "mixed binaries" (i.e., for when C or C++ and Rust -compiled code share the same virtual address space) will be provided in later work as part of this project by identifying C char and integer type uses at the time types are encoded (see Type metadata in the design document in the tracking issue #89653).
LLVM KCFI can be enabled with -Zsanitizer=kcfi.
Thank you again, `@bjorn3,` `@eddyb,` `@nagisa,` and `@ojeda,` for all the help!