Commit Graph

1482 Commits

Author SHA1 Message Date
Matthias Krüger
efb264fa78
Rollup merge of #123409 - ZhuUx:master, r=oli-obk
Implement Modified Condition/Decision  Coverage

This is an implementation based on llvm backend support (>= 18) by `@evodius96` and branch coverage support by `@Zalathar.`

### Major changes:

* Add -Zcoverage-options=mcdc as switch. Now coverage options accept either `no-branch`, `branch`, or `mcdc`. `mcdc` also enables `branch` because it is essential to work.
* Add coverage mapping for MCDCBranch and MCDCDecision. Note that MCDCParameter evolves from  llvm 18 to llvm 19. The mapping in rust side mainly references to 19 and is casted to 18 types in llvm wrapper.
* Add wrapper for mcdc instrinc functions from llvm. And inject associated statements to mir.
* Add BcbMappingKind::Decision, I'm not sure is it proper but can't find a better way temporarily.
* Let coverage-dump support parsing MCDCBranch and MCDCDecision from llvm ir.
* Add simple tests to check whether mcdc works.
* Same as clang, currently rustc does not generate instrument for decision with more than 6 condtions or only 1 condition due to considerations of resource.

### Implementation Details

1. To get information about conditions and decisions, `MCDCState` in `BranchInfoBuilder` is used during hir lowering to mir. For expressions with logical op we call `Builder::visit_coverage_branch_operation` to record its sub conditions, generate condition ids for them and save their spans (to construct the span of whole decision). This process mainly references to the implementation in clang and is described in comments over `MCDCState::record_conditions`. Also true marks and false marks introduced by branch coverage are used to detect where the decision evaluation ends: the next id  of the condition == 0.
2. Once the `MCDCState::decision_stack` popped all recorded conditions, we can ensure that the decision is checked over and push it into `decision_spans`. We do not manually insert decision span to avoid complexity from then_else_break in nested if scopes.
3. When constructing CoverageSpans, add condition info to BcbMappingKind::Branch and decision info to BcbMappingKind::Decision. If the branch mapping has non-zero condition id it will be transformed to MCDCBranch mapping and insert `CondBitmapUpdate` statements to its evaluated blocks. While decision bcb mapping will insert `TestVectorBitmapUpdate` in all its end blocks.

### Usage
```bash
 echo "[build]\nprofiler=true" >> config.toml
./x build --stage 1
./x test tests/coverage/mcdc_if.rs
```
to build the compiler and run tests.

```shell
export PATH=path/to/llvm-build:$PATH
rustup toolchain link mcdc build/host/stage1
cargo +mcdc rustc --bin foo -- -Cinstrument-coverage -Zcoverage-options=mcdc
cd target/debug
LLVM_PROFILE_FILE="foo.profraw" ./foo
llvm-profdata merge -sparse foo.profraw -o foo.profdata
llvm-cov show ./foo -instr-profile=foo.profdata --show-mcdc
```
to check "foo" code.

### Problems to solve

For now decision mapping will insert statements to its all end blocks, which may be optimized by inserting a final block of the decision. To do this we must also trace the evaluated value at each end of the decision and join them separately.

This implementation is not heavily tested so there should be some unrevealed issues. We are going to check our rust products in the next.  Please let me know if you had any suggestions or comments.
2024-04-20 11:10:31 +02:00
Oli Scherer
fbc9b94064 Move stable_crate_ids from CrateStore to Untracked
This way it's like `Definitions`, which creates `DefId`s by interning `DefPathData`s, but for interning stable crate hashes
2024-04-19 14:16:18 +00:00
bors
13e63f7490 Auto merge of #117919 - daxpedda:wasm-c-abi, r=wesleywiser
Introduce perma-unstable `wasm-c-abi` flag

Now that `wasm-bindgen` v0.2.88 supports the spec-compliant C ABI, the idea is to switch to that in a future version of Rust. In the meantime it would be good to let people test and play around with it.

This PR introduces a new perma-unstable `-Zwasm-c-abi` compiler flag, which switches to the new spec-compliant C ABI when targeting `wasm32-unknown-unknown`.

Alternatively, we could also stabilize this and then deprecate it when we switch. I will leave this to the Rust maintainers to decide.

This is a companion PR to #117918, but they could be merged independently.
MCP: https://github.com/rust-lang/compiler-team/issues/703
Tracking issue: https://github.com/rust-lang/rust/issues/122532
2024-04-19 03:35:10 +00:00
zhuyunxing
68f86381ee coverage. Add coverage-options=mcdc as gate for MC/DC instrument 2024-04-19 10:43:53 +08:00
Scott McMurray
90b4c86335 Ensure [rust] debuginfo-level-std doesn't change core's MIR 2024-04-18 09:35:36 -07:00
Guillaume Gomez
14496d561e
Rollup merge of #122811 - nnethercote:mv-SourceMap-init, r=WaffleLapkin
Move `SourceMap` initialization

So it happens at the same time as `SessionGlobals` initialization, rather than shortly afterward.

r? `@WaffleLapkin`
2024-04-16 21:41:23 +02:00
Matthias Krüger
f54219c473
Rollup merge of #123501 - Urgau:stabilize-check-cfg, r=petrochenkov
Stabilize checking of cfgs at compile-time: `--check-cfg` option

