Commit Graph

32266 Commits

Author SHA1 Message Date
Nicholas Nethercote 749afe2050 Rename `LintLevelsBuilder::struct_lint` as `LintLevelsBuilder::opt_span_lint`. 2024-01-23 08:08:27 +11:00
Nicholas Nethercote 1881bfaa2b Rename `LintContext::emit_spanned_lint` as `LintContext::emit_span_lint`. 2024-01-23 08:08:25 +11:00
Nicholas Nethercote c915e90f7e Rename `LintContext::lookup_with_diagnostics` as `LintContext::span_lint_with_diagnostics`. 2024-01-23 07:59:45 +11:00
Nicholas Nethercote 2de5242ea6 Rename `LintContext::lookup` as `LintContext::opt_span_lint`. 2024-01-23 07:59:45 +11:00
Nicholas Nethercote c56d71f418 Rename `LintContext::struct_span_lint` as `LintContext::span_lint`. 2024-01-23 07:59:45 +11:00
Esteban Küber ac56a2b564 Suggest boxing if then expr if that solves divergent arms
When encountering

```rust
let _ = if true {
    Struct
} else {
    foo() // -> Box<dyn Trait>
};
```

if `Struct` implements `Trait`, suggest boxing the then arm tail expression.

Part of #102629.
2024-01-22 20:53:41 +00:00
Esteban Küber 390ef9ba02 Fix incorrect suggestion for boxing tail expression in blocks 2024-01-22 20:51:19 +00:00
bors d5fd099729 Auto merge of #120242 - matthiaskrgr:rollup-a93yj3i, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #117910 (Refactor uses of `objc_msgSend` to no longer have clashing definitions)
 - #118639 (Undeprecate lint `unstable_features` and make use of it in the compiler)
 - #119801 (Fix deallocation with wrong allocator in (A)Rc::from_box_in)
 - #120058 (bootstrap: improvements for compiler builds)
 - #120059 (Make generic const type mismatches not hide trait impls from the trait solver)
 - #120097 (Report unreachable subpatterns consistently)
 - #120137 (Validate AggregateKind types in MIR)
 - #120164 (`maybe_lint_impl_trait`: separate `is_downgradable` from `is_object_safe`)
 - #120181 (Allow any `const` expression blocks in `thread_local!`)
 - #120218 (rustfmt: Check that a token can begin a nonterminal kind before parsing it as a macro arg)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 18:22:32 +00:00
Erik Kaneda 966b94e0a2
rustc: implement support for `riscv32im_risc0_zkvm_elf`
This also adds changes in the rust test suite in order to get a few of them to
pass.

Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: Urgau <3616612+Urgau@users.noreply.github.com>
2024-01-22 10:07:36 -08:00
Esteban Küber 29bdf9ea51 Account for single `where` bound being removed 2024-01-22 17:52:36 +00:00
David Carlier dec4740b7c compiler: update freebsd and netbsd base specs.
both support thread local.
2024-01-22 17:09:44 +00:00
Michael Goulet f700ee4e70 Do not normalize closure signature when building FnOnce shim 2024-01-22 16:50:30 +00:00
Wesley Wiser 21e5beae3c
Use debug_assert instead of expanded equivalent 2024-01-22 10:10:00 -06:00
Matthias Krüger 6e4933f94f
Rollup merge of #120164 - trevyn:is_downgradable, r=compiler-errors
`maybe_lint_impl_trait`: separate `is_downgradable` from `is_object_safe`

https://github.com/rust-lang/rust/pull/119752 leveraged and overloaded `is_object_safe` to prevent an ICE, but accurate object safety information is needed for precise suggestions. This separates out `is_downgradable`, used for the ICE prevention, and `is_object_safe`, which returns to its original meaning.
2024-01-22 16:54:59 +01:00
Matthias Krüger a12e2ff7b2
Rollup merge of #120137 - compiler-errors:validate-aggregates, r=nnethercote
Validate AggregateKind types in MIR

Would have helped me catch some bugs when writing shims for async closures
2024-01-22 16:54:59 +01:00
Matthias Krüger f194a84ce2
Rollup merge of #120097 - Nadrieril:consistent_unreachable_subpats, r=compiler-errors
Report unreachable subpatterns consistently

We weren't reporting unreachable subpatterns in function arguments and `let` expressions. This wasn't very important, but never patterns make it more relevant: a user might write `let (Ok(x) | Err(!)) = ...` in a case where `let Ok(x) = ...` is accepted, so we should report the `Err(!)` as redundant.

r? ```@compiler-errors```
2024-01-22 16:54:58 +01:00
Matthias Krüger d942357d7a
Rollup merge of #120059 - oli-obk:const_arg_type_mismatch, r=compiler-errors
Make generic const type mismatches not hide trait impls from the trait solver

pulled out of https://github.com/rust-lang/rust/pull/119895

It does improve diagnostics somewhat, but also causes some extraneous diagnostics in potentially misleading order.

The issue was that a const type mismatch, instead of reporting an error, would silently poison the constant, only for that information to be thrown away and the impl to be treated as "not matching". In #119895 this would cause ICEs as well as errors on impls stating that the impl needs to exist for itself to be valid.
2024-01-22 16:54:58 +01:00
Matthias Krüger a54c295665
Rollup merge of #118639 - fmease:deny-features-in-stable-rustc-crates, r=WaffleLapkin
Undeprecate lint `unstable_features` and make use of it in the compiler

See also #117937.

r? compiler
2024-01-22 16:54:56 +01:00
Matthias Krüger ba542c823d
Rollup merge of #120213 - compiler-errors:dont-make-non-lifetime-binders-in-rtn, r=fmease
Don't actually make bound ty/const for RTN

Avoid creating an unnecessary non-lifetime binder when we do RTN on a method that has ty/const params.

Fixes #120208

r? oli-obk
2024-01-22 16:13:30 +01:00
Matthias Krüger 2346647daf
Rollup merge of #120152 - rowan-sl:help-message-for-range-pattern, r=oli-obk
add help message for `exclusive_range_pattern` error

Fixes #120047

this error
```
error[E0658]: exclusive range pattern syntax is experimental
 --> src/lib.rs:3:9
  |
3 |         0..42 => {},
  |         ^^^^^
  |
  = note: see issue #37854 <https://github.com/rust-lang/rust/issues/37854> for more information
  = help: use an inclusive range pattern, like N..=M
  ```
now includes a help message

Not sure of proper procedure here but this seemed like a good help message (used the one suggested in the original issue), if you have a idea for one that is better or something I missed please comment!
2024-01-22 16:13:29 +01:00
Matthias Krüger 34bab29ef9
Rollup merge of #119948 - asquared31415:unsafe_op_in_unsafe_fn_fix, r=TaKO8Ki
Make `unsafe_op_in_unsafe_fn` migrated in edition 2024

fixes rust-lang/rust#119823
2024-01-22 16:13:28 +01:00
Matthias Krüger c5984caa44
Rollup merge of #119369 - bvanjoi:fix-119301, r=petrochenkov
exclude unexported macro bindings from extern crate

Fixes #119301

Macros that aren't exported from an external crate should not be defined.

r? ``@petrochenkov``
2024-01-22 16:13:25 +01:00
Oli Scherer 1829aa631f Use an enum instead of a bool 2024-01-22 14:35:47 +00:00
Oli Scherer f75361fec7 Limit impl trait in assoc type defining scope 2024-01-22 14:35:46 +00:00
Oli Scherer ac332bd916 Pull opaque type check into a separate method 2024-01-22 14:35:46 +00:00
Oli Scherer f58af9ba28 Add a simpler and more targetted code path for impl trait in assoc items 2024-01-22 14:35:46 +00:00
Oli Scherer 9a20cf1697 Revert "Auto merge of #118133 - Urgau:stabilize_trait_upcasting, r=WaffleLapkin"
This reverts commit 6d2b84b3ed, reversing
changes made to 73bc12199e.
2024-01-22 14:24:31 +00:00
Nadrieril d1f1075931 Never pattern in `let` statement diverges 2024-01-22 15:12:57 +01:00
Nadrieril a9ea07d17c Never pattern in function arguments diverges 2024-01-22 15:12:57 +01:00
Nadrieril dbc1f074bc Tweak 2024-01-22 15:12:57 +01:00
Oli Scherer 9454b51b05 Make generic const type mismatches not hide trait impls from the trait solver 2024-01-22 13:23:45 +00:00
bors 3066253050 Auto merge of #120080 - cuviper:128-align-packed, r=nikic
Pack u128 in the compiler to mitigate new alignment

This is based on #116672, adding a new `#[repr(packed(8))]` wrapper on `u128` to avoid changing any of the compiler's size assertions. This is needed in two places:

* `SwitchTargets`, otherwise its `SmallVec<[u128; 1]>` gets padded up to 32 bytes.
* `LitKind::Int`, so that entire `enum` can stay 24 bytes.
  * This change definitely has far-reaching effects though, since it's public.
2024-01-22 13:08:19 +00:00
bors 366d112fa6 Auto merge of #120226 - matthiaskrgr:rollup-9xwx0si, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #118714 ( Explanation that fields are being used when deriving `(Partial)Ord` on enums)
 - #119710 (Improve `let_underscore_lock`)
 - #119726 (Tweak Library Integer Division Docs)
 - #119746 (rustdoc: hide modals when resizing the sidebar)
 - #119986 (Fix error counting)
 - #120194 (Shorten `#[must_use]` Diagnostic Message for `Option::is_none`)
 - #120200 (Correct the anchor of an URL in an error message)
 - #120203 (Replace `#!/bin/bash` with `#!/usr/bin/env bash` in rust-installer tests)
 - #120212 (Give nnethercote more reviews)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 11:08:57 +00:00
bors 6fff796eac Auto merge of #120196 - matthiaskrgr:rollup-id2zocf, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #120005 (Update Readme)
 - #120045 (Un-hide `iter::repeat_n`)
 - #120128 (Make stable_mir::with_tables sound)
 - #120145 (fix: Drop guard was deallocating with the incorrect size)
 - #120158 (`rustc_mir_dataflow`: Restore removed exports)
 - #120167 (Capture the rationale for `-Zallow-features=` in bootstrap.py)
 - #120174 (Warn users about limited review for tier 2 and 3 code)
 - #120180 (Document some alternatives to `Vec::split_off`)

Failed merges:

 - #120171 (Fix assume and assert in jump threading)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 08:56:22 +00:00
Ralf Jung 2ab85e4178 reword comment 2024-01-22 09:28:00 +01:00
Ralf Jung 73ce868c7e more clear code
Co-authored-by: Oli Scherer <github35764891676564198441@oli-obk.de>
2024-01-22 09:28:00 +01:00
Ralf Jung 0288a0bfa0 raw pointers are not references 2024-01-22 09:28:00 +01:00
Ralf Jung 2f1a8e2d7a const-eval interner: from-scratch rewrite using mutability information from provenance rather than types 2024-01-22 09:28:00 +01:00
Matthias Krüger 50d0f24620
Rollup merge of #120200 - noritada:fix/broken-error-message-link, r=dtolnay
Correct the anchor of an URL in an error message

Following error message from rustc points to a URL, but its anchor does not exist.
The destination seems to be https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib.
This PR makes that correction.

      = note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-libkindname)
