Commit Graph

26682 Commits

Author SHA1 Message Date
blyxyas
654b924340 Add sym::iter_mut + sym::as_mut_ptr 2023-07-25 23:33:08 +00:00
Nicholas Nethercote
39d51bd51c Remove Parser::desugar_doc_comments.
It's currently stored twice: once in `Parser`, once in the `TokenStream`
within `Parser`. We only need the latter.
2023-07-26 09:11:18 +10:00
Matthias Krüger
f9b8e6bb62
Rollup merge of #114044 - ericmarkmartin:more-stable-impls, r=spastorino
factor out more stable impls

I saw some logic must resembling stable impls and thought it might be nice to factor it out

r? `@spastorino`
2023-07-25 23:34:08 +02:00
Matthias Krüger
0b13deb548
Rollup merge of #113661 - oli-obk:tait_wtf, r=lcnr
Double check that hidden types match the expected hidden type

Fixes https://github.com/rust-lang/rust/issues/113278 specifically, but I left a TODO for where we should also add some hardening.

It feels a bit like papering over the issue, but at least this way we don't get unsoundness, but just surprising errors. Errors will be improved and given spans before this PR lands.

r? `@compiler-errors` `@lcnr`
2023-07-25 23:34:07 +02:00
Matthias Krüger
a6bf68d8d0
Rollup merge of #113578 - compiler-errors:uncallable-sig, r=b-naber
Don't say that a type is uncallable if its fn signature has errors in it

This is fallout from #106309, where we don't consider param-env candidates that reference errors because they unify with everything. This means, however, that we don't consider an APIT like `impl Fn(MissingType)` isn't considered to implement `Fn`, for example.

