Rename InstCombine to InstSimplify
```
╭ ➜ ben@archlinux:~/rust
╰ ➤ rg -i instcombine
src/doc/rustc-dev-guide/src/mir/optimizations.md
134:may have been misapplied. Examples of this are `InstCombine` and `ConstantPropagation`.
src/ci/docker/host-x86_64/disabled/dist-x86_64-haiku/llvm-config.sh
38: instcombine instrumentation interpreter ipo irreader lanai \
tests/codegen/slice_as_from_ptr_range.rs
4:// min-llvm-version: 15.0 (because this is a relatively new instcombine)
```
r? `@scottmcm`
Constify `[u8]::is_ascii` (unstably)
UTF-8 checking in `const fn`-stabilized back in 1.63 (#97367), but apparently somehow ASCII checking was never const-ified, despite being simpler.
New constness-tracking issue for `is_ascii`: #111090
I noticed this working on `ascii::Char`: #110998
Support return-type bounds on associated methods from supertraits
Support `T: Trait<method(): Bound>` when `method` comes from a supertrait, aligning it with the behavior of associated type bounds (both equality and trait bounds).
The only wrinkle is that I have to extend `super_predicates_that_define_assoc_type` to look for *all* items, not just `AssocKind::Ty`. This will also be needed to support `feature(associated_const_equality)` as well, which is subtly broken when it comes to supertraits, though this PR does not fix those yet. There's a slight chance there's a perf regression here, in which case I guess I could split it out into a separate query.
added TraitAlias to check_item() for missing_docs
As in issue #111025 the `missing_docs` was not being triggered for trait aliases. I added `TraitAlias` to the pattern match for check_item(), and the lint seems to be behaving appropriately
Operand::extract_field: only cast llval if it's a pointer and replace bitcast w/ pointercast.
Fixes#105439.
Also cc `@erikdesjardins,` looks like another place to cleanup as part of #105545
Output LLVM optimization remark kind in `-Cremark` output
Since https://github.com/rust-lang/rust/pull/90833, the optimization remark kind has not been printed. Therefore it wasn't possible to easily determine from the log (in a programmatic way) which remark kind was produced. I think that the most interesting remarks are the missed ones, which can lead users to some code optimization.
Maybe we could also change the format closer to the "old" one:
```
note: optimization remark for tailcallelim at /checkout/src/libcore/num/mod.rs:1:0: marked this call a tail call candidate
```
I wanted to programatically parse the remarks so that they could work e.g. with https://github.com/OfekShilon/optview2. However, now that I think about it, probably the proper solution is to tell rustc to output them to YAML and then use the YAML as input for the opt remark visualization tools. The flag for enabling this does not seem to work though (https://github.com/rust-lang/rust/issues/96705#issuecomment-1117632322).
Still I think that it's good to output the remark kind anyway, it's an important piece of information.
r? ```@tmiasko```
add hint for =< as <=
Adds a compiler hint for when `=<` is typed instead of `<=`
Example hint:
```rust
fn foo() {
if 1 =< 3 {
println!("Hello, World!");
}
}
```
```
error: expected type, found `3`
--> main.rs:2:13
|
2 | if 1 =< 3 {
| -- ^ expected type
| |
| help: did you mean: `<=`
```
This PR only emits the suggestion if there is no space between the `=` and `<`. This hopefully narrows the scope of when this error is emitted, however this still allows this error to be emitted in cases such as this:
```
error: expected expression, found `;`
--> main.rs:2:18
|
2 | if 1 =< [i32;; 3]>::hello() {
| -- ^ expected expression
| |
| help: did you mean: `<=`
```
Which could be a good reason not to merge since I haven't been able to think of any other ways of narrowing the scope of this diagnostic.
closes#111128
debuginfo: split method declaration and definition
When we're adding a method to a type DIE, we only want a DW_AT_declaration
there, because LLVM LTO can't unify type definitions when a child DIE is a
full subprogram definition. Now the subprogram definition gets added at the
CU level with a specification link back to the abstract declaration.
Both GCC and Clang write debuginfo this way for C++ class methods.
Fixes#109730.
Fixes#109934.
Make the BUG_REPORT_URL configurable by tools
This greatly simplifies how hard it is to set a custom bug report url; previously tools had to copy
the entire hook implementation.
I haven't changed clippy in case they want to make the change upstream instead of the subtree, but
I'm happy to do so here if the maintainers want - cc ````@rust-lang/clippy````
Fixes https://github.com/rust-lang/rust/issues/109486.
Use fulfillment to check `Drop` impl compatibility
Use an `ObligationCtxt` to ensure that a `Drop` impl does not have stricter requirements than the ADT that it's implemented for, rather than using a `SimpleEqRelation` to (more or less) syntactically equate predicates on an ADT with predicates on an impl.
r? types
### Some background
The old code reads:
```rust
// An earlier version of this code attempted to do this checking
// via the traits::fulfill machinery. However, it ran into trouble
// since the fulfill machinery merely turns outlives-predicates
// 'a:'b and T:'b into region inference constraints. It is simpler
// just to look for all the predicates directly.
```
I'm not sure what this means, but perhaps in the 8 years since that this comment was written (cc #23638) it's gotten easier to process region constraints after doing fulfillment? I don't know how this logic differs from anything we do in the `compare_impl_item` module. Ironically, later on it says:
```rust
// However, it may be more efficient in the future to batch
// the analysis together via the fulfill (see comment above regarding
// the usage of the fulfill machinery), rather than the
// repeated `.iter().any(..)` calls.
```
Also:
* Removes `SimpleEqRelation` which was far too syntactical in its relation.
* Fixes#110557
Add `force` option for `--extern` flag
When `--extern force:foo=libfoo.so` is passed to `rustc` and `foo` is not actually used in the crate, ~inject an `extern crate foo;` statement into the AST~ force it to be resolved anyway in `CrateLoader::postprocess()`. This allows you to, for instance, inject a `#[panic_handler]` implementation into a `#![no_std]` crate without modifying its source so that it can be built as a `dylib`. It may also be useful for `#![panic_runtime]` or `#[global_allocator]`/`#![default_lib_allocator]` implementations.
My work previously involved integrating Rust into an existing C/C++ codebase which was built with Buck and shipped on, among other platforms, Android. When targeting Android, Buck builds all "native" code with shared linkage* so it can be loaded from Java/Kotlin. My project was not itself `#![no_std]`, but many of our dependencies were, and they would fail to build with shared linkage due to a lack of a panic handler. With this change, that project can add the new `force` option to the `std` dependency it already explicitly provides to every crate to solve this problem.
*This is an oversimplification - Buck has a couple features for aggregating dependencies into larger shared libraries, but none that I think sustainably solve this problem.
~The AST injection happens after macro expansion around where we similarly inject a test harness and proc-macro harness. The resolver's list of actually-used extern flags is populated during macro expansion, and if any of our `--extern` arguments have the `force` option and weren't already used, we inject an `extern crate` statement for them. The injection logic was added in `rustc_builtin_macros` as that's where similar injections for tests, proc-macros, and std/core already live.~
(New contributor - grateful for feedback and guidance!)
rustdoc-search: add slices and arrays to index
This indexes them as primitives with generics, so `slice<u32>` is how you search for `[u32]`, and `array<u32>` for `[u32; 1]`. A future commit will desugar the square bracket syntax to search both arrays and slices at once.
Stabilize raw-dylib, link_ordinal, import_name_type and -Cdlltool
This stabilizes the `raw-dylib` feature (#58713) for all architectures (i.e., `x86` as it is already stable for all other architectures).
Changes:
* Permit the use of the `raw-dylib` link kind for x86, the `link_ordinal` attribute and the `import_name_type` key for the `link` attribute.
* Mark the `raw_dylib` feature as stable.
* Stabilized the `-Zdlltool` argument as `-Cdlltool`.
* Note the path to `dlltool` if invoking it failed (we don't need to do this if `dlltool` returns an error since it prints its path in the error message).
* Adds tests for `-Cdlltool`.
* Adds tests for being unable to find the dlltool executable, and dlltool failing.
* Fixes a bug where we were checking the exit code of dlltool to see if it failed, but dlltool always returns 0 (indicating success), so instead we need to check if anything was written to `stderr`.
NOTE: As previously noted (https://github.com/rust-lang/rust/pull/104218#issuecomment-1315895618) using dlltool within rustc is temporary, but this is not the first time that Rust has added a temporary tool use and argument: https://github.com/rust-lang/rust/pull/104218#issuecomment-1318720482
Big thanks to ``````@tbu-`````` for the first version of this PR (#104218)
Such implementations are usually mistakes and are not used in the
compiler or standard library (after this commit) so forbid them with
`min_specialization`.
Improve check-cfg implementation
This PR makes multiple improvements into the implementation of check-cfg, it is a prerequisite to a follow-up PR that will introduce a simpler and more explicit syntax.
The 2 main area of improvements are:
1. Internal representation of expected values:
- now uses `FxHashSet<Option<Symbol>>` instead of `FxHashSet<Symbol>`, it made the no value expected case only possible when no values where in the `HashSet` which is now represented as `None` (same as cfg represent-it).
- a enum with `Some` and `Any` makes it now clear if some values are expected or not, necessary for `feature` and `target_feature`.
2. Diagnostics: Improve the diagnostics in multiple case and fix case where a missing value could have had a new name suggestion instead of the value diagnostic; and some drive by improvements
I highly recommend reviewing commit by commit.
r? `@petrochenkov`
Reduce MIR dump file count for MIR-opt tests
As referenced in issue #109502 , mir-opt tests previously used the -Zdump-mir=all flag, which generates very large output. This PR only dumps the passes under test, greatly reducing dump output.
Fix problems with backtraces in two ui tests.
`default-backtrace-ice.rs` started started failing for me recently,
because on my Ubuntu 23.04 system there are 100 stack frames, and the
current stack filtering pattern doesn't match on a stack frame with a
three digit number.
`issue-86800.rs` can also be improved, backtrace-wise.
r? `@Nilstrieb`
This test is supposed to ensure that full backtraces are used for ICEs.
But it doesn't actually do that -- the filtering done cannot distinguish
between a full backtrace versus a short backtrace.
So this commit changes the filtering to preserve the existence of
`__rust_{begin,end}_short_backtrace` markers, which only appear in full
backtraces. This change means the test now tests what it is supposed to
test.
Also, the existing filtering included a rule that excluded any line
starting with two spaces. This was too strong because it filtered out
some parts of the error message. (This was not a showstopper). It was
also not strong enough because it didn't work with three digit stack
frame numbers, which just started seeing after upgrading my Ubuntu
distro to 23.04 machine (this *was* a showstopper).
So the commit replaces that rule with two more precise rules, one for
lines with stack frame numbers, and one for "at ..." lines.
Because it then just has to be filtered out.
This change makes this test more like these other tests:
- tests/ui/treat-err-as-bug/err.rs
- tests/ui/treat-err-as-bug/delay_span_bug.rs
- tests/ui/mir/validate/storage-live.rs
- tests/ui/associated-inherent-types/bugs/ice-substitution.rs
- tests/ui/layout/valid_range_oob.rs
check array type of repeat exprs is wf
Fixes#111091
Also makes sure that we actually renumber regions in the length of repeat exprs which we previously weren't doing and would cause ICEs in `adt_const_params` + `generic_const_exprs` from attempting to prove the wf goals when the length was an unevaluated constant with `'erased` in the `ty` field of `Const`
The duplicate errors are caused by the fact that `const_arg_to_const`/`array_len_to_const` in `FnCtxt` adds a `WellFormed` goal for the created `Const` which is also checked by the added `WellFormed(array_ty)`. I don't want to change this to just emit a `T: Sized` goal for the element type since that would ignore `ConstArgHasType` wf requirements and generally uncomfortable with the idea of trying to sync up `wf::obligations` for arrays and the code in hir typeck for repeat exprs.
r? `@compiler-errors`
correctly recurse when expanding anon consts
recursing with `super_fold_with` is wrong in case `bac` is itself normalizable, the test that was supposed to test for this being wrong did not actually test for this in reality because of the usage of `{ (N) }` instead of `{{ N }}`. The former resulting in a simple `ConstKind::Param` instead of `ConstKind::Unevaluated`. Tbh generally this test seems very brittle and it will be a lot easier to test once we have normalization of assoc consts since then we can just test that `T::ASSOC` normalizes to some `U::OTHER` which normalizes to some third thing.
r? `@compiler-errors`
Encode def span for foreign return-position `impl Trait` in trait
Fixes#111031, yet another def-span encoding issue :/
Includes a smaller repro than the issue, but I can confirm it ICEs:
```
query stack during panic:
#0 [def_span] looking up span for `rpitit::Foo::bar::{opaque#0}`
#1 [object_safety_violations] determining object safety of trait `rpitit::Foo`
#2 [check_is_object_safe] checking if trait `rpitit::Foo` is object safe
#3 [typeck] type-checking `main`
#4 [used_trait_imports] finding used_trait_imports `main`
#5 [analysis] running analysis passes on this crate
```
Luckily since this only affects nightly, this desn't need to be backported.
Explicitly reject negative and reservation drop impls
Fixes#110858
It doesn't really make sense for a type to have a `!Drop` impl. Or at least, I don't want us to implicitly assign a meaning to it by the way the compiler *currently* handles it (incompletely), and rather I would like to see a PR (or an RFC...) assign a meaning to `!Drop` if we actually wanted one for it.
Add cross-language LLVM CFI support to the Rust compiler
This PR adds cross-language LLVM Control Flow Integrity (CFI) support to the Rust compiler by adding the `-Zsanitizer-cfi-normalize-integers` option to be used with Clang `-fsanitize-cfi-icall-normalize-integers` for normalizing integer types (see https://reviews.llvm.org/D139395).
It provides 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). For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler, see design document in the tracking issue #89653.
Cross-language LLVM CFI can be enabled with -Zsanitizer=cfi and -Zsanitizer-cfi-normalize-integers, and requires proper (i.e., non-rustc) LTO (i.e., -Clinker-plugin-lto).
Thank you again, ``@bjorn3,`` ``@nikic,`` ``@samitolvanen,`` and the Rust community for all the help!
Implement tuple<->array convertions via `From`
This PR adds the following impls that convert between homogeneous tuples and arrays of the corresponding lengths:
```rust
impl<T> From<[T; 1]> for (T,) { ... }
impl<T> From<[T; 2]> for (T, T) { ... }
/* ... */
impl<T> From<[T; 12]> for (T, T, T, T, T, T, T, T, T, T, T, T) { ... }
impl<T> From<(T,)> for [T; 1] { ... }
impl<T> From<(T, T)> for [T; 2] { ... }
/* ... */
impl<T> From<(T, T, T, T, T, T, T, T, T, T, T, T)> for [T; 12] { ... }
```
IMO these are quite uncontroversial but note that they are, just like any other trait impls, insta-stable.
When we're adding a method to a type DIE, we only want a DW_AT_declaration
there, because LLVM LTO can't unify type definitions when a child DIE is a
full subprogram definition. Now the subprogram definition gets added at the
CU level with a specification link back to the abstract declaration.
This commit adds cross-language LLVM Control Flow Integrity (CFI)
support to the Rust compiler by adding the
`-Zsanitizer-cfi-normalize-integers` option to be used with Clang
`-fsanitize-cfi-icall-normalize-integers` for normalizing integer types
(see https://reviews.llvm.org/D139395).
It provides 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). For more
information about LLVM CFI and cross-language LLVM CFI support for the
Rust compiler, see design document in the tracking issue #89653.
Cross-language LLVM CFI can be enabled with -Zsanitizer=cfi and
-Zsanitizer-cfi-normalize-integers, and requires proper (i.e.,
non-rustc) LTO (i.e., -Clinker-plugin-lto).
Don't bail out early when checking invalid `repr` attr
Fixes#111051
An invalid repr delays a bug. If there are other invalid attributes on the item, we emit a warning and exit without re-checking the repr here, so no error is emitted and the delayed bug ICEs
Implement negative bounds for internal testing purposes
Implements partial support the `!` negative polarity on trait bounds. This is incomplete, but should allow us to at least be able to play with the feature.
Not even gonna consider them as a public-facing feature, but I'm implementing them because would've been nice to have in UI tests, for example in #110671.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
Mark`feature(return_position_impl_trait_in_trait)` and`feature(async_fn_in_trait)` as not incomplete
I think they've graduated, since as far as I'm aware, they don't cause compiler crashes or unsoundness anymore.
Fix elaboration with associated type bounds
When computing a trait's supertrait predicates, do not add any associated type *trait* bounds to that list of supertrait predicates. This is because supertrait predicates are expected to have the same `Self` type as the trait.
For example, given:
```rust
trait Foo: Bar<Assoc: Send>
```
Before, we would compute that the supertrait predicates of `T: Foo` are `T: Bar` and `<T as Bar>::Assoc: Send`. However, the last bound is a trait predicate for a totally different type than `T`, and existing code that uses supertrait bounds such as vtable construction, closure fn signature deduction, etc. all rely on the invariant that we have a list of predicates for self type `T`.
Fixes#76593
The reason for all the extra diagnostic noise is that we're recomputing predicates with a different filter now. These diagnostics should be deduplicated for any end-user though.
---
This does bring up an interesting question -- is the predicate `<T as Bar>::Assoc: Send` an implied bound of `T: Foo`? Because currently the only bounds implied by a (non-alias) trait are its supertraits. I guess I could fix this too, but it would require even more changes, and I'm inclined to punt this question along.
Stabilize debugger_visualizer
This stabilizes the `debugger_visualizer` attribute (#95939).
* Marks the `debugger_visualizer` feature as `accepted`.
* Marks the `debugger_visualizer` attribute as `ungated`.
* Deletes feature gate test, removes feature gate from other tests.
Closes#95939
Add `ConstParamTy` trait
This is a bit sketch, but idk.
r? `@BoxyUwU`
Yet to be done:
- [x] ~~Figure out if it's okay to implement `StructuralEq` for primitives / possibly remove their special casing~~ (it should be okay, but maybe not in this PR...)
- [ ] Maybe refactor the code a little bit
- [x] Use a macro to make impls a bit nicer
Future work:
- [ ] Actually™ use the trait when checking if a `const` generic type is allowed
- [ ] _Really_ refactor the surrounding code
- [ ] Refactor `marker.rs` into multiple modules for each "theme" of markers
Don't validate constants in const propagation
Validation is neither necessary nor desirable.
The constant validation is already omitted at mir-opt-level >= 3, so there there are not changes in MIR test output (the propagation of invalid constants is covered by an existing test in tests/mir-opt/const_prop/invalid_constant.rs).
This greatly simplifies how hard it is to set a custom bug report url; previously tools had to copy
the entire hook implementation.
- Switch clippy to the new hook
This also adds a `extra_info` callback so clippy can include its own version number, which differs
from rustc's.
- Call `install_ice_hook` in rustfmt
Round-trip encoding/decoding of many types is tested in
`compiler/rustc_serialize/tests/opaque.rs`. There is also a small amount
of encoding/decoding testing in three files in `tests/ui-fulldeps`.
There is no obvious reason why these three files are necessary. They
were originally added in 2014. Maybe it wasn't possible for a proc
macro to run in a unit test back then?
This commit just moves the testing from those three files into the unit
test.
Add `#[no_coverage]` to the test harness's `fn main`
There are two main motivations for adding `#[no_coverage]` to the test harness's entry point:
- The entry point is trivial compiler-generated code that doesn't correspond to user source, and it always runs, so there's no value in instrumenting it for coverage.
- Because it has dummy spans, it causes the instrumentor implementation to emit invalid coverage mappings that confuse `llvm-cov` and result in strange coverage reports.
Fixes#110749.
Leave promoteds untainted by errors when borrowck fails
Previously, when borrowck failed it would taint all promoteds within the MIR body. An attempt to evaluated the promoteds would subsequently fail with spurious "note: erroneous constant used". For example:
```console
...
note: erroneous constant used
--> tests/ui/borrowck/tainted-promoteds.rs:7:9
|
7 | a = &0 * &1 * &2 * &3;
| ^^
note: erroneous constant used
--> tests/ui/borrowck/tainted-promoteds.rs:7:14
|
7 | a = &0 * &1 * &2 * &3;
| ^^
note: erroneous constant used
--> tests/ui/borrowck/tainted-promoteds.rs:7:19
|
7 | a = &0 * &1 * &2 * &3;
| ^^
note: erroneous constant used
--> tests/ui/borrowck/tainted-promoteds.rs:7:24
|
7 | a = &0 * &1 * &2 * &3;
| ^^
```
Borrowck failure doesn't indicate that there is anything wrong with promoteds. Leave them untainted.
Fixes#110856.
Make `mem::replace` simpler in codegen
Since they'd mentioned more intrinsics for simplifying stuff recently,
r? `@WaffleLapkin`
This is a continuation of me looking at foundational stuff that ends up with more instructions than it really needs. Specifically I noticed this one because `Range::next` isn't MIR-inlining, and one of the largest parts of it is a `replace::<usize>` that's a good dozen instructions instead of the two it could be.
So this means that `ptr::write` with a `Copy` type no longer generates worse IR than manually dereferencing (well, at least in LLVM -- MIR still has bonus pointer casts), and in doing so means that we're finally down to just the two essential `memcpy`s when emitting `mem::replace` for a large type, rather than the bonus-`alloca` and three `memcpy`s we emitted before this ([or the 6 we currently emit in 1.69 stable](https://rust.godbolt.org/z/67W8on6nP)). That said, LLVM does _usually_ manage to optimize the extra code away. But it's still nice for it not to have to do as much, thanks to (for example) not going through an `alloca` when `replace`ing a primitive like a `usize`.
(This is a new intrinsic, but one that's immediately lowered to existing MIR constructs, so not anything that MIRI or the codegen backends or MIR semantics needs to do work to handle.)
My type ascription
Oh rip it out
Ah
If you think we live too much then
You can sacrifice diagnostics
Don't mix your garbage
Into my syntax
So many weird hacks keep diagnostics alive
Yet I don't even step outside
So many bad diagnostics keep tyasc alive
Yet tyasc doesn't even bother to survive!