2024-01-22 07:56:44 +01:00
Matthias Krüger bef2e85359
Rollup merge of #119986 - nnethercote:fix-error-counting, r=compiler-errors,oli-obk
Fix error counting

There is some messiness in how errors get counted. Here are some cleanups.

r? `@compiler-errors`
2024-01-22 07:56:43 +01:00
Matthias Krüger 72dddeaeb7
Rollup merge of #119710 - Nilstrieb:let-_-=-oops, r=TaKO8Ki
Improve `let_underscore_lock`

- lint if the lock was in a nested pattern
- lint if the lock is inside a `Result<Lock, _>`

addresses https://github.com/rust-lang/rust/pull/119704#discussion_r1444044745
2024-01-22 07:56:41 +01:00
bors a58ec8ff03 Auto merge of #120161 - cjgillot:static-pass-name, r=tmiasko
Make MIR pass name a compile-time constant.

Post-processing a compile-time string at runtime is a bit silly. This PR makes CTFE do it all.
2024-01-22 02:34:55 +00:00
Zalathar 41dcba805d coverage: Don't instrument `#[automatically_derived]` functions 2024-01-22 12:18:57 +11:00
Nicholas Nethercote 012a304a16 Fix a `trimmed_def_paths` assertion failure.
`RegionHighlightMode::force_print_trimmed_def_path` can call
`trimmed_def_paths` even when `tcx.sess.opts.trimmed_def_paths` is
false. Based on the `force` in the method name, it seems this is
deliberate, so I have removed the assertion.

Fixes #120035.
2024-01-22 11:00:30 +11:00
Nicholas Nethercote 1f9fa2305a Tweak error counting.
We have several methods indicating the presence of errors, lint errors,
and delayed bugs. I find it frustrating that it's very unclear which one
you should use in any particular spot. This commit attempts to instill a
basic principle of "use the least general one possible", because that
reflects reality in practice -- `has_errors` is the least general one
and has by far the most uses (esp. via `abort_if_errors`).

Specifics:
- Add some comments giving some usage guidelines.
- Prefer `has_errors` to comparing `err_count` to zero.
- Remove `has_errors_or_span_delayed_bugs` because it's a weird one: in
  the cases where we need to count delayed bugs, we should really be
  counting lint errors as well.
- Rename `is_compilation_going_to_fail` as
  `has_errors_or_lint_errors_or_span_delayed_bugs`, for consistency with
  `has_errors` and `has_errors_or_lint_errors`.
- Change a few other `has_errors_or_lint_errors` calls to `has_errors`,
  as per the "least general" principle.

This didn't turn out to be as neat as I hoped when I started, but I
think it's still an improvement.
2024-01-22 10:14:01 +11:00
Nicholas Nethercote 807c8687de Count "unused extern" errors as lints rather than normal errors. 2024-01-22 10:14:01 +11:00
Nicholas Nethercote f00c088393 Clarify comments about diagnostic count fields. 2024-01-22 10:14:00 +11:00
Michael Goulet 802d16ce3a Don't actually make bound ty/const for RTN 2024-01-21 23:08:03 +00:00
trevyn b58a8a98cd `maybe_lint_impl_trait`: separate `is_downgradable` from `is_object_safe` 2024-01-21 20:04:39 +04:00
Noritada Kobayashi ff02662d44 Correct the anchor of an URL in an error message 2024-01-22 01:02:20 +09:00
bohan 9c3091e9cf exclude unexported macro bindings from extern crate 2024-01-21 20:24:40 +08:00
Zalathar 6d7e80c5bc Add `#[coverage(off)]` to closures introduced by `#[test]`/`#[bench]` 2024-01-21 23:17:00 +11:00
Matthias Krüger e59a6fe63f
Rollup merge of #120158 - jubnzv:120130-mirdf-exports, r=nnethercote
`rustc_mir_dataflow`: Restore removed exports

Added back previously available exports:

* `Forward`/`Backward`: used when implementing `AnalysisDomain`
* `Engine`: used in user's code to solve the dataflow problem
* `SwitchIntEdgeEffects`: used when implementing functions of the `Analysis` trait
* `graphviz`: potentially useful for debugging purposes

Closes #120130
2024-01-21 12:28:53 +01:00
Matthias Krüger a72d6c114b
Rollup merge of #120128 - oli-obk:smir_internal_lift, r=celinval
Make stable_mir::with_tables sound

See the first commit for the actual soundness fix. The rest is just fallout from that and is entirely safe code. Includes most of #120120

The major difference to #120120 is that we don't need an unsafe trait, as we can now rely on the type system (the only unsafe part, and the actual source of the unsoundness was in `with_tables`)

r? `@celinval`
2024-01-21 12:28:52 +01:00
Nadrieril e7f3dc76f5
Rollup merge of #120027 - Nadrieril:remove-ty-copy-bound, r=compiler-errors
pattern_analysis: Remove `Ty: Copy` bound