We can double-check that with a weaker heuristic [`extract_callable_info`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_typeck/fn_ctxt/struct.FnCtxt.html#method.extract_callable_info), and suppress the knock-down error using that.

Fixes #113566
2023-07-25 23:34:07 +02:00
Matthias Krüger
c5c0aa143c
Rollup merge of #112995 - strottos:ref-clone-suggestions, r=fee1-dead
Check for `<&NotClone as Clone>::clone()` calls and suggest to add Clone trait appropriately

Added recursive checking back up the HIR to see if a `Clone` suggestion would be helpful.

Addresses https://github.com/rust-lang/rust/issues/112857

Largely based on: https://github.com/rust-lang/rust/pull/112977
2023-07-25 23:34:06 +02:00
Matthias Krüger
c64ef5e070 inline format!() args from rustc_codegen_llvm to the end (4)
r? @WaffleLapkin
2023-07-25 23:20:28 +02:00
Eric Huss
2d92f4f2aa Remove -Z diagnostic-width 2023-07-25 14:00:56 -07:00
Ralf Jung
da3f0d0eb7 make MPlaceTy non-Copy 2023-07-25 22:35:07 +02:00
Ralf Jung
77ff1b83cd interpret: make read functions generic over operand type 2023-07-25 22:33:59 +02:00
Ralf Jung
00fb45dccd interpret: make write functions generic over the place type 2023-07-25 22:33:58 +02:00
Catherine Flores
79b6ed0e08 Only early return if recovered 2023-07-25 19:17:33 +00:00
bors
18fa7b9104 Auto merge of #114063 - matthiaskrgr:rollup-c90czu6, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #114008 (coverage: Obtain the `__llvm_covfun` section name outside a per-function loop)
 - #114014 (builtin_macros: expect raw strings too)
 - #114043 (docs(LazyLock): add example pass local LazyLock variable to struct)
 - #114051 (Add regression test for invalid "unused const" in method)
 - #114052 (Suggest `{Option,Result}::as_ref()` instead of `cloned()` in some cases)
 - #114058 (Add help for crate arg when crate name is invalid)
 - #114060 (abi: unsized field in union - assert to delay bug )

r? `@ghost`
`@rustbot` modify labels: rollup
2023-07-25 18:58:30 +00:00
Catherine Flores
faa73953c0 Remove unnecessary maybe_ternary_lo field 2023-07-25 18:37:56 +00:00
Catherine Flores
16481807f5 Gracefully handle missing ternary operator 2023-07-25 18:27:24 +00:00
Matthias Krüger
ba6982b8a0
Rollup merge of #114060 - davidtwco:issue-113279, r=wesleywiser
abi: unsized field in union - assert to delay bug

Fixes #113279.

> Unions cannot have unsized fields, and as such, layout computation for
unions asserts that each union field is sized (as this would normally
have halted compilation earlier).
>
> However, if a generator ends up with an unsized local - a circumstance
in which an error will always have been emitted earlier, for example, if
attempting to dereference a `&str` - then the generator transform will
produce a union with an unsized field.
>
> Since https://github.com/rust-lang/rust/pull/110107, later passes will be run, such as constant propagation,
and can attempt layout computation on the generator, which will result
in layout computation of `str` in the context of it being a field of a
union - and so the aforementioned assertion would cause an ICE.
>
> It didn't seem appropriate to try and detect this case in the MIR body
and skip this specific pass; tainting the MIR body or delaying a bug
from the generator transform (or elsewhere) wouldn't prevent this either
(as neither would prevent the later pass from running); and tainting when
the deref of `&str` is reported, if that's possible, would unnecessarily
prevent potential other errors from being reported later in compilation,
and is very tailored to this specific case of getting a unsized type in
a generator.
>
> Given that this circumstance can only happen when an error should have
already been reported, the correct fix appears to be just changing the
assert to a delayed bug. This will still assert if there is some
circumstance where this occurs and no error has been reported, but it
won't crash the compiler in this instance.

While debugging this, I noticed a translation ICE in a delayed bug, so I fixed that too:

> During borrowck, the `MultiSpan` from a buffered diagnostic is cloned and
used to emit a delayed bug indicating a diagnostic was buffered - when
the buffered diagnostic is translated, then the cloned `MultiSpan` may
contain labels which can only render with the diagnostic's arguments, but
the delayed bug being emitted won't have those arguments. Adds a function
which clones `MultiSpan` without also cloning the contained labels, and
use this function when creating the buffered diagnostic delayed bug.
2023-07-25 19:21:39 +02:00
Matthias Krüger
de5228e489
Rollup merge of #114058 - chenyukang:yukang-fix-113981-crate-arg, r=fmease,oli-obk
Add help for crate arg when crate name is invalid

Fixes #113981
2023-07-25 19:21:38 +02:00
Matthias Krüger
b7a1ff2aaa
Rollup merge of #114052 - clubby789:suggest-option-asref, r=WaffleLapkin
Suggest `{Option,Result}::as_ref()` instead of `cloned()` in some cases

Fixes #114050

When we have an expr available that produces the type expectation, we can suggest appending `.as_ref()` to the span, instead of cloning the expr producing the mismatch
2023-07-25 19:21:38 +02:00
Matthias Krüger
8ecaf2ae57
Rollup merge of #114014 - davidtwco:issue-114010-env-rawstr, r=cjgillot
builtin_macros: expect raw strings too

Fixes #114010.

`expr_to_string` allows raw strings through so this code should be expected to handle those.
2023-07-25 19:21:37 +02:00
Matthias Krüger
24e34e2014
Rollup merge of #114008 - Zalathar:covfun-section-name, r=cjgillot
coverage: Obtain the `__llvm_covfun` section name outside a per-function loop

This section name is always constant for a given target, but obtaining it from LLVM requires a few intermediate allocations. There's no need to do so repeatedly from inside a per-function loop.
2023-07-25 19:21:36 +02:00
bors
8327047b23 Auto merge of #113393 - compiler-errors:next-solver-unsize-rhs, r=lcnr
Normalize the RHS of an `Unsize` goal in the new solver

`Unsize` goals are... tricky. Not only do they structurally match on their self type, but they're also structural on their other type parameter. I'm pretty certain that it is both incomplete and also just plain undesirable to not consider normalizing the RHS of an unsize goal. More practically, I'd like for this code to work:

```rust
trait A {}
trait B: A {}

impl A for usize {}
impl B for usize {}

trait Mirror {
    type Assoc: ?Sized;
}

impl<T: ?Sized> Mirror for T {
    type Assoc = T;
}

fn main() {
    // usize: Unsize<dyn B>
    let x = Box::new(1usize) as Box<<dyn B as Mirror>::Assoc>;
    // dyn A: Unsize<dyn B>
    let y = x as Box<<dyn A as Mirror>::Assoc>;
}
```

---

In order to achieve this, we add `EvalCtxt::normalize_non_self_ty` (naming modulo bikeshedding), which *must* be used for all non-self type arguments that are structurally matched in candidate assembly. Currently this is only necessary for `Unsize`'s argument, but I could see future traits requiring this (hopefully rarely) in the future. It uses `repeat_while_none` to limit infinite looping, and normalizes the self type until it is no longer an alias.

Also, we need to fix feature gate detection for `trait_upcasting` and `unsized_tuple_coercion` when HIR typeck has unnormalized types. We can do that by checking the `ImplSource` returned by selection, which necessitates adding a new impl source for tuple upcasting.
2023-07-25 17:10:31 +00:00
Michael Goulet
a7ed9c1da7 Make everything builtin! 2023-07-25 16:08:58 +00:00
yukang
e0c479eea2 Add help for crate arg when crate name is invalid 2023-07-26 00:05:00 +08:00
Michael Goulet
de81007d13 Consolidate trait upcasting and unsize into one normalization 2023-07-25 15:15:25 +00:00
Michael Goulet
c02d1a6553 Restore tuple unsizing feature gate 2023-07-25 15:15:25 +00:00
Michael Goulet
24eefd08e2 Make sure to detect trait upcasting coercion even after normalization 2023-07-25 15:15:25 +00:00
Michael Goulet
7e66c0b7ed Normalize the RHS of an unsize goal 2023-07-25 15:15:25 +00:00
David Wood
037b27430b
abi: unsized field in union - assert to delay bug
Unions cannot have unsized fields, and as such, layout computation for
unions asserts that each union field is sized (as this would normally
have halted compilation earlier).

However, if a generator ends up with an unsized local - a circumstance
in which an error will always have been emitted earlier, for example, if
attempting to dereference a `&str` - then the generator transform will
produce a union with an unsized field.

Since #110107, later passes will be run, such as constant propagation,
and can attempt layout computation on the generator, which will result
in layout computation of `str` in the context of it being a field of a
union - and so the aforementioned assertion would cause an ICE.

It didn't seem appropriate to try and detect this case in the MIR body
and skip this specific pass; tainting the MIR body or delaying a bug
from the generator transform (or elsewhere) wouldn't prevent this either
(as neither would prevent the later pass from running); and tainting when
the deref of `&str` is reported, if that's possible, would unnecessarily
prevent potential other errors from being reported later in compilation,
and is very tailored to this specific case of getting a unsized type in
a generator.

Given that this circumstance can only happen when an error should have
already been reported, the correct fix appears to be just changing the
assert to a delayed bug. This will still assert if there is some
circumstance where this occurs and no error has been reported, but it
won't crash the compiler in this instance.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-25 15:50:39 +01:00
bors
4fc6b33474 Auto merge of #114011 - RalfJung:place-projection, r=oli-obk
interpret: Unify projections for MPlaceTy, PlaceTy, OpTy

For ~forever, we didn't really have proper shared code for handling projections into those three types. This is mostly because `PlaceTy` projections require `&mut self`: they might have to `force_allocate` to be able to represent a project part-way into a local.

This PR finally fixes that, by enhancing `Place::Local` with an `offset` so that such an optimized place can point into a part of a place without having requiring an in-memory representation. If we later write to that place, we will still do `force_allocate` -- for now we don't have an optimized path in `write_immediate` that would avoid allocation for partial overwrites of immediately stored locals. But in `write_immediate` we have `&mut self` so at least this no longer pollutes all our type signatures.

(Ironically, I seem to distantly remember that many years ago, `Place::Local` *did* have an `offset`, and I removed it to simplify things. I guess I didn't realize why it was so useful... I am also not sure if this was actually used to achieve place projection on `&self` back then.)

The `offset` had type `Option<Size>`, where `None` represent "no projection was applied". This is needed because locals *can* be unsized (when they are arguments) but `Place::Local` cannot store metadata: if the offset is `None`, this refers to the entire local, so we can use the metadata of the local itself (which must be indirect); if a projection gets applied, since the local is indirect, it will turn into a `Place::Ptr`. (Note that even for indirect locals we can have `Place::Local`: when the local appears in MIR, we always start with `Place::Local`, and only check `frame.locals` later. We could eagerly normalize to `Place::Ptr` but I don't think that would actually simplify things much.)

Having done all that, we can finally properly abstract projections: we have a new `Projectable` trait that has the basic methods required for projecting, and then all projection methods are implemented for anything that implements that trait. We can even implement it for `ImmTy`! (Not that we need that, but it seems neat.) The visitor can be greatly simplified; it doesn't need its own trait any more but it can use the `Projectable` trait. We also don't need the separate `Mut` visitor any more; that was required only to reflect that projections on `PlaceTy` needed `&mut self`.

It is possible that there are some more `&mut self` that can now become `&self`... I guess we'll notice that over time.

r? `@oli-obk`
2023-07-25 14:18:08 +00:00
Oli Scherer
2b444672e1 Use a builder instead of boolean/option arguments 2023-07-25 13:51:15 +00:00
Oli Scherer
df4bfd9e97 Try explaining where Inner is in the signature better 2023-07-25 13:40:04 +00:00
Oli Scherer
cf9f53c837 Remove a redundant field 2023-07-25 13:33:09 +00:00
Oli Scherer
b7f8eba9fd Inline a function that is only used once 2023-07-25 13:30:04 +00:00
Oli Scherer
8d60f7573d Remove some arguments that are always the same 2023-07-25 13:25:53 +00:00
clubby789
c83dfe9aed Suggest {Option,Result}::as_ref() instead of cloned() in some cases 2023-07-25 13:19:27 +00:00
Ralf Jung
d127600511 add some sanity checks in write_immediate_no_validate 2023-07-25 14:30:58 +02:00
Ralf Jung
14a674c88c interpret: read_discriminant: only return VariantIdx 2023-07-25 14:30:58 +02:00
Ralf Jung
a2bcafa500 interpret: refactor projection code to work on a common trait, and use that for visitors 2023-07-25 14:30:58 +02:00
bors
23405bb123 Auto merge of #113476 - fee1-dead-contrib:c-str-lit, r=petrochenkov
Reimplement C-str literals

This reverts #113334, cc `@fmease.`

While converting lexer tokens to ast Tokens in `rustc_parse`, we check the edition of the span of the token. If the edition < 2021, we split the token into two, one being the identifier and other being the str literal.
2023-07-25 12:04:34 +00:00
Mahdi Dibaiee
b2d052b22d write-long-types-to-disk: update tests 2023-07-25 12:08:44 +01:00
David Wood
75df62d4a2
builtin_macros: raw str in diagnostic output
If a raw string was used in the `env!` invocation, then it should also
be shown in the diagnostic messages as a raw string.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-25 11:12:52 +01:00
Deadbeef
a0376e9ec2 extract common code 2023-07-25 09:24:12 +00:00
Steven Trotter
25db1fac81 Added recursive checking back up to see if a Clone suggestion would be helpful. 2023-07-25 10:09:26 +01:00
bors
5b1dc9de77 Auto merge of #113980 - bvanjoi:fix-113953, r=petrochenkov
fix(resolve): skip panic when resolution is dummy

Fixes #113953

Skip the panic when the binding refers to a dummy node during the finalization.

r? `@petrochenkov`
2023-07-25 05:25:11 +00:00
Eric Mark Martin
0a0ce4905d factor out more stable impls 2023-07-25 00:49:49 -04:00
bors
d24c4da1d6 Auto merge of #113411 - unikraft:unikraft, r=wesleywiser
Add `x86_64-unikraft-linux-musl` target

This introduces `x86_64-unikraft-linux-musl` as the first Rust target for the [Unikraft] Unikernel Development Kit.

[Unikraft]: https://unikraft.org/

Unikraft imitates Linux and uses musl as libc.
It is extremely configurable, and does not even provide a `poll` implementation or a network stack, unless enabled by the end user who compiles the application.

Our approach for integrating the build process with `rustc` is to hide the build process as well as the actual final linking step behind a linker-shim (`kraftld`, see https://github.com/unikraft/kraftkit/issues/612).

## Tier 3 target policy

> - A tier 3 target must have a designated developer or developers (the "target
>   maintainers") on record to be CCed when issues arise regarding the target.
>   (The mechanism to track and CC such developers may evolve over time.)

I will be the target maintainer.

> - Targets must use naming consistent with any existing targets; for instance, a
>   target for the same CPU or OS as an existing Rust target should use the same
>   name for that CPU or OS. Targets should normally use the same names and
>   naming conventions as used elsewhere in the broader ecosystem beyond Rust
>   (such as in other toolchains), unless they have a very good reason to
>   diverge. Changing the name of a target can be highly disruptive, especially
>   once the target reaches a higher tier, so getting the name right is important
>   even for a tier 3 target.
>   - Target names should not introduce undue confusion or ambiguity unless
>     absolutely necessary to maintain ecosystem compatibility. For example, if
>     the name of the target makes people extremely likely to form incorrect
>     beliefs about what it targets, the name should be changed or augmented to
>     disambiguate it.
>   - If possible, use only letters, numbers, dashes and underscores for the name.
>     Periods (`.`) are known to cause issues in Cargo.

The target name `x86_64-unikraft-linux-musl` was derived from `x86_64-unknown-linux-musl`, setting Unikraft as vendor.
Unikraft exactly imitates Linux + musl.

> - Tier 3 targets may have unusual requirements to build or use, but must not
>   create legal issues or impose onerous legal terms for the Rust project or for
>   Rust developers or users.
>   - The target must not introduce license incompatibilities.
>   - Anything added to the Rust repository must be under the standard Rust
>     license (`MIT OR Apache-2.0`).
>   - The target must not cause the Rust tools or libraries built for any other
>     host (even when supporting cross-compilation to the target) to depend
>     on any new dependency less permissive than the Rust licensing policy. This
>     applies whether the dependency is a Rust crate that would require adding
>     new license exceptions (as specified by the `tidy` tool in the
>     rust-lang/rust repository), or whether the dependency is a native library
>     or binary. In other words, the introduction of the target must not cause a
>     user installing or running a version of Rust or the Rust tools to be
>     subject to any new license requirements.
>   - Compiling, linking, and emitting functional binaries, libraries, or other
>     code for the target (whether hosted on the target itself or cross-compiling
>     from another target) must not depend on proprietary (non-FOSS) libraries.
>     Host tools built for the target itself may depend on the ordinary runtime
>     libraries supplied by the platform and commonly used by other applications
>     built for the target, but those libraries must not be required for code
>     generation for the target; cross-compilation to the target must not require
>     such libraries at all. For instance, `rustc` built for the target may
>     depend on a common proprietary C runtime library or console output library,
>     but must not depend on a proprietary code generation library or code
>     optimization library. Rust's license permits such combinations, but the
>     Rust project has no interest in maintaining such combinations within the
>     scope of Rust itself, even at tier 3.
>   - "onerous" here is an intentionally subjective term. At a minimum, "onerous"
>     legal/licensing terms include but are *not* limited to: non-disclosure
>     requirements, non-compete requirements, contributor license agreements
>     (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms,
>     requirements conditional on the employer or employment of any particular
>     Rust developers, revocable terms, any requirements that create liability
>     for the Rust project or its developers or users, or any requirements that
>     adversely affect the livelihood or prospects of the Rust project or its
>     developers or users.

No dependencies were added to Rust.
Requirements for linking are [Unikraft] and [KraftKit] (both BSD-3-Clause), but none of these are added to Rust.

[KraftKit]: https://github.com/unikraft/kraftkit

> - Neither this policy nor any decisions made regarding targets shall create any
>   binding agreement or estoppel by any party. If any member of an approving
>   Rust team serves as one of the maintainers of a target, or has any legal or
>   employment requirement (explicit or implicit) that might affect their
>   decisions regarding a target, they must recuse themselves from any approval
>   decisions regarding the target's tier status, though they may otherwise
>   participate in discussions.
>   - This requirement does not prevent part or all of this policy from being
>     cited in an explicit contract or work agreement (e.g. to implement or
>     maintain support for a target). This requirement exists to ensure that a
>     developer or team responsible for reviewing and approving a target does not
>     face any legal threats or obligations that would prevent them from freely
>     exercising their judgment in such approval, even if such judgment involves
>     subjective matters or goes beyond the letter of these requirements.

Understood.
I am not a member of a Rust team.

> - Tier 3 targets should attempt to implement as much of the standard libraries
>   as possible and appropriate (`core` for most targets, `alloc` for targets
>   that can support dynamic memory allocation, `std` for targets with an
>   operating system or equivalent layer of system-provided functionality), but
>   may leave some code unimplemented (either unavailable or stubbed out as
>   appropriate), whether because the target makes it impossible to implement or
>   challenging to implement. The authors of pull requests are not obligated to
>   avoid calling any portions of the standard library on the basis of a tier 3
>   target not implementing those portions.

Understood.
`std` is supported.

> - The target must provide documentation for the Rust community explaining how
>   to build for the target, using cross-compilation if possible. If the target
>   supports running binaries, or running tests (even if they do not pass), the
>   documentation must explain how to run such binaries or tests for the target,
>   using emulation if possible or dedicated hardware if necessary.

Building is described in the platform support doc.
It will be updated once proper `kraftld` support has landed.

> - Tier 3 targets must not impose burden on the authors of pull requests, or
>   other developers in the community, to maintain the target. In particular,
>   do not post comments (automated or manual) on a PR that derail or suggest a
>   block on the PR based on a tier 3 target. Do not send automated messages or
>   notifications (via any medium, including via ``@`)` to a PR author or others
>   involved with a PR regarding a tier 3 target, unless they have opted into
>   such messages.
>   - Backlinks such as those generated by the issue/PR tracker when linking to
>     an issue or PR are not considered a violation of this policy, within
>     reason. However, such messages (even on a separate repository) must not
>     generate notifications to anyone involved with a PR who has not requested
>     such notifications.

Understood.

> - Patches adding or updating tier 3 targets must not break any existing tier 2
>   or tier 1 target, and must not knowingly break another tier 3 target without
>   approval of either the compiler team or the maintainers of the other tier 3
>   target.
>   - In particular, this may come up when working on closely related targets,
>     such as variations of the same architecture with different features. Avoid
>     introducing unconditional uses of features that another variation of the
>     target may not have; use conditional compilation or runtime detection, as
>     appropriate, to let each target run code supported by that target.

I don't think this PR breaks anything.

r? compiler-team
2023-07-25 03:41:56 +00:00
bors
beef07fe8f Auto merge of #113958 - lukas-code:doc-links, r=GuillaumeGomez,petrochenkov
fix intra-doc links on nested `use` and `extern crate` items

This PR fixes two rustdoc ICEs that happen if there are any intra-doc links on nested `use` or `extern crate` items, for example:
```rust
/// Re-export [`fmt`] and [`io`].
pub use std::{fmt, io}; // "nested" use = use with braces

/// Re-export [`std`].
pub extern crate std;
```

Nested use items were incorrectly considered private and therefore didn't have their intra-doc links resolved. I fixed this by always resolving intra-doc links for nested `use` items that are declared `pub`.

<details>

During AST->HIR lowering, nested `use` items are desugared like this:
```rust
pub use std::{}; // "list stem"
pub use std::fmt;
pub use std::io;
```
Each of these HIR nodes has it's own effective visibility and the list stem is always considered private.
To check the effective visibility of an AST node, the AST node is mapped to a HIR node with `Resolver::local_def_id`, which returns the (private) list stem for nested use items.

</details>

For `extern crate`, there was a hack in rustdoc that stored the `DefId` of the crate itself in the cleaned item, instead of the `DefId` of the `extern crate` item. This made rustdoc look at the resolved links of the extern crate's crate root instead of the `extern crate` item. I've removed this hack and instead translate the `DefId` in the appropriate places.

As as side effect of fixing `extern crate`, i've turned
```rust
#[doc(masked)]
extern crate self as _;
```
into a no-op instead of hiding all trait impls. Proper verification for `doc(masked)` is included as a bonus.

fixes https://github.com/rust-lang/rust/issues/113896
2023-07-25 01:35:53 +00:00
bors
fd56162af0 Auto merge of #113921 - davidtwco:lint-ctypes-issue-113900, r=petrochenkov
lint/ctypes: only try normalize

Fixes #113900.

Now that this lint runs on any external-ABI fn-ptr, normalization won't always succeed, so use `try_normalize_erasing_regions` instead.
2023-07-24 19:40:01 +00:00
bohan
4cc3834a5c resolve: ensure compile failed when has dummy or ambiguous 2023-07-25 01:57:12 +08:00
bohan
02f1f6a8a8 fix(resolve): skip panic when resolution is dummy 2023-07-25 01:34:03 +08:00
bors
fc8a3e357a Auto merge of #114024 - matthiaskrgr:rollup-uhdbq64, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #113969 (add dynamic for smir)
 - #113985 (Use erased self type when autoderefing for trait error suggestion)
 - #113987 (Comment stuff in the new solver)
 - #113992 (arm-none fixups)
 - #113993 (Optimize format usage)
 - #113994 (Optimize format usage)
 - #114006 (Update sparc-unknown-none-elf platform README)
 - #114021 (Add missing documentation for `Session::time`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-07-24 17:13:24 +00:00
Martin Kröning
bb77aa845b
compiler: Add x86_64-unikraft-linux-musl target
Signed-off-by: Martin Kröning <martin.kroening@eonerc.rwth-aachen.de>
2023-07-24 18:24:50 +02:00
Lukas Markeffsky
637ea3f746 validate doc(masked) 2023-07-24 18:04:35 +02:00
Matthias Krüger
a5164252ad
Rollup merge of #114021 - GuillaumeGomez:session-time-docs, r=lcnr
Add missing documentation for `Session::time`

r? `@lcnr`
2023-07-24 17:47:11 +02:00
Matthias Krüger
3723b309c0
Rollup merge of #113994 - nyurik:parser-fmt-ref, r=davidtwco
Optimize format usage

Per #112156, using `&` in `format!` may cause a small perf delay, so I tried to clean up one module at a time format usage. This PR includes a few removals of the ref in format (they do compile locally without the ref), as well as a few format inlining for consistency.
2023-07-24 17:47:10 +02:00
Matthias Krüger
974a1c242f
Rollup merge of #113993 - nyurik:ref_format_errors, r=WaffleLapkin
Optimize format usage

Per #112156, using `&` in `format!` may cause a small perf delay, so I tried to clean up one module at a time format usage. This PR includes a few removals of the ref in format (they do compile locally without the ref), as well as a few format inlining for consistency.
2023-07-24 17:47:10 +02:00
Matthias Krüger
4d2f98d306
Rollup merge of #113992 - chrisnc:arm-none-fixups, r=oli-obk
arm-none fixups

- Remove "-unknown" from `llvm_target` for arm\*v7r-none-eabi\* targets.
- Remove redundant `c_enum_min_bits` option from the thumbv4t-none-eabi target.
- Fix comments about GCC/Clang's enum width for arm-none targets.

Previously part of #110482, which is a larger change to add a new target.
These nits were found along the way.
2023-07-24 17:47:09 +02:00
Matthias Krüger
2660d5d977
Rollup merge of #113987 - compiler-errors:comments, r=lcnr
Comment stuff in the new solver

r? `@lcnr`
2023-07-24 17:47:09 +02:00
Matthias Krüger
15c723433f
Rollup merge of #113985 - compiler-errors:issue-113951, r=estebank
Use erased self type when autoderefing for trait error suggestion

Let's not try to pass something from `skip_binder` into autoderef.

Fixes #113951
2023-07-24 17:47:08 +02:00
Matthias Krüger
60a5d2dbde
Rollup merge of #113969 - ericmarkmartin:smir-ty-dynamic, r=spastorino
add dynamic for smir

r? spastorino
2023-07-24 17:47:08 +02:00
Michael Goulet
3ad3bb64d9
lcnr's suggestions
Co-authored-by: lcnr <rust@lcnr.de>
2023-07-24 08:37:40 -07:00
Oli Scherer
30f787800a Explain RPITs in the way they actually work 2023-07-24 15:34:36 +00:00
bors
cb6ab9516b Auto merge of #113956 - fmease:rustdoc-fix-x-crate-rpitits, r=GuillaumeGomez,compiler-errors
rustdoc: handle cross-crate RPITITs correctly

Filter out the internal associated types synthesized during the desugaring of RPITITs, they really shouldn't show up in the docs.

This also fixes #113929 since we're no longer invoking `is_impossible_associated_item` (renamed from `is_impossible_method`) which cannot handle them (leading to an ICE). I don't think it makes sense to try to make `is_impossible_associated_item` handle this exotic kind of associated type (CC original author `@compiler-errors).`

@ T-rustdoc reviewers, currently I'm throwing out ITIT assoc tys before cleaning assoc tys at each usage-site. I'm thinking about making `clean_middle_assoc_item` return an `Option<_>` instead and doing the check inside of it to prevent any call sites from forgetting the check for ITITs. Since I wasn't sure if you would like that approach, I didn't go through with it. Let me know what you think.

<details><summary>Explanation on why <code>is_impossible_associated_item(itit_assoc_ty)</code> leads to an ICE</summary>

Given the following code:

```rs
pub trait Trait { fn def<T>() -> impl Default {} }
impl Trait for () {}
```

The generated associated type looks something like (simplified):

```rs
type {opaque#0}<T>: Default = impl Default; // the name is actually `kw::Empty` but this is the `def_path_str` repr
```

The query `is_impossible_associated_item` goes through all predicates of the associated item – in this case `<T as Sized>` – to check if they contain any generic parameters from the (generic) associated type itself. For predicates that don't contain any *own* generics, it does further processing, part of which is instantiating the predicate with the generic arguments of the impl block (which is only correct if they truly don't contain any own generics since they wouldn't get instantiated this way leading to an ICE).

It checks if `parent_def_id(T) == assoc_ty_def_id` to get to know if `T` is owned by the assoc ty. Unfortunately this doesn't work for ITIT assoc tys. In this case, the parent of `T` is `Trait::def` (!) which is the associated function (I'm pretty sure this is very intentional) which is of course not equal to the assoc ty `Trait::{opaque#0}`.

</details>

`@rustbot` label A-cross-crate-reexports
2023-07-24 15:19:00 +00:00
Guillaume Gomez
8cab95ef9b Add missing documentation for Session::time 2023-07-24 16:50:25 +02:00
David Wood
3857d9c2da
borrowck/errors: fix i18n error in delayed bug
During borrowck, the `MultiSpan` from a buffered diagnostic is cloned and
used to emit a delayed bug indicating a diagnostic was buffered - when
the buffered diagnostic is translated, then the cloned `MultiSpan` may
contain labels which can only render with the diagnostic's arguments, but
the delayed bug being emitted won't have those arguments. Adds a function
which clones `MultiSpan` without also cloning the contained labels, and
use this function when creating the buffered diagnostic delayed bug.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-24 15:47:03 +01:00
Martin Nordholts
504acf8760 Make --error-format human-annotate-rs handle multiple files 2023-07-24 16:29:58 +02:00
Oli Scherer
5b4549dd13 Some documentation nits 2023-07-24 14:20:53 +00:00
David Wood
c06a7eb2a6
builtin_macros: expect raw strings too
`expr_to_string` allows raw strings through so this code should be
expected to handle those.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-24 15:06:50 +01:00
Oli Scherer
10d0ff975c Explain what the heck is going on with this lifetime remapping business 2023-07-24 13:48:06 +00:00
Ralf Jung
a593de4fab interpret: support projecting into Place::Local without force_allocation 2023-07-24 15:35:47 +02:00
bors
48c0c25395 Auto merge of #114004 - hermitcore:riscv64gc-unknown-hermit, r=davidtwco
Add `riscv64gc-unknown-hermit` target

This PR adds the new `riscv64gc-unknown-hermit` target, initially created by `@simonschoening,` a 64-bit RISC-V target for the [Hermit] unikernel project.

Furthermore, this cleans up the existing Hermit targets and adds a platform support documentation page for _all_ Hermit targets and goes through the new tier 3 target policy process:

[Hermit]: https://github.com/hermitcore

## Tier 3 target policy

> - A tier 3 target must have a designated developer or developers (the "target
>   maintainers") on record to be CCed when issues arise regarding the target.
>   (The mechanism to track and CC such developers may evolve over time.)

`@stlankes` as the Hermit project lead and I will be the target maintainers.

> - Targets must use naming consistent with any existing targets; for instance, a
>   target for the same CPU or OS as an existing Rust target should use the same
>   name for that CPU or OS. Targets should normally use the same names and
>   naming conventions as used elsewhere in the broader ecosystem beyond Rust
>   (such as in other toolchains), unless they have a very good reason to
>   diverge. Changing the name of a target can be highly disruptive, especially
>   once the target reaches a higher tier, so getting the name right is important
>   even for a tier 3 target.
>   - Target names should not introduce undue confusion or ambiguity unless
>     absolutely necessary to maintain ecosystem compatibility. For example, if
>     the name of the target makes people extremely likely to form incorrect
>     beliefs about what it targets, the name should be changed or augmented to
>     disambiguate it.
>   - If possible, use only letters, numbers, dashes and underscores for the name.
>     Periods (`.`) are known to cause issues in Cargo.

The target name `riscv64gc-unknown-hermit` was derived from the existing `x86_64-unknown-hermit` and `aarch64-unknown-hermit` targets.

> - Tier 3 targets may have unusual requirements to build or use, but must not
>   create legal issues or impose onerous legal terms for the Rust project or for
>   Rust developers or users.
>   - The target must not introduce license incompatibilities.
>   - Anything added to the Rust repository must be under the standard Rust
>     license (`MIT OR Apache-2.0`).
>   - The target must not cause the Rust tools or libraries built for any other
>     host (even when supporting cross-compilation to the target) to depend
>     on any new dependency less permissive than the Rust licensing policy. This
>     applies whether the dependency is a Rust crate that would require adding
>     new license exceptions (as specified by the `tidy` tool in the
>     rust-lang/rust repository), or whether the dependency is a native library
>     or binary. In other words, the introduction of the target must not cause a
>     user installing or running a version of Rust or the Rust tools to be
>     subject to any new license requirements.
>   - Compiling, linking, and emitting functional binaries, libraries, or other
>     code for the target (whether hosted on the target itself or cross-compiling
>     from another target) must not depend on proprietary (non-FOSS) libraries.
>     Host tools built for the target itself may depend on the ordinary runtime
>     libraries supplied by the platform and commonly used by other applications
>     built for the target, but those libraries must not be required for code
>     generation for the target; cross-compilation to the target must not require
>     such libraries at all. For instance, `rustc` built for the target may
>     depend on a common proprietary C runtime library or console output library,
>     but must not depend on a proprietary code generation library or code
>     optimization library. Rust's license permits such combinations, but the
>     Rust project has no interest in maintaining such combinations within the
>     scope of Rust itself, even at tier 3.
>   - "onerous" here is an intentionally subjective term. At a minimum, "onerous"
>     legal/licensing terms include but are *not* limited to: non-disclosure
>     requirements, non-compete requirements, contributor license agreements
>     (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms,
>     requirements conditional on the employer or employment of any particular
>     Rust developers, revocable terms, any requirements that create liability
>     for the Rust project or its developers or users, or any requirements that
>     adversely affect the livelihood or prospects of the Rust project or its
>     developers or users.

No dependencies were added to Rust.

> - Neither this policy nor any decisions made regarding targets shall create any
>   binding agreement or estoppel by any party. If any member of an approving
>   Rust team serves as one of the maintainers of a target, or has any legal or
>   employment requirement (explicit or implicit) that might affect their
>   decisions regarding a target, they must recuse themselves from any approval
>   decisions regarding the target's tier status, though they may otherwise
>   participate in discussions.
>   - This requirement does not prevent part or all of this policy from being
>     cited in an explicit contract or work agreement (e.g. to implement or
>     maintain support for a target). This requirement exists to ensure that a
>     developer or team responsible for reviewing and approving a target does not
>     face any legal threats or obligations that would prevent them from freely
>     exercising their judgment in such approval, even if such judgment involves
>     subjective matters or goes beyond the letter of these requirements.

Understood.
I am not a member of a Rust team.

> - Tier 3 targets should attempt to implement as much of the standard libraries
>   as possible and appropriate (`core` for most targets, `alloc` for targets
>   that can support dynamic memory allocation, `std` for targets with an
>   operating system or equivalent layer of system-provided functionality), but
>   may leave some code unimplemented (either unavailable or stubbed out as
>   appropriate), whether because the target makes it impossible to implement or
>   challenging to implement. The authors of pull requests are not obligated to
>   avoid calling any portions of the standard library on the basis of a tier 3
>   target not implementing those portions.

Understood.
`std` is supported.

> - The target must provide documentation for the Rust community explaining how
>   to build for the target, using cross-compilation if possible. If the target
>   supports running binaries, or running tests (even if they do not pass), the
>   documentation must explain how to run such binaries or tests for the target,
>   using emulation if possible or dedicated hardware if necessary.

Building is described in the platform support doc.

> - Tier 3 targets must not impose burden on the authors of pull requests, or
>   other developers in the community, to maintain the target. In particular,
>   do not post comments (automated or manual) on a PR that derail or suggest a
>   block on the PR based on a tier 3 target. Do not send automated messages or
>   notifications (via any medium, including via ``@`)` to a PR author or others
>   involved with a PR regarding a tier 3 target, unless they have opted into
>   such messages.
>   - Backlinks such as those generated by the issue/PR tracker when linking to
>     an issue or PR are not considered a violation of this policy, within
>     reason. However, such messages (even on a separate repository) must not
>     generate notifications to anyone involved with a PR who has not requested
>     such notifications.

Understood.

> - Patches adding or updating tier 3 targets must not break any existing tier 2
>   or tier 1 target, and must not knowingly break another tier 3 target without
>   approval of either the compiler team or the maintainers of the other tier 3
>   target.
>   - In particular, this may come up when working on closely related targets,
>     such as variations of the same architecture with different features. Avoid
>     introducing unconditional uses of features that another variation of the
>     target may not have; use conditional compilation or runtime detection, as
>     appropriate, to let each target run code supported by that target.

I don't think this PR breaks anything.

r? compiler-team
2023-07-24 13:28:18 +00:00
Zalathar
01f3cc1272 coverage: Obtain the __llvm_covfun section name outside a per-function loop
This section name is always constant for a given target, but obtaining it from
LLVM requires a few intermediate allocations. There's no need to do so
repeatedly from inside a per-function loop.
2023-07-24 21:58:00 +10:00
bors
f475098ffd Auto merge of #113877 - JhonnyBillM:reuse-codegen-ssa-monomorphization-errors-in-gcc, r=davidtwco
Reuse `codegen_ssa` monomorphization errors in `codegen_gcc`

Removes monomorphization errors duplication by reusing the ones defined in `codegen_ssa`.

Also updates `expected_simd` errors usage in `codegen_gcc` by assuming we want to treat those parameters as translatable. See 7a888fb56e
2023-07-24 11:29:59 +00:00
Mahdi Dibaiee
8df39667dc new unstable option: -Zwrite-long-types-to-disk
This option guards the logic of writing long type names in files and
instead using short forms in error messages in rustc_middle/ty/error
behind a flag. The main motivation for this change is to disable this
behaviour when running ui tests.

This logic can be triggered by running tests in a directory that has a
long enough path, e.g. /my/very-long-path/where/rust-codebase/exists/

This means ui tests can fail depending on how long the path to their
file is.

Some ui tests actually rely on this behaviour for their assertions,
so for those we enable the flag manually.
2023-07-24 12:25:05 +01:00
Simon Schöning
3003fe2d80
compiler: Add riscv64gc-unknown-hermit target
Co-authored-by: Martin Kröning <martin.kroening@eonerc.rwth-aachen.de>
Signed-off-by: Martin Kröning <martin.kroening@eonerc.rwth-aachen.de>
2023-07-24 10:36:05 +02:00
Martin Kröning
636804e032
compiler: Hermit targets: Use functional update syntax
instead of mutating the base.

Signed-off-by: Martin Kröning <martin.kroening@eonerc.rwth-aachen.de>
2023-07-24 10:36:05 +02:00
Martin Kröning
a4e1bf416d
compiler: Hermit targets: Sort base fields by declaration
Signed-off-by: Martin Kröning <martin.kroening@eonerc.rwth-aachen.de>
2023-07-24 10:36:05 +02:00
Martin Kröning
2676637666
compiler: Hermit targets: Remove pre-link args.
These pre-link args are remains from Hermit's old C version.
We don't need them and we have no reason to override the defaults here.
See ld [1] for details.

[1]: https://sourceware.org/binutils/docs/ld/Options.html

Signed-off-by: Martin Kröning <martin.kroening@eonerc.rwth-aachen.de>
2023-07-24 10:36:04 +02:00
Yuri Astrakhan
bb1ad0a2f1 Optimize format usage
Per #112156, using `&` in `format!` may cause a small perf delay, so I tried to clean up one module at a time format usage. This PR includes a few removals of the ref in format (they do compile locally without the ref), as well as a few format inlining for consistency.
2023-07-24 00:18:52 -04:00
Eric Mark Martin
badb617eb5 Dynamic for smir 2023-07-24 00:17:45 -04:00
Yuri Astrakhan
e36b901933 Optimize format usage
Per #112156, using `&` in `format!` may cause a small perf delay, so I tried to clean up one module at a time format usage. This PR includes a few removals of the ref in format (they do compile locally without the ref), as well as a few format inlining for consistency.
2023-07-24 00:08:09 -04:00
Eric Mark Martin
c2158a44e1 generic smir stable impl for Binder 2023-07-24 00:06:29 -04:00
Chris Copeland
8e54caba04
Fix comments about GCC/Clang's enum width for arm-none targets.
GCC uses the `-fshort-enums` ABI for arm-none and the `int`-sized enum
ABI for arm-linux.
Clang uses the `int`-sized enum ABI for all arm targets.

Both options are permitted by AAPCS.

Rust is matching GCC's behavior for these targets, as interop with code
code compiled by GCC is desirable in the bare-metal context. See #87917.
2023-07-23 20:19:38 -07:00
Chris Copeland
ef8994827e
Remove redundant c_enum_min_bits option from the thumbv4t-none-eabi target.
This option is the same as the `thumb_base` defaults used by this target.
2023-07-23 20:19:26 -07:00
Chris Copeland
a8f1b72f08
Remove "-unknown" from llvm_target for arm*v7r-none-eabi* targets. 2023-07-23 20:19:04 -07:00
Matthias Krüger
af2b370100 more clippy::style fixes:
get_first
single_char_add_str
unnecessary_mut_passed
manual_map
manual_is_ascii_check
2023-07-23 23:39:04 +02:00
Matthias Krüger
ed4c5fef72 fix some clippy::style findings
comparison_to_empty
iter_nth_zero
for_kv_map
manual_next_back
redundant_pattern
2023-07-23 23:36:56 +02:00
Michael Goulet
f3553691a8 Comment stuff in the new solver 2023-07-23 12:30:52 -07:00
Michael Goulet
d1380a1844 Use erased self type when autoderefing for trait error suggestion 2023-07-23 14:13:52 -04:00
bors
c474aa7db0 Auto merge of #113975 - matthiaskrgr:clippy_07_2023, r=fee1-dead
clippy::style fixes

r? `@oli-obk`

filter_map_identity
iter_kv_map
needless_question_mark
redundant_at_rest_pattern
filter_next
derivable_impls
useless_format
2023-07-23 14:09:19 +00:00
bors
d4fe4c8b95 Auto merge of #113973 - matthiaskrgr:charstr, r=cjgillot
match on chars instead of &strs for .split() or .strip_prefix()
2023-07-23 12:21:42 +00:00
Deadbeef
2a76c570d6 add suggestion 2023-07-23 09:58:31 +00:00
Deadbeef
626efab67f fix 2023-07-23 09:58:31 +00:00
Matthias Krüger
b594798ae3 fix clippy::useless_format 2023-07-23 11:14:52 +02:00
Matthias Krüger
adf759bf6a fix couple of clippy findings:
filter_map_identity
iter_kv_map
needless_question_mark
redundant_at_rest_pattern
filter_next
derivable_impls
2023-07-23 10:50:14 +02:00
Matthias Krüger
7a7708904b match on chars instead of &strs for .split() or .strip_prefix() 2023-07-23 10:13:41 +02:00
Matthias Krüger
abde841f0a remove redundant clones 2023-07-23 09:48:07 +02:00
Deadbeef
33ec4e4bb0 make noop_method_call warn by default 2023-07-23 07:09:14 +00:00
Deadbeef
df9bd80d74 reimplement C string literals 2023-07-23 06:54:07 +00:00
bors
cec34a43b1 Auto merge of #113961 - fmease:fewer-features_untracked, r=compiler-errors
Use `features()` over `features_untracked()` where possible

`Resolver` has a `TyCtxt` nowadays.

`@rustbot` label C-cleanup
2023-07-23 02:03:21 +00:00
bors
1c44af9b79 Auto merge of #111836 - calebzulawski:target-feature-closure, r=workingjubilee
Fix #[inline(always)] on closures with target feature 1.1

Fixes #108655.  I think this is the most obvious solution that isn't overly complicated.  The comment includes more justification, but I think this is likely better than demoting the `#[inline(always)]` to `#[inline]`, since existing code is unaffected.
2023-07-23 00:16:03 +00:00
bors
98179ad634 Auto merge of #113943 - ericmarkmartin:smir-ty-alias, r=spastorino
Add Alias to smir

r? Spastorino
2023-07-22 22:20:54 +00:00
bors
1d56e3a6d9 Auto merge of #112953 - compiler-errors:interpolated-block-exprs, r=WaffleLapkin
Support interpolated block for `try` and `async`

I'm putting this up for T-lang discussion, to decide whether or not they feel like this should be supported. This was raised in #112952, which surprised me. There doesn't seem to be a *technical* reason why we don't support this.

### Precedent:

This is supported:

```rust
macro_rules! always {
  ($block:block) => {
    if true $block
  }
}

fn main() {
    always!({});
}
```

### Counterpoint:

However, for context, this is *not* supported:

```rust
macro_rules! unsafe_block {
  ($block:block) => {
    unsafe $block
  }
}

fn main() {
    unsafe_block!({});
}
```

If this support for `async` and `try` with interpolated blocks is *not* desirable, then I can convert them to instead the same diagnostic as `unsafe $block` and make this situation a lot less ambiguous.

----

I'll try to write up more before T-lang triage on Tuesday. I couldn't find anything other than #69760 for why something like `unsafe $block` is not supported, and even that PR doesn't have much information.

Fixes #112952
2023-07-22 20:37:44 +00:00
Eric Mark Martin
7ac0ef9d11 add docs for AliasKind::Inherent 2023-07-22 15:38:41 -04:00
Eric Mark Martin
aa33e8945c add Alias for smir 2023-07-22 15:38:41 -04:00
bors
a6fbd1c58d Auto merge of #113968 - matthiaskrgr:rollup-7vdfcba, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #112508 (Tweak spans for self arg, fix borrow suggestion for signature mismatch)
 - #113901 (Get rid of subst-relate incompleteness in new solver)
 - #113948 (Fix rustc-args passing issue in bootstrap)
 - #113950 (Remove Scope::Elision from bound-vars resolution.)
 - #113957 (Add regression test for issue #113941 - naive layout isn't refined)
 - #113959 (Migrate GUI colors test to original CSS color format)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-07-22 18:49:42 +00:00
León Orell Valerian Liehr
2a75a0f724
Use features() over features_untracked() where possible 2023-07-22 20:09:40 +02:00
Matthias Krüger
00e147543c
Rollup merge of #113950 - cjgillot:clean-resolve, r=jackh726
Remove Scope::Elision from bound-vars resolution.

This scope is a remnant of HIR-based lifetime resolution.

It's only role was to ensure that object lifetime resolution falled back to `'static`. This can be done using `ObjectLifetimeDefault` scope.
2023-07-22 19:57:37 +02:00
Matthias Krüger
8f4b81b146
Rollup merge of #113901 - compiler-errors:only-bidi-norm, r=lcnr
Get rid of subst-relate incompleteness in new solver

We shouldn't need subst-relate if we have bidirectional-normalizes-to in the new solver.

The only potential issue may happen if we have an unconstrained projection like `<Wrapper<?0> as Trait>::Assoc == <Wrapper<T> as Trait>::Assoc` where they both normalize to something that doesn't mention any substs, which would possibly prefer `?0 = T` if we fall back to subst-relate. But I'd prefer if we remove incompleteness until we can determine some case where we need them, and the bidirectional-normalizes-to seems better to have in general.

I can update https://github.com/rust-lang/trait-system-refactor-initiative/issues/26 and https://github.com/rust-lang/trait-system-refactor-initiative/issues/25 once this lands.

r? `@lcnr`
2023-07-22 19:57:36 +02:00
Matthias Krüger
0ed5f091a6
Rollup merge of #112508 - compiler-errors:trait-sig-lifetime-sugg-ice, r=cjgillot
Tweak spans for self arg, fix borrow suggestion for signature mismatch

1. Adjust a suggestion message that was annoying me
2. Fix #112503 by recording the right spans for the `self` part of the `&self` 0th argument
3. Remove the suggestion for adjusting a trait signature on type mismatch, bc that's gonna probably break all the other impls of the trait even if it fixes its one usage 😅
2023-07-22 19:57:35 +02:00
bors
c39995485f Auto merge of #113853 - cjgillot:split-validator, r=compiler-errors
Reuse the MIR validator for MIR inlining

Instead of having the inliner home-cook its own validation, we just check that the substituted MIR body passes the regular validation.

The MIR validation is first split in two: control flow validation (MIR syntax and CFG invariants) and type validation (subtyping relationship in assignments and projections). Only the latter can be affected by instantiating type parameters.
2023-07-22 16:59:23 +00:00
Michael Goulet
e32011209d Get rid of subst-relate incompleteness in new solver 2023-07-22 15:33:37 +00:00
Michael Goulet
c0c2d39668 Don't call a type uncallable if its signature has errors in it 2023-07-22 15:27:21 +00:00
Michael Goulet
7b962d7543 Support interpolated block for try and async 2023-07-22 15:22:12 +00:00
bjorn3
36708123c1 Merge commit '1eded3619d0e55d57521a259bf27a03906fdfad0' into sync_cg_clif-2023-07-22 2023-07-22 13:32:34 +00:00
León Orell Valerian Liehr
5924043b86
rustdoc: handle cross-crate RPITITs correctly 2023-07-22 12:20:17 +02:00
Lukas Markeffsky
9ebd8095fa fix doc links on use items 2023-07-22 12:14:26 +02:00
Lukas Markeffsky
a342617059 improve debuggability 2023-07-22 11:54:28 +02:00
Camille GILLOT
b8701ff9d3 Remove Scope::Elision. 2023-07-22 08:32:53 +00:00
David Tolnay
5bbf0a8306
Revert "Auto merge of #113166 - moulins:ref-niches-initial, r=oli-obk"
This reverts commit 557359f925, reversing
changes made to 1e6c09a803.
2023-07-21 22:35:57 -07:00
bors
0308df23e6 Auto merge of #97550 - ojeda:comment-section, r=bjorn3
[RFC] Support `.comment` section like GCC/Clang (`!llvm.ident`)

Both GCC and Clang write by default a `.comment` section with compiler information:

```txt
$ gcc -c -xc /dev/null && readelf -p '.comment' null.o

String dump of section '.comment':
  [     1]  GCC: (GNU) 11.2.0

$ clang -c -xc /dev/null && readelf -p '.comment' null.o

String dump of section '.comment':
  [     1]  clang version 14.0.1 (https://github.com/llvm/llvm-project.git c62053979489ccb002efe411c3af059addcb5d7d)
```

They also implement the `-Qn` flag to avoid doing so:

```txt
$ gcc -Qn -c -xc /dev/null && readelf -p '.comment' null.o
readelf: Warning: Section '.comment' was not dumped because it does not exist!

$ clang -Qn -c -xc /dev/null && readelf -p '.comment' null.o
readelf: Warning: Section '.comment' was not dumped because it does not exist!
```

So far, `rustc` only does it for WebAssembly targets and only when debug info is enabled:

```txt
$ echo 'fn main(){}' | rustc --target=wasm32-unknown-unknown --emit=llvm-ir -Cdebuginfo=2 - && grep llvm.ident rust_out.ll
!llvm.ident = !{!27}
```

The RFC part of this PR is about which behavior should `rustc` follow:
  - Always add it.
  - Add it by default, i.e. have an opt-out flag (GCC, Clang).
  - Have an opt-in flag.
  - Never add it (current).

There is also the question of whether debug info being enabled matters for that decision, given the current behavior of WebAssembly targets.

For instance, adding it by default gets us closer to other popular compilers, but that may surprise some users with an information leak. The most conservative option is to only do so opt-in, even if debug info is enabled (some users may be stripping debug info and not expecting something else to be leaked elsewhere).

Implementation-wise, this covers both `ModuleLlvm::new()` and `ModuleLlvm::new_metadata()` cases by moving the addition to `context::create_module` and adds a few test cases.

ThinLTO also sees the `llvm.ident` named metadata duplicated (in temporary outputs), so this deduplicates it like it is done for `wasm.custom_sections`. The tests also check this duplication does not take place.
2023-07-21 21:17:27 +00:00
Miguel Ojeda
74b8d324eb Support .comment section like GCC/Clang (!llvm.ident)
Both GCC and Clang write by default a `.comment` section with compiler
information:

```txt
$ gcc -c -xc /dev/null && readelf -p '.comment' null.o

String dump of section '.comment':
  [     1]  GCC: (GNU) 11.2.0

$ clang -c -xc /dev/null && readelf -p '.comment' null.o

String dump of section '.comment':
  [     1]  clang version 14.0.1 (https://github.com/llvm/llvm-project.git c62053979489ccb002efe411c3af059addcb5d7d)
```

They also implement the `-Qn` flag to avoid doing so:

```txt
$ gcc -Qn -c -xc /dev/null && readelf -p '.comment' null.o
readelf: Warning: Section '.comment' was not dumped because it does not exist!

$ clang -Qn -c -xc /dev/null && readelf -p '.comment' null.o
readelf: Warning: Section '.comment' was not dumped because it does not exist!
```

So far, `rustc` only does it for WebAssembly targets and only
when debug info is enabled:

```txt
$ echo 'fn main(){}' | rustc --target=wasm32-unknown-unknown --emit=llvm-ir -Cdebuginfo=2 - && grep llvm.ident rust_out.ll
!llvm.ident = !{!27}
```

In the RFC part of this PR it was decided to always add
the information, which gets us closer to other popular compilers.
An opt-out flag like GCC and Clang may be added later on if deemed
necessary.

Implementation-wise, this covers both `ModuleLlvm::new()` and
`ModuleLlvm::new_metadata()` cases by moving the addition to
`context::create_module` and adds a few test cases.

ThinLTO also sees the `llvm.ident` named metadata duplicated (in
temporary outputs), so this deduplicates it like it is done for
`wasm.custom_sections`. The tests also check this duplication does
not take place.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-07-21 22:01:50 +02:00
bors
d908a5b08e Auto merge of #113892 - RalfJung:uninit-undef-poison, r=wesleywiser
clarify MIR uninit vs LLVM undef/poison

In [this LLVM discussion](https://discourse.llvm.org/t/rfc-load-instruction-uninitialized-memory-semantics/67481) I learned that mapping our uninitialized memory in MIR to poison in LLVM would be quite problematic due to the lack of a byte type. I am not sure where to write down this insight but this seems like a reasonable start.
2023-07-21 19:32:17 +00:00
bors
c3c5a5c5f7 Auto merge of #113922 - matthiaskrgr:rollup-90cj2vv, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #113887 (new solver: add a separate cache for coherence)
 - #113910 (Add FnPtr ty to SMIR)
 - #113913 (error/E0691: include alignment in error message)
 - #113914 (rustc_target: drop duplicate code)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-07-21 16:52:21 +00:00
Matthias Krüger
1aaf583fa4
Rollup merge of #113914 - dvdhrm:pr/zstdup, r=cjgillot
rustc_target: drop duplicate code

Drop duplicate helper methods on `Layout`, which are already implemented on `LayoutS`. Note that `Layout` has a `Deref` implementation to `LayoutS`, so all accessors are automatically redirected.

The methods are identical and have been copied to `rustc_abi` in:

    commit 390a637e29
    Author: hamidreza kalbasi <hamidrezakalbasi@protonmail.com>
    Date:   Mon Nov 7 00:36:11 2022 +0330

        move things from rustc_target::abi to rustc_abi

This commit left behind the original implementation. Drop it now.

(originally moved by ``@HKalbasi)``
2023-07-21 17:17:42 +02:00
Matthias Krüger
4a90553717
Rollup merge of #113913 - dvdhrm:pr/transpalign, r=jackh726
error/E0691: include alignment in error message

Include the computed alignment of the violating field when rejecting transparent types with non-trivially aligned ZSTs.

ZST member fields in transparent types must have an alignment of 1 (to ensure it does not raise the layout requirements of the transparent field). The current error message looks like this:

```text
 LL | struct Foobar(u32, [u32; 0]);
    |                    ^^^^^^^^ has alignment larger than 1
```

This patch changes the report to include the alignment of the violating field:

```text
 LL | struct Foobar(u32, [u32; 0]);
    |                    ^^^^^^^^ has alignment of 4, which is larger than 1
```

In case of unknown alignments, it will yield:

```text
 LL | struct Foobar(u32, [u32; 0]);
    |                    ^^^^^^^^ may have alignment larger than 1
```

This allows developers to get a better grasp why a specific field is rejected. Knowing the alignment of the violating field makes it easier to judge where that alignment-requirement originates, and thus hopefully provide better hints on how to mitigate the problem.

This idea was proposed in 2022 in #98071 as part of a bigger change. This commit simply extracts this error-message change, to decouple it from the other diagnostic improvements.

(Originally proposed by `@compiler-errors` in #98071)
2023-07-21 17:17:42 +02:00
Matthias Krüger
b91c41b1f4
Rollup merge of #113910 - spastorino:smir-types-5, r=oli-obk
Add FnPtr ty to SMIR

r? `@oli-obk`
2023-07-21 17:17:41 +02:00
Matthias Krüger
af1e082200
Rollup merge of #113887 - lcnr:cache-coherence, r=compiler-errors
new solver: add a separate cache for coherence

based on #113835

`typenum` now compiles with `-Ztrait-solver=next-coherence`. Because we disable caching once we encounter the recursion limit it is still really slow, but at least it passes and I will deal with overflow handling afterwards.

`typenum` previously hanged. The top 10 goals were
```rust
1749948 counts
(  1)   601056 (34.3%, 34.3%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: ProjectionPredicate(AliasTy { args: [^1_0], def_id: DefId(0:1196 ~ typenum[0ab6]::type_operators::Len::Output) }, Term::Ty(^1_1)), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }, CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  2)   240422 (13.7%, 48.1%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: ProjectionPredicate(AliasTy { args: [<^1_0 as type_operators::Len>::Output, bit::B1], def_id: DefId(1:2752 ~ core[a405]::ops::arith::Add::Output) }, Term::Ty(^1_1)), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }, CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  3)   198367 (11.3%, 59.4%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: TraitPredicate(<^1_0 as core::marker::Sized>, polarity:Positive), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  4)    96168 ( 5.5%, 64.9%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: ProjectionPredicate(AliasTy { args: [<^1_0 as type_operators::Len>::Output, bit::B1], def_id: DefId(1:2752 ~ core[a405]::ops::arith::Add::Output) }, Term::Ty(<<^1_0 as type_operators::Len>::Output as core::ops::Add<bit::B1>>::Output)), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  5)    78155 ( 4.5%, 69.4%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: TraitPredicate(<^1_0 as marker_traits::Unsigned>, polarity:Positive), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  6)    72140 ( 4.1%, 73.5%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: TraitPredicate(<^1_0 as marker_traits::Bit>, polarity:Positive), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  7)    60107 ( 3.4%, 76.9%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: TraitPredicate(<^1_0 as type_operators::Len>, polarity:Positive), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  8)    60106 ( 3.4%, 80.4%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: ProjectionPredicate(AliasTy { args: [uint::UInt<^1_0, ^1_1>], def_id: DefId(0:1196 ~ typenum[0ab6]::type_operators::Len::Output) }, Term::Ty(^1_2)), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }, CanonicalVarInfo { kind: Ty(General(U0)) }, CanonicalVarInfo { kind: Ty(General(U0)) }] }
(  9)    60106 ( 3.4%, 83.8%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: TraitPredicate(<<<^1_0 as type_operators::Len>::Output as core::ops::Add<bit::B1>>::Output as marker_traits::Unsigned>, polarity:Positive), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
( 10)    60106 ( 3.4%, 87.2%): Canonical { value: QueryInput { goal: Goal { predicate: Binder { value: TraitPredicate(<<^1_0 as type_operators::Len>::Output as core::ops::Add<bit::B1>>, polarity:Positive), bound_vars: [] }, param_env: ParamEnv { caller_bounds: [], reveal: UserFacing, constness: NotConst } }, anchor: Bubble, predefined_opaques_in_body: PredefinedOpaques(PredefinedOpaquesData { opaque_types: [] }) }, max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }] }
```

r? ``@compiler-errors``
2023-07-21 17:17:41 +02:00
bors
557359f925 Auto merge of #113166 - moulins:ref-niches-initial, r=oli-obk
Prototype: Add unstable `-Z reference-niches` option

MCP: rust-lang/compiler-team#641
Relevant RFC: rust-lang/rfcs#3204

This prototype adds a new `-Z reference-niches` option, controlling the range of valid bit-patterns for reference types (`&T` and `&mut T`), thereby enabling new enum niching opportunities. Like `-Z randomize-layout`, this setting is crate-local; as such, references to built-in types (primitives, tuples, ...) are not affected.

The possible settings are (here, `MAX` denotes the all-1 bit-pattern):
| `-Z reference-niches=` | Valid range |
|:---:|:---:|
| `null` (the default) | `1..=MAX` |
| `size` | `1..=(MAX- size)` |
| `align` | `align..=MAX.align_down_to(align)` |
| `size,align` | `align..=(MAX-size).align_down_to(align)` |

------

This is very WIP, and I'm not sure the approach I've taken here is the best one, but stage 1 tests pass locally; I believe this is in a good enough state to unleash this upon unsuspecting 3rd-party code, and see what breaks.
2023-07-21 15:00:36 +00:00
Santiago Pastorino
634db101ec
Implement Stable for ty::Ty 2023-07-21 11:56:49 -03:00
David Wood
09434a2575
lint/ctypes: only try normalize
Now that this lint runs on any external-ABI fn-ptr, normalization won't
always succeed, so use `try_normalize_erasing_regions` instead.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-21 15:42:25 +01:00
Camille GILLOT
b6cd7006e0 Reuse MIR validator for inliner. 2023-07-21 13:58:33 +00:00
Camille GILLOT
2ef2ac0b51 Make type validation buffer errors. 2023-07-21 13:54:34 +00:00
Camille GILLOT
030589d488 Separate CFG validation from type validation. 2023-07-21 13:54:34 +00:00
Oli Scherer
44e21503a8 Double check that hidden types match the expected hidden type 2023-07-21 13:19:36 +00:00
Moulins
7f109086ee Track (partial) niche information in NaiveLayout
Still more complexity, but this allows computing exact `NaiveLayout`s
for null-optimized enums, and thus allows calls like
`transmute::<Option<&T>, &U>()` to work in generic contexts.
2023-07-21 14:23:23 +02:00
bors
c06b2b9117 Auto merge of #113847 - SparrowLii:path_clone, r=cjgillot
avoid clone path prefix when lowering to hir

Found this while trying to parallelize `lower_to_hir`.

When lowering to hir, `Nested` paths in `ast` will be split and the prefix segments will be cloned. This could be omited, since the only consequence is that the prefix segments in `Path`s in hir will have the same `HirId`s, and it seems harmless.

This simplifies the process of lowering to hir and avoids re-modification of `ResolverAstLowering`.

r? `@Aaron1011`
cc #99292
2023-07-21 11:02:47 +00:00
bors
6b290367ec Auto merge of #113802 - cjgillot:check-debuginfo, r=compiler-errors
Substitute types before checking inlining compatibility.

Addresses https://github.com/rust-lang/rust/issues/112332 and https://github.com/rust-lang/rust/issues/113781

I don't have a minimal test, but I this seems to remove the ICE locally.

This whole pre-inlining validation mirrors the "real" MIR validation pass to verify that inlined MIR will still pass validation.
The debuginfo loop is added because MIR validation check projections in debuginfo.
Likewise, MIR validation only checks `is_subtype`, so there is no reason for a stronger check.

The types were not being substituted in `check_equal`, so we were not bailing out of inlining if the substituted MIR callee body would not pass validation.
2023-07-21 09:14:55 +00:00
David Rheinsberg
b0dadff6de error/E0691: include alignment in error message
Include the computed alignment of the violating field when rejecting
transparent types with non-trivially aligned ZSTs.

ZST member fields in transparent types must have an alignment of 1 (to
ensure it does not raise the layout requirements of the transparent
field). The current error message looks like this:

 LL | struct Foobar(u32, [u32; 0]);
    |                    ^^^^^^^^ has alignment larger than 1

This patch changes the report to include the alignment of the violating
field:

 LL | struct Foobar(u32, [u32; 0]);
    |                    ^^^^^^^^ has alignment of 4, which is larger than 1

In case of unknown alignments, it will yield:

 LL | struct Foobar<T>(u32, [T; 0]);
    |                       ^^^^^^ may have alignment larger than 1

This allows developers to get a better grasp why a specific field is
rejected. Knowing the alignment of the violating field makes it easier
to judge where that alignment-requirement originates, and thus hopefully
provide better hints on how to mitigate the problem.

This idea was proposed in 2022 in #98071 as part of a bigger change.
This commit simply extracts this error-message change, to decouple it
from the other diagnostic improvements.
2023-07-21 11:04:16 +02:00
David Rheinsberg
3e0389561b rustc_target: drop duplicate code
Drop duplicate helper methods on `Layout`, which are already implemented
on `LayoutS`. Note that `Layout` has a `Deref` implementation to
`LayoutS`, so all accessors are automatically redirected.

The methods are identical and have been copied to `rustc_abi` in:

    commit 390a637e29
    Author: hamidreza kalbasi <hamidrezakalbasi@protonmail.com>
    Date:   Mon Nov 7 00:36:11 2022 +0330

        move things from rustc_target::abi to rustc_abi

This commit left behind the original implementation. Drop it now.

Signed-off-by: David Rheinsberg <david@readahead.eu>
2023-07-21 10:31:01 +02:00
lcnr
303af36be7 new solver: add a separate cache for coherence 2023-07-21 09:34:10 +02:00
bors
5419aa3a66 Auto merge of #113707 - sivadeilra:user/ardavis/sha256, r=eholk
Use SHA256 source file checksums by default when targeting MSVC

Currently, when targeting Windows (more specifically, the MSVC toolchain), Rust will use SHA1 source file checksums by default.  SHA1 has been superseded by SHA256, and Microsoft recommends migrating to SHA256.

As of Visual Studio 2022, MSVC defaults to SHA256.  This change aligns Rust and MSVC.

LLVM can already use SHA256 checksums, so this does not require any change to LLVM.

MSVC docs on source file checksums: https://learn.microsoft.com/en-us/cpp/build/reference/zh?view=msvc-170
2023-07-21 07:24:27 +00:00
Matthias Krüger
b1d1e99c22
Rollup merge of #113780 - dtolnay:printkindpath, r=b-naber
Support `--print KIND=PATH` command line syntax

As is already done for `--emit KIND=PATH` and `-L KIND=PATH`.

In the discussion of #110785, it was pointed out that `--print KIND=PATH` is nicer than trying to apply the single global `-o` path to `--print`'s output, because in general there can be multiple print requests within a single rustc invocation, and anyway `-o` would already be used for a different meaning in the case of `link-args` and `native-static-libs`.

I am interested in using `--print cfg=PATH` in Buck2. Currently Buck2 works around the lack of support for `--print KIND=PATH` by [indirecting through a Python wrapper script](d43cf3a51a/prelude/rust/tools/get_rustc_cfg.py) to redirect rustc's stdout into the location dictated by the build system.

From skimming Cargo's usages of `--print`, it definitely seems like it would benefit from `--print KIND=PATH` too. Currently it is working around the lack of this by inserting `--crate-name=___ --print=crate-name` so that it can look for a line containing `___` as a delimiter between the 2 other `--print` informations it actually cares about. This is commented as a "HACK" and "abuse". 31eda6f7c3/src/cargo/core/compiler/build_context/target_info.rs (L242) (FYI `@weihanglo` as you dealt with this recently in https://github.com/rust-lang/cargo/pull/11633.)

Mentioning reviewers active in #110785: `@fee1-dead` `@jyn514` `@bjorn3`
2023-07-21 06:52:28 +02:00
Matthias Krüger
2734b5ada9
Rollup merge of #113723 - khei4:khei4/llvm-stats, r=oli-obk,nikic
Resurrect: rustc_llvm: Add a -Z `print-codegen-stats` option to expose LLVM statistics.

This resurrects PR https://github.com/rust-lang/rust/pull/104000, which has sat idle for a while. And I want to see the effect of stack-move optimizations on LLVM (like https://reviews.llvm.org/D153453) :).

I have applied the changes requested by `@oli-obk` and `@nagisa`  https://github.com/rust-lang/rust/pull/104000#discussion_r1014625377 and https://github.com/rust-lang/rust/pull/104000#discussion_r1014642482 in the latest commits.

r? `@oli-obk`

-----

LLVM has a neat [statistics](https://llvm.org/docs/ProgrammersManual.html#the-statistic-class-stats-option) feature that tracks how often optimizations kick in. It's very handy for optimization work. Since we expose the LLVM pass timings, I thought it made sense to expose the LLVM statistics too.

-----
(Edit: fix broken link
(Edit2: fix segmentation fault and use malloc

If `rustc` is built with
```toml
[llvm]
assertions = true
```
Then you can see like
```
rustc +stage1 -Z print-codegen-stats -C opt-level=3  tmp.rs
===-------------------------------------------------------------------------===
                          ... Statistics Collected ...
===-------------------------------------------------------------------------===
         3 aa                           - Number of MayAlias results
       193 aa                           - Number of MustAlias results
       531 aa                           - Number of NoAlias results
...
```

And the current default build emits only
```
$ rustc +stage1 -Z print-codegen-stats -C opt-level=3  tmp.rs
===-------------------------------------------------------------------------===
                          ... Statistics Collected ...
===-------------------------------------------------------------------------===
$
```
This might be better to emit the message to tell assertion flag necessity, but now I can't find how to do that...
2023-07-21 06:52:27 +02:00
Santiago Pastorino
17b8977f9b
Add FnPtr ty to SMIR 2023-07-20 23:18:40 -03:00
Santiago Pastorino
93bcc2ef98
Implement Stable for ty::GenericArgs 2023-07-20 23:18:33 -03:00
Moulins
39cfe70e4f CTFE: move target_{i, u}size_{min, max) to rustc_abi::TargetDataLayout 2023-07-21 03:31:47 +02:00
Moulins
bf2f8ff2ec Move naive_layout_of query provider in separate sibling module 2023-07-21 03:31:46 +02:00
Moulins
8e28729a82 Add doc-comments for NaiveLayout 2023-07-21 03:31:46 +02:00
Moulins
feb20f2fe7 Track ABI info. in NaiveLayout, and use it for PointerLike checks
THis significantly complicates `NaiveLayout` logic, but is necessary to
ensure that bounds like `NonNull<T>: PointerLike` hold in generic
contexts.

Also implement exact layout computation for structs.
2023-07-21 03:31:46 +02:00
Moulins
c30fbb95a6 Track exactness in NaiveLayout and use it for SizeSkeleton checks 2023-07-21 03:31:46 +02:00
Moulins
403f34b599 Don't treat ref. fields with non-null niches as dereferenceable_or_null 2023-07-21 03:31:46 +02:00
Moulins
4fb039ed6c recover null-ptr optimization by adding a special case to the niching logic 2023-07-21 03:31:46 +02:00
Moulins
76c49aead6 support non-null pointer niches in CTFE 2023-07-21 03:31:45 +02:00
Moulins
3c05276866 restrict the valid range of references if -Z reference-niches is set
Note that this doesn't actually work at all, as many places in rustc
assume that references only have the null niche.
2023-07-21 03:31:45 +02:00
Moulins
8b847ef734 add crate-local -Z reference_niches unstable flag (does nothing for now) 2023-07-21 03:31:45 +02:00
Moulins
30ae640a3c properly handle arrays and wide pointers in naive_layout_of 2023-07-21 03:31:45 +02:00
Moulins
cb8b1d1bc9 add naive_layout_of query 2023-07-21 03:31:45 +02:00
Santiago Pastorino
cbabd00c12
Add tables to Stable::stable 2023-07-20 22:20:53 -03:00
bors
e2a7ba2771 Auto merge of #113858 - cjgillot:const-prop-pairs, r=oli-obk
Always const-prop scalars and scalar pairs

This removes some complexity from the pass.

The limitation to propagate ScalarPairs only for tuple comes from https://github.com/rust-lang/rust/pull/67015, when ScalarPair constant were modeled using `Rvalue::Aggregate`. Nowadays, we use `ConstValue::ByRef`, which does not care about the underlying type.

The justification for not propagating in all cases was perf. This seems not to be a clear cut any more: https://github.com/rust-lang/rust/pull/113858#issuecomment-1642396746
2023-07-20 22:22:31 +00:00
Camille GILLOT
4a177406ee Inline should_const_prop. 2023-07-20 21:30:51 +00:00
Camille GILLOT
3f708add2f Remove visit_terminator. 2023-07-20 21:30:51 +00:00
Camille GILLOT
ccfa9af29d Propagate ScalarPair for any type. 2023-07-20 21:30:51 +00:00
Camille GILLOT
895e2159f8 Also propagate ScalarPair operands. 2023-07-20 21:30:51 +00:00
Camille GILLOT
12a2edd149 Always propagate into operands. 2023-07-20 21:30:51 +00:00
bors
399b068235 Auto merge of #113856 - WaffleLapkin:vtablin', r=oli-obk
Refactor vtable encoding and optimize it for the case of multiple marker traits

This PR does two things
- Refactor `prepare_vtable_segments` (this was motivated by the other change, `prepare_vtable_segments` was quite hard to understand and while trying to edit it I've refactored it)
  - Mostly remove `loop`s labeled `break`s/`continue`s whenever there is a simpler solution
  - Also use `?`
- Make vtable format a bit more efficient wrt to marker traits
  - See the tests for an example

Fixes https://github.com/rust-lang/rust/issues/113840
cc `@crlf0710`

----

Review wise it's probably best to review each commit individually, as then it's more clear why the refactoring is correct.

I can split the last two commits (which change behavior) into a separate PR if it makes reviewing easier
2023-07-20 20:34:06 +00:00
bors
1554942cdc Auto merge of #113546 - cjgillot:unused-query, r=compiler-errors
Querify unused trait check.

This code transitively loads information for all bodies, and from resolutions. As it does not return a value, it should be beneficial to have it as a query.
2023-07-20 18:45:09 +00:00
David Tolnay
11ae0afc93
Create separate match arms for FileNames and CrateNames
This introduces a bit of code duplication, but we don't have the
build_output_filenames in the CrateName arm and this seems a little
cleaner overall.
2023-07-20 11:04:32 -07:00
David Tolnay
26fd6b15b0
Add note about writing native-static-libs to file 2023-07-20 11:04:32 -07:00
David Tolnay
dcfe94a009
Implement printing to file for link-args and native-static-libs 2023-07-20 11:04:31 -07:00
David Tolnay
815a114974
Implement printing to file in PassWrapper 2023-07-20 11:04:31 -07:00
David Tolnay
6e734fce63
Implement printing to file in llvm_util 2023-07-20 11:04:31 -07:00
David Tolnay
c80cbe4bae
Implement printing to file in codegen_backend.print 2023-07-20 11:04:31 -07:00
David Tolnay
5a60660ff8
Implement printing to file in print_crate_info 2023-07-20 11:04:31 -07:00
David Tolnay
f2e3d3fc63
Move OutFileName writing into rustc_session 2023-07-20 11:04:31 -07:00
David Tolnay
32cac2e002
Disallow overlapping prints to the same location 2023-07-20 11:04:30 -07:00
David Tolnay
f72bdb1501
Parse --print KIND=PATH command line syntax 2023-07-20 11:04:30 -07:00
David Tolnay
c0dc0c6875
Store individual output file name with every PrintRequest 2023-07-20 11:04:30 -07:00
bors
092e4f46be Auto merge of #113890 - matthiaskrgr:rollup-k1w2vii, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #110765 (rustdoc: fix position of `default` in method rendering)
 - #113529 (Permit pre-evaluated constants in simd_shuffle)
 - #113800 (Avoid another gha group nesting)
 - #113827 (Add Foreign, Never, FnDef, Closure and Generator tys to SMIR)
 - #113835 (new solver: don't consider blanket impls multiple times)
 - #113883 (Remove outdated Firefox-specific CSS for search's crate selector appearance)
 - #113884 (Don't translate compiler-internal bug messages)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-07-20 16:57:05 +00:00
Ralf Jung
41a73d8251 clarify MIR uninit vs LLVM undef/poison 2023-07-20 18:43:54 +02:00
Matthias Krüger
464e02a267
Rollup merge of #113884 - oli-obk:delay_span_bug_detrans_late, r=davidtwco
Don't translate compiler-internal bug messages

These are not very useful to be translated, as

* translators would get really weird and bad english versions to start out from,
* compiler devs have to do some work for what is supposed to be dead code and just a sanity check,
* the target audience is other compiler devs.

r? `@davidtwco`
2023-07-20 17:19:34 +02:00
Matthias Krüger
add8298aff
Rollup merge of #113835 - lcnr:assemble-candidates-considering-self-ty, r=compiler-errors
new solver: don't consider blanket impls multiple times

only consider candidates which rely on the self type in `assemble_candidates_after_normalizing_self_ty`.

r? ``@compiler-errors``
2023-07-20 17:19:33 +02:00
Matthias Krüger
1a748f0460
Rollup merge of #113827 - spastorino:smir-types-4, r=oli-obk
Add Foreign, Never, FnDef, Closure and Generator tys to SMIR

r? ``@oli-obk``
2023-07-20 17:19:33 +02:00
Matthias Krüger
8c17e0701e
Rollup merge of #113529 - oli-obk:simd_shuffle_evaluated, r=wesleywiser
Permit pre-evaluated constants in simd_shuffle

fixes https://github.com/rust-lang/rust/issues/113500
2023-07-20 17:19:32 +02:00
bors
06a53ddc0b Auto merge of #113758 - cjgillot:move-dse, r=JakobDegen,oli-obk
Turn copy into moves during DSE.

Dead store elimination computes whether removing a direct store to an unborrowed place is allowed.
Where removing a store is allowed, writing `uninit` is too.

This means that we can use this pass to transform `copy` operands into `move` operands. This is only interesting in call terminators, so we only handle those.

Special care is taken for the `use_both(_1, _1)` case:
- moving the second argument is ok, as `_1` is not live after the call;
- moving the first argument is not, as the second argument reads `_1`.

Fixes #75993
Fixes https://github.com/rust-lang/rust/issues/108068

r? `@RalfJung`
cc `@JakobDegen`
2023-07-20 15:05:39 +00:00
lcnr
5c75bc5317 update doc comments 2023-07-20 12:01:34 +02:00
lcnr
2062f2ca82 review 2023-07-20 12:01:34 +02:00
Oli Scherer
d97ec97b94 Don't translate compiler-internal bug messages 2023-07-20 09:51:47 +00:00
lcnr
7c97a76b76 re-add comment 2023-07-20 11:05:52 +02:00
lcnr
aa28b77b5a add FIXME 2023-07-20 11:05:52 +02:00
lcnr
2d99f40ec5 assembly: only consider blanket impls once 2023-07-20 11:05:52 +02:00
lcnr
fdaec57a28 XSimplifiedType to SimplifiedType::X 2023-07-20 11:05:52 +02:00
bors
b14fd2359f Auto merge of #113695 - bjorn3:fix_rlib_cdylib_metadata_handling, r=pnkfelix,petrochenkov
Verify that all crate sources are in sync

This ensures that rustc will not attempt to link against a cdylib as if it is a rust dylib when an rlib for the same crate is available. Previously rustc didn't actually check if any further formats of a crate which has been loaded are of the same version and if they are actually valid. This caused a cdylib to be interpreted as rust dylib as soon as the corresponding rlib was loaded. As cdylibs don't export any rust symbols, linking would fail if rustc decides to link against the cdylib rather than the rlib.

Two crates depended on the previous behavior by separately compiling a test crate as both rlib and dylib. These have been changed to capture their original spirit to the best of my ability while still working when rustc verifies that all crates are in sync. It is unlikely that build systems depend on the current behavior and in any case we are taking a lot of measures to ensure that any change to either the source or the compilation options (including crate type) results in rustc rejecting it as incompatible. We merely didn't do this check here for now obsolete perf reasons.

Fixes https://github.com/rust-lang/rust/issues/10786
Fixes https://github.com/rust-lang/rust/issues/82151
Fixes https://github.com/rust-lang/rust/issues/82972
Closes https://github.com/bevy-cheatbook/bevy-cheatbook/issues/114
2023-07-20 09:00:10 +00:00
Oli Scherer
c7428d5052 Monomorphize constants before inspecting them 2023-07-20 08:53:09 +00:00
khei4
c7bf20dfdc address feedback from nikic and oli-obk https://github.com/rust-lang/rust/pull/113723/files
use slice memcpy rather than strcpy and write it on stdout

use println on failure

Co-authored-by: Oli Scherer <github35764891676564198441@oli-obk.de>
2023-07-20 16:53:06 +09:00
Matthias Krüger
770c8d0667
Rollup merge of #113871 - clubby789:derive-sugg-span, r=compiler-errors
Use the correct span for displaying the line following a derive sugge…

`span` here is the main span of the diagnostic. In the linked issue's case, this belongs to `main.rs`. However, the line numbers (and line we are trying to display) are in `name.rs`, so using `span_to_lines` gives us the wrong `FileLines`.

Use `parts[0].span` (the span of the suggestion) here like the rest of the code does to get the right file.

Not sure if this needs a dedicated test because this fixes an existing error in the UI suite

Fixes #113844
2023-07-20 07:08:43 +02:00
Matthias Krüger
b128750bc4
Rollup merge of #113795 - compiler-errors:doc, r=spastorino
Properly document `lifetime_mapping` in `OpaqueTy`

Also use an `Option` to signify that the value is actually present, instead of just no captured lifetimes.
2023-07-20 07:08:42 +02:00
Jhonny Bill Mena
7a888fb56e UPDATE - replace expected_simd error with one from codegen_ssa
Here I am assuming we want to treat these parameters (input, first, second, third, return) as translatable
2023-07-20 00:20:00 -04:00
Jhonny Bill Mena
051615e198 UPDATE - replace gcc monomorphization errors with ssa ones
Reduces error duplication and makes it more consistent across backends
2023-07-19 23:40:08 -04:00
bors
0646a5d1aa Auto merge of #113622 - RickleAndMortimer:issue-113184-fix, r=oli-obk
add links to query documentation for E0391

This PR adds links to https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for the rustc --explain E0391 and within the compiler error itself.

Fixes: #113184
2023-07-20 03:18:41 +00:00