This PR stabilize the `--check-cfg` CLI option of `rustc` (and `rustdoc`) 🎉.

In particular this PR does two things:
  1. it makes the `--check-cfg` option stable
  2. and it moves the documentation to the stable books

FCP: https://github.com/rust-lang/rust/issues/82450#issuecomment-1965328542

Resolves #82450

``@rustbot`` labels +S-blocked +F-check-cfg
r? ``@petrochenkov``
2024-04-16 17:54:41 +02:00
Guillaume Gomez
26b6a234a1
Rollup merge of #121694 - davidtwco:stabilize-relro-level, r=Mark-Simulacrum
sess: stabilize `-Zrelro-level` as `-Crelro-level`

Stabilise `-Zrelro-level` as `-Crelro-level`. There's no tracking issue for this flag to close.
2024-04-16 15:19:10 +02:00
Nicholas Nethercote
9b0ced000a Move initialize_checked_jobserver.
Currently it's a method on `EarlyDiagCtxt`, which is not the right place
for it at all -- `EarlyDiagCtxt` is used to issue diagnostics, but
shouldn't be doing any of the actual checking.

This commit moves it into a standalone function that takes an
`EarlyDiagCtxt` as an argument, which is more sensible. This does
require adding `EarlyDiagCtxt::early_struct_warn`, so a warning can be
returned and then modified with a note. (And that likely explains why
somebody put `initialize_checked_jobserver` into `EarlyDiagCtxt` in the
first place.)
2024-04-16 13:02:55 +10:00
Nicholas Nethercote
62c32aeeab Construct SourceMap at the same time as SessionGlobals.
Currently `SourceMap` is constructed slightly later than
`SessionGlobals`, and inserted. This commit changes things so they are
done at the same time.

Benefits:
- `SessionGlobals::source_map` changes from
  `Lock<Option<Lrc<SourceMap>>>` to `Option<Lrc<SourceMap>>`. It's still
  optional, but mutability isn't required because it's initialized at
  construction.
- `set_source_map` is removed, simplifying `run_compiler`, which is
  good because that's a critical function and it's nice to make it
  simpler.

This requires moving things around a bit, so the necessary inputs are
available when `SessionGlobals` is created, in particular the `loader`
and `hash_kind`, which are no longer computed by `build_session`. These
inputs are captured by the new `SourceMapInputs` type, which is threaded
through various places.
2024-04-16 13:02:53 +10:00
Urgau
a20de73ccf Move --check-cfg documentation to stable books 2024-04-15 21:49:56 +02:00
Urgau
909fcfcb6a Stabilize checking of cfgs at compile-time: --check-cfg option 2024-04-15 21:49:55 +02:00
Jeremy Fitzhardinge
fdcb8a9fea Stabilize --json unused-externs(-silent)
Implement https://github.com/rust-lang/compiler-team/issues/674
2024-04-14 14:20:55 -07:00
bors
3a0db6c152 Auto merge of #123854 - petrochenkov:searchdirs2, r=lqd
linker: Remove laziness and caching from native search directory walks

It shouldn't be necessary for performance now.

Follow up to https://github.com/rust-lang/rust/pull/123827.
2024-04-13 13:12:56 +00:00
bors
7106800e16 Auto merge of #123656 - lqd:linker-features, r=petrochenkov
Linker flavors next steps: linker features

This is my understanding of the first step towards `@petrochenkov's` vision for the future of linker flavors, described in https://github.com/rust-lang/rust/pull/119906#issuecomment-1895693162 and the discussion that followed.

To summarize: having `Cc` and `Lld` embedded in linker flavors creates tension about naming, and a combinatorial explosion of flavors for each new linker feature we'd want to use. Linker features are an extension mechanism that is complementary to principal flavors, with benefits described in #119906.

The most immediate use of this flag would be to turn self-contained linking on and off via features instead of flavors. For example, `-Clinker-features=+/-lld` would toggle using lld instead of selecting a precise flavor, and would be "generic" and work cross-platform (whereas linker flavors are currently more tied to targets). Under this scheme, MCP510 is expected to be `-Clink-self-contained=+linker -Zlinker-features=+lld -Zunstable-options` (though for the time being, the original flags using lld-cc flavors still work).

I purposefully didn't add or document CLI support for `+/-cc`, as it would be a noop right now. I only expect that we'd initially want to stabilize `+/-lld` to begin with.

r? `@petrochenkov`

You had requested that minimal churn would be done to the 230 target specs and this does none yet: the linker features are inferred from the flavor since they're currently isomorphic. We of course expect this to change sooner rather than later.

In the future, we can allow targets to define linker features independently from their flavor, and remove the cc and lld components from the flavors to use the features instead, this actually doesn't need to block stabilization, as we discussed.

(Best reviewed per commit)
2024-04-13 11:10:01 +00:00
Vadim Petrochenkov
ed62b57c86 linker: Remove laziness and caching from native search directory walks
It shouldn't be necessary for performance now.
2024-04-12 17:28:00 +03:00
Rémy Rakic
2398d8cf08 add -Z linker-features to toggle lld on the CLI
but don't expose `+/-cc` yet
2024-04-12 09:43:05 +00:00
Vadim Petrochenkov
4ded0b82ca linker: Avoid some allocations in search directory iteration 2024-04-12 00:41:08 +03:00
bors
bd12986fd6 Auto merge of #123099 - oli-obk:span_tcx, r=petrochenkov
Replace some `CrateStore` trait methods with hooks.