To make it compatible with rust-analyzer's `Ty` which isn't `Copy` (it's an `Arc`).

r? ``@compiler-errors``
2024-01-21 06:38:38 +01:00
Nadrieril 203cc6930e
Rollup merge of #119461 - cjgillot:jump-threading-interp, r=tmiasko
Use an interpreter in MIR jump threading

This allows to understand assignments of aggregate constants. This case appears more frequently with GVN promoting aggregates to constants.
2024-01-21 06:38:36 +01:00
Nadrieril e8d1c2ef9c
Rollup merge of #118811 - EbbDrop:is-sorted-by-bool, r=Mark-Simulacrum
Use `bool` instead of `PartiolOrd` as return value of the comparison closure in `{slice,Iteraotr}::is_sorted_by`

Changes the function signature of the closure given to `{slice,Iteraotr}::is_sorted_by` to return a `bool` instead of a `PartiolOrd` as suggested by the libs-api team here: https://github.com/rust-lang/rust/issues/53485#issuecomment-1766411980.

This means these functions now return true if the closure returns true for all the pairs of values.
2024-01-21 06:38:35 +01:00
yukang 3ed96e35c4 Suggest arry::from_fn for array initialization 2024-01-21 09:57:26 +08:00
bors 867d39cdf6 Auto merge of #120100 - oli-obk:astconv_lifetimes, r=BoxyUwU
Don't forget that the lifetime on hir types is `'tcx`

This PR just tracks the `'tcx` lifetime to wherever the original objects actually have that lifetime. This code is needed for https://github.com/rust-lang/rust/pull/107606 (now #120131) so that `ast_ty_to_ty` can invoke `lit_to_const` on an argument passed to it. Currently the argument is `&hir::Ty<'_>`, but after this PR it is `&'tcx hir::Ty<'tcx>`.
2024-01-21 00:33:43 +00:00
Camille GILLOT ad25f0eb2c Make MIR pass name a compile-time constant. 2024-01-21 00:21:33 +00:00
EbbDrop 606eeb84ad Use bool instead of PartiolOrd in is_sorted_by 2024-01-20 21:38:34 +01:00
Georgiy Komarov 7842043b99
Add a warning comment 2024-01-20 16:52:18 -03:00
Guillaume Gomez 8f5f967031
Rollup merge of #120063 - clubby789:remove-box-handling, r=Nilstrieb
Remove special handling of `box` expressions from parser

#108471 added a temporary hack to parse `box expr`. It's been almost a year since then, so I think it's safe to remove the special handling.

As a drive-by cleanup, move `parser/removed-syntax*` tests to their own directory.
2024-01-20 20:06:34 +01:00
Georgiy Komarov 270f1510be
rustc_mir_dataflow: Add exports for external tools
Added back previously available exports:

* Forward/Backward: used when implementing `AnalysisDomain`
* Engine: used in user's code to solve the dataflow problem
* SwitchIntEdgeEffects: used when implementing functions of the `Analysis` trait
* graphviz: potentially useful for debugging purposes

These exports are used when implementing external tools based on MIR
dataflow framework.

Closes #120130
2024-01-20 14:42:27 -03:00
bors 159bdc1e93 Auto merge of #108359 - Zoxc:side-effects-tweak, r=cjgillot
Avoid code generation for ThinVec<Diagnostic>'s destructor in the query system

This avoids 2 instances of the destructor of `ThinVec<Diagnostic>` from being included in `execute_job`. It also outlines the cold branch in `store_side_effects` / `store_side_effects_for_anon_node`.
2024-01-20 15:20:15 +00:00
Nadrieril 796cdc590c Remove Ty: Copy bound 2024-01-20 15:22:14 +01:00
bors 6745c6000a Auto merge of #116185 - Zoxc:rem-one-thread, r=cjgillot
Remove `OneThread`

This removes `OneThread` by switching `incr_comp_session` over to `RwLock`.
2024-01-20 13:18:33 +00:00
jyn c3e4c457fe Track `verbose` and `verbose_internals`
bjorn3 says:
> On errors we don't finalize the incr comp cache, but non-fatal diagnostics are cached afaik.
Otherwise we would have to replay the query in question, which we may not be able to do if the query
key is not reconstructible from the dep node fingerprint.

So we must track these flags to avoid replaying incorrect diagnostics.
2024-01-20 08:00:09 -05:00
John Kåre Alsaker 862011e1ca Avoid code generation for ThinVec<Diagnostic>'s destructor in the query system 2024-01-20 13:43:05 +01:00
bors 227abacaef Auto merge of #120003 - Mark-Simulacrum:opt-promoted, r=davidtwco
perf: Don't track specific live points for promoteds

We don't query this information out of the promoted (it's basically a single "unit" regardless of the complexity within it) and this saves on re-initializing the SparseIntervalMatrix's backing IndexVec with mostly empty rows for all of the leading regions in the function. Typical promoteds will only contain a few regions that need up be uplifted, while the parent function can have thousands.

For a simple function repeating println!("Hello world"); 50,000 times this reduces compile times from 90 to 15 seconds in debug mode. The previous implementations re-initialization led to an overall roughly n^2 runtime as each promoted initialized slots for ~n regions, now we scale closer to linearly (5000 hello worlds takes 1.1 seconds).

cc https://github.com/rust-lang/rust/issues/50994, https://github.com/rust-lang/rust/issues/86244
2024-01-20 11:21:28 +00:00
Matthias Krüger bb816e67b4
Rollup merge of #120155 - compiler-errors:no-erased-when-promoting, r=aliemjay
Don't use `ReErased` to detect type test promotion failed

Using `ReErased` here is convenient because it implicitly stores the state that we are explicitly recording with the `failed` variable now, but I also think it adds a tiny bit of complexity that is not worth it.

r? `@aliemjay`
2024-01-20 09:37:30 +01:00
Matthias Krüger b7c2ba71c8
Rollup merge of #120148 - trevyn:issue-117965, r=cjgillot
`single_use_lifetimes`: Don't suggest deleting lifetimes with bounds

Closes #117965

```
9 |     pub fn get<'b: 'a>(&'b self) -> &'a str {
  |                ^^       -- ...is used only here
  |                |
  |                this lifetime...
```

In this example, I think the `&'b self` can be replaced with the bound itself, yielding `&'a self`, but this would require a deeper refactor. Happy to do as a follow-on PR if desired.
2024-01-20 09:37:28 +01:00
Matthias Krüger 409949bc23
Rollup merge of #120135 - oli-obk:smir_private, r=celinval
SMIR: Make the remaining "private" fields actually private

Turns out we have already created a trait that allows us to make the fields private: https://doc.rust-lang.org/nightly/nightly-rustc/stable_mir/ty/trait.IndexedVal.html

fixes https://github.com/rust-lang/project-stable-mir/issues/56

r? `@celinval`
2024-01-20 09:37:28 +01:00
Matthias Krüger 177d51372c
Rollup merge of #119752 - estebank:ice-ice, r=fmease
Avoid ICEs in trait names without `dyn`

Check diagnostic is error before downgrading. Fix #119633.

 Account for traits using self-trait by name without `dyn`. Fix #119652.
2024-01-20 09:37:27 +01:00
Matthias Krüger 2de5ca25d2
Rollup merge of #119613 - gavinleroy:expose-obligations, r=lcnr
Expose Obligations created during type inference.

This PR is a first pass at exposing the trait obligations generated and solved for during the type-check progress. Exposing these obligations allows for rustc plugins to use the public interface for proof trees (provided by the next gen trait solver).

The changes proposed track *all* obligations during the type-check process, this is desirable to not only look at the trees of failed obligations, but also those of successfully proved obligations. This feature is placed behind an unstable compiler option `track-trait-obligations` which should be used together with the `next-solver` option. I should note that the main interface is the function `inspect_typeck` made public in `rustc_hir_typeck/src/lib.rs` which allows the caller to provide a callback granting access to the `FnCtxt`.

r? `@lcnr`
2024-01-20 09:37:26 +01:00
Matthias Krüger 6f67208d72
Rollup merge of #118799 - GKFX:stabilize-simple-offsetof, r=wesleywiser
Stabilize single-field offset_of

This PR stabilizes offset_of for a single field. There has been some further discussion at https://github.com/rust-lang/rust/issues/106655 about whether this is advisable; I'm opening the PR anyway so that the code is available.
2024-01-20 09:37:26 +01:00
bors 5378c1cf07 Auto merge of #119821 - oli-obk:reveal_all_const_evals, r=lcnr
Always use RevealAll for const eval queries

implements what is described in https://github.com/rust-lang/rust/pull/116803#discussion_r1364089471

Using `UserFacing` for const eval does not make sense anymore, unless we significantly change things like avoiding revealing opaque types.

New tests are copied from https://github.com/rust-lang/rust/pull/101478
2024-01-20 04:57:51 +00:00
Josh Stone 33e0422826 Pack the u128 in LitKind::Int 2024-01-19 20:10:39 -08:00
Josh Stone 167555f36a Pack the u128 in SwitchTargets 2024-01-19 20:10:39 -08:00
Josh Stone cb7d863e74 Add Pu128 = #[repr(packed(8))] u128 2024-01-19 20:10:38 -08:00
bors 128148d4cf Auto merge of #120136 - matthiaskrgr:rollup-3zzb0z9, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #117561 (Stabilize `slice_first_last_chunk`)
 - #117662 ([rustdoc] Allows links in headings)
 - #119815 (Format sources into the error message when loading codegen backends)
 - #119835 (Exhaustiveness: simplify empty pattern logic)
 - #119984 (Change return type of unstable `Waker::noop()` from `Waker` to `&Waker`.)
 - #120009 (never_patterns: typecheck never patterns)
 - #120122 (Don't add needs-triage to A-diagnostics)
 - #120126 (Suggest `.swap()` when encountering conflicting borrows from `mem::swap` on a slice)
 - #120134 (Restrict access to the private field of newtype indexes)

Failed merges:

 - #119968 (Remove unused/unnecessary features)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-20 02:58:08 +00:00
Michael Goulet 078a979229 Don't use ReErased to detect type test promotion failed 2024-01-20 02:35:08 +00:00
Mark Rousskov c3364a23d2 perf: Don't track specific live points for promoteds
We don't query this information out of the promoted (it's basically a
single "unit" regardless of the complexity within it) and this saves on
re-initializing the SparseIntervalMatrix's backing IndexVec with mostly
empty rows for all of the leading regions in the function. Typical
promoteds will only contain a few regions that need up be uplifted,
while the parent function can have thousands.

For a simple function repeating println!("Hello world"); 50,000 times
this reduces compile times from 90 to 15 seconds in debug mode. The
previous implementations re-initialization led to an overall roughly n^2
runtime as each promoted initialized slots for ~n regions, now we scale
closer to linearly (5000 hello worlds takes 1.1 seconds).
2024-01-19 20:49:51 -05:00
bors 0547c41f90 Auto merge of #116672 - maurer:128-align, r=nikic
LLVM 18 x86 data layout update

With https://reviews.llvm.org/D86310 LLVM now has i128 aligned to 16-bytes on x86 based platforms. This will be in LLVM-18. This patch updates all our spec targets to be 16-byte aligned, and removes the alignment when speaking to older LLVM.

This results in Rust overaligning things relative to LLVM on older LLVMs.

This implements MCP https://github.com/rust-lang/compiler-team/issues/683.

See #54341
2024-01-20 00:56:53 +00:00
Esteban Küber c85bb274f6 Account for trailing comma in removal suggestion 2024-01-19 23:55:05 +00:00
Esteban Küber 2c2f3ed2c4 Provide more context on recursive `impl` evaluation overflow
When an associated type `Self::Assoc` is part of a `where` clause,
we end up unable to evaluate the requirement and emit a E0275.

We now point at the associated type if specified in the `impl`. If
so, we also suggest using that type instead of `Self::Assoc`.
Otherwise, we explain that these are not allowed.

```
error[E0275]: overflow evaluating the requirement `<(T,) as Grault>::A == _`
  --> $DIR/impl-wf-cycle-1.rs:15:1
   |
LL | / impl<T: Grault> Grault for (T,)
LL | |
LL | | where
LL | |     Self::A: Baz,
LL | |     Self::B: Fiz,
   | |_________________^
LL |   {
LL |       type A = ();
   |       ------ associated type `<(T,) as Grault>::A` is specified here
   |
note: required for `(T,)` to implement `Grault`
  --> $DIR/impl-wf-cycle-1.rs:15:17
   |
LL | impl<T: Grault> Grault for (T,)
   |                 ^^^^^^     ^^^^
...
LL |     Self::A: Baz,
   |              --- unsatisfied trait bound introduced here
   = note: 1 redundant requirement hidden
   = note: required for `(T,)` to implement `Grault`
help: associated type for the current `impl` cannot be restricted in `where` clauses, remove this bound
   |
LL -     Self::A: Baz,
LL +     ,
   |
```
```
error[E0275]: overflow evaluating the requirement `<T as B>::Type == <T as B>::Type`
  --> $DIR/impl-wf-cycle-3.rs:7:1
   |
LL | / impl<T> B for T
LL | | where
LL | |     T: A<Self::Type>,
   | |_____________________^
LL |   {
LL |       type Type = bool;
   |       --------- associated type `<T as B>::Type` is specified here
   |
note: required for `T` to implement `B`
  --> $DIR/impl-wf-cycle-3.rs:7:9
   |
LL | impl<T> B for T
   |         ^     ^
LL | where
LL |     T: A<Self::Type>,
   |        ------------- unsatisfied trait bound introduced here
help: replace the associated type with the type specified in this `impl`
   |
LL |     T: A<bool>,
   |          ~~~~
```
```
error[E0275]: overflow evaluating the requirement `<T as Filter>::ToMatch == <T as Filter>::ToMatch`
  --> $DIR/impl-wf-cycle-4.rs:5:1
   |
LL | / impl<T> Filter for T
LL | | where
LL | |     T: Fn(Self::ToMatch),
   | |_________________________^
   |
note: required for `T` to implement `Filter`
  --> $DIR/impl-wf-cycle-4.rs:5:9
   |
LL | impl<T> Filter for T
   |         ^^^^^^     ^
LL | where
LL |     T: Fn(Self::ToMatch),
   |        ----------------- unsatisfied trait bound introduced here
note: associated types for the current `impl` cannot be restricted in `where` clauses
  --> $DIR/impl-wf-cycle-4.rs:7:11
   |
LL |     T: Fn(Self::ToMatch),
   |           ^^^^^^^^^^^^^
```

Fix #116925
2024-01-19 23:55:05 +00:00
Esteban Küber 6b7e6ea590 Account for traits using self-trait by name without `dyn`
Fix #119652.
2024-01-19 23:37:39 +00:00
Esteban Küber b1688b48d2 Avoid ICE: Check diagnostic is error before downgrading
Fix #119633.
2024-01-19 23:36:20 +00:00
trevyn de2575f35d Don't delete any lifetimes with bounds 2024-01-20 02:30:58 +04:00
Michael Goulet f2ef88ba06 Consolidate logic around resolving built-in coroutine trait impls 2024-01-19 21:28:37 +00:00
George Bateman 7924c9bcdf
Split remaining offset_of features into new tracking issues 2024-01-19 21:13:11 +00:00
George Bateman 615946db4f
Stabilize simple offset_of 2024-01-19 20:38:51 +00:00
Michael Goulet f26f52c42b Validate AggregateKind types in MIR 2024-01-19 19:47:03 +00:00
Catherine Flores 5a4561749a Add new intrinsic `is_constant` and optimize `pow`
Fix overflow check

Make MIRI choose the path randomly and rename the intrinsic

Add back test

Add miri test and make it operate on `ptr`

Define `llvm.is.constant` for primitives

Update MIRI comment and fix test in stage2

Add const eval test

Clarify that both branches must have the same side effects

guaranteed non guarantee

use immediate type instead

Co-Authored-By: Ralf Jung <post@ralfj.de>
2024-01-19 13:46:27 -05:00
Rowan S-L 1c77f8738f add help message for `exclusive_range_pattern` error 2024-01-19 13:38:24 -05:00
Matthias Krüger ee126973b0
Rollup merge of #120134 - oli-obk:newtype_index_private_field, r=compiler-errors
Restrict access to the private field of newtype indexes

Well... we don't have the capability to forbid you to access private fields in the same module, and I don't want to add module shenanigans in the expansion of the macro. So... we just name the field creatively so that no one actually uses it.
2024-01-19 19:27:03 +01:00
Matthias Krüger c851150236
Rollup merge of #120126 - sjwang05:issue-102269, r=compiler-errors
Suggest `.swap()` when encountering conflicting borrows from `mem::swap` on a slice

This PR modifies the existing suggestion by matching on `[ProjectionElem::Deref, ProjectionElem::Index(_)]` instead of just `[ProjectionElem::Index(_)]`, which caused us to miss many cases. Additionally, it adds a more specific, machine-applicable suggestion in the case we determine `mem::swap` was used to swap elements in a slice.

Closes #102269
2024-01-19 19:27:03 +01:00
Matthias Krüger 5761c36c0a
Rollup merge of #120009 - Nadrieril:never_patterns_tyck, r=compiler-errors
never_patterns: typecheck never patterns

This checks that a `!` pattern is only used on an uninhabited type (modulo match ergonomics, i.e. `!` is allowed on `&Void`).

r? `@compiler-errors`
2024-01-19 19:27:02 +01:00
Matthias Krüger 2587100a9b
Rollup merge of #119835 - Nadrieril:simplify-empty-logic, r=compiler-errors
Exhaustiveness: simplify empty pattern logic

The logic that handles empty patterns had gotten quite convoluted. This PR simplifies it a lot. I tried to make the logic as easy as possible to follow; this only does logically equivalent changes.

The first commit is a drive-by comment clarification that was requested after another PR a while back.

r? `@compiler-errors`
2024-01-19 19:27:00 +01:00
Matthias Krüger ae09415fa4
Rollup merge of #119815 - nagisa:nagisa/polishes-libloading-use-somewhat, r=bjorn3
Format sources into the error message when loading codegen backends

cc https://github.com/rust-lang/rustc_codegen_cranelift/issues/1447
cc `@bjorn3`
2024-01-19 19:27:00 +01:00
Matthias Krüger 64461dab01
Rollup merge of #117561 - tgross35:split-array, r=scottmcm
Stabilize `slice_first_last_chunk`

This PR does a few different things based around stabilizing `slice_first_last_chunk`. They are split up so this PR can be by-commit reviewed, I can move parts to a separate PR if desired.

This feature provides a very elegant API to extract arrays from either end of a slice, such as for parsing integers from binary data.

## Stabilize `slice_first_last_chunk`

ACP: https://github.com/rust-lang/libs-team/issues/69
Implementation: https://github.com/rust-lang/rust/issues/90091
Tracking issue: https://github.com/rust-lang/rust/issues/111774

This stabilizes the functionality from https://github.com/rust-lang/rust/issues/111774:

```rust
impl [T] {
    pub const fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>;
    pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
    pub const fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>;
    pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>;
    pub const fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>;
    pub fn split_first_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T; N], &mut [T])>;
    pub const fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>;
    pub fn split_last_chunk_mut<const N: usize>(&mut self) -> Option<(&mut [T], &mut [T; N])>;
}
```

Const stabilization is included for all non-mut methods, which are blocked on `const_mut_refs`. This change includes marking the trivial function `slice_split_at_unchecked` const-stable for internal use (but not fully stable).

## Remove `split_array` slice methods

Tracking issue: https://github.com/rust-lang/rust/issues/90091
Implementation: https://github.com/rust-lang/rust/pull/83233#pullrequestreview-780315524

This PR also removes the following unstable methods from the `split_array` feature, https://github.com/rust-lang/rust/issues/90091:

```rust
impl<T> [T] {
    pub fn split_array_ref<const N: usize>(&self) -> (&[T; N], &[T]);
    pub fn split_array_mut<const N: usize>(&mut self) -> (&mut [T; N], &mut [T]);

    pub fn rsplit_array_ref<const N: usize>(&self) -> (&[T], &[T; N]);
    pub fn rsplit_array_mut<const N: usize>(&mut self) -> (&mut [T], &mut [T; N]);
}
```

This is done because discussion at #90091 and its implementation PR indicate a strong preference for nonpanicking APIs that return `Option`. The only difference between functions under the `split_array` and `slice_first_last_chunk` features is `Option` vs. panic, so remove the duplicates as part of this stabilization.

This does not affect the array methods from `split_array`. We will want to revisit these once `generic_const_exprs` is further along.

## Reverse order of return tuple for `split_last_chunk{,_mut}`

An unresolved question for #111774 is whether to return `(preceding_slice, last_chunk)` (`(&[T], &[T; N])`) or the reverse (`(&[T; N], &[T])`), from `split_last_chunk` and `split_last_chunk_mut`. It is currently implemented as `(last_chunk, preceding_slice)` which matches `split_last -> (&T, &[T])`. The first commit changes these to `(&[T], &[T; N])` for these reasons:

- More consistent with other splitting methods that return multiple values: `str::rsplit_once`, `slice::split_at{,_mut}`, `slice::align_to` all return tuples with the items in order
- More intuitive (arguably opinion, but it is consistent with other language elements like pattern matching `let [a, b, rest @ ..] ...`
- If we ever added a varidic way to obtain multiple chunks, it would likely return something in order: `.split_many_last::<(2, 4)>() -> (&[T], &[T; 2], &[T; 4])`
- It is the ordering used in the `rsplit_array` methods

I think the inconsistency with `split_last` could be acceptable in this case, since for `split_last` the scalar `&T` doesn't have any internal order to maintain with the other items.

## Unresolved questions

Do we want to reserve the same names on `[u8; N]` to avoid inference confusion? https://github.com/rust-lang/rust/pull/117561#issuecomment-1793388647

---

`slice_first_last_chunk` has only been around since early 2023, but `split_array` has been around since 2021.

`@rustbot` label -T-libs +T-libs-api -T-libs +needs-fcp
cc `@rust-lang/wg-const-eval,` `@scottmcm` who raised this topic, `@clarfonthey` implementer of `slice_first_last_chunk` `@jethrogb` implementer of `split_array`

Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Stabilizing.20array-from-slice.20*something*.3F

Fixes: #111774
2024-01-19 19:26:59 +01:00
bors 88189a71e4 Auto merge of #120123 - lcnr:sadboi-compat, r=jackh726
use implied bounds compat mode in MIR borrowck

cc
- #119956
- #118553

This should hopefully fix bevy 🤔 `cargo test` ends up freezing my computer though, cargo build went from err to ok however 😁

r? `@jackh726`
2024-01-19 18:25:19 +00:00
Oli Scherer 225f0b9fef Make the remaining "private" fields actually private 2024-01-19 16:37:50 +00:00
bors 32ec40c685 Auto merge of #120121 - matthiaskrgr:rollup-razammh, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #118665 (Consolidate all associated items on the NonZero integer types into a single impl block per type)
 - #118798 (Use AtomicU8 instead of AtomicUsize in backtrace.rs)
 - #119062 (Deny braced macro invocations in let-else)
 - #119138 (Docs: Use non-SeqCst in module example of atomics)
 - #119907 (Update `fn()` trait implementation docs)
 - #120083 (Warn when not having a profiler runtime means that coverage tests won't be run/blessed)
 - #120107 (dead_code treats #[repr(transparent)] the same as #[repr(C)])
 - #120110 (Update documentation for Vec::into_boxed_slice to be more clear about excess capacity)
 - #120113 (Remove myself from review rotation)
 - #120118 (Fix typo in documentation in base.rs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-19 16:26:37 +00:00
Oli Scherer 93740f9493 Restrict access to the private field of newtype indexes 2024-01-19 15:38:47 +00:00
Gavin Gray 130b7e713e Add trait obligation tracking to FulfillCtxt and expose FnCtxt in rustc_infer using callback.
Pass each obligation to an fn callback with its respective inference context. This avoids needing to keep around copies of obligations or inference contexts.

Specify usability of inspect_typeck in comment.
2024-01-19 15:38:27 +01:00
lcnr 058ab53dc5 use implied bounds compat mode in MIR borrowck 2024-01-19 15:27:32 +01:00
Oli Scherer 867831a170 Always use RevealAll for const eval queries 2024-01-19 11:32:34 +00:00
Oli Scherer 6cd6539026 Use the new `with_tables` everywhere 2024-01-19 11:25:38 +00:00
Nikita Popov ec55a05374 Update more data layouts 2024-01-19 11:09:30 +01:00
Celina G. Val 9aace67235 Ensure internal function is safe
The internal function was unsound, it could cause UB in rare cases where
the user inadvertly stored the returned object in a location that could
outlive the TyCtxt.

In order to make it safe, we now take a type context as an argument to
the internal fn, and we ensure that interned items are lifted using the
provided context.

Thus, this change ensures that the compiler can properly enforce
that the object does not outlive the type context it was lifted to.
2024-01-19 10:00:32 +00:00
Matthew Maurer dbff90c2a7 LLVM 18 x86 data layout update
With https://reviews.llvm.org/D86310 LLVM now has i128 aligned to
16-bytes on x86 based platforms. This will be in LLVM-18. This patch
updates all our spec targets to be 16-byte aligned, and removes the
alignment when speaking to older LLVM.

This results in Rust overaligning things relative to LLVM on older LLVMs.

This alignment change was discussed in rust-lang/compiler-team#683

See #54341 for additional information about why this is happening and
where this will be useful in the future.

This *does not* stabilize `i128`/`u128` for FFI.
2024-01-19 10:52:01 +01:00
Oli Scherer 61361c16aa Fix `Stable` trait and its impls to work with the new `with_tables` 2024-01-19 09:42:51 +00:00
Oli Scherer 06a9dbe5e8 Fix a soundness bug in `with_tables`.
We were able to uplift any value from `Tables` to `'static`, which is unsound.
2024-01-19 09:42:30 +00:00
sjwang05 f9faf16181
Suggest .swap() instead of mem::swap() in more cases 2024-01-19 01:30:46 -08:00
bors 92d727796b Auto merge of #120112 - matthiaskrgr:rollup-48o3919, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119582 (bootstrap: handle vendored sources when remapping crate paths)
 - #119730 (docs: fix typos)
 - #119828 (Improved collapse_debuginfo attribute, added command-line flag)
 - #119869 (replace `track_errors` usages with bubbling up `ErrorGuaranteed`)
 - #120037 (Remove `next_root_ty_var`)
 - #120094 (tests/ui/asm/inline-syntax: adapt for LLVM 18)
 - #120096 (Set RUSTC_BOOTSTRAP=1 consistently)
 - #120101 (change `.unwrap()` to `?` on write where `fmt::Result` is returned)
 - #120102 (Fix typo in munmap_partial.rs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-19 08:42:17 +00:00
Matthias Krüger b4616f5f65
Rollup merge of #120118 - kapilsinha:patch-1, r=Nilstrieb
Fix typo in documentation in base.rs
2024-01-19 08:15:06 +01:00
Matthias Krüger 332f8f73ea
Rollup merge of #120107 - shepmaster:dead-code-repr-transparent, r=Nilstrieb
dead_code treats #[repr(transparent)] the same as #[repr(C)]

In #92972 we enabled linting on unused fields in tuple structs. In #118297 that lint was enabled by default. That exposed issues like #119659, where the fields of a struct marked `#[repr(transparent)]` were reported by the `dead_code` lint. The language team [decided](https://github.com/rust-lang/rust/issues/119659#issuecomment-1885172045) that the lint should treat `repr(transparent)` the same as `#[repr(C)]`.

Fixes #119659
2024-01-19 08:15:05 +01:00
Matthias Krüger 2e4c6fc998
Rollup merge of #119062 - compiler-errors:asm-in-let-else, r=davidtwco,est31
Deny braced macro invocations in let-else

Fixes #119057

Pending T-lang decision

cc `@dtolnay`
2024-01-19 08:15:03 +01:00
bors 16fadb3f25 Auto merge of #120069 - Mark-Simulacrum:fast-memcpy, r=oli-obk
Optimize large array creation in const-eval

This changes repeated memcpy's to a memset for the case that we're propagating a single byte into a region of memory. It also optimizes the element-by-element copies to have a tighter loop; I'm pretty sure the old code was actually doing a multiply within each loop iteration.

For an 8GB array (`static SLICE: [u8; SIZE] = [0u8; 1 << 33];`) this takes us from ~23 seconds to ~6 seconds locally, which is spent roughly 50/50 in (a) memset to zero and (b) memcpy of the original place into a new place, when popping stack frame. The latter seems hard to avoid but is a big memcpy (since we're copying the type rather than initializing a region, so it's pretty fast), and the first is as good as it's going to get without special casing constant-valued arrays.

Closes https://github.com/rust-lang/rust/issues/55795. (That issue's references to lint checking don't appear true anymore, but I think this closes that case as something that is slow due to *time* pretty fully. An 8GB array taking only 6 seconds feels reasonable enough to not merit further tracking).
2024-01-19 06:44:19 +00:00
bors 1bd42be8cb Auto merge of #120076 - Mark-Simulacrum:unhash, r=cjgillot
Use UnhashMap for a few more maps

This avoids a few cases of hashing data that's already hashed.

cc https://github.com/rust-lang/rust/issues/56308
2024-01-19 04:43:17 +00:00
Kamalesh Palanisamy d0dea8323e Modify GenericArg and Term structs to use strict provenance rules 2024-01-18 23:03:46 -05:00
bors d3c9082a44 Auto merge of #120006 - cjgillot:no-hir-owner, r=wesleywiser
Get rid of the hir_owner query.

This query was meant as a firewall between `hir_owner_nodes` which is supposed to change often, and the queries that only depend on the item signature. That firewall was inefficient, leaking the contents of the HIR body through `HirId`s.

`hir_owner` incurs a significant cost, as we need to hash HIR twice in multiple modes. This PR proposes to remove it, and simplify the hashing scheme.

For the future, `def_kind`, `def_span`... are much more efficient for incremental decoupling, and should be preferred.
2024-01-19 02:36:13 +00:00
kapilsinha 1a343424f3
Fix typo in documentation in base.rs 2024-01-18 17:49:06 -08:00
Camille GILLOT e72b2b18c0 Extract process_assign. 2024-01-18 22:53:07 +00:00
Camille GILLOT b22742e8f3 Extract process_constant. 2024-01-18 22:53:07 +00:00
Camille GILLOT be9668d398 Use an interpreter in jump threading. 2024-01-18 22:53:07 +00:00
Nadrieril d8b72e796e Typecheck never patterns 2024-01-18 21:15:24 +01:00
Matthias Krüger ca0c740041
Rollup merge of #120101 - mj10021:issue-120090-fix, r=WaffleLapkin
change `.unwrap()` to `?` on write where `fmt::Result` is returned

Fixes #120090 which points out that some of the `.unwrap()`s in `rustc_middle/src/mir/pretty.rs` are likely meant to be `?`s
2024-01-18 20:56:22 +01:00
Matthias Krüger 39514a9a3f
Rollup merge of #120037 - compiler-errors:remove-next-root-var-helper, r=lcnr
Remove `next_root_ty_var`

Uhh we seem to not have any test that relies on this anymore. Maybe due to the way we changed alias-relate or whatever.

Removing this hack helper fn because #119106 is the general solution.

r? lcnr
2024-01-18 20:56:20 +01:00
Matthias Krüger fa52edaa51
Rollup merge of #119869 - oli-obk:track_errors2, r=matthewjasper
replace `track_errors` usages with bubbling up `ErrorGuaranteed`

more of the same as https://github.com/rust-lang/rust/pull/117449 (removing `track_errors`)
2024-01-18 20:56:20 +01:00
Matthias Krüger c0da80f418
Rollup merge of #119828 - azhogin:azhogin/collapse_debuginfo_improved_attr, r=petrochenkov
Improved collapse_debuginfo attribute, added command-line flag

Improved attribute collapse_debuginfo with variants: `#[collapse_debuginfo=(no|external|yes)]`.
Added command-line flag for default behaviour.
Work-in-progress: will add more tests.

cc https://github.com/rust-lang/rust/issues/100758
2024-01-18 20:56:19 +01:00
bors 25f8d01fd8 Auto merge of #114231 - ttsugriy:binary_search_slice, r=cjgillot
[rustc_data_structures] Use partition_point to find  slice range end.

This PR uses approach introduced in https://github.com/rust-lang/rust/pull/114152 to find
the end of the range. It's much easier to understand and reason about invariants of such
implementation.
Technically it's possible to make it even shorter by returning `&[start..end]` unconditionally
because even if searched item is not present in the slice, `start` and `end` would point at
the same index, so the range would be empty. The reason I decided not to use this shorter
implementation is because it would involve more comparisons in case there are no elements
in the slice with key equal to `key`.

Also, not that it matters much, but this implementation also improves perf according to the
benchmark below:
https://gist.github.com/ttsugriy/63c0ed39ae132b131931fa1f8a3dea55

The results on my M1 macbook air are:
```
Running benches/bin_search_slice_benchmark.rs (target/release/deps/bin_search_slice_benchmark-90fa6d68c3bd1298)
Benchmarking multiply add/binary_search_slice: Collecting 100 samples in estimated 5.0002 s (1
multiply add/binary_search_slice
                        time:   [44.719 ns 44.918 ns 45.158 ns]
                        No change in performance detected.
Found 3 outliers among 100 measurements (3.00%)
  1 (1.00%) high mild
  2 (2.00%) high severe
Benchmarking multiply add/binary_search_slice_new: Collecting 100 samples in estimated 5.0001
multiply add/binary_search_slice_new
                        time:   [36.955 ns 37.060 ns 37.221 ns]
                        No change in performance detected.
Found 7 outliers among 100 measurements (7.00%)
  3 (3.00%) high mild
  4 (4.00%) high severe
```
2024-01-18 18:54:54 +00:00
Michael Goulet 9d15b5037f Remove next_root_ty_var 2024-01-18 18:28:35 +00:00
Jake Goulding d95d6ceecb `dead_code` treats `#[repr(transparent)]` the same as `#[repr(C)]`
Fixes #119659
2024-01-18 13:04:31 -05:00
bors 8424f8e8cd Auto merge of #120089 - matthiaskrgr:rollup-xyfqrb5, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #119172 (Detect `NulInCStr` error earlier.)
 - #119833 (Make tcx optional from StableMIR run macro and extend it to accept closures)
 - #119967 (Add `PatKind::Err` to AST/HIR)
 - #119978 (Move async closure parameters into the resultant closure's future eagerly)
 - #120021 (don't store const var origins for known vars)
 - #120038 (Don't create a separate "basename" when naming and opening a MIR dump file)
 - #120057 (Don't ICE when deducing future output if other errors already occurred)
 - #120073 (Remove spastorino from users_on_vacation)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-18 16:39:32 +00:00
Nadrieril 0a9bb97229 Consistently warn unreachable subpatterns 2024-01-18 17:29:54 +01:00
Oli Scherer e532b0dd7e Don't forget that the lifetime on hir types is `'tcx` 2024-01-18 16:07:10 +00:00
James Dietz c13c746b47 change unwrap to `?` on write where result is returned 2024-01-18 10:11:04 -05:00
Nadrieril 753680afe8 Consistently set `MatchVisitor.error` on error 2024-01-18 15:42:25 +01:00
bors a34faab155 Auto merge of #118553 - jackh726:lint-implied-bounds, r=lcnr
error on incorrect implied bounds in wfcheck except for Bevy dependents

Rebase of #109763

Additionally, special cases Bevy `ParamSet` types to not trigger the lint. This is tracked in #119956.

Fixes #109628
2024-01-18 14:16:55 +00:00
David Wood 46652dd254
llvm: simplify data layout check
Don't skip the inconsistent data layout check for custom LLVMs.

With #118708, all targets will have a simple test that would trigger this
check if LLVM's data layouts do change - so data layouts would be
corrected during the LLVM upgrade. Therefore, with builtin targets, this
check won't trigger with our LLVM because each target will have been
confirmed to work. With non-builtin targets, this check is probably
useful to have because you can change the data layout in your target and
if its wrong then that could lead to bugs.

When using a custom LLVM, the same justification makes sense for
non-builtin targets as with our LLVM, the user can update their target to
match their LLVM and that's probably a good thing to do. However, with
a custom LLVM, the user cannot change the builtin target data layouts if
they don't match - though given that the compiler's data layout is used
for layout computation and a bunch of other things - you could get some
bugs because of the mismatch and probably want to know about that.

`CFG_LLVM_ROOT` was also always set during local development with
`download-ci-llvm` so this bug would never trigger locally.

Signed-off-by: David Wood <david@davidtw.co>
2024-01-18 10:46:03 +00:00
Matthias Krüger 34362b826d
Rollup merge of #120057 - oli-obk:not_sure_wtf_is_going_on, r=compiler-errors
Don't ICE when deducing future output if other errors already occurred

The situation can't really happen outside of erroneous code. What was interesting is that it ICEd before emitting any other diagnostics. This was because the other errors were silenced due to cycle_delay_bug cycle errors.

r? ```@compiler-errors```

fixes #119890
2024-01-18 10:34:20 +01:00
Matthias Krüger c526cce281
Rollup merge of #120038 - Zalathar:dump-path, r=WaffleLapkin
Don't create a separate "basename" when naming and opening a MIR dump file

These functions were split up by #77080, in order to support passing the dump file's “basename” (filename without extension) to the implementation of `-Zdump-mir-spanview`, so that it could be used as a page title.

That flag has since been removed (#119566), so now there's no particular reason for this code to handle the basename separately from the filename or full path.

This PR therefore restores things to (roughly) how they were before #77080.
2024-01-18 10:34:19 +01:00
Matthias Krüger b185606961
Rollup merge of #120021 - lcnr:const-var-value, r=compiler-errors
don't store const var origins for known vars

r? types
2024-01-18 10:34:19 +01:00
Matthias Krüger 536fc22917
Rollup merge of #119978 - compiler-errors:async-closure-captures, r=oli-obk
Move async closure parameters into the resultant closure's future eagerly

Move async closure parameters into the closure's resultant future eagerly.

Before, we used to desugar `async |p1, p2, ..| { body }` as `|p1, p2, ..| { || async { body } }`. Now, we desugar the above like `|p1, p2, ..| { async move { let p1 = p1; let p2 = p2; ... body } }`. This mirrors the same desugaring that `async fn` does with its parameter types, and the compiler literally uses the same code via a shared helper function.

This removes the necessity for E0708, since now expressions like `async |x: i32| { x }` will not give you confusing borrow errors.

This does *not* fix the case where async closures have self-borrows. This will come with a general implementation of async closures, which is still in the works.

r? oli-obk
2024-01-18 10:34:18 +01:00
Matthias Krüger 1f93d2b411
Rollup merge of #119967 - ShE3py:patkind-err, r=WaffleLapkin
Add `PatKind::Err` to AST/HIR

#116715 added `thir::PatKind::Error`; this PR adds `hir::PatKind::Err` and `ast::PatKind::Err` (see https://github.com/rust-lang/rust/pull/118625#discussion_r1446587901.)

---

``@rustbot`` label +A-patterns
r? WaffleLapkin
2024-01-18 10:34:18 +01:00
Matthias Krüger c3e237c3ac
Rollup merge of #119833 - celinval:smir-accept-closures, r=oli-obk
Make tcx optional from StableMIR run macro and extend it to accept closures

Change `run` macro to avoid sometimes unnecessary dependency on `TyCtxt`, and introduce `run_with_tcx` to capture use cases where `tcx` is required. Additionally, extend both macros to accept closures that may capture variables.

I've also modified the `internal()` method to make it safer, by accepting the type context to force the `'tcx` lifetime to match the context lifetime.

These are non-backward compatible changes, but they only affect internal APIs which are provided today as helper functions until we have a stable API to start the compiler.
2024-01-18 10:34:17 +01:00
Matthias Krüger ff8c7a7816
Rollup merge of #119172 - nnethercote:earlier-NulInCStr, r=petrochenkov
Detect `NulInCStr` error earlier.

By making it an `EscapeError` instead of a `LitError`. This makes it like the other errors produced when checking string literals contents, e.g. for invalid escape sequences or bare CR chars.

NOTE: this means these errors are issued earlier, before expansion, which changes behaviour. It will be possible to move the check back to the later point if desired. If that happens, it's likely that all the string literal contents checks will be delayed together.

One nice thing about this: the old approach had some code in `report_lit_error` to calculate the span of the nul char from a range. This code used a hardwired `+2` to account for the `c"` at the start of a C string literal, but this should have changed to a `+3` for raw C string literals to account for the `cr"`, which meant that the caret in `cr"` nul error messages was one short of where it should have been. The new approach doesn't need any of this and avoids the off-by-one error.

r? ```@fee1-dead```
2024-01-18 10:34:17 +01:00
Celina G. Val 6a573cbc60 Revert changes to internal method for now
- Move fix to a separate PR
2024-01-17 19:59:57 -08:00
Jack Huey a9e30e6cdf Don't use compat versions of implied bounds in ImpliedOutlivesBounds query 2024-01-17 22:03:06 -05:00
John Kåre Alsaker 63446d00ee Remove `OneThread` 2024-01-18 03:30:05 +01:00
Jack Huey acab76573f Add -Zno-implied-bounds-compat option and use it 2024-01-17 21:27:34 -05:00
Ali MJ Al-Nasrawy d96003dd2a Correctly handle normalization in implied bounds
Special-case Bevy dependents to not error
2024-01-17 21:27:34 -05:00
Mark Rousskov e68f3039d4 Optimize large array creation in const-eval
This changes repeated memcpy's to a memset for the case that we're
propagating a single byte into a region of memory.
2024-01-17 20:24:20 -05:00
Michael Goulet ec263df5e4 Suggest wrapping mac args in parens rather than the whole expression 2024-01-18 00:01:13 +00:00
Michael Goulet c1c7707238 Deny braced macro invocations in let-else 2024-01-17 23:59:11 +00:00
Mark Rousskov 510fcd318b Use UnhashMap for a few more maps
This avoids hashing data that's already hashed.
2024-01-17 17:09:55 -05:00
clubby789 b9ebeee4da Remove `box <expr>` recovery 2024-01-17 21:16:22 +00:00
Matthias Krüger 99a8b6aa67
Rollup merge of #120056 - oli-obk:arg_mismatch_ice, r=compiler-errors
Use FnOnceOutput instead of FnOnce where expected

fixes #119847
2024-01-17 20:21:24 +01:00
Matthias Krüger 3a3242a0f9
Rollup merge of #120039 - Nadrieril:remove-idx, r=compiler-errors
pat_analysis: Don't rely on contiguous `VariantId`s outside of rustc

Today's pattern_analysis uses `BitSet` and `IndexVec` on the provided enum variant ids, which only makes sense if these ids count the variants from 0. In rust-analyzer, the variant ids are global interning ids, which would make `BitSet` and `IndexVec` ridiculously wasteful. In this PR I add some shims to use `FxHashSet`/`FxHashMap` instead outside of rustc.

r? ```@compiler-errors```
2024-01-17 20:21:23 +01:00
Matthias Krüger e0aa4df798
Rollup merge of #120032 - Nadrieril:fix-rustc_abi, r=Nilstrieb
Fix `rustc_abi` build on stable

https://github.com/rust-lang/rust/pull/119446 broke the ability of `rustc_abi` to build on stable, which is required by rust-analyzer. This fixes it.
2024-01-17 20:21:22 +01:00
Matthias Krüger cd5eb6a896
Rollup merge of #120031 - compiler-errors:construct-closure-ty-eagerly, r=oli-obk
Construct closure type eagerly

Construct the returned closure type *before* checking the body, in the same match as we were previously deducing the coroutine types based off of the closure kind.

This simplifies some changes I'm doing in the async closure PR, and imo just seems easier to read (since we only need one match on closure kind, instead of two). There's no reason I can tell that we needed to create the closure type *after* the body was checked.

~~This also has the side-effect of making it so that the universe of the closure synthetic infer vars are lower than any infer vars that come from checking the body. We can also get rid of `next_root_ty_var` hack from closure checking (though in general we still need this, #119106). cc ```@lcnr``` since you may care about this hack 😆~~

r? ```@oli-obk```
2024-01-17 20:21:22 +01:00
Matthias Krüger 6ca77ff722
Rollup merge of #120020 - oli-obk:long_const_eval_err_taint, r=compiler-errors
Gracefully handle missing typeck information if typeck errored

fixes #116893

I created some logs and the typeck of `fn main` is exactly the same, no matter whether the constant's body is what it is, or if it is replaced with `panic!()`. The latter will cause the ICE not to be emitted though. The reason for that is that we abort compilation if *errors* were emitted, but not if *lint errors* were emitted. This took me way too long to debug, and is another reason why I would have liked https://github.com/rust-lang/compiler-team/issues/633
2024-01-17 20:21:21 +01:00
Matthias Krüger 22f19130df
Rollup merge of #119975 - lukas-code:inferring-return-types-and-opaque-types-do-mix-sometimes, r=compiler-errors
Don't ICE if TAIT-defining fn contains a closure with `_` in return type

The `delay_span_bug` got added in 0e82aaeb67 to reduce the amount of errors emitted for functions that have `_` in their return type, because inference doesn't apply to function items. But this logic shouldn't apply to closures, because their return types *can* be inferred.

Fixes https://github.com/rust-lang/rust/issues/119916.
2024-01-17 20:21:20 +01:00
Matthias Krüger c9779afc9c
Rollup merge of #119855 - rellerreller:freebsd-static, r=wesleywiser
Enable Static Builds for FreeBSD

Enable crt-static for FreeBSD to enable statically compiled binaries.
2024-01-17 20:21:19 +01:00
Matthias Krüger 3ae7ab698f
Rollup merge of #115291 - cjgillot:dest-prop-save, r=JakobDegen
Save liveness results for DestinationPropagation

`DestinationPropagation` needs to verify that merge candidates do not conflict with each other. This is done by verifying that a local is not live when its counterpart is written to.

To get the liveness information, the pass runs `MaybeLiveLocals` dataflow analysis repeatedly, once for each propagation round. This is quite costly, and the main driver for the perf impact on `ucd` and `diesel`. (See https://github.com/rust-lang/rust/pull/115105#issuecomment-1689205908)

In order to mitigate this cost, this PR proposes to save the result of the analysis into a `SparseIntervalMatrix`, and mirror merges of locals into that matrix: `liveness(destination) := liveness(destination) union liveness(source)`.

<details>
<summary>Proof</summary>

We denote by `'` all the quantities of the transformed program. Let $\varphi$ be a mapping of locals, which maps `source` to `destination`, and is identity otherwise. The exact liveness set after a statement is $out'(statement)$, and the proposed liveness set is $\varphi(out(statement))$.

Consider a statement. Suppose that the output state verifies $out' \subset phi(out)$. We want to prove that $in' \subset \varphi(in)$ where $in = (out - kill) \cup gen$, and conclude by induction.

We have 2 cases: either that statement is kept with locals renumbered by $\varphi$, or it is a tautological assignment and it removed.

1. If the statement is kept: the gen-set and the kill-set of $statement' = \varphi(statement)$ are $gen' = \varphi(gen)$ and $kill' = \varphi(kill)$ exactly.
From soundness requirement 3, $\varphi(in)$ is disjoint from $\varphi(kill)$.
This implies that $\varphi(out - kill)$ is disjoint from $\varphi(kill)$, and so $\varphi(out - kill) = \varphi(out) - \varphi(kill)$. Then $\varphi(in) = (\varphi(out) - \varphi(kill)) \cup \varphi(gen) = (\varphi(out) - kill') \cup gen'$.
We can conclude that $out' \subset \varphi(out) \implies in' \subset \varphi(in)$.

2. If the statement is removed. As $\varphi(statement)$ is a tautological assignment, we know that $\varphi(gen) = \varphi(kill) = \\{ destination \\}$, while $gen' = kill' = \emptyset$. So $\varphi(in) = \varphi(out) \cup \\{ destination \\}$. Then $in' = out' \subset out \subset \varphi(in)$.

By recursion, we can conclude by that $in' \subset \varphi(in)$ everywhere.
</details>

This approximate liveness results is only suboptimal if there are locals that fully disappear from the CFG due to an assignment cycle. These cases are quite unlikely, so we do not bother with them.

This change allows to reduce the perf impact of DestinationPropagation by half on diesel and ucd (https://github.com/rust-lang/rust/pull/115105#issuecomment-1694701904).

cc ````@JakobDegen````
2024-01-17 20:21:19 +01:00
Oli Scherer f1ef930c9d Don't ICE when deducing future output if other errors already occurred 2024-01-17 16:27:57 +00:00
bors 6ae4cfbbb0 Auto merge of #118708 - davidtwco:target-tier-assembly-test, r=Mark-Simulacrum
tests: add sanity-check assembly test for every target

Fixes #119910.

Adds a basic assembly test checking that each target can produce assembly and update the target tier policy to require this.

cc rust-lang/compiler-team#655
r? `@wesleywiser`
2024-01-17 16:18:28 +00:00
Andrew Zhogin 8507f5105b Improved collapse_debuginfo attribute, added command-line flag (no|external|yes) 2024-01-17 23:18:14 +07:00
Oli Scherer d6b99b9c92 Use FnOnceOutput instead of FnOnce where expected 2024-01-17 14:23:41 +00:00
bors c58a5da7d4 Auto merge of #119930 - Urgau:check-cfg-empty-values-means-empty, r=petrochenkov
Add way to express that no values are expected with check-cfg

This PR adds way to express no-values (no values expected) with `--check-cfg` by making empty `values()` no longer mean `values(none())` (internal: `&[None]`) and now be an empty list (internal: `&[]`).

### Context

Currently `--check-cfg` has a way to express that _any value is expected_ with `values(any())`, but has no way to do the inverse and say that _no value is expected_.

This would be particularly useful for build systems that control a config name and it's values as they could always declare a config name as expected and if in the current state they have values pass them and if not pass an empty list.

To give a more concrete example, Cargo `--check-cfg` currently needs to generate:
 - `--check-cfg=cfg(feature, values(...))` for the case with declared features
 - and `--check-cfg=cfg()` for the case without any features declared

This means that when there are no features declared, users will get an `unexpected config name` but from the point of view of Cargo the config name `feature` is expected, it's just that for now there aren't any values for it.

See [Cargo `check_cfg_args` function](92395d9010/src/cargo/core/compiler/mod.rs (L1263-L1281)) for more details.

### De-specializing *empty* `values()`

To solve this issue I propose that we "de-specialize" empty `values()` to no longer mean `values(none())` but to actually mean empty set/list. This is one of the last source of confusion for my-self and others with the `--check-cfg` syntax.

> The confusing part here is that an empty `values()` currently means the same as `values(none())`, i.e. an expected list of values with the _none_ variant (as in `#[cfg(name)]` where the value is none) instead of meaning an empty set.

Before the new `cfg()` syntax, defining the _none_ variant was only possible under certain circumstances, so in https://github.com/rust-lang/rust/pull/111068 I decided to make `values()` to mean the _none_ variant, but it is no longer necessary since https://github.com/rust-lang/rust/pull/119473 which introduced the `none()` syntax.

A simplified representation of the proposed "de-specialization" would be:

| Syntax                                  | List/set of expected values |
|-----------------------------------------|-----------------------------|
| `cfg(name)`/`cfg(name, values(none()))` | `&[None]`                   |
| `cfg(name, values())`                   | `&[]`                       |

Note that I have my-self made the mistake of using an empty `values()` as meaning empty set, see https://github.com/rust-lang/cargo/pull/13011.

`@rustbot` label +F-check-cfg
r? `@petrochenkov`
cc `@epage`
2024-01-17 14:01:05 +00:00
bors 52790a98e5 Auto merge of #119670 - cjgillot:gvn-arithmetic, r=oli-obk
Fold arithmetic identities in GVN

Extracted from https://github.com/rust-lang/rust/pull/111344

This PR implements a few arithmetic folds for unary and binary operations.
This should take care of the missed optimizations introduced by https://github.com/rust-lang/rust/pull/116012.
2024-01-17 11:46:49 +00:00
David Wood 12c19a2bb7
target: fix powerpc64-unknown-linux-musl datalayout
In LLVM 17, PowerPC targets started including function pointer alignments
in data layouts, and in Rust's update to that version (#114048), we added
the function pointer alignments. `powerpc64-unknown-linux-musl` had
`Fi64` set but this seems incorrect, and the code in LLVM would always
have computed `Fn32` because it is a MUSL target.

Signed-off-by: David Wood <david@davidtw.co>
2024-01-17 10:38:50 +00:00
Oli Scherer 557b111870 Make crate_inherent_impls fallible and stop using `track_errors` for it 2024-01-17 10:02:29 +00:00
Oli Scherer 49347ee12d Make crate_inherent_impls_overlap_check bubble up its errors 2024-01-17 10:02:25 +00:00
Oli Scherer b1ce8a4ecd Move `check_mod_impl_wf` query call out of track_errors and bubble errors up instead. 2024-01-17 10:02:19 +00:00
Oli Scherer 4db93c5750 Stop using track_errors for some forever unstable rustc_attr analyses 2024-01-17 10:02:14 +00:00
David Wood a87034c297
tests: add sanity-check assembly test for every target
Adds a basic assembly test checking that each target can produce assembly
and update the target tier policy to require this.

Signed-off-by: David Wood <david@davidtw.co>
2024-01-17 09:44:11 +00:00
bors 25b706cde3 Auto merge of #119111 - michaelwoerister:measureme-11, r=Mark-Simulacrum
Update measureme crate to version 11

perf.rlo has been updated to use 11.0.0 already, so it should be able to handle the new file format.

r? `@Mark-Simulacrum`

Fixes https://github.com/rust-lang/rust/issues/99282
Fixes https://github.com/rust-lang/rust/issues/119103
2024-01-17 09:32:03 +00:00
bors 16f4b02dd8 Auto merge of #119922 - nnethercote:fix-Diag-code-is_lint, r=oli-obk
Rework how diagnostic lints are stored.

`Diagnostic::code` has the type `DiagnosticId`, which has `Error` and
`Lint` variants. Plus `Diagnostic::is_lint` is a bool, which should be
redundant w.r.t. `Diagnostic::code`.

Seems simple. Except it's possible for a lint to have an error code, in
which case its `code` field is recorded as `Error`, and `is_lint` is
required to indicate that it's a lint. This is what happens with
`derive(LintDiagnostic)` lints. Which means those lints don't have a
lint name or a `has_future_breakage` field because those are stored in
the `DiagnosticId::Lint`.

It's all a bit messy and confused and seems unintentional.

This commit:
- removes `DiagnosticId`;
- changes `Diagnostic::code` to `Option<String>`, which means both
  errors and lints can straightforwardly have an error code;
- changes `Diagnostic::is_lint` to `Option<IsLint>`, where `IsLint` is a
  new type containing a lint name and a `has_future_breakage` bool, so
  all lints can have those, error code or not.

r? `@oli-obk`
2024-01-17 07:33:52 +00:00
bors 6bf600bc98 Auto merge of #120019 - lcnr:fn-wf, r=BoxyUwU
fix fn/const items implied bounds and wf check (rebase)

A rebase of #104098, see that PR for discussion. This is pretty much entirely the work of `@aliemjay.` I received his permission for this rebase.

---

These are two distinct changes (edit: actually three, see below):
1. Wf-check all fn item args. This is a soundness fix.
Fixes #104005

2. Use implied bounds from impl header in borrowck of associated functions/consts. This strictly accepts more code and helps to mitigate the impact of other breaking changes.
Fixes #98852
Fixes #102611

The first is a breaking change and will likely have a big impact without the the second one. See the first commit for how it breaks libstd.

Landing the second one without the first will allow more incorrect code to pass. For example an exploit of #104005 would be as simple as:
```rust
use core::fmt::Display;

trait ExtendLt<Witness> {
    fn extend(self) -> Box<dyn Display>;
}

impl<T: Display> ExtendLt<&'static T> for T {
    fn extend(self) -> Box<dyn Display> {
        Box::new(self)
    }
}

fn main() {
    let val = (&String::new()).extend();
    println!("{val}");
}
```

The third change is to to check WF of user type annotations before normalizing them (fixes #104764, fixes #104763). It is mutually dependent on the second change above: an attempt to land it separately in #104746 caused several crater regressions that can all be mitigated by using the implied from the impl header. It is also necessary for the soundness of associated consts that use the implied bounds of impl header. See #104763 and how the third commit fixes the soundness issue in `tests/ui/wf/wf-associated-const.rs` that was introduces by the previous commit.

r? types
2024-01-17 02:35:06 +00:00
Lieselotte 7889e99b55
Add `PatKind::Err` 2024-01-17 03:14:16 +01:00
Nadrieril 19d6f068ee Don't rely on contiguous `VariantId`s outside of rustc 2024-01-17 03:09:06 +01:00
Zalathar 1ec567b99a Inline `dump_file_basename` into `dump_path` 2024-01-17 11:46:20 +11:00
Zalathar b82d1d32b4 Inline `create_dump_file_with_basename` 2024-01-17 11:46:20 +11:00
Michael Goulet 37a5464bc8 Eagerly instantiate closure ty 2024-01-17 00:43:44 +00:00
Camille GILLOT d59968b5f6 Simplify BodyId hashing. 2024-01-16 23:52:30 +00:00
Camille GILLOT b99c3ae6d6 Get rid of the hir_owner query. 2024-01-16 23:49:38 +00:00
Celina G. Val 2564811e7b Remove tcx function and make `internal` fn safer
I added `tcx` argument to `internal` to force 'tcx to be the same
lifetime as TyCtxt. The only other solution I could think is to change
this function to be `unsafe`.
2024-01-16 14:35:18 -08:00
Camille GILLOT 0cc2102c4a Expand match over binops. 2024-01-16 22:34:04 +00:00
Camille GILLOT 166fe54eba Explain side-effects from simplify_operand. 2024-01-16 22:34:04 +00:00
Camille GILLOT 22ed51e136 Do not read a scalar on a non-scalar layout. 2024-01-16 22:32:48 +00:00
Camille GILLOT 3c48243b6f Simplify Len. 2024-01-16 22:20:54 +00:00
Camille GILLOT 5fc23ad8e6 Simplify unary operations. 2024-01-16 22:20:54 +00:00
Camille GILLOT 666030c51b Simplify binary ops. 2024-01-16 22:20:53 +00:00
bors 098d4fd74c Auto merge of #119977 - Mark-Simulacrum:defid-cache, r=cjgillot
Cache local DefId-keyed queries without hashing

This caches local DefId-keyed queries using just an IndexVec. This costs ~5% extra max-rss at most but brings significant runtime improvement, up to 13% cycle counts (mean: 4%) on primary benchmarks. It's possible that further tweaks could reduce the memory overhead further but this win seems worth landing despite the increased memory, particularly with regards to eliminating the present set in non-incr or storing it inline (skip list?) with the main data.

We tried applying this scheme to all keys in the [first perf run] but found that it carried a significant memory hit (50%). instructions/cycle counts were also much more mixed, though that may have been due to the lack of the present set optimization (needed for fast iter() calls in incremental scenarios).

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

[first perf run]: https://perf.rust-lang.org/compare.html?start=30dfb9e046aeb878db04332c74de76e52fb7db10&end=6235575300d8e6e2cc6f449cb9048722ef43f9c7&stat=instructions:u
2024-01-16 21:58:10 +00:00
Nadrieril e12101c4db Fix `rustc_abi` build on stable 2024-01-16 21:15:31 +01:00
LegionMammal978 bc3fb5245a Rename `pointer` field on `Pin`
The internal, unstable field of `Pin` can conflict with fields from the
inner type accessed via the `Deref` impl. Rename it from `pointer` to
`__pointer`, to make it less likely to conflict with anything else.
2024-01-16 14:58:42 -05:00
bors 92f2e0aa62 Auto merge of #116520 - Enselic:large-copy-into-fn, r=oli-obk
large_assignments: Lint on specific large args passed to functions

Requires lowering function call arg spans down to MIR, which is done in the second commit.

Part of #83518

Also see
* https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/arg.20Spans.20for.20TerminatorKind.3A.3ACall.3F
* https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/move_size_limit.20lint

r? `@oli-obk` (E-mentor)
2024-01-16 19:33:14 +00:00
Celina G. Val f91ccf9ace Remove tcx from SMIR run macro and accept closures
Simplify the `run` macro to avoid sometimes unnecessary dependency
on `TyCtxt`. Instead, users can use the new internal method `tcx()`.
Additionally, extend the macro to accept closures that may capture
variables.

These are non-backward compatible changes, but they only affect
internal APIs which are provided today as helper functions until we
have a stable API to start the compiler.
2024-01-16 11:17:51 -08:00
Michael Goulet f4e35c60b0 Fix async closure call suggestion 2024-01-16 17:12:10 +00:00
Michael Goulet f1ee076f81 Async closures will move params into the future always 2024-01-16 17:12:10 +00:00
Matthias Krüger 1f0daa5738
Rollup merge of #120002 - Nadrieril:dont-collect, r=compiler-errors
Lint `overlapping_ranges_endpoints` directly instead of collecting into a Vec

In https://github.com/rust-lang/rust/pull/119396 I was a bit silly: I was trying to avoid any lints being fired from within the exhaustiveness algorithm for some vague aesthetic/reusability reason that doesn't really hold. This PR fixes that: instead of passing a `&mut Vec` around I just added a method to the `TypeCx` trait.

r? `@compiler-errors`
2024-01-16 17:55:25 +01:00
Matthias Krüger 4735171667
Rollup merge of #119969 - compiler-errors:simplify-closure-env-ty, r=oli-obk
Simplify `closure_env_ty` and `closure_env_param`

Random cleanup that I found when working on async closures. This makes it easier to separate the latter into a new tykind.
2024-01-16 17:55:23 +01:00
Matthias Krüger 5f9d1d4e09
Rollup merge of #119900 - compiler-errors:closure-checking, r=oli-obk
Inline `check_closure`, simplify `deduce_sig_from_projection`

Some minor cleanups that I've collected when reimplementing async closure

r? oli-obk
2024-01-16 17:55:22 +01:00
Matthias Krüger d4b276caa4
Rollup merge of #119816 - oli-obk:tait_ice_unify_obligations, r=lcnr
Define hidden types in confirmation

fixes  #111470

r? `@lcnr` or `@compiler-errors`

explanation in the newly added test
2024-01-16 17:55:22 +01:00
Lukas Markeffsky 450cb5eda6 Don't ICE if TAIT-defining fn contains a closure with `_` in return type 2024-01-16 15:37:03 +00:00
Mark Rousskov 1696148a89 Merge into larger interval set
This reduces the work done while merging rows. In at least one case
(issue 50450), we have thousands of union([range], [20,000 ranges]),
which previously inserted each of the 20,000 ranges one by one. Now we
only insert one range into the right hand set after copying the set
over.
2024-01-16 10:21:55 -05:00
Michael Goulet 8bb1eaee64 Introduce helper that deals with moving async args into the coroutine 2024-01-16 15:15:00 +00:00
bors 533cfde67c Auto merge of #119947 - compiler-errors:old-solver-instantiate-response, r=lcnr
Make sure to instantiate placeholders correctly in old solver

When creating the query substitution guess for an input placeholder type like `!1_T` (in universe 1), we were guessing the response substitution with something like `!0_T`. This failed to unify with `!1_T`, causing an ICE.

This PR reworks the query substitution guess code to work a bit more like the new solver. I'm *pretty* sure this is correct, though I'd really appreciate some scrutiny from someone (*cough* lcnr) who knows a bit more about query instantiation :)

Fixes #119941

r? lcnr
2024-01-16 13:33:04 +00:00
bors fa0dc208d0 Auto merge of #119672 - cjgillot:dse-sandwich, r=oli-obk
Sandwich MIR optimizations between DSE.

This PR reorders MIR optimization passes in an attempt to increase their efficiency.

- Stop running CopyProp before GVN, it's useless as GVN will do the same thing anyway. Instead, we perform CopyProp at the end of the pipeline, to ensure we do not emit copy/move chains.
- Run DSE before GVN, as it increases the probability to have single-assignment locals.
- Run DSE after the final CopyProp to turn copies into moves.

r? `@ghost`
2024-01-16 11:34:16 +00:00
Oli Scherer 3599c18874 Skip dead code checks on items that failed typeck 2024-01-16 10:52:28 +00:00
lcnr 290651be72 don't store const var origins for known vars 2024-01-16 11:06:42 +01:00
Ali MJ Al-Nasrawy 66090ef7ba try fast path for wf type ops 2024-01-16 09:25:28 +01:00
Ali MJ Al-Nasrawy aac2f84794 wf-check type annotations before normalization 2024-01-16 09:25:28 +01:00
Ali MJ Al-Nasrawy 8d4693c0f8 borrowck: use implied bounds from impl header 2024-01-16 09:25:28 +01:00
Ali MJ Al-Nasrawy a3fe3bbb2c borrowck: wf-check fn item args 2024-01-16 09:25:28 +01:00
bors f9c2421a2a Auto merge of #119439 - cjgillot:gvn-faster, r=oli-obk
Avoid some redundant work in GVN

The first 2 commits are about reducing the perf effect.

Third commit avoids doing redundant work: is a local is SSA, it already has been simplified, and the resulting value is in `self.locals`. No need to call any code on it.

The last commit avoids removing some storage statements.

r? wg-mir-opt
2024-01-16 05:17:49 +00:00
asquared31415 a8bb418ae5 make unsafe_op_in_unsafe_fn MachineApplicable and add it to 2024 compatibility 2024-01-15 23:06:39 +00:00
Mark Rousskov 37849643c6 Cache local DefId-keyed queries without hashing
Foreign maps are used to cache external DefIds, typically backed by
metadata decoding. In the future we might skip caching `V` there (since
loading from metadata usually is already cheap enough), but for now this
cuts down on the impact to memory usage and time to None-init a bunch of
memory. Foreign data is usually much sparser, since we're not usually
loading *all* entries from the foreign crate(s).
2024-01-15 17:16:45 -05:00
bors 714b29a17f Auto merge of #119610 - Nadrieril:never_pattern_bindings, r=compiler-errors
never patterns: Check bindings wrt never patterns

Never patterns:
- Shouldn't contain bindings since they never match anything;
- Don't count when checking that or-patterns have consistent bindings.

r? `@compiler-errors`
2024-01-15 21:24:13 +00:00
Nadrieril 448c4a4efb Remove the unused `overlapping_range_endpoints` Vec 2024-01-15 19:27:06 +01:00
Nadrieril 8b66f497eb Lint overlapping ranges directly from exhaustiveness 2024-01-15 19:27:06 +01:00
Martin Nordholts 8f440f06c6 large_assignments: Lint on specific large args passed to functions 2024-01-15 19:07:12 +01:00
Martin Nordholts 16ba56c242 compiler: Lower fn call arg spans down to MIR
To enable improved accuracy of diagnostics in upcoming commits.
2024-01-15 19:07:11 +01:00
Martin Nordholts 924ea05103 Implement TypeVisitable and TypeFoldable for Spanned
The traits are already implemented for Span, so it makes sense to also
have them for Spanned (upcoming commits will make use of this).
2024-01-15 19:07:11 +01:00
bors 67e7b84425 Auto merge of #119987 - matthiaskrgr:rollup-f7lkx4w, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #119818 (Silence some follow-up errors [3/x])
 - #119870 (std: Doc blocking behavior of LazyLock)
 - #119897 (`OutputTypeParameterMismatch` -> `SignatureMismatch`)
 - #119963 (Fix `allow_internal_unstable` for `(min_)specialization`)
 - #119971 (Use `zip_eq` to enforce that things being zipped have equal sizes)
 - #119974 (Minor `trimmed_def_paths` improvements)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-15 16:45:41 +00:00
Nadrieril d95644d3ae Simplify empty pattern logic some more 2024-01-15 16:56:18 +01:00
Nadrieril de77f1a86e Simplify empty pattern logic a bit 2024-01-15 16:56:18 +01:00
Nadrieril edb27a306a Make all the empty pattern decisions in `usefulness` 2024-01-15 16:56:18 +01:00
Nadrieril bf913ad0ae Simplify use of `ValidityConstraint`
We had reached a point where the shenanigans about omitting empty arms
are unnecessary.
2024-01-15 16:52:51 +01:00
Nadrieril 2ad780eaf0 Clarify that the status of `&!` is undecided 2024-01-15 16:52:51 +01:00
Oli Scherer 9a8f117d7b Don't create the array type twice 2024-01-15 15:49:58 +00:00
Matthias Krüger 82f38ab62e
Rollup merge of #119974 - nnethercote:trimmed_def_paths-improvements, r=compiler-errors
Minor `trimmed_def_paths` improvements

r? `@compiler-errors`
2024-01-15 08:44:50 +01:00
Matthias Krüger b6f68a7fca
Rollup merge of #119971 - compiler-errors:zip-eq, r=nnethercote
Use `zip_eq` to enforce that things being zipped have equal sizes

Some `zip`s are best enforced to be equal, since size mismatches suggest deeper bugs in the compiler.
2024-01-15 08:44:49 +01:00
Matthias Krüger 0891cb4d81
Rollup merge of #119963 - clubby789:spec-allow-internal-unstable, r=compiler-errors
Fix `allow_internal_unstable` for `(min_)specialization`

Fixes #119950

Blocked on #119949 (comment doesn't make sense until that merges)

I'd like to follow this up and look for more instances of not properly checking spans for features but I wanted to fix the motivating issue.
2024-01-15 08:44:49 +01:00
Matthias Krüger 1e46be6a53
Rollup merge of #119897 - compiler-errors:fulfillment-errors, r=lcnr
`OutputTypeParameterMismatch` -> `SignatureMismatch`

I'm probably missing something that made this rename more complicated. What did you end up getting stuck on when renaming this selection error, `@lcnr?`

**also** I renamed the `FulfillmentErrorCode` variants. This is just churn but I wanted to do it forever. I can move it out of this PR if desired.

r? lcnr
2024-01-15 08:44:48 +01:00
Matthias Krüger 73256c68b8
Rollup merge of #119818 - oli-obk:even_more_follow_up_errors3, r=compiler-errors
Silence some follow-up errors [3/x]

this is one piece of the requested cleanups from https://github.com/rust-lang/rust/pull/117449

Keep error types around, even in obligations.

These help silence follow-up errors, as we now figure out that some types (most notably inference variables) are equal to an error type.

But it also allows figuring out more types in the presence of errors, possibly causing more errors.
2024-01-15 08:44:46 +01:00
bors 73252d51d1 Auto merge of #119508 - Zalathar:graph, r=compiler-errors
coverage: Simplify building the coverage graph with `CoverageSuccessors`

This is a collection of simplifications to the code that builds the *basic coverage block* graph, which is a simplified view of the MIR control-flow graph that ignores panics and merges straight-line sequences of blocks into a single BCB node.

The biggest change is to how we determine the coverage-relevant successors of a block. Previously we would call `Terminator::successors` and apply some ad-hoc postprocessing, but with this PR we instead have our own `match` on the terminator kind that produces a coverage-specific enum `CoverageSuccessors`. That enum also includes information about whether a block has exactly one successor that it can be chained into as part of a single BCB.
2024-01-15 06:45:33 +00:00
bors 9567c3ee73 Auto merge of #119581 - Nadrieril:detangle-arena, r=compiler-errors
Exhaustiveness: remove the need for arena-allocation within the algorithm

After https://github.com/rust-lang/rust/pull/119688, exhaustiveness checking doesn't need access to the arena anymore. This simplifies the lifetime story and makes it compile on stable without the extra dependency.

r? `@compiler-errors`
2024-01-15 00:04:09 +00:00
Nicholas Nethercote 32de78cade Replace `TrimmedDefPaths` with a bool.
It's a tri-state enum but the `Always` variant is never used, so a bool
is simpler.
2024-01-15 09:16:14 +11:00
Nicholas Nethercote 086d17b7cb Refactor `try_print_trimmed_def_path`.
Inverting the condition lets us merge the two `Ok(false)` paths. I also
find the inverted condition easier to read: "all the things that must be
true for trimming to occur", instead of "any of the things that must be
true for trimming to not occur".
2024-01-15 09:04:31 +11:00
Nicholas Nethercote 4efddb141a Add some helpful comments in `trimmed_def_paths`.
To explain things that took me a minute to work out.
2024-01-15 08:58:36 +11:00
Michael Goulet c811662fb0 Use zip_eq to enforce that things being zipped have equal sizes 2024-01-14 20:01:12 +00:00
Michael Goulet c5cb87cf0c Closure body was being built incorrectly on error... 2024-01-14 19:59:10 +00:00
Guillaume Gomez d635cec7c6
Rollup merge of #119960 - cjgillot:inline-dg, r=WaffleLapkin
Inline 2 functions that appear in dep-graph profiles.

Those functions are small enough not to deserve a dedicated symbol.
2024-01-14 20:17:24 +01:00
Michael Goulet 6f98a6cc80 Simplify closure_env_ty and closure_env_param 2024-01-14 19:15:46 +00:00
clubby789 eb63d3a49d `allow_internal_unstable(min_specialization)` on `newtype_index` 2024-01-14 19:07:13 +00:00
clubby789 0529ccf341 Fix `allow_internal_unstable` for `(min_)specialization` 2024-01-14 13:50:02 +00:00