NLL Liveness: Skip regionless types when visiting free regions
The tuple-stress benchmark exercises the liveness constraint generation code for types which do not have regions
Closes#52027
ARM: expose the "mclass" target feature
This let us differentiate, in conditional compilation context, between ARM Cortex-M targets, like
the `thumbv*` targets, and other ARM targets, like the ARM Cortex-A Linux targets.
r? @alexcrichton
cc @gnzlbg
cc rust-lang-nursery/stdsimd#437
Deprecate `std::env::home_dir` and fix incorrect documentation
Compare `std::env::home_dir`s claim:
> Returns the value of the 'HOME' environment variable if it is set and not equal to the empty string.
... with its actual behavior:
```
std::env::set_var("HOME", "");
println!("{:?}", std::env::var_os("HOME")); // Some("")
println!("{:?}", std::env::home_dir()); // Some("")
```
The implementation is incorrect in two cases:
- `$HOME` is set, but empty.
- An entry for the user exists in `/etc/passwd`, but it's `pw_dir` is empty.
In both cases Rust considers an empty string to be a valid home directory. This contradicts the documentation, and is wrong in general.
refactor and cleanup region errors for NLL
This is a WIP commit. It simplifies some of the code from https://github.com/rust-lang/rust/pull/51536 and extends a few more steps towards the errors that @davidtwco and I were shooting for. These are intended as a replacement for the general "unable to infer lifetime" messages -- one that is actually actionable. We're certainly not there yet, but the overall shape hopefully gets a bit clearer.
I'm thinking about trying to open up an internals thread to sketch out the overall plan and perhaps discuss how to get the wording right, which special cases to handle, etc.
r? @estebank
cc @davidtwco
Haiku: several smaller fixes to build and run rust on Haiku
This PR combines three small patches that help Rust build and run on the Haiku platform. These patches do not intend to impact other platforms.
enable Atomic*.{load,store} for ARMv6-M / MSP430
closes#45085
as proposed in https://github.com/rust-lang/rust/issues/45085#issuecomment-384825434
this commit adds an `atomic_cas` target option and extends the `#[cfg(target_has_atomic)]`
attribute to enable a subset of the `Atomic*` API on architectures that don't support atomic CAS
natively, like MSP430 and ARMv6-M.
r? @alexcrichton
Rollup of 14 pull requests
Successful merges:
- #51619 (rust: add initial changes to support powerpc64le musl)
- #51793 (Fix variant background color on hover in search results)
- #52005 (Update LLVM to bring in a wasm codegen fix)
- #52016 (Deduplicate error reports for statics)
- #52019 ([cross-lang-lto] Allow the linker to choose the LTO-plugin (which is useful when using LLD))
- #52030 (Any docs preposition change)
- #52031 (Strenghten synchronization in `Arc::is_unique`)
- #52033 ([Gardening] Update outdated comments: ByVal -> Scalar)
- #52055 (Include VS 2017 in error message.)
- #52063 (Add a link to the rustc docs)
- #52073 (Add a punch card to weird expressions test)
- #52080 (Improve dependency deduplication diagnostics)
- #52093 (rustc: Update tracking issue for wasm_import_module)
- #52096 (Fix typo in cell.rs)
Failed merges:
By default, Haiku has the desired 16 MB stack, therefore in general
we do not have to spawn a new thread. The code has been written in
such a way that any changes in Haiku or in Rust will be adapted to.
[Gardening] Update outdated comments: ByVal -> Scalar
ByVal enum cases in mir::interpret::value were renamed to Scalar a while ago but comments still refer to the old names.
Strenghten synchronization in `Arc::is_unique`
Previously, `is_unique` would not synchronize at all with a `drop` that returned
early because it was not the last reference, leading to a data race.
Fixes#51780
Unfortunately I have no idea how to add a test for this.
Cc @jhjourdan
Any docs preposition change
This changes the docs referring to where a user should be wary of depending on "Any" trait impls from warning about relying on them "outside" of their code to warning about relying on them "inside" of their code.
[cross-lang-lto] Allow the linker to choose the LTO-plugin (which is useful when using LLD)
This PR allows for not specifying an LTO-linker plugin but still let `rustc` invoke the linker with the correct plugin arguments. This is useful when using LLD which does not need the `-plugin` argument. Since LLD is the best linker for this scenario anyway, this change should improve ergonomics quite a bit.
r? @alexcrichton
closes#45085
this commit adds an `atomic_cas` target option and an unstable `#[cfg(target_has_atomic_cas)]`
attribute to enable a subset of the `Atomic*` API on architectures that don't support atomic CAS
natively, like MSP430 and ARMv6-M.
We represent `bool` as `i1` in a `ScalarPair`, unlike other aggregates,
to optimize IR for checked operators and the like. With this patch, we
still do so when the pair is an immediate value, but we use the `i8`
memory type when the value is loaded or stored as an LLVM aggregate.
So `(bool, bool)` looks like an `{ i1, i1 }` immediate, but `{ i8, i8 }`
in memory. When a pair is a direct function argument, `PassMode::Pair`,
it is still passed using the immediate `i1` type, but as a return value
it will use the `i8` memory type. Also, `bool`-like` enum tags will now
use scalar pairs when possible, where they were previously excluded due
to optimization issues.
The docs were not specifying how to compute the alignment of the struct, so I had to spend some time trying to figure out how that works. Found the answer [on this page](http://camlorn.net/posts/April%202017/rust-struct-field-reordering.html):
> The total size of this struct is 5, but the most-aligned field is b with alignment 2, so we round up to 6 and give the struct an alignment of 2 bytes.
Fix various issues with control-flow statements inside anonymous constants
Fixes#51761.
Fixes#51963 (and the host of other reported issues there).
(Might be easiest to review per commit, as they should be standalone.)
r? @estebank
rename rustc's lld to rust-lld
to not shadow the system installed LLD when linking with LLD.
Before:
- `-C linker=lld -Z linker-flavor=ld.lld` uses rustc's LLD
- It's not possible to use a system installed LLD that's named `lld`
With this commit:
- `-C linker=rust-lld -Z linker-flavor=ld.lld` uses rustc's LLD
- `-C linker=lld -Z linker-flavor=ld.lld` uses the system installed LLD
we don't offer guarantees about the availability of LLD in the rustc sysroot so we can rename the tool as long as we don't break the wasm32-unknown-unknown target which depends on it.
r? @alexcrichton we discussed this before
in which we plug the crack where `?`-desugaring leaked into errors
Most of the time, it's not a problem that the types of the arm bodies in
a desugared-from-`?` match are different (that is, specifically: in `x?`
where x is a `Result<A, B>`, the `Ok` arm body is an `A`, whereas the
`Err` arm diverges to return a `Result<A, B>`), because they're being
assigned to different places. But in tail position, the types do need to
match, and our error message was explicitly referring to "match arms",
which is confusing when there's no `match` in the sweetly sugared
source.
It is not without some misgivings that we pollute the clarity-of-purpose
of `note_error_origin` with the suggestion to wrap with `Ok` (the other
branches are pointing out the odd-arm-out in the HIR that is the origin
of the error; the new branch that issues the `Ok` suggestion is serving
a different purpose), but it's the natural place to do it given that
we're already matching on `ObligationCauseCode::MatchExpressionArm {
arm_span, source }` there.
Resolves#51632.
[NLL] Fix various unused mut errors
Closes#51801Closes#50897Closes#51830Closes#51904
cc #51918 - keeping this one open in case there are any more issues
This PR contains multiple changes. List of changes with examples of what they fix:
* Change mir generation so that the parameter variable doesn't get a name when a `ref` pattern is used as an argument
```rust
fn f(ref y: i32) {} // doesn't trigger lint
```
* Change mir generation so that by-move closure captures don't get first moved into a temporary.
```rust
let mut x = 0; // doesn't trigger lint
move || {
x = 1;
};
```
* Treat generator upvars the same as closure upvars
```rust
let mut x = 0; // This mut is now necessary and is not linted against.
move || {
x = 1;
yield;
};
```
r? @nikomatsakis
This removes the `usize` argument to `inc_step_counter`. Now, the step
counter increments by exactly one for every terminator evaluated. After
`STEPS_UNTIL_DETECTOR_ENABLED` steps elapse, the detector is run every
`DETECTOR_SNAPSHOT_PERIOD` steps. The step counter is only kept modulo
this period.
This test relies on the fact that restrictions on expressions in `const
fn` do not apply when computing array lengths. It is more difficult to
statically analyze than the simple `loop{}` mentioned in #50637.
This test should be updated to ignore the warning after #49980 is resolved.
The detector runs every `DETECTOR_SNAPSHOT_PERIOD` steps. Since the
number of steps can increase by more than 1 (I'd like to remove this),
the detector may fail if the step counter is incremented past the
scheduled detection point during the loop.
This reverts commit 59d21c526c036d7097d05edd6dffdad9c5b1cb62, and uses
tuple to store the mutable parts of an EvalContext (which now includes
`Machine`). This requires that `Machine` be `Clone`.
Use the approach suggested by @oli-obk, a table holding `EvalState`
hashes and a table holding full `EvalState` objects. When a hash
collision is observed, the state is cloned and put into the full
table. If the collision was not spurious, it will be detected during the
next iteration of the infinite loop.
I use a pattern binding in each custom impl, so that adding fields to
`Memory` or `Frame` will cause a compiler error instead of causing e.g.
`PartialEq` to become invalid. This may be too cute.
This adds several requirements to `Machine::MemoryData`. These can be
removed if we don't want this associated type to be part of the equality
of `Memory`.
rustdoc codeblock hash escape
So that docstring text such as the following (in a code block) can be created ergonomically:
```rust
let s = "
foo
# bar
baz
";
```
Such code in a docstring hide the <code> # bar</code> line.
Previously, using two consecutive hashes <code> ## bar</code> would turn the line into _shown_ `# bar`, losing the leading whitespace. A line of code like <code> # bar</code> (such as in the example above) **could not be represented** in the docstring text.
This commit makes the two consecutive hashes not also trim the leading whitespace — the two hashes simply **escape** into a single hash and do not hide the line, leaving the rest of that line unaffected. The new docstring text to achieve the above code block is:
```rust
/// ```
/// let s = "
/// foo
/// ## bar
/// baz
/// ";
/// ```
```
rustdoc: import cross-crate macros alongside everything else
The thrilling conclusion of the cross-crate macro saga in rustdoc! After https://github.com/rust-lang/rust/pull/51425 made sure we saw all the namespaces of an import (and prevented us from losing the `vec!` macro in std's documentation), here is the PR to handle cross-crate macro re-exports at the same time as everything else. This way, attributes like `#[doc(hidden)]` and `#[doc(no_inline)]` can be used to control how the documentation for these macros is seen, rather than rustdoc inlining every macro every time.
Fixes https://github.com/rust-lang/rust/issues/50647
Reuse the `DefsUsesVisitor` in `simulate_block()`.
This avoids a bunch of allocations for the bitsets within it,
speeding up a number of NLL benchmarks, the best by 1%.
r? @nikomatsakis
Unpin references
I also considered adding an impl for raw pointers as well, but that makes it easy to accidentally have unsound owning-collections that might otherwise be able to project pinned-ness (e.g. `Box`).
cc @RalfJung
r? @withoutboats
Move self trait predicate to items
This is a "reimagination" of @tmandry's PR #50183. The main effect is described in this comment from one of the commits:
---
Before we had the following results for `predicates_of`:
```rust
trait Foo { // predicates_of: Self: Foo
fn bar(); // predicates_of: Self: Foo (inherited from trait)
}
```
Now we have removed the `Self: Foo` from the trait. However, we still
add it to the trait ITEM. This is because when people do things like
`<T as Foo>::bar()`, they still need to prove that `T: Foo`, and
having it in the `predicates_of` seems to be the cleanest way to
ensure that happens right now (otherwise, we'd need special case code
in various places):
```rust
trait Foo { // predicates_of: []
fn bar(); // predicates_of: Self: Foo
}
```
However, we sometimes want to get the list of *just* the predicates
truly defined on a trait item (e.g., for chalk, but also for a few
other bits of code). For that, we define `predicates_defined_on`,
which does not contain the `Self: Foo` predicate yet, and we plumb
that through metadata and so forth.
---
I'm assigning @eddyb as the main reviewer, but I thought I might delegate to scalexm for this one in any case. I also want to post an alternative that I'll leave in the comments; it occurred to me as I was writing. =)
r? @eddyb
cc @scalexm @tmandry @leodasvacas
This commit updates the stage0 build of tools to use the libraries of the stage0
compiler instead of the compiled libraries by the stage0 compiler. This should
enable us to avoid any stage0 hacks (like missing SIMD).
[NLL] Use better span for initializing a variable twice
Closes#51217
When assigning to a (projection from a) local immutable local which starts initialised (everything except `let PATTERN;`):
* Point to the declaration of that local
* Make the error message refer to the local, rather than the projection.
r? @nikomatsakis
introduce dirty list to dataflow
@nikomatsakis my naive implementation never worked, So, I decided to implement using `work_queue` data structure. This PR also includes your commits from `nll-liveness-dirty-list` branch. Those commits should not visible once your branch is merged.
r? @nikomatsakis
Previously, `is_unique` would not synchronize at all with a `drop` that returned
early because it was not the last reference, leading to a data race.
Fixes#51780
This changes the docs referring to where a user should be wary of depending on "Any" trait impls from warning about relying on them "outside" of their code to warning about relying on them "inside" of their code.
Rollup of 13 pull requests
Successful merges:
- #51548 (Initialize LLVM's AMDGPU target machine, if available.)
- #51809 (Add read_exact_at and write_all_at methods to FileExt on unix)
- #51914 (add outlives annotations to `BTreeMap`)
- #51958 (Show known meta items in unknown meta items error)
- #51973 (Make Stdio handle UnwindSafe)
- #51977 (bootstrap: tests should use rustc from config.toml)
- #51978 (Do not suggest changes to str literal if it isn't one)
- #51979 (Get rid of `TyImplTraitExistential`)
- #51980 (Emit column info in debuginfo for non msvc like targets)
- #51982 (incr.comp.: Take names of children into account when computing the ICH of a module's HIR.)
- #51997 (add entry for cargo-metadata feature to RELEASES)
- #52004 (toolstate: Fixed detection of changed submodule, and other fixes.)
- #52006 ( Change --keep-stage to apply more often)
Failed merges:
r? @ghost
Change --keep-stage to apply more often
Previously, the --keep-stage argument would only function for compilers
that were depended on by future stages. For example, if trying to build
a stage 1 compiler you could --keep-stage 0 to avoid re-building the
stage 0 compiler. However, this is often not what users want in
practice.
The new implementation essentially skips builds all higher stages of the
compiler, so an argument of 1 to keep-stage will skip rebuilds of the
libraries, just linking them into the sysroot. This is unlikely to work
well in cases where metadata or similar changes have been made, but is
likely fine otherwise.
This change is somewhat untested, but since it shouldn't have any effect
except with --keep-stage, I don't see that as a large problem.
r? @alexcrichton
cc @nikomatsakis - I believe you wanted this functionality
toolstate: Fixed detection of changed submodule, and other fixes.
1. Make sure that if a submodule is updated but failed to test-pass, we'll block the merge.
2. Make sure failure on external docs (nomicon/RBE/etc) are properly checked.
3. If the commit message starts with "Update RLS" (or clippy etc), automatically run the "tools" job on the PR, so that we could know if the update failed before merging.
incr.comp.: Take names of children into account when computing the ICH of a module's HIR.
Fixes#40876. Red-green tracking does not make this a problem anymore. We should verify this via a perf-run though.
r? @nikomatsakis
bootstrap: tests should use rustc from config.toml
Tests should always use "rustc" and "cargo" from config.toml instead of assuming that stage0 binaries was downloaded to build directory.
Without this change `./x.py test src/bootstrap` will always try to use `build/ARCH/stage0/bin/rustc` file as compiler, but when we use local compiler to bootstrap this file does not exist.
Show known meta items in unknown meta items error
This PR adds a label to E0541. It also factors built-in attribute parsing into a submodule of `attr` for ease of future refactoring.
Fixes#51469.
Add read_exact_at and write_all_at methods to FileExt on unix
This PR adds `FileExt::read_exact_at()` and `FileExt::write_all_at()`, which are to `read_at()` and `write_at()` as `read_exact()` and `write_all()` are to `read()` and `write()`. This allows the user to not have to deal with `ErrorKind::Interrupted` and calling the functions in a loop.
I was unsure as to how to mark these new methods so I marked them `unstable`, please let me know if I should have done it differently.
I asked in Discord and was told that as this change is small it does not require an RFC.
Initialize LLVM's AMDGPU target machine, if available.
Note this isn't useful, yet. More changes will be necessary to be able to
actually codegen for this machine. As such, it is not enabled by default.
This patch is on its own for the benefit of the reviewers.
Implement always-fallible TryFrom for usize/isize conversions that are infallible on some platforms
This reverts commit 837d6c7023 "Remove TryFrom impls that might become conditionally-infallible with a portability lint".
This fixes#49415 by adding (restoring) missing `TryFrom` impls for integer conversions to or from `usize` or `isize`, by making them always fallible at the type system level (that is, with `Error=TryFromIntError`) even though they happen to be infallible on some platforms (for some values of `size_of::<usize>()`).
They had been removed to allow the possibility to conditionally having some of them be infallible `From` impls instead, depending on the platforms, and have the [portability lint](https://github.com/rust-lang/rfcs/pull/1868) warn when they are used in code that is not already opting into non-portability. For example `#[allow(some_lint)] usize::from(x: u64)` would be valid on code that only targets 64-bit platforms.
This PR gives up on this possiblity for two reasons:
* Based on discussion with @aturon, it seems that the portability lint is not happening any time soon. It’s better to have the conversions be available *at all* than keep blocking them for so long. Portability-lint-gated platform-specific APIs can always be added separately later.
* For code that is fine with fallibility, the alternative would force it to opt into "non-portability" even though there would be no real portability issue.
Previously, the --keep-stage argument would only function for compilers
that were depended on by future stages. For example, if trying to build
a stage 1 compiler you could --keep-stage 0 to avoid re-building the
stage 0 compiler. However, this is often not what users want in
practice.
The new implementation essentially skips builds all higher stages of the
compiler, so an argument of 1 to keep-stage will skip rebuilds of the
libraries, just linking them into the sysroot. This is unlikely to work
well in cases where metadata or similar changes have been made, but is
likely fine otherwise.
This change is somewhat untested, but since it shouldn't have any effect
except with --keep-stage, I don't see that as a large problem.
Make custom trait object for `Future` generic
- `TaskObj` -> `FutureObj<'static, ()>`
- The `impl From<...> for FutureObj<'a, T>` impls are impossible because of the type parameter `T`. The impl has to live in libstd, but `FutureObj<'a, T>` is from libcore. Therefore `Into<FutureObj<'a, T>>` was implemented instead. Edit: This didn‘t compile without warnings. I am now using non-generic Form impls.
See https://github.com/rust-lang-nursery/futures-rs/issues/1058
r? @cramertj
Edit: Added lifetime
introduce dirty list to liveness, eliminate `ins` vector
At least in my measurements, this seems to knock much of the liveness computation off the profile.
r? @Zoxc
cc @nnethercote
This new query returns only the predicates *directly defined* on an
item (in contrast to the more common `predicates_of`, which returns
the predicates that must be proven to reference an item). These two
sets are almost always identical except for traits, where
`predicates_of` includes an artificial `Self: Trait<...>` predicate
(basically saying that you cannot use a trait item without proving
that the trait is implemented for the type parameters).
This new query is only used in chalk lowering, where this artificial
`Self: Trait` predicate is problematic. We encode it in metadata but
only where needed since it is kind of repetitive with existing
information.
Co-authored-by: Tyler Mandry <tmandry@gmail.com>
If we have
```rust
struct Foo<T: Copy = String> { .. }
```
the old code would have proven that `String: Copy` was WF -- this,
incidentally, also proved that `String: Copy`. The new code just
proves `String: Copy` directly.
Co-authored-by: Tyler Mandry <tmandry@gmail.com>
(The present author fears not being knowledgeable enough to rewrite the
comments unilaterally; merely calling it out is a lazy half-measure, but
at least doesn't actively make things worse the way an ill-informed
rewrite would.)
add modifier keyword spans to hir::Visibility; improve unreachable-pub, private-no-mangle lint suggestions
#50455 pointed out that the unreachable-pub suggestion for brace-grouped `use`s was bogus; #50476 partially ameliorated this by marking the suggestion as `Applicability::MaybeIncorrect`, but this is the actual fix.
Meanwhile, another application of having spans available in `hir::Visibility` is found in the private-no-mangle lints, where we can now issue a suggestion to use `pub` if the item has a more restricted visibility marker (this seems much less likely to come up in practice than not having any visibility keyword at all, but thoroughness is a virtue). While we're there, we can also add a helpful note if the item does have a `pub` (but triggered the lint presumably because enclosing modules were private).
![hir_vis](https://user-images.githubusercontent.com/1076988/42018064-ca830290-7a65-11e8-9c4c-48bc846f861f.png)
r? @nrc
cc @Manishearth
Loosened rules involving statics mentioning other statics
Before this PR, trying to mention a static in any way other than taking a reference to it caused a compile-time error. So, while
```rust
static A: u32 = 42;
static B: &u32 = &A;
```
compiles successfully,
```rust
static A: u32 = 42;
static B: u32 = A; // error
```
and
```rust
static A: u32 = 42;
static B: u32 = *&A; // error
```
are not possible to express in Rust. On the other hand, introducing an intermediate `const fn` can presently allow one to do just that:
```rust
static A: u32 = 42;
static B: u32 = foo(&A); // success!
const fn foo(a: &u32) -> u32 {
*a
}
```
Preventing `const fn` from allowing to work around the ban on reading from statics would cripple `const fn` almost into uselessness.
Additionally, the limitation for reading from statics comes from the old const evaluator(s) and is not shared by `miri`.
This PR loosens the rules around use of statics to allow statics to evaluate other statics by value, allowing all of the above examples to compile and run successfully.
Reads from extern (foreign) statics are however still disallowed by miri, because there is no compile-time value to be read.
```rust
extern static A: u32;
static B: u32 = A; // error
```
This opens up a new avenue of potential issues, as a static can now not just refer to other statics or read from other statics, but even contain references that point into itself.
While it might seem like this could cause subtle bugs like allowing a static to be initialized by its own value, this is inherently impossible in miri.
Reading from a static causes the `const_eval` query for that static to be invoked. Calling the `const_eval` query for a static while already inside the `const_eval` query of said static will cause cycle errors.
It is not possible to accidentally create a bug in miri that would enable initializing a static with itself, because the memory of the static *does not exist* while being initialized.
The memory is not uninitialized, it is not there. Thus any change that would accidentally allow reading from a not yet initialized static would cause ICEs.
Tests have been modified according to the new rules, and new tests have been added for writing to `static mut`s within definitions of statics (which needs to fail), and incremental compilation with complex/interlinking static definitions.
Note that incremental compilation did not need to be adjusted, because all of this was already possible before with workarounds (like intermediate `const fn`s) and the encoding/decoding already supports all the possible cases.
r? @eddyb
Fix some doc links
The futures crate CI always fails because of these intra doc links. I hope that this will fix this issue.
r? @steveklabnik
@cramertj
Edit: I added @steveklabnik as reviewer because this PR also adjusts a link in `src/libstd/error.rs`
Stabilize Iterator::flatten in 1.29, fixes#48213.
This PR stabilizes [`Iterator::flatten`](https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#method.flatten) in *version 1.29* (1.28 goes to beta in 10 days, I don't think there's enough time to land it in that time, but let's see...).
Tracking issue is: #48213.
cc @bluss re. itertools.
r? @SimonSapin
ping @pietroalbini -- let's do a crater run when this passes CI :)
Speed up compilation of large constant arrays
This is a different approach to #51672 as suggested by @oli-obk. Rather
than write each repeated value one-by-one, we write the first one and
then copy its value directly into the remaining memory.
With this change, the [toy program](c2f4744d2d/src/test/run-pass/mir_heavy_promoted.rs) goes from 63 seconds to 19 seconds on my machine.
Edit: Inlining `Size::bytes()` saves an additional 6 seconds dropping the total time to 13 seconds on my machine.
Edit2: Now down to 2.8 seconds.
r? @oli-obk
cc @nnethercote @eddyb