Just like with the `CrateStore` trait, this avoids the cyclic definition issues with `CStore` being
defined after TyCtxt, but needing to be used in TyCtxt.
2024-04-09 03:04:20 +00:00
Ben Kimock
a7912cb421 Put checks that detect UB under their own flag below debug_assertions 2024-04-06 11:21:47 -04:00
Urgau
5b14497f01 Move cfg and check-cfg configuration in it's own module and add docs 2024-04-05 23:41:00 +02:00
Matthew Jasper
a277c901d9 Remove MIR unsafe check
This also remove safety information from MIR.
2024-04-03 08:50:12 +00:00
Matthias Krüger
3afd111489
Rollup merge of #123200 - maurer:kcfi-abort, r=compiler-errors
KCFI: Require -C panic=abort

While the KCFI scheme is not incompatible with unwinding, LLVM's `invoke` instruction does not currently support KCFI bundles. While it likely will in the near future, we won't be able to assume that in Rust for a while.

We encountered this problem while [turning on closure support](https://github.com/rust-lang/rust/pull/123106#issuecomment-2027436640).

r? ``@workingjubilee``
2024-03-30 14:30:50 +01:00
Matthew Maurer
29c1a2b9e9 KCFI: Require -C panic=abort
While the KCFI scheme is not incompatible with unwinding, LLVM's
`invoke` instruction does not currently support KCFI bundles. While it
likely will in the near future, we won't be able to assume that in Rust
for a while.
2024-03-29 16:35:58 +00:00
bors
399fa2f6e4 Auto merge of #123194 - matthiaskrgr:rollup-vhdc8hw, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #123176 (Normalize the result of `Fields::ty_with_args`)
 - #123186 (copy any file from stage0/lib to stage0-sysroot/lib)
 - #123187 (Forward port 1.77.1 release notes)
 - #123188 (compiler: fix few unused_peekable and needless_pass_by_ref_mut clippy lints)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-29 16:02:04 +00:00
Urgau
fefb8f1f9c Replace Session should_remap_filepaths with filename_display_preference 2024-03-28 18:47:26 +01:00
Urgau
4f4fa42b0e Introduce FileNameMapping::to_real_filename and use it everywhere 2024-03-28 18:47:26 +01:00
Urgau
ee2898d3f1 Make local_crate_source_file return a RealFileName
so it can be remapped (or not) by callers
2024-03-28 18:47:26 +01:00
Urgau
106146fd95 Replace RemapFileNameExt::for_codegen with explicit calls 2024-03-28 18:47:26 +01:00
Urgau
777c6b46cc Simplify trim-paths feature by merging all debuginfo options together 2024-03-28 18:47:26 +01:00
klensy
aa35530319 compiler: fix few needless_pass_by_ref_mut clippy lints
warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_session\src\config.rs:2013:16
     |
2013 |     early_dcx: &mut EarlyDiagCtxt,
     |                ^^^^^^^^^^^^^^^^^^ help: consider changing to: `&EarlyDiagCtxt`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_ast_passes\src\ast_validation.rs:1555:11
     |
1555 |     this: &mut AstValidator<'_>,
     |           ^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&AstValidator<'_>`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
  --> compiler\rustc_infer\src\infer\snapshot\fudge.rs:16:12
   |
16 |     table: &mut UnificationTable<'_, 'tcx, T>,
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&UnificationTable<'_, 'tcx, T>`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
   --> compiler\rustc_expand\src\expand.rs:961:13
    |
961 |     parser: &mut Parser<'a>,
    |             ^^^^^^^^^^^^^^^ help: consider changing to: `&Parser<'a>`
    |
    = warning: changing this function will impact semver compatibility
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 11:37:52 +03:00
klensy
b6cfe71f38 compiler: fix some clippy needless_pass_by_ref_mut
warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_session\src\config.rs:2111:20
     |
2111 |     unstable_opts: &mut UnstableOptions,
     |                    ^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&UnstableOptions`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 11:04:39 +03:00
klensy
bf47641726 compiler: fix unused_peekable clippy lint
warning: `peek` never called on `Peekable` iterator
   --> compiler\rustc_session\src\utils.rs:130:13
    |
130 |     let mut args = std::env::args_os().map(|arg| arg.to_string_lossy().to_string()).peekable();
    |             ^^^^
    |
    = help: consider removing the call to `peekable`
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable

warning: `peek` never called on `Peekable` iterator
    --> compiler\rustc_trait_selection\src\traits\error_reporting\suggestions.rs:4934:17
     |
4934 |         let mut bounds = pred.bounds.iter().peekable();
     |                 ^^^^^^
     |
     = help: consider removing the call to `peekable`
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_peekable
2024-03-28 10:50:09 +03:00
Oli Scherer
24fc6e96d6 Make def_path_hash_to_def_id a hook 2024-03-27 08:20:06 +00:00
Oli Scherer
0f5911c626 Move CrateStore::expn_hash_to_expn_id to a hook 2024-03-27 08:20:06 +00:00
Oli Scherer
32bd3c30d8 Start replacing CStore trait methods with hooks.
This also avoids the cyclic definition issues with CrateStore being
defined after TyCtxt, but needing to be used in TyCtxt.
2024-03-27 08:20:00 +00:00
Lukas Wirth
3d65c92040 Replace implementation with @RUSTC_BUILTIN prefix substitution var 2024-03-25 22:20:13 +00:00
Lukas Wirth
2fae4ee92e Make sysroot mandatory for rustdoc 2024-03-25 22:19:41 +00:00
Lukas Wirth
91547573af Implement -L builtin:$path 2024-03-25 22:18:31 +00:00
Matthias Krüger
ded16b3a97
Rollup merge of #122842 - pacak:explicit_name, r=michaelwoerister
Don't emit an error about failing to produce a file with a specific name if user never gave an explicit name

Fixes #122509

You can ask `rustc` to produce some intermediate results with `--emit foo`, this operation comes in two flavors: `--emit asm` and `--emit asm=foo.s`. First one produces one or more `.s` files without any name guarantees, second one renames it into `foo.s`. Second version only works when compiler produces a single file - for asm files this means using a single compilation unit for example.

In case compilation produced more than a single file `rustc` runs following check to emit some warnings:

```rust
            if crate_output.outputs.contains_key(&output_type) {
                // 2) Multiple codegen units, with `--emit foo=some_name`. We have
                //    no good solution for this case, so warn the user.
                sess.dcx().emit_warn(errors::IgnoringEmitPath { extension });
            } else if crate_output.single_output_file.is_some() {
                // 3) Multiple codegen units, with `-o some_name`. We have
                //    no good solution for this case, so warn the user.
                sess.dcx().emit_warn(errors::IgnoringOutput { extension });
            } else {
                // 4) Multiple codegen units, but no explicit name. We
                //    just leave the `foo.0.x` files in place.
                // (We don't have to do any work in this case.)
            }
```

Comment in the final `else` branch implies that if user didn't ask for a specific name - there's no need to emit warnings. However because of the internal representation of `crate_output.outputs` - this doesn't work as expected: if user asked to produce an asm file without giving it an implicit name it will contain `Some(None)`.

To fix the problem new code actually checks if user gave an explicit name. I think this was an original intentional behavior, at least comments imply that.
2024-03-25 17:05:32 +01:00
Matthias Krüger
3fe9f66133
Rollup merge of #122737 - ytmimi:conditionally_ignore_fatal_diagnostic, r=davidtwco
conditionally ignore fatal diagnostic in the SilentEmitter

This change is primarily meant to allow rustfmt to ignore all diagnostics when using the `SilentEmitter`. Back in #121301 the `SilentEmitter` was shared between rustc and rustfmt. This changed rustfmt's behavior from ignoring all diagnostic to emitting fatal diagnostics, which lead to https://github.com/rust-lang/rustfmt/issues/6109.

These changes allow rustfmt to maintain its previous behaviour when using the `SilentEmitter`, while allowing rustc code to still emit fatal diagnostics.
2024-03-24 17:08:15 +01:00
Kevin Reid
44d185b0d0 -Zprint-type-sizes: print the types of awaitees and unnamed coroutine locals.
This should assist comprehending the size of coroutines.
In particular, whenever a future is suspended while awaiting another
future, the latter is given the special name `__awaitee`, and now the
type of the awaited future will be printed, allowing identifying
caller/callee — er, I mean, poller/pollee — relationships.

It would be possible to include the type name in more cases, but I
thought that that might be overly verbose (`print-type-sizes` is already
a lot of text) and ordinary named fields or variables are easier for
readers to discover the types of.
2024-03-22 18:07:15 -07:00
Michael Baikov
bf12aa49e7 Don't emit an error about failing to produce a file with a specific name
If user never gave an explicit name
2024-03-22 10:59:13 -04:00
Nicholas Nethercote
5744be2727 Rename some target_cfg variables as target.
Because the underlying type is called `Target`. (There is also a
separate type called `TargetCfg`.)
2024-03-21 11:50:40 +11:00
Nicholas Nethercote
23ee523ea6 Remove CodegenBackend::target_override.
Backend and target selection is a mess: the target can override the
backend (via `Target::default_codegen_backend`), *and* the backend can
override the target (via `CodegenBackend::target_override`).

The code that handles this is ugly. It calls `build_target_config`
twice, once before getting the backend and once again afterward. It also
must check that both overrides aren't triggering at the same time.

This commit removes the latter override. It's used in rust-gpu but
@eddyb said via Zulip that removing it would be ok. This simplifies the
code greatly, and will allow some nice follow-up refactorings.
2024-03-21 11:48:49 +11:00
Matthias Krüger
53a753e31f
Rollup merge of #122748 - nnethercote:rustc_session-pub, r=jackh726
Reduce `pub` usage in `rustc_session`.

In particular, almost none of the errors in `errors.rs` are used outside the crate.

r? `@jackh726`
2024-03-20 05:51:24 +01:00
Nicholas Nethercote
de38888256 Reduce pub usage in rustc_session.
In particular, almost none of the errors in `errors.rs` are used outside
the crate.
2024-03-20 08:07:15 +11:00
Yacin Tmimi
d49d136b3a conditionally ignore fatal diagnostic in the SilentEmitter
This change is primarily meant to allow rustfmt to ignore all
diagnostics when using the `SilentEmitter`. Back in PR 121301 the
`SilentEmitter` was shared between rustc and rustfmt. This changed
rustfmt's behavior from ignoring all diagnostic to emitting fatal
diagnostics.

These changes allow rustfmt to maintain it's previous behaviour when
using the SilentEmitter, while allowing rustc code to still emit fatal
diagnostics.
2024-03-19 13:48:07 -04:00
Matthias Krüger
980248605a
Rollup merge of #122158 - estebank:feature-sugg, r=WaffleLapkin
Provide structured suggestion for `#![feature(foo)]`

```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 22:24:38 +01:00
Esteban Küber
6c31f6ce12 Provide structured suggestion for #![feature(foo)]
```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 16:08:58 +00:00
Matthias Krüger
0437a0c372 some minor code simplifications 2024-03-17 13:44:44 +01:00
Matthias Krüger
2b8fc6fd54
Rollup merge of #121207 - chriswailes:z-external-clangrt, r=michaelwoerister
Add `-Z external-clangrt`

This adds the unstable `-Z external-clangrt` flag that will prevent rustc from emitting linker paths for the in-tree LLVM sanitizer runtime library.
2024-03-15 10:14:53 +01:00
Matthias Krüger
54a5a49af0
Rollup merge of #122322 - Zalathar:branch, r=oli-obk
coverage: Initial support for branch coverage instrumentation

(This is a review-ready version of the changes that were drafted in #118305.)

This PR adds support for branch coverage instrumentation, gated behind the unstable flag value `-Zcoverage-options=branch`. (Coverage instrumentation must also be enabled with `-Cinstrument-coverage`.)

During THIR-to-MIR lowering (MIR building), if branch coverage is enabled, we collect additional information about branch conditions and their corresponding then/else blocks. We inject special marker statements into those blocks, so that the `InstrumentCoverage` MIR pass can reliably identify them even after the initially-built MIR has been simplified and renumbered.

The rest of the changes are mostly just plumbing needed to gather up the information that was collected during MIR building, and include it in the coverage metadata that we embed in the final binary.

Note that `llvm-cov show` doesn't print branch coverage information in its source views by default; that needs to be explicitly enabled with `--show-branches=count` or similar.

---

The current implementation doesn't have any support for instrumenting `if let` or let-chains. I think it's still useful without that, and adding it would be non-trivial, so I'm happy to leave that for future work.
2024-03-14 20:00:19 +01:00
Matthias Krüger
4dff106433
Rollup merge of #121764 - Zoxc:incr-sess-no-source, r=oli-obk
Make incremental sessions identity no longer depend on the crate names provided by source code

This makes incremental sessions identity no longer depend on the crate names provided by source code, implementing
https://github.com/rust-lang/compiler-team/issues/726.

r? ````@oli-obk````
2024-03-14 20:00:18 +01:00
Zalathar
060c7ce7e9 coverage: -Zcoverage-options=branch is no longer a placeholder 2024-03-14 17:19:06 +11:00
Chris Wailes
2a9d1ed538 Add -Z external-sanitizer-runtime
This adds the unstable `-Z external-sanitizer-runtime` flag that will
prevent rustc from emitting linker paths for the in-tree LLVM sanitizer
runtime library.
2024-03-13 11:27:05 -07:00
John Kåre Alsaker
12cd322062 Make incremental sessions identity no longer depend on the crate names provided by source code 2024-03-13 16:40:02 +01:00
Ralf Jung
2366d97d81 extend docs of -Zprint-mono-items 2024-03-13 16:11:48 +01:00
Matthias Krüger
8b9ef3b996
Rollup merge of #122226 - Zalathar:zcoverage-options, r=nnethercote
coverage: Remove or migrate all unstable values of `-Cinstrument-coverage`

(This PR was substantially overhauled from its original version, which migrated all of the existing unstable values intact.)

This PR takes the three nightly-only values that are currently accepted by `-Cinstrument-coverage`, completely removes two of them (`except-unused-functions` and `except-unused-generics`), and migrates the third (`branch`) over to a newly-introduced unstable flag `-Zcoverage-options`.

I have a few motivations for wanting to do this:

- It's unclear whether anyone actually uses the `except-unused-*` values, so this serves as an opportunity to either remove them, or prompt existing users to object to their removal.
- After #117199, the stable values of `-Cinstrument-coverage` treat it as a boolean-valued flag, so having nightly-only extra values feels out-of-place.
  - Nightly-only values also require extra ad-hoc code to make sure they aren't accidentally exposed to stable users.
- The new system allows multiple different settings to be toggled independently, which isn't possible in the current single-value system.
- The new system makes it easier to introduce new behaviour behind an unstable toggle, and then gather nightly-user feedback before possibly making it the default behaviour for all users.
- The new system also gives us a convenient place to put relatively-narrow options that won't ever be the default, but that nightly users might still want access to.
- It's likely that we will eventually want to give stable users more fine-grained control over coverage instrumentation. The new flag serves as a prototype of what that stable UI might eventually look like.

The `branch` option is a placeholder that currently does nothing. It will be used by #122322 to opt into branch coverage instrumentation.

---

I see `-Zcoverage-options` as something that will exist more-or-less indefinitely, though individual sub-options might come and go as appropriate. I think there will always be some demand for nightly-only toggles, so I don't see `-Zcoverage-options` itself ever being stable, though we might eventually stabilize something similar to it.
2024-03-13 06:41:22 +01:00
bors
d3555f3d8e Auto merge of #122227 - Zoxc:query-hash-verify, r=michaelwoerister
Verify that query keys result in unique dep nodes

This implements checking that query keys result into unique dep nodes as mentioned in https://github.com/rust-lang/rust/pull/112469.

We could do a perf check to see how expensive this is.

r? `@michaelwoerister`
2024-03-13 02:01:56 +00:00
Zalathar
3407fcc12e coverage: Add -Zcoverage-options for fine control of coverage
This new nightly-only flag can be used to toggle fine-grained flags that
control the details of coverage instrumentation.

Currently the only supported flag value is `branch` (or `no-branch`), which is
a placeholder for upcoming support for branch coverage. Other flag values can
be added in the future, to prototype proposed new behaviour, or to enable
special non-default behaviour.
2024-03-13 11:14:10 +11:00
Zalathar
1f544ce305 coverage: Remove all unstable values of -Cinstrument-coverage 2024-03-13 11:14:09 +11:00
David Wood
420c58fb11
sess: stabilize relro-level
Signed-off-by: David Wood <david@davidtw.co>
2024-03-12 13:40:40 +00:00
John Kåre Alsaker
55ba7a7c62 Verify that query keys result in unique dep nodes 2024-03-12 05:31:41 +01:00
Jubilee
86af4d25a5
Rollup merge of #116793 - WaffleLapkin:target_rules_the_backend, r=cjgillot
Allow targets to override default codegen backend

Implements https://github.com/rust-lang/compiler-team/issues/670.
2024-03-11 09:29:32 -07:00
Jubilee
88d387b263
Rollup merge of #116791 - WaffleLapkin:unparallel-backends, r=oli-obk
Allow codegen backends to opt-out of parallel codegen

This makes it a bit easier to write cursed codegen backends.
2024-03-11 09:29:31 -07:00
Nicholas Nethercote
7a294e998b Rename IntoDiagnostic as Diagnostic.
To match `derive(Diagnostic)`.

Also rename `into_diagnostic` as `into_diag`.
2024-03-11 09:15:09 +11:00
Nicholas Nethercote
a09b1d33a7 Rename IntoDiagnosticArg as IntoDiagArg.
Also rename `into_diagnostic_arg` as `into_diag_arg`, and
`NotIntoDiagnosticArg` as `NotInotDiagArg`.
2024-03-11 09:12:19 +11:00
daxpedda
f09c19ac3a
Introduce perma-unstable wasm-c-abi flag 2024-03-10 09:00:01 +01:00
Matthias Krüger
16d37fa804
Rollup merge of #121959 - sundeep-kokkonda:patch-2, r=davidtwco
Removing absolute path in proc-macro

With rust 1.75 the absolute build path name is embedding into proc-macro (.rustc section) and which causes reproducibility issues.
Detailed issue description is here - https://github.com/rust-lang/rust/issues/120825#issuecomment-1964307219

With this change the 'absolute path' changed back to '/rust/$hash' format as in earlier revisions.
2024-03-06 22:02:47 +01:00
Matthias Krüger
efe9deace8
Rollup merge of #121382 - nnethercote:rework-untranslatable_diagnostic-lint, r=davidtwco
Rework `untranslatable_diagnostic` lint

Currently it only checks calls to functions marked with `#[rustc_lint_diagnostics]`. This PR changes it to check calls to any function with an `impl Into<{D,Subd}iagnosticMessage>` parameter. This greatly improves its coverage and doesn't rely on people remembering to add `#[rustc_lint_diagnostics]`. It also lets us add `#[rustc_lint_diagnostics]` to a number of functions that don't have an `impl Into<{D,Subd}iagnosticMessage>`, such as `Diag::span`.

r? ``@davidtwco``
2024-03-06 22:02:46 +01:00
Zalathar
9f287dd7b3 Change the documented implicit value of -C instrument-coverage to =yes 2024-03-06 17:50:13 +11:00
Nicholas Nethercote
3591e77b35 Add missing #[rustc_lint_diagnostics] attributes.
Prior to the previous commit, `#[rust_lint_diagnostics]` attributes
could only be used on methods with an `impl Into<{D,Subd}iagMessage>`
parameter. But there are many other nearby diagnostic methods (e.g.
`Diag::span`) that don't take such a parameter and should have the
attribute.

This commit adds the missing attribute to these `Diag` methods. This
requires adding some missing
`#[allow(rustc::diagnostic_outside_of_impl)]` markers at call sites to
these methods.
2024-03-06 14:19:38 +11:00
Nicholas Nethercote
b7d58eef4b Rewrite the untranslatable_diagnostic lint.
Currently it only checks calls to functions marked with
`#[rustc_lint_diagnostics]`. This commit changes it to check calls to
any function with an `impl Into<{D,Subd}iagMessage>` parameter. This
greatly improves its coverage and doesn't rely on people remembering to
add `#[rustc_lint_diagnostics]`.

The commit also adds `#[allow(rustc::untranslatable_diagnostic)`]
attributes to places that need it that are caught by the improved lint.
These places that might be easy to convert to translatable diagnostics.

Finally, it also:
- Expands and corrects some comments.
- Does some minor formatting improvements.
- Adds missing `DecorateLint` cases to
  `tests/ui-fulldeps/internal-lints/diagnostics.rs`.
2024-03-06 14:19:01 +11:00
Matthias Krüger
9153451a91
Rollup merge of #121301 - davidtwco:rustfmt-silent-emitter, r=pnkfelix
errors: share `SilentEmitter` between rustc and rustfmt

Fixes rust-lang/rustfmt#6082.

Shares the `SilentEmitter` between rustc and rustfmt, and gives it a fallback bundle (since it can emit diagnostics in some contexts).
2024-03-05 19:53:18 +01:00
David Wood
2ee0409f32
errors: share SilentEmitter between rustc and rustfmt
Signed-off-by: David Wood <david@davidtw.co>
2024-03-05 10:14:36 +00:00
Urgau
9d9b26bca9 Limit the number of names and values in check-cfg diagnostics 2024-03-05 07:54:04 +01:00
Nicholas Nethercote
7aa0eea19c Rename BuiltinLintDiagnostics as BuiltinLintDiag.
Not the dropping of the trailing `s` -- this type describes a single
diagnostic and its name should be singular.
2024-03-05 12:15:10 +11:00
Nicholas Nethercote
18715c98c6 Rename DiagnosticMessage as DiagMessage. 2024-03-05 12:14:49 +11:00
Nicholas Nethercote
80d2bdb619 Rename all ParseSess variables/fields/lifetimes as psess.
Existing names for values of this type are `sess`, `parse_sess`,
`parse_session`, and `ps`. `sess` is particularly annoying because
that's also used for `Session` values, which are often co-located, and
it can be difficult to know which type a value named `sess` refers to.
(That annoyance is the main motivation for this change.) `psess` is nice
and short, which is good for a name used this much.

The commit also renames some `parse_sess_created` values as
`psess_created`.
2024-03-05 08:11:45 +11:00
Nicholas Nethercote
3996447b37 Remove file_path_mapping param from ParseSess::new.
It's always empty.
2024-03-04 16:22:06 +11:00
Sundeep KOKKONDA
a9a979839b
Removing absolute path in proc-macro
With rust 1.75 the absolute build path is embedding into '.rustc' section and which causes reproducibility issues. Detailed issue is here.
https://github.com/rust-lang/rust/issues/120825#issuecomment-1964307219

With this change the 'absolute path' changed back to '/rust/$hash' format.
2024-03-04 08:18:54 +05:30
Ramon de C Valle
dee4e02102 Add initial support for DataFlowSanitizer
Adds initial support for DataFlowSanitizer to the Rust compiler. It
currently supports `-Zsanitizer-dataflow-abilist`. Additional options
for it can be passed to LLVM command line argument processor via LLVM
arguments using `llvm-args` codegen option (e.g.,
`-Cllvm-args=-dfsan-combine-pointer-labels-on-load=false`).
2024-03-01 18:50:40 -08:00
Guillaume Gomez
0e9f02d6fa
Rollup merge of #121783 - nnethercote:emitter-cleanups, r=oli-obk
Emitter cleanups

Some cleanups I made when reading emitter code. In particular, `HumanEmitter` and `JsonEmitter` have gone from three constructors to one.

r? `@oli-obk`
2024-02-29 17:08:38 +01:00
Nicholas Nethercote
9ff4487999 Make JsonEmitter more like HumanEmitter.
Use `derive(Setters)` to derive setters, and then change
`JsonEmitter::new` to only have the arguments that are always used.
2024-02-29 17:50:26 +11:00
Nicholas Nethercote
2999d8dc72 Inline and remove JsonEmitter::{basic,stderr}.
They are so similar to `JsonEmitter::new` it's not worth having separate
functions, it makes the code harder to read.
2024-02-29 17:50:26 +11:00
Nicholas Nethercote
067d7c3d00 Inline and remove HumanEmitter::stderr.
Because `HumanEmitter::new` is enough, in conjunction with the (renamed)
`stderr_destination` function.
2024-02-29 17:50:23 +11:00
Nicholas Nethercote
880c1c585f Rename DiagCtxt::with_emitter as DiagCtxt::new.
Because it's now the only constructor.
2024-02-29 16:30:12 +11:00
Nicholas Nethercote
f9eef38e32 Inline and remove DiagCtxt::with_tty_emitter
It only has two call sites, and one of those doesn't set the source map.
2024-02-29 16:30:12 +11:00
Nicholas Nethercote
260ae70140 Overhaul how stashed diagnostics work, again.
Stashed errors used to be counted as errors, but could then be
cancelled, leading to `ErrorGuaranteed` soundness holes. #120828 changed
that, closing the soundness hole. But it introduced other difficulties
because you sometimes have to account for pending stashed errors when
making decisions about whether errors have occured/will occur and it's
easy to overlook these.

This commit aims for a middle ground.
- Stashed errors (not warnings) are counted immediately as emitted
  errors, avoiding the possibility of forgetting to consider them.
- The ability to cancel (or downgrade) stashed errors is eliminated, by
  disallowing the use of `steal_diagnostic` with errors, and introducing
  the more restrictive methods `try_steal_{modify,replace}_and_emit_err`
  that can be used instead.

Other things:
- `DiagnosticBuilder::stash` and `DiagCtxt::stash_diagnostic` now both
  return `Option<ErrorGuaranteed>`, which enables the removal of two
  `delayed_bug` calls and one `Ty::new_error_with_message` call. This is
  possible because we store error guarantees in
  `DiagCtxt::stashed_diagnostics`.
- Storing the guarantees also saves us having to maintain a counter.
- Calls to the `stashed_err_count` method are no longer necessary
  alongside calls to `has_errors`, which is a nice simplification, and
  eliminates two more `span_delayed_bug` calls and one FIXME comment.
- Tests are added for three of the four fixed PRs mentioned below.
- `issue-121108.rs`'s output improved slightly, omitting a non-useful
  error message.

Fixes #121451.
Fixes #121477.
Fixes #121504.
Fixes #121508.
2024-02-29 11:08:27 +11:00
Nicholas Nethercote
8199632aa8 Rename DiagnosticArg{,Map,Name,Value} as DiagArg{,Map,Name,Value}. 2024-02-28 08:55:37 +11:00
Nicholas Nethercote
899cb40809 Rename DiagnosticBuilder as Diag.
Much better!

Note that this involves renaming (and updating the value of)
`DIAGNOSTIC_BUILDER` in clippy.
2024-02-28 08:55:35 +11:00
Matthias Krüger
86a7fc840f compiler: clippy::complexity fixes 2024-02-23 19:56:35 +01:00
Matthias Krüger
01ec4eb319
Rollup merge of #121427 - nnethercote:fix-Rocket, r=oli-obk
Fix panic when compiling `Rocket`.

This panic was reported [here](https://github.com/rust-lang/rust/pull/120576#issuecomment-1957515484).

r? ``@oli-obk``
2024-02-22 18:09:54 +01:00
Nicholas Nethercote
02423a5747 Make some IntoDiagnostic impls generic.
PR #119097 made the decision to make all `IntoDiagnostic` impls generic,
because this allowed a bunch of nice cleanups. But four hand-written
impls were unintentionally overlooked. This commit makes them generic.
2024-02-22 13:47:30 +11:00
Nicholas Nethercote
4da67fff61 Replace unnecessary abort_if_errors.
Replace `abort_if_errors` calls that are certain to abort -- because
we emit an error immediately beforehand -- with `FatalErro.raise()`.
2024-02-22 08:03:47 +11:00
Nicholas Nethercote
c2512a130f Inline and remove Session::compile_status.
Because it's now simple enough that it doesn't provide much benefit.
2024-02-22 08:03:47 +11:00
Nicholas Nethercote
72b172bdf6 Overhaul the handling of errors at the top-level.
Currently `emit_stashed_diagnostic` is called from four(!) different
places: `print_error_count`, `DiagCtxtInner::drop`, `abort_if_errors`,
and `compile_status`.

And `flush_delayed` is called from two different places:
`DiagCtxtInner::drop` and `Queries`.

This is pretty gross! Each one should really be called from a single
place, but there's a bunch of entanglements. This commit cleans up this
mess.

Specifically, it:
- Removes all the existing calls to `emit_stashed_diagnostic`, and adds
  a single new call in `finish_diagnostics`.
- Removes the early `flush_delayed` call in `codegen_and_build_linker`,
  replacing it with a simple early return if delayed bugs are present.
- Changes `DiagCtxtInner::drop` and `DiagCtxtInner::flush_delayed` so
  they both assert that the stashed diagnostics are empty (i.e.
  processed beforehand).
- Changes `interface::run_compiler` so that any errors emitted during
  `finish_diagnostics` (i.e. late-emitted stashed diagnostics) are
  counted and cannot be overlooked. This requires adding
  `ErrorGuaranteed` return values to several functions.
- Removes the `stashed_err_count` call in `analysis`. This is possible
  now that we don't have to worry about calling `flush_delayed` early
  from `codegen_and_build_linker` when stashed diagnostics are pending.
- Changes the `span_bug` case in `handle_tuple_field_pattern_match` to a
  `delayed_span_bug`, because it now can be reached due to the removal
  of the `stashed_err_count` call in `analysis`.
- Slightly changes the expected output of three tests. If no errors are
  emitted but there are delayed bugs, the error count is no longer
  printed. This is because delayed bugs are now always printed after the
  error count is printed (or not printed, if the error count is zero).

There is a lot going on in this commit. It's hard to break into smaller
pieces because the existing code is very tangled. It took me a long time
and a lot of effort to understand how the different pieces interact, and
I think the new code is a lot simpler and easier to understand.
2024-02-22 08:03:47 +11:00
Nicholas Nethercote
46f4983356 Adjust the has_errors* methods.
Currently `has_errors` excludes lint errors. This commit changes it to
include lint errors.

The motivation for this is that for most places it doesn't matter
whether lint errors are included or not. But there are multiple places
where they must be includes, and only one place where they must not be
included. So it makes sense for `has_errors` to do the thing that fits
the most situations, and the new `has_errors_excluding_lint_errors`
method in the one exceptional place.

The same change is made for `err_count`. Annoyingly, this requires the
introduction of `err_count_excluding_lint_errs` for one place, to
preserve existing error printing behaviour. But I still think the change
is worthwhile overall.
2024-02-22 08:03:47 +11:00
Nicholas Nethercote
9919c3dab3 Remove EarlyDiagCtxt::abort_if_errors.
Its one use isn't necessary, because it's not possible for errors to
have been emitted at that point.
2024-02-22 08:03:47 +11:00