diff --git a/Cargo.lock b/Cargo.lock index a8e4490aa1a45..3d40ded19dd5a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1928,6 +1928,17 @@ dependencies = [ "opaque-debug 0.2.3", ] +[[package]] +name = "md-5" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5a279bb9607f9f53c22d496eade00d138d1bdcccd07d74650387cf94942a15" +dependencies = [ + "block-buffer 0.9.0", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + [[package]] name = "mdbook" version = "0.4.3" @@ -2467,7 +2478,7 @@ checksum = "54be6e404f5317079812fc8f9f5279de376d8856929e21c184ecf6bbd692a11d" dependencies = [ "maplit", "pest", - "sha-1", + "sha-1 0.8.2", ] [[package]] @@ -3281,14 +3292,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c267f15c3cfc82a8a441d2bf86bcccf299d1eb625822468e3d8ee6f7c5a1c89" dependencies = [ "cfg-if 0.1.10", - "md-5", + "md-5 0.8.0", "rustc-ap-rustc_arena", "rustc-ap-rustc_data_structures", "rustc-ap-rustc_index", "rustc-ap-rustc_macros", "rustc-ap-rustc_serialize", "scoped-tls", - "sha-1", + "sha-1 0.8.2", "tracing", "unicode-width", ] @@ -4138,14 +4149,15 @@ name = "rustc_span" version = "0.0.0" dependencies = [ "cfg-if 0.1.10", - "md-5", + "md-5 0.9.1", "rustc_arena", "rustc_data_structures", "rustc_index", "rustc_macros", "rustc_serialize", "scoped-tls", - "sha-1", + "sha-1 0.9.1", + "sha2", "tracing", "unicode-width", ] @@ -4510,6 +4522,19 @@ dependencies = [ "opaque-debug 0.2.3", ] +[[package]] +name = "sha-1" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "170a36ea86c864a3f16dd2687712dd6646f7019f301e57537c7f4dc9f5916770" +dependencies = [ + "block-buffer 0.9.0", + "cfg-if 0.1.10", + "cpuid-bool", + "digest 0.9.0", + "opaque-debug 0.3.0", +] + [[package]] name = "sha2" version = "0.9.1" diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 48238c8bbf571..2fd625c2a6c26 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -637,19 +637,15 @@ pub struct Deprecation { } /// Finds the deprecation attribute. `None` if none exists. -pub fn find_deprecation(sess: &Session, attrs: &[Attribute], item_sp: Span) -> Option { - find_deprecation_generic(sess, attrs.iter(), item_sp) +pub fn find_deprecation(sess: &Session, attrs: &[Attribute]) -> Option<(Deprecation, Span)> { + find_deprecation_generic(sess, attrs.iter()) } -fn find_deprecation_generic<'a, I>( - sess: &Session, - attrs_iter: I, - item_sp: Span, -) -> Option +fn find_deprecation_generic<'a, I>(sess: &Session, attrs_iter: I) -> Option<(Deprecation, Span)> where I: Iterator, { - let mut depr: Option = None; + let mut depr: Option<(Deprecation, Span)> = None; let diagnostic = &sess.parse_sess.span_diagnostic; 'outer: for attr in attrs_iter { @@ -658,8 +654,11 @@ where continue; } - if depr.is_some() { - struct_span_err!(diagnostic, item_sp, E0550, "multiple deprecated attributes").emit(); + if let Some((_, span)) = &depr { + struct_span_err!(diagnostic, attr.span, E0550, "multiple deprecated attributes") + .span_label(attr.span, "repeated deprecation attribute") + .span_label(*span, "first deprecation attribute") + .emit(); break; } @@ -780,7 +779,7 @@ where sess.mark_attr_used(&attr); let is_since_rustc_version = sess.check_name(attr, sym::rustc_deprecated); - depr = Some(Deprecation { since, note, suggestion, is_since_rustc_version }); + depr = Some((Deprecation { since, note, suggestion, is_since_rustc_version }, attr.span)); } depr diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/bootstrap_rustc.yml b/compiler/rustc_codegen_cranelift/.github/workflows/bootstrap_rustc.yml new file mode 100644 index 0000000000000..8c94a0aa5e6eb --- /dev/null +++ b/compiler/rustc_codegen_cranelift/.github/workflows/bootstrap_rustc.yml @@ -0,0 +1,44 @@ +name: Bootstrap rustc using cg_clif + +on: + - push + +jobs: + bootstrap_rustc: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Cache cargo installed crates + uses: actions/cache@v2 + with: + path: ~/.cargo/bin + key: ${{ runner.os }}-cargo-installed-crates + + - name: Cache cargo registry and index + uses: actions/cache@v2 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + key: ${{ runner.os }}-cargo-registry-and-index-${{ hashFiles('**/Cargo.lock') }} + + - name: Cache cargo target dir + uses: actions/cache@v2 + with: + path: target + key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }} + + - name: Prepare dependencies + run: | + git config --global user.email "user@example.com" + git config --global user.name "User" + ./prepare.sh + + - name: Test + run: | + # Enable backtraces for easier debugging + export RUST_BACKTRACE=1 + + ./scripts/test_bootstrap.sh diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/main.yml b/compiler/rustc_codegen_cranelift/.github/workflows/main.yml index 841e1a0870ed3..e6d3375fb1bab 100644 --- a/compiler/rustc_codegen_cranelift/.github/workflows/main.yml +++ b/compiler/rustc_codegen_cranelift/.github/workflows/main.yml @@ -51,4 +51,13 @@ jobs: export COMPILE_RUNS=2 export RUN_RUNS=2 - ./test.sh --release + ./test.sh + + - name: Package prebuilt cg_clif + run: tar cvfJ cg_clif.tar.xz build + + - name: Upload prebuilt cg_clif + uses: actions/upload-artifact@v2 + with: + name: cg_clif-${{ runner.os }} + path: cg_clif.tar.xz diff --git a/compiler/rustc_codegen_cranelift/.gitignore b/compiler/rustc_codegen_cranelift/.gitignore index 0da9927b479b4..18196bce00945 100644 --- a/compiler/rustc_codegen_cranelift/.gitignore +++ b/compiler/rustc_codegen_cranelift/.gitignore @@ -6,7 +6,7 @@ perf.data perf.data.old *.events *.string* -/build_sysroot/sysroot +/build /build_sysroot/sysroot_src /rust /rand diff --git a/compiler/rustc_codegen_cranelift/Cargo.lock b/compiler/rustc_codegen_cranelift/Cargo.lock index 6cfbed0a5e430..2889fac77f6a4 100644 --- a/compiler/rustc_codegen_cranelift/Cargo.lock +++ b/compiler/rustc_codegen_cranelift/Cargo.lock @@ -44,7 +44,7 @@ checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "cranelift-bforest" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "cranelift-entity", ] @@ -52,7 +52,7 @@ dependencies = [ [[package]] name = "cranelift-codegen" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "byteorder", "cranelift-bforest", @@ -70,7 +70,7 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "cranelift-codegen-shared", "cranelift-entity", @@ -79,17 +79,17 @@ dependencies = [ [[package]] name = "cranelift-codegen-shared" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" [[package]] name = "cranelift-entity" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" [[package]] name = "cranelift-frontend" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "cranelift-codegen", "log", @@ -100,7 +100,7 @@ dependencies = [ [[package]] name = "cranelift-module" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "anyhow", "cranelift-codegen", @@ -112,7 +112,7 @@ dependencies = [ [[package]] name = "cranelift-native" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "cranelift-codegen", "raw-cpuid", @@ -122,7 +122,7 @@ dependencies = [ [[package]] name = "cranelift-object" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "anyhow", "cranelift-codegen", @@ -135,7 +135,7 @@ dependencies = [ [[package]] name = "cranelift-simplejit" version = "0.67.0" -source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#4fd90dccabb266e983740e1f5daf8bde9266b286" +source = "git+https://github.com/bytecodealliance/wasmtime/?branch=main#44cbdecea03c360ea82e6482f0cf6c614effef21" dependencies = [ "cranelift-codegen", "cranelift-entity", diff --git a/compiler/rustc_codegen_cranelift/Readme.md b/compiler/rustc_codegen_cranelift/Readme.md index 680ff877656b0..f8a5e13ed54c1 100644 --- a/compiler/rustc_codegen_cranelift/Readme.md +++ b/compiler/rustc_codegen_cranelift/Readme.md @@ -2,41 +2,56 @@ > ⚠⚠⚠ Certain kinds of FFI don't work yet. ⚠⚠⚠ -The goal of this project is to create an alternative codegen backend for the rust compiler based on [Cranelift](https://github.com/bytecodealliance/wasmtime/blob/master/cranelift). This has the potential to improve compilation times in debug mode. If your project doesn't use any of the things listed under "Not yet supported", it should work fine. If not please open an issue. +The goal of this project is to create an alternative codegen backend for the rust compiler based on [Cranelift](https://github.com/bytecodealliance/wasmtime/blob/master/cranelift). +This has the potential to improve compilation times in debug mode. +If your project doesn't use any of the things listed under "Not yet supported", it should work fine. +If not please open an issue. -## Building +## Building and testing ```bash $ git clone https://github.com/bjorn3/rustc_codegen_cranelift.git $ cd rustc_codegen_cranelift $ ./prepare.sh # download and patch sysroot src and install hyperfine for benchmarking -$ ./test.sh --release +$ ./build.sh ``` +To run the test suite replace the last command with: + +```bash +$ ./test.sh +``` + +This will implicitly build cg_clif too. Both `build.sh` and `test.sh` accept a `--debug` argument to +build in debug mode. + +Alternatively you can download a pre built version from [GHA]. It is listed in the artifacts section +of workflow runs. Unfortunately due to GHA restrictions you need to be logged in to access it. + +[GHA]: https://github.com/bjorn3/rustc_codegen_cranelift/actions?query=branch%3Amaster+event%3Apush+is%3Asuccess + ## Usage rustc_codegen_cranelift can be used as a near-drop-in replacement for `cargo build` or `cargo run` for existing projects. -Assuming `$cg_clif_dir` is the directory you cloned this repo into and you followed the instructions (`prepare.sh` and `test.sh`). +Assuming `$cg_clif_dir` is the directory you cloned this repo into and you followed the instructions (`prepare.sh` and `build.sh` or `test.sh`). ### Cargo In the directory with your project (where you can do the usual `cargo build`), run: ```bash -$ $cg_clif_dir/cargo.sh run +$ $cg_clif_dir/build/cargo.sh run ``` This should build and run your project with rustc_codegen_cranelift instead of the usual LLVM backend. -If you compiled cg_clif in debug mode (aka you didn't pass `--release` to `./test.sh`) you should set `CHANNEL="debug"`. - ### Rustc > You should prefer using the Cargo method. ```bash -$ $cg_clif_dir/target/release/cg_clif my_crate.rs +$ $cg_clif_dir/build/cg_clif my_crate.rs ``` ### Jit mode @@ -47,13 +62,13 @@ In jit mode cg_clif will immediately execute your code without creating an execu > The jit mode will probably need cargo integration to make this possible. ```bash -$ $cg_clif_dir/cargo.sh jit +$ $cg_clif_dir/build/cargo.sh jit ``` or ```bash -$ $cg_clif_dir/target/release/cg_clif --jit my_crate.rs +$ $cg_clif_dir/build/cg_clif --jit my_crate.rs ``` ### Shell @@ -62,7 +77,7 @@ These are a few functions that allow you to easily run rust code from the shell ```bash function jit_naked() { - echo "$@" | $cg_clif_dir/target/release/cg_clif - --jit + echo "$@" | $cg_clif_dir/build/cg_clif - --jit } function jit() { diff --git a/compiler/rustc_codegen_cranelift/build.sh b/compiler/rustc_codegen_cranelift/build.sh new file mode 100755 index 0000000000000..f9a87e68a046a --- /dev/null +++ b/compiler/rustc_codegen_cranelift/build.sh @@ -0,0 +1,47 @@ +#!/bin/bash +set -e + +# Settings +export CHANNEL="release" +build_sysroot=1 +target_dir='build' +while [[ $# != 0 ]]; do + case $1 in + "--debug") + export CHANNEL="debug" + ;; + "--without-sysroot") + build_sysroot=0 + ;; + "--target-dir") + target_dir=$2 + shift + ;; + *) + echo "Unknown flag '$1'" + echo "Usage: ./build.sh [--debug] [--without-sysroot] [--target-dir DIR]" + ;; + esac + shift +done + +# Build cg_clif +export RUSTFLAGS="-Zrun_dsymutil=no" +if [[ "$CHANNEL" == "release" ]]; then + cargo build --release +else + cargo build +fi + +rm -rf $target_dir +mkdir $target_dir +cp -a target/$CHANNEL/cg_clif{,_build_sysroot} target/$CHANNEL/*rustc_codegen_cranelift* $target_dir/ +cp -a rust-toolchain scripts/config.sh scripts/cargo.sh $target_dir + +if [[ "$build_sysroot" == "1" ]]; then + echo "[BUILD] sysroot" + export CG_CLIF_INCR_CACHE_DISABLED=1 + dir=$(pwd) + cd $target_dir + time $dir/build_sysroot/build_sysroot.sh +fi diff --git a/compiler/rustc_codegen_cranelift/build_sysroot/build_sysroot.sh b/compiler/rustc_codegen_cranelift/build_sysroot/build_sysroot.sh index 04c82ca2a5128..eba15c0dd4308 100755 --- a/compiler/rustc_codegen_cranelift/build_sysroot/build_sysroot.sh +++ b/compiler/rustc_codegen_cranelift/build_sysroot/build_sysroot.sh @@ -3,25 +3,28 @@ # Requires the CHANNEL env var to be set to `debug` or `release.` set -e -cd $(dirname "$0") -pushd ../ >/dev/null -source ./scripts/config.sh -popd >/dev/null +source ./config.sh -# Cleanup for previous run -# v Clean target dir except for build scripts and incremental cache -rm -r target/*/{debug,release}/{build,deps,examples,libsysroot*,native} 2>/dev/null || true -rm -r sysroot/ 2>/dev/null || true +dir=$(pwd) # Use rustc with cg_clif as hotpluggable backend instead of the custom cg_clif driver so that # build scripts are still compiled using cg_llvm. -export RUSTC=$(pwd)/../"target/"$CHANNEL"/cg_clif_build_sysroot" +export RUSTC=$dir"/cg_clif_build_sysroot" export RUSTFLAGS=$RUSTFLAGS" --clif" +cd $(dirname "$0") + +# Cleanup for previous run +# v Clean target dir except for build scripts and incremental cache +rm -r target/*/{debug,release}/{build,deps,examples,libsysroot*,native} 2>/dev/null || true + +# We expect the target dir in the default location. Guard against the user changing it. +export CARGO_TARGET_DIR=target + # Build libs export RUSTFLAGS="$RUSTFLAGS -Zforce-unstable-if-unmarked -Cpanic=abort" -if [[ "$1" == "--release" ]]; then +if [[ "$1" != "--debug" ]]; then sysroot_channel='release' # FIXME Enable incremental again once rust-lang/rust#74946 is fixed # FIXME Enable -Zmir-opt-level=2 again once it doesn't ice anymore @@ -32,5 +35,5 @@ else fi # Copy files to sysroot -mkdir -p sysroot/lib/rustlib/$TARGET_TRIPLE/lib/ -cp -r target/$TARGET_TRIPLE/$sysroot_channel/deps/* sysroot/lib/rustlib/$TARGET_TRIPLE/lib/ +mkdir -p $dir/sysroot/lib/rustlib/$TARGET_TRIPLE/lib/ +cp -a target/$TARGET_TRIPLE/$sysroot_channel/deps/* $dir/sysroot/lib/rustlib/$TARGET_TRIPLE/lib/ diff --git a/compiler/rustc_codegen_cranelift/build_sysroot/prepare_sysroot_src.sh b/compiler/rustc_codegen_cranelift/build_sysroot/prepare_sysroot_src.sh index 14aa77478f54d..d0fb09ce745d4 100755 --- a/compiler/rustc_codegen_cranelift/build_sysroot/prepare_sysroot_src.sh +++ b/compiler/rustc_codegen_cranelift/build_sysroot/prepare_sysroot_src.sh @@ -12,7 +12,7 @@ fi rm -rf $DST_DIR mkdir -p $DST_DIR/library -cp -r $SRC_DIR/library $DST_DIR/ +cp -a $SRC_DIR/library $DST_DIR/ pushd $DST_DIR echo "[GIT] init" diff --git a/compiler/rustc_codegen_cranelift/clean_all.sh b/compiler/rustc_codegen_cranelift/clean_all.sh index 3003a0ea2d102..5a69c862d016d 100755 --- a/compiler/rustc_codegen_cranelift/clean_all.sh +++ b/compiler/rustc_codegen_cranelift/clean_all.sh @@ -1,5 +1,5 @@ #!/bin/bash --verbose set -e -rm -rf target/ build_sysroot/{sysroot/,sysroot_src/,target/} perf.data{,.old} +rm -rf target/ build/ build_sysroot/{sysroot_src/,target/} perf.data{,.old} rm -rf rand/ regex/ simple-raytracer/ diff --git a/compiler/rustc_codegen_cranelift/docs/env_vars.md b/compiler/rustc_codegen_cranelift/docs/env_vars.md index 07b75622a58ef..f0a0a6ad42ef5 100644 --- a/compiler/rustc_codegen_cranelift/docs/env_vars.md +++ b/compiler/rustc_codegen_cranelift/docs/env_vars.md @@ -9,7 +9,4 @@ object files when their content should have been changed by a change to cg_clif.
CG_CLIF_DISPLAY_CG_TIME
If "1", display the time it took to perform codegen for a crate
-
CG_CLIF_FUNCTION_SECTIONS
-
Use a single section for each function. This will often reduce the executable size at the - cost of making linking significantly slower.
diff --git a/compiler/rustc_codegen_cranelift/example/mini_core.rs b/compiler/rustc_codegen_cranelift/example/mini_core.rs index a972beedaa387..ce07fe83df18f 100644 --- a/compiler/rustc_codegen_cranelift/example/mini_core.rs +++ b/compiler/rustc_codegen_cranelift/example/mini_core.rs @@ -48,6 +48,7 @@ unsafe impl Copy for u8 {} unsafe impl Copy for u16 {} unsafe impl Copy for u32 {} unsafe impl Copy for u64 {} +unsafe impl Copy for u128 {} unsafe impl Copy for usize {} unsafe impl Copy for i8 {} unsafe impl Copy for i16 {} @@ -283,6 +284,15 @@ impl PartialEq for u64 { } } +impl PartialEq for u128 { + fn eq(&self, other: &u128) -> bool { + (*self) == (*other) + } + fn ne(&self, other: &u128) -> bool { + (*self) != (*other) + } +} + impl PartialEq for usize { fn eq(&self, other: &usize) -> bool { (*self) == (*other) diff --git a/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs b/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs index 376056e19383f..4a8375afac3ce 100644 --- a/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs +++ b/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs @@ -287,6 +287,8 @@ fn main() { assert_eq!(repeat[0], Some(42)); assert_eq!(repeat[1], Some(42)); + from_decimal_string(); + #[cfg(not(jit))] test_tls(); @@ -446,3 +448,23 @@ fn check_niche_behavior () { intrinsics::abort(); } } + +fn from_decimal_string() { + loop { + let multiplier = 1; + + take_multiplier_ref(&multiplier); + + if multiplier == 1 { + break; + } + + unreachable(); + } +} + +fn take_multiplier_ref(_multiplier: &u128) {} + +fn unreachable() -> ! { + panic("unreachable") +} diff --git a/compiler/rustc_codegen_cranelift/example/std_example.rs b/compiler/rustc_codegen_cranelift/example/std_example.rs index 079b429904911..cb512a4aa335e 100644 --- a/compiler/rustc_codegen_cranelift/example/std_example.rs +++ b/compiler/rustc_codegen_cranelift/example/std_example.rs @@ -315,13 +315,13 @@ fn test_checked_mul() { assert_eq!(1i8.checked_mul(-128i8), Some(-128i8)); assert_eq!((-128i8).checked_mul(-128i8), None); - assert_eq!(1u64.checked_mul(u64::max_value()), Some(u64::max_value())); - assert_eq!(u64::max_value().checked_mul(u64::max_value()), None); - assert_eq!(1i64.checked_mul(i64::max_value()), Some(i64::max_value())); - assert_eq!(i64::max_value().checked_mul(i64::max_value()), None); - assert_eq!((-1i64).checked_mul(i64::min_value() + 1), Some(i64::max_value())); - assert_eq!(1i64.checked_mul(i64::min_value()), Some(i64::min_value())); - assert_eq!(i64::min_value().checked_mul(i64::min_value()), None); + assert_eq!(1u64.checked_mul(u64::MAX), Some(u64::MAX)); + assert_eq!(u64::MAX.checked_mul(u64::MAX), None); + assert_eq!(1i64.checked_mul(i64::MAX), Some(i64::MAX)); + assert_eq!(i64::MAX.checked_mul(i64::MAX), None); + assert_eq!((-1i64).checked_mul(i64::MIN + 1), Some(i64::MAX)); + assert_eq!(1i64.checked_mul(i64::MIN), Some(i64::MIN)); + assert_eq!(i64::MIN.checked_mul(i64::MIN), None); } #[derive(PartialEq)] diff --git a/compiler/rustc_codegen_cranelift/rust-toolchain b/compiler/rustc_codegen_cranelift/rust-toolchain index 87e54719fdc76..0ca96be9ae731 100644 --- a/compiler/rustc_codegen_cranelift/rust-toolchain +++ b/compiler/rustc_codegen_cranelift/rust-toolchain @@ -1 +1 @@ -nightly-2020-10-26 +nightly-2020-10-31 diff --git a/compiler/rustc_codegen_cranelift/cargo.sh b/compiler/rustc_codegen_cranelift/scripts/cargo.sh similarity index 51% rename from compiler/rustc_codegen_cranelift/cargo.sh rename to compiler/rustc_codegen_cranelift/scripts/cargo.sh index cebc3e67363a8..e63daa40f3540 100755 --- a/compiler/rustc_codegen_cranelift/cargo.sh +++ b/compiler/rustc_codegen_cranelift/scripts/cargo.sh @@ -1,19 +1,13 @@ #!/bin/bash -if [ -z $CHANNEL ]; then -export CHANNEL='release' -fi - -pushd $(dirname "$0") >/dev/null -source scripts/config.sh +dir=$(dirname "$0") +source $dir/config.sh # read nightly compiler from rust-toolchain file -TOOLCHAIN=$(cat rust-toolchain) - -popd >/dev/null +TOOLCHAIN=$(cat $dir/rust-toolchain) cmd=$1 -shift +shift || true if [[ "$cmd" = "jit" ]]; then cargo +${TOOLCHAIN} rustc $@ -- --jit diff --git a/compiler/rustc_codegen_cranelift/scripts/config.sh b/compiler/rustc_codegen_cranelift/scripts/config.sh index 530b7f242a098..af181f4f72439 100644 --- a/compiler/rustc_codegen_cranelift/scripts/config.sh +++ b/compiler/rustc_codegen_cranelift/scripts/config.sh @@ -39,18 +39,19 @@ echo export RUSTC_WRAPPER= fi -export RUSTC=$(pwd)/"target/"$CHANNEL"/cg_clif" +dir=$(cd $(dirname "$BASH_SOURCE"); pwd) + +export RUSTC=$dir"/cg_clif" export RUSTFLAGS=$linker export RUSTDOCFLAGS=$linker' -Ztrim-diagnostic-paths=no -Cpanic=abort -Zpanic-abort-tests '\ -'-Zcodegen-backend='$(pwd)'/target/'$CHANNEL'/librustc_codegen_cranelift.'$dylib_ext' --sysroot '$(pwd)'/build_sysroot/sysroot' +'-Zcodegen-backend='$dir'/librustc_codegen_cranelift.'$dylib_ext' --sysroot '$dir'/sysroot' # FIXME remove once the atomic shim is gone if [[ `uname` == 'Darwin' ]]; then export RUSTFLAGS="$RUSTFLAGS -Clink-arg=-undefined -Clink-arg=dynamic_lookup" fi -export LD_LIBRARY_PATH="$(pwd)/target/out:$(pwd)/build_sysroot/sysroot/lib/rustlib/"$TARGET_TRIPLE"/lib:\ -$(pwd)/target/"$CHANNEL":$(rustc --print sysroot)/lib" +export LD_LIBRARY_PATH="$dir:$(rustc --print sysroot)/lib:$dir/target/out:$dir/sysroot/lib/rustlib/"$TARGET_TRIPLE"/lib" export DYLD_LIBRARY_PATH=$LD_LIBRARY_PATH export CG_CLIF_DISPLAY_CG_TIME=1 diff --git a/compiler/rustc_codegen_cranelift/scripts/filter_profile.rs b/compiler/rustc_codegen_cranelift/scripts/filter_profile.rs index c70c3ec47f31f..3327c10089d9b 100755 --- a/compiler/rustc_codegen_cranelift/scripts/filter_profile.rs +++ b/compiler/rustc_codegen_cranelift/scripts/filter_profile.rs @@ -1,9 +1,8 @@ #!/bin/bash #![forbid(unsafe_code)]/* This line is ignored by bash # This block is ignored by rustc -CHANNEL="release" pushd $(dirname "$0")/../ -source scripts/config.sh +source build/config.sh popd PROFILE=$1 OUTPUT=$2 exec $RUSTC $RUSTFLAGS --jit $0 #*/ diff --git a/compiler/rustc_codegen_cranelift/scripts/rustup.sh b/compiler/rustc_codegen_cranelift/scripts/rustup.sh index 38991d6d47dd0..541b3c6563bab 100755 --- a/compiler/rustc_codegen_cranelift/scripts/rustup.sh +++ b/compiler/rustc_codegen_cranelift/scripts/rustup.sh @@ -26,6 +26,15 @@ case $1 in git add rust-toolchain build_sysroot/Cargo.lock git commit -m "Rustup to $(rustc -V)" ;; + "push") + cg_clif=$(pwd) + pushd ../rust + branch=update_cg_clif-$(date +%Y-%m-%d) + git checkout -b $branch + git subtree pull --prefix=compiler/rustc_codegen_cranelift/ https://github.com/bjorn3/rustc_codegen_cranelift.git master + git push -u my $branch + popd + ;; *) echo "Unknown command '$1'" echo "Usage: ./rustup.sh prepare|commit" diff --git a/compiler/rustc_codegen_cranelift/scripts/test_bootstrap.sh b/compiler/rustc_codegen_cranelift/scripts/test_bootstrap.sh new file mode 100755 index 0000000000000..7f43f81a6cdcd --- /dev/null +++ b/compiler/rustc_codegen_cranelift/scripts/test_bootstrap.sh @@ -0,0 +1,65 @@ +#!/bin/bash +set -e + +cd $(dirname "$0")/../ + +./build.sh +source build/config.sh + +echo "[TEST] Bootstrap of rustc" +git clone https://github.com/rust-lang/rust.git || true +pushd rust +git fetch +git checkout -- . +git checkout $(rustc -V | cut -d' ' -f3 | tr -d '(') + +git apply - < config.toml < res.txt + diff -u res.txt examples/regexdna-output.txt + + echo "[TEST] rust-lang/regex tests" + ../build/cargo.sh test --tests -- --exclude-should-panic --test-threads 1 -Zunstable-options -q + popd +} + +case "$1" in + "no_sysroot") + no_sysroot_tests + ;; + "base_sysroot") + base_sysroot_tests + ;; + "extended_sysroot") + extended_sysroot_tests + ;; + *) + echo "unknown test suite" + ;; +esac diff --git a/compiler/rustc_codegen_cranelift/src/abi/comments.rs b/compiler/rustc_codegen_cranelift/src/abi/comments.rs index 7bb00c8d46a4c..01073d26e832a 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/comments.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/comments.rs @@ -11,9 +11,9 @@ use crate::abi::pass_mode::*; use crate::prelude::*; pub(super) fn add_args_header_comment(fx: &mut FunctionCx<'_, '_, impl Module>) { - fx.add_global_comment(format!( - "kind loc.idx param pass mode ty" - )); + fx.add_global_comment( + "kind loc.idx param pass mode ty".to_string(), + ); } pub(super) fn add_arg_comment<'tcx>( @@ -56,9 +56,9 @@ pub(super) fn add_arg_comment<'tcx>( pub(super) fn add_locals_header_comment(fx: &mut FunctionCx<'_, '_, impl Module>) { fx.add_global_comment(String::new()); - fx.add_global_comment(format!( - "kind local ty size align (abi,pref)" - )); + fx.add_global_comment( + "kind local ty size align (abi,pref)".to_string(), + ); } pub(super) fn add_local_place_comments<'tcx>( diff --git a/compiler/rustc_codegen_cranelift/src/abi/mod.rs b/compiler/rustc_codegen_cranelift/src/abi/mod.rs index 8016912284317..81091728692f3 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/mod.rs @@ -300,7 +300,7 @@ impl<'tcx, M: Module> FunctionCx<'_, 'tcx, M> { return_ty: Ty<'tcx>, ) -> CValue<'tcx> { let (input_tys, args): (Vec<_>, Vec<_>) = args - .into_iter() + .iter() .map(|arg| { ( self.clif_type(arg.layout().ty).unwrap(), @@ -421,34 +421,31 @@ pub(crate) fn codegen_fn_prelude<'tcx>( // While this is normally an optimization to prevent an unnecessary copy when an argument is // not mutated by the current function, this is necessary to support unsized arguments. - match arg_kind { - ArgKind::Normal(Some(val)) => { - if let Some((addr, meta)) = val.try_to_ptr() { - let local_decl = &fx.mir.local_decls[local]; - // v this ! is important - let internally_mutable = !val.layout().ty.is_freeze( - fx.tcx.at(local_decl.source_info.span), - ParamEnv::reveal_all(), - ); - if local_decl.mutability == mir::Mutability::Not && !internally_mutable { - // We wont mutate this argument, so it is fine to borrow the backing storage - // of this argument, to prevent a copy. - - let place = if let Some(meta) = meta { - CPlace::for_ptr_with_extra(addr, meta, val.layout()) - } else { - CPlace::for_ptr(addr, val.layout()) - }; - - #[cfg(debug_assertions)] - self::comments::add_local_place_comments(fx, place, local); - - assert_eq!(fx.local_map.push(place), local); - continue; - } + if let ArgKind::Normal(Some(val)) = arg_kind { + if let Some((addr, meta)) = val.try_to_ptr() { + let local_decl = &fx.mir.local_decls[local]; + // v this ! is important + let internally_mutable = !val.layout().ty.is_freeze( + fx.tcx.at(local_decl.source_info.span), + ParamEnv::reveal_all(), + ); + if local_decl.mutability == mir::Mutability::Not && !internally_mutable { + // We wont mutate this argument, so it is fine to borrow the backing storage + // of this argument, to prevent a copy. + + let place = if let Some(meta) = meta { + CPlace::for_ptr_with_extra(addr, meta, val.layout()) + } else { + CPlace::for_ptr(addr, val.layout()) + }; + + #[cfg(debug_assertions)] + self::comments::add_local_place_comments(fx, place, local); + + assert_eq!(fx.local_map.push(place), local); + continue; } } - _ => {} } let place = make_local_place(fx, local, layout, is_ssa); @@ -500,7 +497,7 @@ pub(crate) fn codegen_terminator_call<'tcx>( .tcx .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &fn_ty.fn_sig(fx.tcx)); - let destination = destination.map(|(place, bb)| (trans_place(fx, place), bb)); + let destination = destination.map(|(place, bb)| (codegen_place(fx, place), bb)); // Handle special calls like instrinsics and empty drop glue. let instance = if let ty::FnDef(def_id, substs) = *fn_ty.kind() { @@ -553,8 +550,8 @@ pub(crate) fn codegen_terminator_call<'tcx>( // Unpack arguments tuple for closures let args = if fn_sig.abi == Abi::RustCall { assert_eq!(args.len(), 2, "rust-call abi requires two arguments"); - let self_arg = trans_operand(fx, &args[0]); - let pack_arg = trans_operand(fx, &args[1]); + let self_arg = codegen_operand(fx, &args[0]); + let pack_arg = codegen_operand(fx, &args[1]); let tupled_arguments = match pack_arg.layout().ty.kind() { ty::Tuple(ref tupled_arguments) => tupled_arguments, @@ -568,8 +565,8 @@ pub(crate) fn codegen_terminator_call<'tcx>( } args } else { - args.into_iter() - .map(|arg| trans_operand(fx, arg)) + args.iter() + .map(|arg| codegen_operand(fx, arg)) .collect::>() }; @@ -613,7 +610,7 @@ pub(crate) fn codegen_terminator_call<'tcx>( let nop_inst = fx.bcx.ins().nop(); fx.add_comment(nop_inst, "indirect call"); } - let func = trans_operand(fx, func).load_scalar(fx); + let func = codegen_operand(fx, func).load_scalar(fx); ( Some(func), args.get(0) diff --git a/compiler/rustc_codegen_cranelift/src/allocator.rs b/compiler/rustc_codegen_cranelift/src/allocator.rs index 0735ad6f83299..6c5916550ff63 100644 --- a/compiler/rustc_codegen_cranelift/src/allocator.rs +++ b/compiler/rustc_codegen_cranelift/src/allocator.rs @@ -123,7 +123,7 @@ fn codegen_inner( .unwrap(); let mut ctx = Context::new(); - ctx.func = Function::with_name_signature(ExternalName::user(0, 0), sig.clone()); + ctx.func = Function::with_name_signature(ExternalName::user(0, 0), sig); { let mut func_ctx = FunctionBuilderContext::new(); let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx); @@ -131,7 +131,7 @@ fn codegen_inner( let block = bcx.create_block(); bcx.switch_to_block(block); let args = (&[usize_ty, usize_ty]) - .into_iter() + .iter() .map(|&ty| bcx.append_block_param(block, ty)) .collect::>(); diff --git a/compiler/rustc_codegen_cranelift/src/archive.rs b/compiler/rustc_codegen_cranelift/src/archive.rs index 6382f8df3446b..9a970efbcfd0b 100644 --- a/compiler/rustc_codegen_cranelift/src/archive.rs +++ b/compiler/rustc_codegen_cranelift/src/archive.rs @@ -132,7 +132,7 @@ impl<'a> ArchiveBuilder<'a> for ArArchiveBuilder<'a> { } // ok, don't skip this - return false; + false }) } diff --git a/compiler/rustc_codegen_cranelift/src/atomic_shim.rs b/compiler/rustc_codegen_cranelift/src/atomic_shim.rs index 92281fdacc941..2f0157c257b98 100644 --- a/compiler/rustc_codegen_cranelift/src/atomic_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/atomic_shim.rs @@ -7,7 +7,7 @@ use crate::prelude::*; #[cfg(all(feature = "jit", unix))] #[no_mangle] -pub static mut __cg_clif_global_atomic_mutex: libc::pthread_mutex_t = +static mut __cg_clif_global_atomic_mutex: libc::pthread_mutex_t = libc::PTHREAD_MUTEX_INITIALIZER; pub(crate) fn init_global_lock( diff --git a/compiler/rustc_codegen_cranelift/src/backend.rs b/compiler/rustc_codegen_cranelift/src/backend.rs index 8b900fd0dd0c8..9e32259716f51 100644 --- a/compiler/rustc_codegen_cranelift/src/backend.rs +++ b/compiler/rustc_codegen_cranelift/src/backend.rs @@ -73,7 +73,7 @@ impl WriteDebugInfo for ObjectProduct { // FIXME use SHT_X86_64_UNWIND for .eh_frame let section_id = self.object.add_section( segment, - name.clone(), + name, if id == SectionId::EhFrame { SectionKind::ReadOnlyData } else { @@ -198,9 +198,9 @@ pub(crate) fn make_module(sess: &Session, name: String) -> ObjectModule { cranelift_module::default_libcall_names(), ) .unwrap(); - if std::env::var("CG_CLIF_FUNCTION_SECTIONS").is_ok() { - builder.per_function_section(true); - } - let module = ObjectModule::new(builder); - module + // Unlike cg_llvm, cg_clif defaults to disabling -Zfunction-sections. For cg_llvm binary size + // is important, while cg_clif cares more about compilation times. Enabling -Zfunction-sections + // can easily double the amount of time necessary to perform linking. + builder.per_function_section(sess.opts.debugging_opts.function_sections.unwrap_or(false)); + ObjectModule::new(builder) } diff --git a/compiler/rustc_codegen_cranelift/src/base.rs b/compiler/rustc_codegen_cranelift/src/base.rs index fa9b8853d39e9..5474e5960f100 100644 --- a/compiler/rustc_codegen_cranelift/src/base.rs +++ b/compiler/rustc_codegen_cranelift/src/base.rs @@ -5,7 +5,7 @@ use rustc_middle::ty::adjustment::PointerCast; use crate::prelude::*; -pub(crate) fn trans_fn<'tcx>( +pub(crate) fn codegen_fn<'tcx>( cx: &mut crate::CodegenCx<'tcx, impl Module>, instance: Instance<'tcx>, linkage: Linkage, @@ -202,7 +202,7 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) { fx.bcx.ins().nop(); for stmt in &bb_data.statements { fx.set_debug_loc(stmt.source_info); - trans_stmt(fx, block, stmt); + codegen_stmt(fx, block, stmt); } #[cfg(debug_assertions)] @@ -258,7 +258,7 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) { continue; } } - let cond = trans_operand(fx, cond).load_scalar(fx); + let cond = codegen_operand(fx, cond).load_scalar(fx); let target = fx.get_block(*target); let failure = fx.bcx.create_block(); @@ -276,8 +276,8 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) { match msg { AssertKind::BoundsCheck { ref len, ref index } => { - let len = trans_operand(fx, len).load_scalar(fx); - let index = trans_operand(fx, index).load_scalar(fx); + let len = codegen_operand(fx, len).load_scalar(fx); + let index = codegen_operand(fx, index).load_scalar(fx); let location = fx .get_caller_location(bb_data.terminator().source_info.span) .load_scalar(fx); @@ -301,7 +301,7 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) { switch_ty, targets, } => { - let discr = trans_operand(fx, discr).load_scalar(fx); + let discr = codegen_operand(fx, discr).load_scalar(fx); if switch_ty.kind() == fx.tcx.types.bool.kind() { assert_eq!(targets.iter().count(), 1); @@ -396,14 +396,14 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) { | TerminatorKind::FalseUnwind { .. } | TerminatorKind::DropAndReplace { .. } | TerminatorKind::GeneratorDrop => { - bug!("shouldn't exist at trans {:?}", bb_data.terminator()); + bug!("shouldn't exist at codegen {:?}", bb_data.terminator()); } TerminatorKind::Drop { place, target, unwind: _, } => { - let drop_place = trans_place(fx, *place); + let drop_place = codegen_place(fx, *place); crate::abi::codegen_drop(fx, bb_data.terminator().source_info.span, drop_place); let target_block = fx.get_block(*target); @@ -416,7 +416,7 @@ fn codegen_fn_content(fx: &mut FunctionCx<'_, '_, impl Module>) { fx.bcx.finalize(); } -fn trans_stmt<'tcx>( +fn codegen_stmt<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, #[allow(unused_variables)] cur_block: Block, stmt: &Statement<'tcx>, @@ -439,19 +439,19 @@ fn trans_stmt<'tcx>( place, variant_index, } => { - let place = trans_place(fx, **place); + let place = codegen_place(fx, **place); crate::discriminant::codegen_set_discriminant(fx, place, *variant_index); } StatementKind::Assign(to_place_and_rval) => { - let lval = trans_place(fx, to_place_and_rval.0); + let lval = codegen_place(fx, to_place_and_rval.0); let dest_layout = lval.layout(); match &to_place_and_rval.1 { Rvalue::Use(operand) => { - let val = trans_operand(fx, operand); + let val = codegen_operand(fx, operand); lval.write_cvalue(fx, val); } Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { - let place = trans_place(fx, *place); + let place = codegen_place(fx, *place); let ref_ = place.place_ref(fx, lval.layout()); lval.write_cvalue(fx, ref_); } @@ -460,29 +460,29 @@ fn trans_stmt<'tcx>( lval.write_cvalue(fx, val); } Rvalue::BinaryOp(bin_op, lhs, rhs) => { - let lhs = trans_operand(fx, lhs); - let rhs = trans_operand(fx, rhs); + let lhs = codegen_operand(fx, lhs); + let rhs = codegen_operand(fx, rhs); let res = crate::num::codegen_binop(fx, *bin_op, lhs, rhs); lval.write_cvalue(fx, res); } Rvalue::CheckedBinaryOp(bin_op, lhs, rhs) => { - let lhs = trans_operand(fx, lhs); - let rhs = trans_operand(fx, rhs); + let lhs = codegen_operand(fx, lhs); + let rhs = codegen_operand(fx, rhs); let res = if !fx.tcx.sess.overflow_checks() { let val = - crate::num::trans_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx); + crate::num::codegen_int_binop(fx, *bin_op, lhs, rhs).load_scalar(fx); let is_overflow = fx.bcx.ins().iconst(types::I8, 0); CValue::by_val_pair(val, is_overflow, lval.layout()) } else { - crate::num::trans_checked_int_binop(fx, *bin_op, lhs, rhs) + crate::num::codegen_checked_int_binop(fx, *bin_op, lhs, rhs) }; lval.write_cvalue(fx, res); } Rvalue::UnaryOp(un_op, operand) => { - let operand = trans_operand(fx, operand); + let operand = codegen_operand(fx, operand); let layout = operand.layout(); let val = operand.load_scalar(fx); let res = match un_op { @@ -500,7 +500,7 @@ fn trans_stmt<'tcx>( ty::Int(IntTy::I128) => { // FIXME remove this case once ineg.i128 works let zero = CValue::const_val(fx, layout, 0); - crate::num::trans_int_binop(fx, BinOp::Sub, zero, operand) + crate::num::codegen_int_binop(fx, BinOp::Sub, zero, operand) } ty::Int(_) => CValue::by_val(fx.bcx.ins().ineg(val), layout), ty::Float(_) => CValue::by_val(fx.bcx.ins().fneg(val), layout), @@ -534,11 +534,11 @@ fn trans_stmt<'tcx>( | Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, to_ty) | Rvalue::Cast(CastKind::Pointer(PointerCast::ArrayToPointer), operand, to_ty) => { let to_layout = fx.layout_of(fx.monomorphize(to_ty)); - let operand = trans_operand(fx, operand); + let operand = codegen_operand(fx, operand); lval.write_cvalue(fx, operand.cast_pointer_to(to_layout)); } Rvalue::Cast(CastKind::Misc, operand, to_ty) => { - let operand = trans_operand(fx, operand); + let operand = codegen_operand(fx, operand); let from_ty = operand.layout().ty; let to_ty = fx.monomorphize(to_ty); @@ -639,7 +639,7 @@ fn trans_stmt<'tcx>( operand, _to_ty, ) => { - let operand = trans_operand(fx, operand); + let operand = codegen_operand(fx, operand); match *operand.layout().ty.kind() { ty::Closure(def_id, substs) => { let instance = Instance::resolve_closure( @@ -657,18 +657,18 @@ fn trans_stmt<'tcx>( } } Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), operand, _to_ty) => { - let operand = trans_operand(fx, operand); + let operand = codegen_operand(fx, operand); operand.unsize_value(fx, lval); } Rvalue::Discriminant(place) => { - let place = trans_place(fx, *place); + let place = codegen_place(fx, *place); let value = place.to_cvalue(fx); let discr = crate::discriminant::codegen_get_discriminant(fx, value, dest_layout); lval.write_cvalue(fx, discr); } Rvalue::Repeat(operand, times) => { - let operand = trans_operand(fx, operand); + let operand = codegen_operand(fx, operand); let times = fx .monomorphize(times) .eval(fx.tcx, ParamEnv::reveal_all()) @@ -706,7 +706,7 @@ fn trans_stmt<'tcx>( } } Rvalue::Len(place) => { - let place = trans_place(fx, *place); + let place = codegen_place(fx, *place); let usize_layout = fx.layout_of(fx.tcx.types.usize); let len = codegen_array_len(fx, place); lval.write_cvalue(fx, CValue::by_val(len, usize_layout)); @@ -753,14 +753,14 @@ fn trans_stmt<'tcx>( } Rvalue::Aggregate(kind, operands) => match **kind { AggregateKind::Array(_ty) => { - for (i, operand) in operands.into_iter().enumerate() { - let operand = trans_operand(fx, operand); + for (i, operand) in operands.iter().enumerate() { + let operand = codegen_operand(fx, operand); let index = fx.bcx.ins().iconst(fx.pointer_type, i as i64); let to = lval.place_index(fx, index); to.write_cvalue(fx, operand); } } - _ => unreachable!("shouldn't exist at trans {:?}", to_place_and_rval.1), + _ => unreachable!("shouldn't exist at codegen {:?}", to_place_and_rval.1), }, } } @@ -813,20 +813,20 @@ fn trans_stmt<'tcx>( assert!(!alignstack); assert_eq!(inputs.len(), 2); - let leaf = trans_operand(fx, &inputs[0].1).load_scalar(fx); // %eax - let subleaf = trans_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx + let leaf = codegen_operand(fx, &inputs[0].1).load_scalar(fx); // %eax + let subleaf = codegen_operand(fx, &inputs[1].1).load_scalar(fx); // %ecx let (eax, ebx, ecx, edx) = crate::intrinsics::codegen_cpuid_call(fx, leaf, subleaf); assert_eq!(outputs.len(), 4); - trans_place(fx, outputs[0]) + codegen_place(fx, outputs[0]) .write_cvalue(fx, CValue::by_val(eax, fx.layout_of(fx.tcx.types.u32))); - trans_place(fx, outputs[1]) + codegen_place(fx, outputs[1]) .write_cvalue(fx, CValue::by_val(ebx, fx.layout_of(fx.tcx.types.u32))); - trans_place(fx, outputs[2]) + codegen_place(fx, outputs[2]) .write_cvalue(fx, CValue::by_val(ecx, fx.layout_of(fx.tcx.types.u32))); - trans_place(fx, outputs[3]) + codegen_place(fx, outputs[3]) .write_cvalue(fx, CValue::by_val(edx, fx.layout_of(fx.tcx.types.u32))); } "xgetbv" => { @@ -892,7 +892,7 @@ fn codegen_array_len<'tcx>( } } -pub(crate) fn trans_place<'tcx>( +pub(crate) fn codegen_place<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, place: Place<'tcx>, ) -> CPlace<'tcx> { @@ -938,7 +938,7 @@ pub(crate) fn trans_place<'tcx>( let ptr = cplace.to_ptr(); cplace = CPlace::for_ptr( ptr.offset_i64(fx, elem_layout.size.bytes() as i64 * (from as i64)), - fx.layout_of(fx.tcx.mk_array(elem_ty, u64::from(to) - u64::from(from))), + fx.layout_of(fx.tcx.mk_array(elem_ty, to - from)), ); } ty::Slice(elem_ty) => { @@ -964,16 +964,16 @@ pub(crate) fn trans_place<'tcx>( cplace } -pub(crate) fn trans_operand<'tcx>( +pub(crate) fn codegen_operand<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, operand: &Operand<'tcx>, ) -> CValue<'tcx> { match operand { Operand::Move(place) | Operand::Copy(place) => { - let cplace = trans_place(fx, *place); + let cplace = codegen_place(fx, *place); cplace.to_cvalue(fx) } - Operand::Constant(const_) => crate::constant::trans_constant(fx, const_), + Operand::Constant(const_) => crate::constant::codegen_constant(fx, const_), } } diff --git a/compiler/rustc_codegen_cranelift/src/bin/cg_clif.rs b/compiler/rustc_codegen_cranelift/src/bin/cg_clif.rs index 590c9ef0ce191..71ef4d2267368 100644 --- a/compiler/rustc_codegen_cranelift/src/bin/cg_clif.rs +++ b/compiler/rustc_codegen_cranelift/src/bin/cg_clif.rs @@ -24,22 +24,16 @@ impl rustc_driver::Callbacks for CraneliftPassesCallbacks { self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); - // FIXME workaround for an ICE - config.opts.debugging_opts.trim_diagnostic_paths = false; - config.opts.cg.panic = Some(PanicStrategy::Abort); config.opts.debugging_opts.panic_abort_tests = true; config.opts.maybe_sysroot = Some( - std::env::current_exe() - .unwrap() - .parent() - .unwrap() - .parent() - .unwrap() - .parent() - .unwrap() - .join("build_sysroot") - .join("sysroot"), + config.opts.maybe_sysroot.clone().unwrap_or( + std::env::current_exe() + .unwrap() + .parent() + .unwrap() + .join("sysroot"), + ), ); } } diff --git a/compiler/rustc_codegen_cranelift/src/bin/cg_clif_build_sysroot.rs b/compiler/rustc_codegen_cranelift/src/bin/cg_clif_build_sysroot.rs index c207d98d6c197..165d33dcfb509 100644 --- a/compiler/rustc_codegen_cranelift/src/bin/cg_clif_build_sysroot.rs +++ b/compiler/rustc_codegen_cranelift/src/bin/cg_clif_build_sysroot.rs @@ -44,9 +44,6 @@ impl rustc_driver::Callbacks for CraneliftPassesCallbacks { return; } - // FIXME workaround for an ICE - config.opts.debugging_opts.trim_diagnostic_paths = false; - config.opts.cg.panic = Some(PanicStrategy::Abort); config.opts.debugging_opts.panic_abort_tests = true; config.opts.maybe_sysroot = Some( diff --git a/compiler/rustc_codegen_cranelift/src/cast.rs b/compiler/rustc_codegen_cranelift/src/cast.rs index 122a36b5bf741..57204de1135be 100644 --- a/compiler/rustc_codegen_cranelift/src/cast.rs +++ b/compiler/rustc_codegen_cranelift/src/cast.rs @@ -181,12 +181,10 @@ pub(crate) fn clif_int_or_float_cast( fx.bcx.ins().select(has_overflow, max_val, val) }; fx.bcx.ins().ireduce(to_ty, val) + } else if to_signed { + fx.bcx.ins().fcvt_to_sint_sat(to_ty, from) } else { - if to_signed { - fx.bcx.ins().fcvt_to_sint_sat(to_ty, from) - } else { - fx.bcx.ins().fcvt_to_uint_sat(to_ty, from) - } + fx.bcx.ins().fcvt_to_uint_sat(to_ty, from) } } else if from_ty.is_float() && to_ty.is_float() { // float -> float diff --git a/compiler/rustc_codegen_cranelift/src/codegen_i128.rs b/compiler/rustc_codegen_cranelift/src/codegen_i128.rs index e998403dea6bb..d6a38bdafc9ba 100644 --- a/compiler/rustc_codegen_cranelift/src/codegen_i128.rs +++ b/compiler/rustc_codegen_cranelift/src/codegen_i128.rs @@ -21,9 +21,9 @@ pub(crate) fn maybe_codegen<'tcx>( match bin_op { BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor => { assert!(!checked); - return None; + None } - BinOp::Add | BinOp::Sub if !checked => return None, + BinOp::Add | BinOp::Sub if !checked => None, BinOp::Add => { let out_ty = fx.tcx.mk_tup([lhs.layout().ty, fx.tcx.types.bool].iter()); return Some(if is_signed { @@ -57,7 +57,7 @@ pub(crate) fn maybe_codegen<'tcx>( }; fx.easy_call("__multi3", &[lhs, rhs], val_ty) }; - return Some(res); + Some(res) } BinOp::Div => { assert!(!checked); @@ -77,7 +77,7 @@ pub(crate) fn maybe_codegen<'tcx>( } BinOp::Lt | BinOp::Le | BinOp::Eq | BinOp::Ge | BinOp::Gt | BinOp::Ne => { assert!(!checked); - return None; + None } BinOp::Shl | BinOp::Shr => { let is_overflow = if checked { diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index 13c62add41a3b..eda77bf19d354 100644 --- a/compiler/rustc_codegen_cranelift/src/common.rs +++ b/compiler/rustc_codegen_cranelift/src/common.rs @@ -406,7 +406,7 @@ impl<'tcx, M: Module> FunctionCx<'_, 'tcx, M> { caller.line as u32, caller.col_display as u32 + 1, )); - crate::constant::trans_const_value(self, const_loc, self.tcx.caller_location_ty()) + crate::constant::codegen_const_value(self, const_loc, self.tcx.caller_location_ty()) } pub(crate) fn triple(&self) -> &target_lexicon::Triple { diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index 1b514958a4809..ce1d5ed2e6178 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -106,7 +106,7 @@ fn codegen_static_ref<'tcx>( CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout) } -pub(crate) fn trans_constant<'tcx>( +pub(crate) fn codegen_constant<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, constant: &Constant<'tcx>, ) -> CValue<'tcx> { @@ -151,10 +151,10 @@ pub(crate) fn trans_constant<'tcx>( | ConstKind::Error(_) => unreachable!("{:?}", const_), }; - trans_const_value(fx, const_val, const_.ty) + codegen_const_value(fx, const_val, const_.ty) } -pub(crate) fn trans_const_value<'tcx>( +pub(crate) fn codegen_const_value<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, const_val: ConstValue<'tcx>, ty: Ty<'tcx>, @@ -164,7 +164,7 @@ pub(crate) fn trans_const_value<'tcx>( if layout.is_zst() { return CValue::by_ref( - crate::Pointer::const_addr(fx, i64::try_from(layout.align.pref.bytes()).unwrap()), + crate::Pointer::dangling(layout.align.pref), layout, ); } @@ -188,7 +188,7 @@ pub(crate) fn trans_const_value<'tcx>( match x { Scalar::Raw { data, size } => { assert_eq!(u64::from(size), layout.size.bytes()); - return CValue::const_val(fx, layout, data); + CValue::const_val(fx, layout, data) } Scalar::Ptr(ptr) => { let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id); @@ -232,7 +232,7 @@ pub(crate) fn trans_const_value<'tcx>( } else { base_addr }; - return CValue::by_val(val, layout); + CValue::by_val(val, layout) } } } @@ -276,7 +276,7 @@ fn data_id_for_alloc_id( ) -> DataId { module .declare_data( - &format!("__alloc_{:x}", alloc_id.0), + &format!(".L__alloc_{:x}", alloc_id.0), Linkage::Local, mutability == rustc_hir::Mutability::Mut, false, @@ -293,14 +293,12 @@ fn data_id_for_static( let rlinkage = tcx.codegen_fn_attrs(def_id).linkage; let linkage = if definition { crate::linkage::get_static_linkage(tcx, def_id) + } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak) + || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny) + { + Linkage::Preemptible } else { - if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak) - || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny) - { - Linkage::Preemptible - } else { - Linkage::Import - } + Linkage::Import }; let instance = Instance::mono(tcx, def_id).polymorphize(tcx); diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs index cf8fee2b1d17c..f6f795e45615c 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs @@ -195,9 +195,7 @@ impl Writer for WriterRelocate { }); self.write_udata(0, size) } - _ => { - return Err(gimli::write::Error::UnsupportedPointerEncoding(eh_pe)); - } + _ => Err(gimli::write::Error::UnsupportedPointerEncoding(eh_pe)), }, } } diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs index 4de8485532896..d226755d85de0 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs @@ -49,7 +49,7 @@ fn osstr_as_utf8_bytes(path: &OsStr) -> &[u8] { pub(crate) const MD5_LEN: usize = 16; -pub fn make_file_info(hash: SourceFileHash) -> Option { +pub(crate) fn make_file_info(hash: SourceFileHash) -> Option { if hash.kind == SourceFileHashAlgorithm::Md5 { let mut buf = [0u8; MD5_LEN]; buf.copy_from_slice(hash.hash_bytes()); @@ -190,7 +190,7 @@ impl<'tcx> DebugContext<'tcx> { if current_file_changed { let file_id = line_program_add_file(line_program, line_strings, &file); line_program.row().file = file_id; - last_file = Some(file.clone()); + last_file = Some(file); } line_program.row().line = line; diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs index 61ebd931d2f14..68138404c2436 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs @@ -55,6 +55,7 @@ impl<'tcx> UnwindContext<'tcx> { UnwindInfo::WindowsX64(_) => { // FIXME implement this } + unwind_info => unimplemented!("{:?}", unwind_info), } } diff --git a/compiler/rustc_codegen_cranelift/src/driver/jit.rs b/compiler/rustc_codegen_cranelift/src/driver/jit.rs index b5bab3d9e1ed1..3f47df7d844b3 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/jit.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/jit.rs @@ -94,7 +94,7 @@ pub(super) fn run_jit(tcx: TyCtxt<'_>) -> ! { let args = ::std::env::var("CG_CLIF_JIT_ARGS").unwrap_or_else(|_| String::new()); let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()) - .chain(args.split(" ")) + .chain(args.split(' ')) .map(|arg| CString::new(arg).unwrap()) .collect::>(); let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::>(); @@ -151,7 +151,7 @@ fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> { } let dlsym_name = if cfg!(target_os = "macos") { // On macOS `dlsym` expects the name without leading `_`. - assert!(name.starts_with("_"), "{:?}", name); + assert!(name.starts_with('_'), "{:?}", name); &name[1..] } else { &name diff --git a/compiler/rustc_codegen_cranelift/src/driver/mod.rs b/compiler/rustc_codegen_cranelift/src/driver/mod.rs index 2fb353ca1628a..a11dc57ee6453 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/mod.rs @@ -64,11 +64,11 @@ fn codegen_mono_items<'tcx>( for (mono_item, (linkage, visibility)) in mono_items { let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility); - trans_mono_item(cx, mono_item, linkage); + codegen_mono_item(cx, mono_item, linkage); } } -fn trans_mono_item<'tcx, M: Module>( +fn codegen_mono_item<'tcx, M: Module>( cx: &mut crate::CodegenCx<'tcx, M>, mono_item: MonoItem<'tcx>, linkage: Linkage, @@ -80,7 +80,7 @@ fn trans_mono_item<'tcx, M: Module>( crate::PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).name)); debug_assert!(!inst.substs.needs_infer()); tcx.sess - .time("codegen fn", || crate::base::trans_fn(cx, inst, linkage)); + .time("codegen fn", || crate::base::codegen_fn(cx, inst, linkage)); } MonoItem::Static(def_id) => { crate::constant::codegen_static(&mut cx.constants_cx, def_id); diff --git a/compiler/rustc_codegen_cranelift/src/inline_asm.rs b/compiler/rustc_codegen_cranelift/src/inline_asm.rs index aa2edb2dfd4f7..04aac780125d9 100644 --- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs @@ -50,7 +50,7 @@ pub(crate) fn codegen_inline_asm<'tcx>( inputs.push(( reg, new_slot(reg.reg_class()), - crate::base::trans_operand(fx, value).load_scalar(fx), + crate::base::codegen_operand(fx, value).load_scalar(fx), )); } InlineAsmOperand::Out { @@ -64,7 +64,7 @@ pub(crate) fn codegen_inline_asm<'tcx>( outputs.push(( reg, new_slot(reg.reg_class()), - crate::base::trans_place(fx, place), + crate::base::codegen_place(fx, place), )); } } @@ -79,13 +79,13 @@ pub(crate) fn codegen_inline_asm<'tcx>( inputs.push(( reg, new_slot(reg.reg_class()), - crate::base::trans_operand(fx, in_value).load_scalar(fx), + crate::base::codegen_operand(fx, in_value).load_scalar(fx), )); if let Some(out_place) = out_place { outputs.push(( reg, new_slot(reg.reg_class()), - crate::base::trans_place(fx, out_place), + crate::base::codegen_place(fx, out_place), )); } } diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs index 18d86f0c5f959..171445f2d71b6 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs @@ -53,7 +53,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>( }; llvm.x86.sse2.cmp.ps | llvm.x86.sse2.cmp.pd, (c x, c y, o kind) { let kind_const = crate::constant::mir_operand_get_const_val(fx, kind).expect("llvm.x86.sse2.cmp.* kind not const"); - let flt_cc = match kind_const.val.try_to_bits(Size::from_bytes(1)).expect(&format!("kind not scalar: {:?}", kind_const)) { + let flt_cc = match kind_const.val.try_to_bits(Size::from_bytes(1)).unwrap_or_else(|| panic!("kind not scalar: {:?}", kind_const)) { 0 => FloatCC::Equal, 1 => FloatCC::LessThan, 2 => FloatCC::LessThanOrEqual, @@ -84,7 +84,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>( llvm.x86.sse2.psrli.d, (c a, o imm8) { let imm8 = crate::constant::mir_operand_get_const_val(fx, imm8).expect("llvm.x86.sse2.psrli.d imm8 not const"); simd_for_each_lane(fx, a, ret, |fx, _lane_layout, res_lane_layout, lane| { - let res_lane = match imm8.val.try_to_bits(Size::from_bytes(4)).expect(&format!("imm8 not scalar: {:?}", imm8)) { + let res_lane = match imm8.val.try_to_bits(Size::from_bytes(4)).unwrap_or_else(|| panic!("imm8 not scalar: {:?}", imm8)) { imm8 if imm8 < 32 => fx.bcx.ins().ushr_imm(lane, i64::from(imm8 as u8)), _ => fx.bcx.ins().iconst(types::I32, 0), }; @@ -94,7 +94,7 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>( llvm.x86.sse2.pslli.d, (c a, o imm8) { let imm8 = crate::constant::mir_operand_get_const_val(fx, imm8).expect("llvm.x86.sse2.psrli.d imm8 not const"); simd_for_each_lane(fx, a, ret, |fx, _lane_layout, res_lane_layout, lane| { - let res_lane = match imm8.val.try_to_bits(Size::from_bytes(4)).expect(&format!("imm8 not scalar: {:?}", imm8)) { + let res_lane = match imm8.val.try_to_bits(Size::from_bytes(4)).unwrap_or_else(|| panic!("imm8 not scalar: {:?}", imm8)) { imm8 if imm8 < 32 => fx.bcx.ins().ishl_imm(lane, i64::from(imm8 as u8)), _ => fx.bcx.ins().iconst(types::I32, 0), }; diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 9a3e4c7b56e9c..a5f45b7abf4c8 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -9,6 +9,7 @@ pub(crate) use cpuid::codegen_cpuid_call; pub(crate) use llvm::codegen_llvm_intrinsic_call; use crate::prelude::*; +use rustc_middle::ty::print::with_no_trimmed_paths; macro intrinsic_pat { (_) => { @@ -30,10 +31,10 @@ macro intrinsic_arg { $arg }, (c $fx:expr, $arg:ident) => { - trans_operand($fx, $arg) + codegen_operand($fx, $arg) }, (v $fx:expr, $arg:ident) => { - trans_operand($fx, $arg).load_scalar($fx) + codegen_operand($fx, $arg).load_scalar($fx) } } @@ -89,7 +90,7 @@ macro call_intrinsic_match { assert!($substs.is_noop()); if let [$(ref $arg),*] = *$args { let ($($arg,)*) = ( - $(trans_operand($fx, $arg),)* + $(codegen_operand($fx, $arg),)* ); let res = $fx.easy_call(stringify!($func), &[$($arg),*], $fx.tcx.types.$ty); $ret.write_cvalue($fx, res); @@ -576,7 +577,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( "unchecked_shr" => BinOp::Shr, _ => unreachable!("intrinsic {}", intrinsic), }; - let res = crate::num::trans_int_binop(fx, bin_op, x, y); + let res = crate::num::codegen_int_binop(fx, bin_op, x, y); ret.write_cvalue(fx, res); }; _ if intrinsic.ends_with("_with_overflow"), (c x, c y) { @@ -588,7 +589,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( _ => unreachable!("intrinsic {}", intrinsic), }; - let res = crate::num::trans_checked_int_binop( + let res = crate::num::codegen_checked_int_binop( fx, bin_op, x, @@ -604,7 +605,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( "wrapping_mul" => BinOp::Mul, _ => unreachable!("intrinsic {}", intrinsic), }; - let res = crate::num::trans_int_binop( + let res = crate::num::codegen_int_binop( fx, bin_op, x, @@ -622,7 +623,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( let signed = type_sign(T); - let checked_res = crate::num::trans_checked_int_binop( + let checked_res = crate::num::codegen_checked_int_binop( fx, bin_op, lhs, @@ -819,29 +820,29 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( assert_inhabited | assert_zero_valid | assert_uninit_valid, () { let layout = fx.layout_of(T); if layout.abi.is_uninhabited() { - crate::base::codegen_panic( + with_no_trimmed_paths(|| crate::base::codegen_panic( fx, &format!("attempted to instantiate uninhabited type `{}`", T), span, - ); + )); return; } if intrinsic == "assert_zero_valid" && !layout.might_permit_raw_init(fx, /*zero:*/ true).unwrap() { - crate::base::codegen_panic( + with_no_trimmed_paths(|| crate::base::codegen_panic( fx, &format!("attempted to zero-initialize type `{}`, which is invalid", T), span, - ); + )); return; } if intrinsic == "assert_uninit_valid" && !layout.might_permit_raw_init(fx, /*zero:*/ false).unwrap() { - crate::base::codegen_panic( + with_no_trimmed_paths(|| crate::base::codegen_panic( fx, &format!("attempted to leave type `{}` uninitialized, which is invalid", T), span, - ); + )); return; } }; @@ -866,7 +867,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( size_of | pref_align_of | min_align_of | needs_drop | type_id | type_name | variant_count, () { let const_val = fx.tcx.const_eval_instance(ParamEnv::reveal_all(), instance, None).unwrap(); - let val = crate::constant::trans_const_value( + let val = crate::constant::codegen_const_value( fx, const_val, ret.layout().ty, @@ -885,12 +886,12 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( }; ptr_guaranteed_eq, (c a, c b) { - let val = crate::num::trans_ptr_binop(fx, BinOp::Eq, a, b); + let val = crate::num::codegen_ptr_binop(fx, BinOp::Eq, a, b); ret.write_cvalue(fx, val); }; ptr_guaranteed_ne, (c a, c b) { - let val = crate::num::trans_ptr_binop(fx, BinOp::Ne, a, b); + let val = crate::num::codegen_ptr_binop(fx, BinOp::Ne, a, b); ret.write_cvalue(fx, val); }; @@ -1068,7 +1069,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( }; fadd_fast | fsub_fast | fmul_fast | fdiv_fast | frem_fast, (c x, c y) { - let res = crate::num::trans_float_binop(fx, match intrinsic { + let res = crate::num::codegen_float_binop(fx, match intrinsic { "fadd_fast" => BinOp::Add, "fsub_fast" => BinOp::Sub, "fmul_fast" => BinOp::Mul, diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs index b4269f4fafa0b..2e31c4669e25b 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs @@ -127,7 +127,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( ); }; - let idx = idx_const.val.try_to_bits(Size::from_bytes(4 /* u32*/)).expect(&format!("kind not scalar: {:?}", idx_const)); + let idx = idx_const.val.try_to_bits(Size::from_bytes(4 /* u32*/)).unwrap_or_else(|| panic!("kind not scalar: {:?}", idx_const)); let (_lane_type, lane_count) = lane_type_and_count(fx.tcx, base.layout()); if idx >= lane_count.into() { fx.tcx.sess.span_fatal(fx.mir.span, &format!("[simd_insert] idx {} >= lane_count {}", idx, lane_count)); @@ -149,7 +149,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( ); }; - let idx = idx_const.val.try_to_bits(Size::from_bytes(4 /* u32*/)).expect(&format!("kind not scalar: {:?}", idx_const)); + let idx = idx_const.val.try_to_bits(Size::from_bytes(4 /* u32*/)).unwrap_or_else(|| panic!("kind not scalar: {:?}", idx_const)); let (_lane_type, lane_count) = lane_type_and_count(fx.tcx, v.layout()); if idx >= lane_count.into() { fx.tcx.sess.span_fatal(fx.mir.span, &format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count)); diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index fd00a2e00a6a4..ba9ee0d450ee6 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -9,6 +9,7 @@ )] #![warn(rust_2018_idioms)] #![warn(unused_lifetimes)] +#![warn(unreachable_pub)] #[cfg(feature = "jit")] extern crate libc; @@ -110,7 +111,7 @@ mod prelude { pub(crate) use cranelift_module::{self, DataContext, DataId, FuncId, Linkage, Module}; pub(crate) use crate::abi::*; - pub(crate) use crate::base::{trans_operand, trans_place}; + pub(crate) use crate::base::{codegen_operand, codegen_place}; pub(crate) use crate::cast::*; pub(crate) use crate::common::*; pub(crate) use crate::debuginfo::{DebugContext, UnwindContext}; diff --git a/compiler/rustc_codegen_cranelift/src/linkage.rs b/compiler/rustc_codegen_cranelift/src/linkage.rs index fe5d1d6444363..dc1e2107ce712 100644 --- a/compiler/rustc_codegen_cranelift/src/linkage.rs +++ b/compiler/rustc_codegen_cranelift/src/linkage.rs @@ -25,11 +25,9 @@ pub(crate) fn get_static_linkage(tcx: TyCtxt<'_>, def_id: DefId) -> Linkage { RLinkage::ExternalWeak | RLinkage::WeakAny => Linkage::Preemptible, _ => panic!("{:?}", linkage), } + } else if tcx.is_reachable_non_generic(def_id) { + Linkage::Export } else { - if tcx.is_reachable_non_generic(def_id) { - Linkage::Export - } else { - Linkage::Hidden - } + Linkage::Hidden } } diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index db34d89fe2be7..10f515e38ead2 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -76,7 +76,7 @@ pub(crate) fn maybe_create_entry_wrapper( .unwrap(); let mut ctx = Context::new(); - ctx.func = Function::with_name_signature(ExternalName::user(0, 0), cmain_sig.clone()); + ctx.func = Function::with_name_signature(ExternalName::user(0, 0), cmain_sig); { let mut func_ctx = FunctionBuilderContext::new(); let mut bcx = FunctionBuilder::new(&mut ctx.func, &mut func_ctx); diff --git a/compiler/rustc_codegen_cranelift/src/metadata.rs b/compiler/rustc_codegen_cranelift/src/metadata.rs index 04369bf89fd2d..cda2a187ff9b7 100644 --- a/compiler/rustc_codegen_cranelift/src/metadata.rs +++ b/compiler/rustc_codegen_cranelift/src/metadata.rs @@ -29,7 +29,7 @@ impl MetadataLoader for CraneliftMetadataLoader { .expect("Rlib metadata file too big to load into memory."), ); ::std::io::copy(&mut entry, &mut buf).map_err(|e| format!("{:?}", e))?; - let buf: OwningRef, [u8]> = OwningRef::new(buf).into(); + let buf: OwningRef, [u8]> = OwningRef::new(buf); return Ok(rustc_erase_owner!(buf.map_owner_box())); } } @@ -47,7 +47,7 @@ impl MetadataLoader for CraneliftMetadataLoader { .data() .map_err(|e| format!("failed to read .rustc section: {:?}", e))? .to_owned(); - let buf: OwningRef, [u8]> = OwningRef::new(buf).into(); + let buf: OwningRef, [u8]> = OwningRef::new(buf); Ok(rustc_erase_owner!(buf.map_owner_box())) } } diff --git a/compiler/rustc_codegen_cranelift/src/num.rs b/compiler/rustc_codegen_cranelift/src/num.rs index b37826d71f4e0..41f4a9b9662bc 100644 --- a/compiler/rustc_codegen_cranelift/src/num.rs +++ b/compiler/rustc_codegen_cranelift/src/num.rs @@ -89,10 +89,10 @@ pub(crate) fn codegen_binop<'tcx>( } match in_lhs.layout().ty.kind() { - ty::Bool => crate::num::trans_bool_binop(fx, bin_op, in_lhs, in_rhs), - ty::Uint(_) | ty::Int(_) => crate::num::trans_int_binop(fx, bin_op, in_lhs, in_rhs), - ty::Float(_) => crate::num::trans_float_binop(fx, bin_op, in_lhs, in_rhs), - ty::RawPtr(..) | ty::FnPtr(..) => crate::num::trans_ptr_binop(fx, bin_op, in_lhs, in_rhs), + ty::Bool => crate::num::codegen_bool_binop(fx, bin_op, in_lhs, in_rhs), + ty::Uint(_) | ty::Int(_) => crate::num::codegen_int_binop(fx, bin_op, in_lhs, in_rhs), + ty::Float(_) => crate::num::codegen_float_binop(fx, bin_op, in_lhs, in_rhs), + ty::RawPtr(..) | ty::FnPtr(..) => crate::num::codegen_ptr_binop(fx, bin_op, in_lhs, in_rhs), _ => unreachable!( "{:?}({:?}, {:?})", bin_op, @@ -102,7 +102,7 @@ pub(crate) fn codegen_binop<'tcx>( } } -pub(crate) fn trans_bool_binop<'tcx>( +pub(crate) fn codegen_bool_binop<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, bin_op: BinOp, in_lhs: CValue<'tcx>, @@ -123,7 +123,7 @@ pub(crate) fn trans_bool_binop<'tcx>( CValue::by_val(res, fx.layout_of(fx.tcx.types.bool)) } -pub(crate) fn trans_int_binop<'tcx>( +pub(crate) fn codegen_int_binop<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, bin_op: BinOp, in_lhs: CValue<'tcx>, @@ -196,7 +196,7 @@ pub(crate) fn trans_int_binop<'tcx>( CValue::by_val(val, in_lhs.layout()) } -pub(crate) fn trans_checked_int_binop<'tcx>( +pub(crate) fn codegen_checked_int_binop<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, bin_op: BinOp, in_lhs: CValue<'tcx>, @@ -357,7 +357,7 @@ pub(crate) fn trans_checked_int_binop<'tcx>( out_place.to_cvalue(fx) } -pub(crate) fn trans_float_binop<'tcx>( +pub(crate) fn codegen_float_binop<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, bin_op: BinOp, in_lhs: CValue<'tcx>, @@ -402,7 +402,7 @@ pub(crate) fn trans_float_binop<'tcx>( CValue::by_val(res, in_lhs.layout()) } -pub(crate) fn trans_ptr_binop<'tcx>( +pub(crate) fn codegen_ptr_binop<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Module>, bin_op: BinOp, in_lhs: CValue<'tcx>, diff --git a/compiler/rustc_codegen_cranelift/src/optimize/stack2reg.rs b/compiler/rustc_codegen_cranelift/src/optimize/stack2reg.rs index f368d65f7f8d8..3c939d5a58639 100644 --- a/compiler/rustc_codegen_cranelift/src/optimize/stack2reg.rs +++ b/compiler/rustc_codegen_cranelift/src/optimize/stack2reg.rs @@ -228,7 +228,8 @@ pub(super) fn optimize_function( match *potential_stores { [] => { #[cfg(debug_assertions)] - clif_comments.add_comment(load, format!("[BUG?] Reading uninitialized memory")); + clif_comments + .add_comment(load, "[BUG?] Reading uninitialized memory".to_string()); } [store] if spatial_overlap(&opt_ctx.ctx.func, store, load) == SpatialOverlap::Full diff --git a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs index 7f8ab953d7199..ff878af7f5eef 100644 --- a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs +++ b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs @@ -131,11 +131,11 @@ impl FuncWriter for &'_ CommentWriter { if !comment.is_empty() { writeln!(w, "; {}", comment)?; } else { - writeln!(w, "")?; + writeln!(w)?; } } if !self.global_comments.is_empty() { - writeln!(w, "")?; + writeln!(w)?; } self.super_preamble(w, func, reg_info) @@ -153,7 +153,7 @@ impl FuncWriter for &'_ CommentWriter { if let Some(comment) = self.entity_comments.get(&entity) { writeln!(w, " ; {}", comment.replace('\n', "\n; ")) } else { - writeln!(w, "") + writeln!(w) } } @@ -261,7 +261,7 @@ pub(crate) fn write_clif_file<'tcx>( writeln!(file, "set is_pic")?; writeln!(file, "set enable_simd")?; writeln!(file, "target {} haswell", target_triple)?; - writeln!(file, "")?; + writeln!(file)?; file.write_all(clif.as_bytes())?; }; if let Err(err) = res { diff --git a/compiler/rustc_codegen_cranelift/src/trap.rs b/compiler/rustc_codegen_cranelift/src/trap.rs index 37dca77bdbd09..690d96764a8f5 100644 --- a/compiler/rustc_codegen_cranelift/src/trap.rs +++ b/compiler/rustc_codegen_cranelift/src/trap.rs @@ -67,4 +67,3 @@ pub(crate) fn trap_unimplemented(fx: &mut FunctionCx<'_, '_, impl Module>, msg: let true_ = fx.bcx.ins().iconst(types::I32, 1); fx.bcx.ins().trapnz(true_, TrapCode::User(!0)); } - diff --git a/compiler/rustc_codegen_cranelift/src/value_and_place.rs b/compiler/rustc_codegen_cranelift/src/value_and_place.rs index 5d513cb3ea022..2b9ea5273b608 100644 --- a/compiler/rustc_codegen_cranelift/src/value_and_place.rs +++ b/compiler/rustc_codegen_cranelift/src/value_and_place.rs @@ -27,10 +27,10 @@ fn codegen_field<'tcx>( return simple(fx); } match field_layout.ty.kind() { - ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(fx), + ty::Slice(..) | ty::Str | ty::Foreign(..) => simple(fx), ty::Adt(def, _) if def.repr.packed() => { assert_eq!(layout.align.abi.bytes(), 1); - return simple(fx); + simple(fx) } _ => { // We have to align the offset for DST's @@ -237,15 +237,12 @@ impl<'tcx> CValue<'tcx> { let clif_ty = fx.clif_type(layout.ty).unwrap(); - match layout.ty.kind() { - ty::Bool => { - assert!( - const_val == 0 || const_val == 1, - "Invalid bool 0x{:032X}", - const_val - ); - } - _ => {} + if let ty::Bool = layout.ty.kind() { + assert!( + const_val == 0 || const_val == 1, + "Invalid bool 0x{:032X}", + const_val + ); } let val = match layout.ty.kind() { @@ -335,7 +332,7 @@ impl<'tcx> CPlace<'tcx> { let stack_slot = fx.bcx.create_stack_slot(StackSlotData { kind: StackSlotKind::ExplicitSlot, - size: layout.size.bytes() as u32, + size: u32::try_from(layout.size.bytes()).unwrap(), offset: None, }); CPlace { @@ -533,6 +530,13 @@ impl<'tcx> CPlace<'tcx> { dst_ty: Type, ) { let src_ty = fx.bcx.func.dfg.value_type(data); + assert_eq!( + src_ty.bytes(), + dst_ty.bytes(), + "write_cvalue_transmute: {:?} -> {:?}", + src_ty, + dst_ty, + ); let data = match (src_ty, dst_ty) { (_, _) if src_ty == dst_ty => data, @@ -544,6 +548,17 @@ impl<'tcx> CPlace<'tcx> { _ if src_ty.is_vector() && dst_ty.is_vector() => { fx.bcx.ins().raw_bitcast(dst_ty, data) } + _ if src_ty.is_vector() || dst_ty.is_vector() => { + // FIXME do something more efficient for transmutes between vectors and integers. + let stack_slot = fx.bcx.create_stack_slot(StackSlotData { + kind: StackSlotKind::ExplicitSlot, + size: src_ty.bytes(), + offset: None, + }); + let ptr = Pointer::stack_slot(stack_slot); + ptr.store(fx, data, MemFlags::trusted()); + ptr.load(fx, dst_ty, MemFlags::trusted()) + } _ => unreachable!("write_cvalue_transmute: {:?} -> {:?}", src_ty, dst_ty), }; fx.bcx diff --git a/compiler/rustc_codegen_cranelift/src/vtable.rs b/compiler/rustc_codegen_cranelift/src/vtable.rs index bb3cf8b3f3a3a..238abc0d8bdfa 100644 --- a/compiler/rustc_codegen_cranelift/src/vtable.rs +++ b/compiler/rustc_codegen_cranelift/src/vtable.rs @@ -108,14 +108,14 @@ fn build_vtable<'tcx>( (&[]).iter() }; let methods = methods.cloned().map(|opt_mth| { - opt_mth.map_or(None, |(def_id, substs)| { - Some(import_function( + opt_mth.map(|(def_id, substs)| { + import_function( tcx, &mut fx.cx.module, Instance::resolve_for_vtable(tcx, ParamEnv::reveal_all(), def_id, substs) .unwrap() .polymorphize(fx.tcx), - )) + ) }) }); components.extend(methods); @@ -137,15 +137,7 @@ fn build_vtable<'tcx>( } } - data_ctx.set_align( - fx.tcx - .data_layout - .pointer_align - .pref - .bytes() - .try_into() - .unwrap(), - ); + data_ctx.set_align(fx.tcx.data_layout.pointer_align.pref.bytes()); let data_id = fx .cx diff --git a/compiler/rustc_codegen_cranelift/test.sh b/compiler/rustc_codegen_cranelift/test.sh index a1c4d9f287283..3cdd4119d794c 100755 --- a/compiler/rustc_codegen_cranelift/test.sh +++ b/compiler/rustc_codegen_cranelift/test.sh @@ -1,119 +1,15 @@ #!/bin/bash set -e -# Build cg_clif export RUSTFLAGS="-Zrun_dsymutil=no" -if [[ "$1" == "--release" ]]; then - export CHANNEL='release' - cargo build --release -else - export CHANNEL='debug' - cargo build --bin cg_clif -fi -# Config -source scripts/config.sh -export CG_CLIF_INCR_CACHE_DISABLED=1 -RUSTC=$RUSTC" "$RUSTFLAGS" -L crate=target/out --out-dir target/out -Cdebuginfo=2" +./build.sh --without-sysroot $@ -# Cleanup rm -r target/out || true -# Perform all tests -echo "[BUILD] mini_core" -$RUSTC example/mini_core.rs --crate-name mini_core --crate-type lib,dylib --target $TARGET_TRIPLE +scripts/tests.sh no_sysroot -echo "[BUILD] example" -$RUSTC example/example.rs --crate-type lib --target $TARGET_TRIPLE +./build.sh $@ -if [[ "$JIT_SUPPORTED" = "1" ]]; then - echo "[JIT] mini_core_hello_world" - CG_CLIF_JIT_ARGS="abc bcd" $RUSTC --jit example/mini_core_hello_world.rs --cfg jit --target $HOST_TRIPLE -else - echo "[JIT] mini_core_hello_world (skipped)" -fi - -echo "[AOT] mini_core_hello_world" -$RUSTC example/mini_core_hello_world.rs --crate-name mini_core_hello_world --crate-type bin -g --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/mini_core_hello_world abc bcd -# (echo "break set -n main"; echo "run"; sleep 1; echo "si -c 10"; sleep 1; echo "frame variable") | lldb -- ./target/out/mini_core_hello_world abc bcd - -echo "[AOT] arbitrary_self_types_pointers_and_wrappers" -$RUSTC example/arbitrary_self_types_pointers_and_wrappers.rs --crate-name arbitrary_self_types_pointers_and_wrappers --crate-type bin --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/arbitrary_self_types_pointers_and_wrappers - -echo "[BUILD] sysroot" -time ./build_sysroot/build_sysroot.sh --release - -echo "[AOT] alloc_example" -$RUSTC example/alloc_example.rs --crate-type bin --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/alloc_example - -if [[ "$JIT_SUPPORTED" = "1" ]]; then - echo "[JIT] std_example" - $RUSTC --jit example/std_example.rs --target $HOST_TRIPLE -else - echo "[JIT] std_example (skipped)" -fi - -echo "[AOT] dst_field_align" -# FIXME Re-add -Zmir-opt-level=2 once rust-lang/rust#67529 is fixed. -$RUSTC example/dst-field-align.rs --crate-name dst_field_align --crate-type bin --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/dst_field_align || (echo $?; false) - -echo "[AOT] std_example" -$RUSTC example/std_example.rs --crate-type bin --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/std_example arg - -echo "[AOT] subslice-patterns-const-eval" -$RUSTC example/subslice-patterns-const-eval.rs --crate-type bin -Cpanic=abort --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/subslice-patterns-const-eval - -echo "[AOT] track-caller-attribute" -$RUSTC example/track-caller-attribute.rs --crate-type bin -Cpanic=abort --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/track-caller-attribute - -echo "[AOT] mod_bench" -$RUSTC example/mod_bench.rs --crate-type bin --target $TARGET_TRIPLE -$RUN_WRAPPER ./target/out/mod_bench - -pushd rand -rm -r ./target || true -../cargo.sh test --workspace -popd - -pushd simple-raytracer -if [[ "$HOST_TRIPLE" = "$TARGET_TRIPLE" ]]; then - echo "[BENCH COMPILE] ebobby/simple-raytracer" - hyperfine --runs ${RUN_RUNS:-10} --warmup 1 --prepare "cargo clean" \ - "RUSTC=rustc RUSTFLAGS='' cargo build" \ - "../cargo.sh build" - - echo "[BENCH RUN] ebobby/simple-raytracer" - cp ./target/debug/main ./raytracer_cg_clif - hyperfine --runs ${RUN_RUNS:-10} ./raytracer_cg_llvm ./raytracer_cg_clif -else - echo "[BENCH COMPILE] ebobby/simple-raytracer (skipped)" - echo "[COMPILE] ebobby/simple-raytracer" - ../cargo.sh build - echo "[BENCH RUN] ebobby/simple-raytracer (skipped)" -fi -popd - -pushd build_sysroot/sysroot_src/library/core/tests -echo "[TEST] libcore" -rm -r ./target || true -../../../../../cargo.sh test -popd - -pushd regex -echo "[TEST] rust-lang/regex example shootout-regex-dna" -../cargo.sh clean -# Make sure `[codegen mono items] start` doesn't poison the diff -../cargo.sh build --example shootout-regex-dna -cat examples/regexdna-input.txt | ../cargo.sh run --example shootout-regex-dna | grep -v "Spawned thread" > res.txt -diff -u res.txt examples/regexdna-output.txt - -echo "[TEST] rust-lang/regex tests" -../cargo.sh test --tests -- --exclude-should-panic --test-threads 1 -Zunstable-options -popd +scripts/tests.sh base_sysroot +scripts/tests.sh extended_sysroot diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 73c1f73ec7fe9..ef1ae807453f2 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -801,6 +801,7 @@ fn file_metadata_raw( let kind = match hash.kind { rustc_span::SourceFileHashAlgorithm::Md5 => llvm::ChecksumKind::MD5, rustc_span::SourceFileHashAlgorithm::Sha1 => llvm::ChecksumKind::SHA1, + rustc_span::SourceFileHashAlgorithm::Sha256 => llvm::ChecksumKind::SHA256, }; (kind, hex_encode(hash.hash_bytes())) } diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index daceda20097da..8b15c8b0eb607 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -558,6 +558,7 @@ pub enum ChecksumKind { None, MD5, SHA1, + SHA256, } extern "C" { diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index b0e43a260e91d..b435def87ac84 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -793,7 +793,7 @@ impl SyntaxExtension { allow_internal_unsafe: sess.contains_name(attrs, sym::allow_internal_unsafe), local_inner_macros, stability, - deprecation: attr::find_deprecation(&sess, attrs, span), + deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d), helper_attrs, edition, is_builtin, diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 048f096aabe13..a1b7c13e4c0f0 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -2705,6 +2705,32 @@ declare_lint! { }; } +declare_lint! { + /// The `useless_deprecated` lint detects deprecation attributes with no effect. + /// + /// ### Example + /// + /// ```rust,compile_fail + /// struct X; + /// + /// #[deprecated = "message"] + /// impl Default for X { + /// fn default() -> Self { + /// X + /// } + /// } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Deprecation attributes have no effect on trait implementations. + pub USELESS_DEPRECATED, + Deny, + "detects deprecation attributes with no effect", +} + declare_tool_lint! { pub rustc::INEFFECTIVE_UNSTABLE_TRAIT_IMPL, Deny, @@ -2792,6 +2818,7 @@ declare_lint_pass! { INEFFECTIVE_UNSTABLE_TRAIT_IMPL, UNINHABITED_STATIC, FUNCTION_ITEM_REFERENCES, + USELESS_DEPRECATED, ] } diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 40a1043424848..938eb19faef6b 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -648,6 +648,7 @@ enum class LLVMRustChecksumKind { None, MD5, SHA1, + SHA256, }; static Optional fromRust(LLVMRustChecksumKind Kind) { @@ -658,6 +659,10 @@ static Optional fromRust(LLVMRustChecksumKind Kind) { return DIFile::ChecksumKind::CSK_MD5; case LLVMRustChecksumKind::SHA1: return DIFile::ChecksumKind::CSK_SHA1; +#if (LLVM_VERSION_MAJOR >= 11) + case LLVMRustChecksumKind::SHA256: + return DIFile::ChecksumKind::CSK_SHA256; +#endif default: report_fatal_error("bad ChecksumKind."); } diff --git a/compiler/rustc_mir/src/transform/function_item_references.rs b/compiler/rustc_mir/src/transform/function_item_references.rs index 61427422e4b59..d592580af9cec 100644 --- a/compiler/rustc_mir/src/transform/function_item_references.rs +++ b/compiler/rustc_mir/src/transform/function_item_references.rs @@ -51,10 +51,11 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { let arg_ty = args[0].ty(self.body, self.tcx); for generic_inner_ty in arg_ty.walk() { if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() { - if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(inner_ty) { - let ident = self.tcx.item_name(fn_id).to_ident_string(); + if let Some((fn_id, fn_substs)) = + FunctionItemRefChecker::is_fn_ref(inner_ty) + { let span = self.nth_arg_span(&args, 0); - self.emit_lint(ident, fn_id, source_info, span); + self.emit_lint(fn_id, fn_substs, source_info, span); } } } @@ -66,6 +67,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { } self.super_terminator(terminator, location); } + /// Emits a lint for function references formatted with `fmt::Pointer::fmt` by macros. These /// cases are handled as operands instead of call terminators to avoid any dependence on /// unstable, internal formatting details like whether `fmt` is called directly or not. @@ -76,13 +78,12 @@ impl<'a, 'tcx> Visitor<'tcx> for FunctionItemRefChecker<'a, 'tcx> { if let ty::FnDef(def_id, substs_ref) = *op_ty.kind() { if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) { let param_ty = substs_ref.type_at(0); - if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(param_ty) { + if let Some((fn_id, fn_substs)) = FunctionItemRefChecker::is_fn_ref(param_ty) { // The operand's ctxt wouldn't display the lint since it's inside a macro so // we have to use the callsite's ctxt. let callsite_ctxt = source_info.span.source_callsite().ctxt(); let span = source_info.span.with_ctxt(callsite_ctxt); - let ident = self.tcx.item_name(fn_id).to_ident_string(); - self.emit_lint(ident, fn_id, source_info, span); + self.emit_lint(fn_id, fn_substs, source_info, span); } } } @@ -115,10 +116,11 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { if TyS::same_type(inner_ty, bound_ty) { // Do a substitution using the parameters from the callsite let subst_ty = inner_ty.subst(self.tcx, substs_ref); - if let Some(fn_id) = FunctionItemRefChecker::is_fn_ref(subst_ty) { - let ident = self.tcx.item_name(fn_id).to_ident_string(); + if let Some((fn_id, fn_substs)) = + FunctionItemRefChecker::is_fn_ref(subst_ty) + { let span = self.nth_arg_span(args, arg_num); - self.emit_lint(ident, fn_id, source_info, span); + self.emit_lint(fn_id, fn_substs, source_info, span); } } } @@ -127,6 +129,7 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { } } } + /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type. fn is_pointer_trait(&self, bound: &PredicateAtom<'tcx>) -> Option> { if let ty::PredicateAtom::Trait(predicate, _) = bound { @@ -139,22 +142,26 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { None } } + /// If a type is a reference or raw pointer to the anonymous type of a function definition, - /// returns that function's `DefId`. - fn is_fn_ref(ty: Ty<'tcx>) -> Option { + /// returns that function's `DefId` and `SubstsRef`. + fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, SubstsRef<'tcx>)> { let referent_ty = match ty.kind() { ty::Ref(_, referent_ty, _) => Some(referent_ty), ty::RawPtr(ty_and_mut) => Some(&ty_and_mut.ty), _ => None, }; referent_ty - .map( - |ref_ty| { - if let ty::FnDef(def_id, _) = *ref_ty.kind() { Some(def_id) } else { None } - }, - ) + .map(|ref_ty| { + if let ty::FnDef(def_id, substs_ref) = *ref_ty.kind() { + Some((def_id, substs_ref)) + } else { + None + } + }) .unwrap_or(None) } + fn nth_arg_span(&self, args: &Vec>, n: usize) -> Span { match &args[n] { Operand::Copy(place) | Operand::Move(place) => { @@ -163,7 +170,14 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { Operand::Constant(constant) => constant.span, } } - fn emit_lint(&self, ident: String, fn_id: DefId, source_info: SourceInfo, span: Span) { + + fn emit_lint( + &self, + fn_id: DefId, + fn_substs: SubstsRef<'tcx>, + source_info: SourceInfo, + span: Span, + ) { let lint_root = self.body.source_scopes[source_info.scope] .local_data .as_ref() @@ -180,6 +194,10 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { s } }; + let ident = self.tcx.item_name(fn_id).to_ident_string(); + let ty_params = fn_substs.types().map(|ty| format!("{}", ty)); + let const_params = fn_substs.consts().map(|c| format!("{}", c)); + let params = ty_params.chain(const_params).collect::>().join(", "); let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" }; @@ -190,7 +208,7 @@ impl<'a, 'tcx> FunctionItemRefChecker<'a, 'tcx> { &format!("cast `{}` to obtain a function pointer", ident), format!( "{} as {}{}fn({}{}){}", - ident, + if params.is_empty() { ident } else { format!("{}::<{}>", ident, params) }, unsafety, abi, vec!["_"; num_args].join(", "), diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index c9497f2a5b2b0..04b5c65e464fb 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -15,7 +15,7 @@ use rustc_middle::middle::privacy::AccessLevels; use rustc_middle::middle::stability::{DeprecationEntry, Index}; use rustc_middle::ty::{self, query::Providers, TyCtxt}; use rustc_session::lint; -use rustc_session::lint::builtin::INEFFECTIVE_UNSTABLE_TRAIT_IMPL; +use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED}; use rustc_session::parse::feature_err; use rustc_session::Session; use rustc_span::symbol::{sym, Symbol}; @@ -31,6 +31,8 @@ enum AnnotationKind { Required, // Annotation is useless, reject it Prohibited, + // Deprecation annotation is useless, reject it. (Stability attribute is still required.) + DeprecationProhibited, // Annotation itself is useless, but it can be propagated to children Container, } @@ -83,14 +85,22 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { did_error = self.forbid_staged_api_attrs(hir_id, attrs, inherit_deprecation.clone()); } - let depr = - if did_error { None } else { attr::find_deprecation(&self.tcx.sess, attrs, item_sp) }; + let depr = if did_error { None } else { attr::find_deprecation(&self.tcx.sess, attrs) }; let mut is_deprecated = false; - if let Some(depr) = &depr { + if let Some((depr, span)) = &depr { is_deprecated = true; - if kind == AnnotationKind::Prohibited { - self.tcx.sess.span_err(item_sp, "This deprecation annotation is useless"); + if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited { + self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| { + lint.build("this `#[deprecated]` annotation has no effect") + .span_suggestion_short( + *span, + "remove the unnecessary deprecation attribute", + String::new(), + rustc_errors::Applicability::MachineApplicable, + ) + .emit() + }); } // `Deprecation` is just two pointers, no need to intern it @@ -114,7 +124,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } } else { self.recurse_with_stability_attrs( - depr.map(|d| DeprecationEntry::local(d, hir_id)), + depr.map(|(d, _)| DeprecationEntry::local(d, hir_id)), None, None, visit_children, @@ -139,11 +149,11 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } } - if depr.as_ref().map_or(false, |d| d.is_since_rustc_version) { + if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr { if stab.is_none() { struct_span_err!( self.tcx.sess, - item_sp, + *span, E0549, "rustc_deprecated attribute must be paired with \ either stable or unstable attribute" @@ -166,7 +176,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { // Check if deprecated_since < stable_since. If it is, // this is *almost surely* an accident. if let (&Some(dep_since), &attr::Stable { since: stab_since }) = - (&depr.as_ref().and_then(|d| d.since), &stab.level) + (&depr.as_ref().and_then(|(d, _)| d.since), &stab.level) { // Explicit version of iter::order::lt to handle parse errors properly for (dep_v, stab_v) in @@ -212,7 +222,7 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> { } self.recurse_with_stability_attrs( - depr.map(|d| DeprecationEntry::local(d, hir_id)), + depr.map(|(d, _)| DeprecationEntry::local(d, hir_id)), stab, const_stab, visit_children, @@ -322,6 +332,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } hir::ItemKind::Impl { of_trait: Some(_), .. } => { self.in_trait_impl = true; + kind = AnnotationKind::DeprecationProhibited; } hir::ItemKind::Struct(ref sd, _) => { if let Some(ctor_hir_id) = sd.ctor_hir_id() { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 492457dde8318..4c00361dd31df 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1076,7 +1076,7 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, span_free_formats: bool = (false, parse_bool, [UNTRACKED], "exclude spans when debug-printing compiler state (default: no)"), src_hash_algorithm: Option = (None, parse_src_file_hash, [TRACKED], - "hash algorithm of source files in debug info (`md5`, or `sha1`)"), + "hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`)"), strip: Strip = (Strip::None, parse_strip, [UNTRACKED], "tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`)"), symbol_mangling_version: SymbolManglingVersion = (SymbolManglingVersion::Legacy, diff --git a/compiler/rustc_span/Cargo.toml b/compiler/rustc_span/Cargo.toml index 1abfd50f00364..08645990c4870 100644 --- a/compiler/rustc_span/Cargo.toml +++ b/compiler/rustc_span/Cargo.toml @@ -17,5 +17,6 @@ scoped-tls = "1.0" unicode-width = "0.1.4" cfg-if = "0.1.2" tracing = "0.1" -sha-1 = "0.8" -md-5 = "0.8" +sha-1 = "0.9" +sha2 = "0.9" +md-5 = "0.9" diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 0e3027273abbc..97b5c11b0fefb 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -59,6 +59,7 @@ use std::str::FromStr; use md5::Md5; use sha1::Digest; use sha1::Sha1; +use sha2::Sha256; use tracing::debug; @@ -1034,6 +1035,7 @@ pub struct OffsetOverflowError; pub enum SourceFileHashAlgorithm { Md5, Sha1, + Sha256, } impl FromStr for SourceFileHashAlgorithm { @@ -1043,6 +1045,7 @@ impl FromStr for SourceFileHashAlgorithm { match s { "md5" => Ok(SourceFileHashAlgorithm::Md5), "sha1" => Ok(SourceFileHashAlgorithm::Sha1), + "sha256" => Ok(SourceFileHashAlgorithm::Sha256), _ => Err(()), } } @@ -1055,7 +1058,7 @@ rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); #[derive(HashStable_Generic, Encodable, Decodable)] pub struct SourceFileHash { pub kind: SourceFileHashAlgorithm, - value: [u8; 20], + value: [u8; 32], } impl SourceFileHash { @@ -1071,6 +1074,9 @@ impl SourceFileHash { SourceFileHashAlgorithm::Sha1 => { value.copy_from_slice(&Sha1::digest(data)); } + SourceFileHashAlgorithm::Sha256 => { + value.copy_from_slice(&Sha256::digest(data)); + } } hash } @@ -1090,6 +1096,7 @@ impl SourceFileHash { match self.kind { SourceFileHashAlgorithm::Md5 => 16, SourceFileHashAlgorithm::Sha1 => 20, + SourceFileHashAlgorithm::Sha256 => 32, } } } diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 593d1c4ae884e..0878b0ff78930 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -1119,6 +1119,10 @@ impl Build { let krate = &self.crates[&krate]; ret.push(krate); for dep in &krate.deps { + if !self.crates.contains_key(dep) { + // Ignore non-workspace members. + continue; + } // Don't include optional deps if their features are not // enabled. Ideally this would be computed from `cargo // metadata --features …`, but that is somewhat slow. Just diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 6c2c05ac7197e..5a73f58304501 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -970,7 +970,8 @@ impl Step for Compiletest { if builder.top_stage == 0 && env::var("COMPILETEST_FORCE_STAGE0").is_err() { eprintln!("\ error: `--stage 0` runs compiletest on the beta compiler, not your local changes, and will almost always cause tests to fail -help: use `--stage 1` instead +help: to test the compiler, use `--stage 1` instead +help: to test the standard library, use `--stage 0 library/std` instead note: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`." ); std::process::exit(1); diff --git a/src/doc/unstable-book/src/compiler-flags/src-hash-algorithm.md b/src/doc/unstable-book/src/compiler-flags/src-hash-algorithm.md index 5a7d0655a440a..ff776741b2122 100644 --- a/src/doc/unstable-book/src/compiler-flags/src-hash-algorithm.md +++ b/src/doc/unstable-book/src/compiler-flags/src-hash-algorithm.md @@ -6,6 +6,6 @@ The tracking issue for this feature is: [#70401](https://github.com/rust-lang/ru The `-Z src-hash-algorithm` compiler flag controls which algorithm is used when hashing each source file. The hash is stored in the debug info and can be used by a debugger to verify the source code matches the executable. -Supported hash algorithms are: `md5`, and `sha1`. Note that not all hash algorithms are supported by all debug info formats. +Supported hash algorithms are: `md5`, `sha1`, and `sha256`. Note that not all hash algorithms are supported by all debug info formats. By default, the compiler chooses the hash algorithm based on the target specification. diff --git a/src/etc/lldb_batchmode.py b/src/etc/lldb_batchmode.py index 629c8e04ec533..fc355c87b52a2 100644 --- a/src/etc/lldb_batchmode.py +++ b/src/etc/lldb_batchmode.py @@ -28,7 +28,7 @@ import _thread as thread # Set this to True for additional output -DEBUG_OUTPUT = False +DEBUG_OUTPUT = True def print_debug(s): @@ -102,7 +102,7 @@ def execute_command(command_interpreter, command): registered_breakpoints.add(breakpoint_id) else: print("Error while trying to register breakpoint callback, id = " + - str(breakpoint_id)) + str(breakpoint_id) + ", message = " + str(res.GetError())) else: print(res.GetError()) diff --git a/src/test/codegen/src-hash-algorithm/src-hash-algorithm-sha256.rs b/src/test/codegen/src-hash-algorithm/src-hash-algorithm-sha256.rs new file mode 100644 index 0000000000000..eaa9eafa1e872 --- /dev/null +++ b/src/test/codegen/src-hash-algorithm/src-hash-algorithm-sha256.rs @@ -0,0 +1,7 @@ +// compile-flags: -g -Z src-hash-algorithm=sha256 +// min-llvm-version: 11.0 + +#![crate_type = "lib"] + +pub fn test() {} +// CHECK: checksumkind: CSK_SHA256 diff --git a/src/test/ui/deprecation/deprecation-sanity.rs b/src/test/ui/deprecation/deprecation-sanity.rs index a559908b792bb..4fc3fddadb99e 100644 --- a/src/test/ui/deprecation/deprecation-sanity.rs +++ b/src/test/ui/deprecation/deprecation-sanity.rs @@ -24,10 +24,19 @@ mod bogus_attribute_types_1 { } #[deprecated(since = "a", note = "b")] -#[deprecated(since = "a", note = "b")] -fn multiple1() { } //~ ERROR multiple deprecated attributes +#[deprecated(since = "a", note = "b")] //~ ERROR multiple deprecated attributes +fn multiple1() { } #[deprecated(since = "a", since = "b", note = "c")] //~ ERROR multiple 'since' items fn f1() { } +struct X; + +#[deprecated = "hello"] //~ ERROR this `#[deprecated]` annotation has no effect +impl Default for X { + fn default() -> Self { + X + } +} + fn main() { } diff --git a/src/test/ui/deprecation/deprecation-sanity.stderr b/src/test/ui/deprecation/deprecation-sanity.stderr index 57143d6810554..7e70c35eeabdf 100644 --- a/src/test/ui/deprecation/deprecation-sanity.stderr +++ b/src/test/ui/deprecation/deprecation-sanity.stderr @@ -41,10 +41,12 @@ LL | #[deprecated("test")] | ^^^^^^ error[E0550]: multiple deprecated attributes - --> $DIR/deprecation-sanity.rs:28:1 + --> $DIR/deprecation-sanity.rs:27:1 | -LL | fn multiple1() { } - | ^^^^^^^^^^^^^^^^^^ +LL | #[deprecated(since = "a", note = "b")] + | -------------------------------------- first deprecation attribute +LL | #[deprecated(since = "a", note = "b")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ repeated deprecation attribute error[E0538]: multiple 'since' items --> $DIR/deprecation-sanity.rs:30:27 @@ -52,7 +54,15 @@ error[E0538]: multiple 'since' items LL | #[deprecated(since = "a", since = "b", note = "c")] | ^^^^^^^^^^^ -error: aborting due to 9 previous errors +error: this `#[deprecated]` annotation has no effect + --> $DIR/deprecation-sanity.rs:35:1 + | +LL | #[deprecated = "hello"] + | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove the unnecessary deprecation attribute + | + = note: `#[deny(useless_deprecated)]` on by default + +error: aborting due to 10 previous errors Some errors have detailed explanations: E0538, E0541, E0550, E0551, E0565. For more information about an error, try `rustc --explain E0538`. diff --git a/src/test/ui/lint/function-item-references.rs b/src/test/ui/lint/function-item-references.rs index 439b56967d072..5f7f5e66eaa9f 100644 --- a/src/test/ui/lint/function-item-references.rs +++ b/src/test/ui/lint/function-item-references.rs @@ -1,5 +1,5 @@ // check-pass -#![feature(c_variadic)] +#![feature(c_variadic, min_const_generics)] #![warn(function_item_references)] use std::fmt::Pointer; use std::fmt::Formatter; @@ -12,6 +12,10 @@ unsafe fn unsafe_fn() { } extern "C" fn c_fn() { } unsafe extern "C" fn unsafe_c_fn() { } unsafe extern fn variadic(_x: u32, _args: ...) { } +fn take_generic_ref<'a, T>(_x: &'a T) { } +fn take_generic_array(_x: [T; N]) { } +fn multiple_generic(_x: T, _y: U) { } +fn multiple_generic_arrays(_x: [T; N], _y: [U; M]) { } //function references passed to these functions should never lint fn call_fn(f: &dyn Fn(u32) -> u32, x: u32) { f(x); } @@ -109,6 +113,14 @@ fn main() { //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &variadic); //~^ WARNING taking a reference to a function item does not give a function pointer + println!("{:p}", &take_generic_ref::); + //~^ WARNING taking a reference to a function item does not give a function pointer + println!("{:p}", &take_generic_array::); + //~^ WARNING taking a reference to a function item does not give a function pointer + println!("{:p}", &multiple_generic::); + //~^ WARNING taking a reference to a function item does not give a function pointer + println!("{:p}", &multiple_generic_arrays::); + //~^ WARNING taking a reference to a function item does not give a function pointer println!("{:p}", &std::env::var::); //~^ WARNING taking a reference to a function item does not give a function pointer @@ -132,6 +144,8 @@ fn main() { std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); //~^ WARNING taking a reference to a function item does not give a function pointer //~^^ WARNING taking a reference to a function item does not give a function pointer + std::mem::transmute::<_, usize>(&take_generic_ref::); + //~^ WARNING taking a reference to a function item does not give a function pointer //the correct way to transmute function pointers std::mem::transmute::<_, usize>(foo as fn() -> u32); diff --git a/src/test/ui/lint/function-item-references.stderr b/src/test/ui/lint/function-item-references.stderr index 610dff04e6edf..33db687df31d2 100644 --- a/src/test/ui/lint/function-item-references.stderr +++ b/src/test/ui/lint/function-item-references.stderr @@ -1,5 +1,5 @@ warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:40:18 + --> $DIR/function-item-references.rs:44:18 | LL | Pointer::fmt(&zst_ref, f) | ^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` @@ -11,166 +11,196 @@ LL | #![warn(function_item_references)] | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:77:22 + --> $DIR/function-item-references.rs:81:22 | LL | println!("{:p}", &foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:79:20 + --> $DIR/function-item-references.rs:83:20 | LL | print!("{:p}", &foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:81:21 + --> $DIR/function-item-references.rs:85:21 | LL | format!("{:p}", &foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:84:22 + --> $DIR/function-item-references.rs:88:22 | LL | println!("{:p}", &foo as *const _); | ^^^^^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:86:22 + --> $DIR/function-item-references.rs:90:22 | LL | println!("{:p}", zst_ref); | ^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:88:22 + --> $DIR/function-item-references.rs:92:22 | LL | println!("{:p}", cast_zst_ptr); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:90:22 + --> $DIR/function-item-references.rs:94:22 | LL | println!("{:p}", coerced_zst_ptr); | ^^^^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:93:22 + --> $DIR/function-item-references.rs:97:22 | LL | println!("{:p}", &fn_item); | ^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:95:22 + --> $DIR/function-item-references.rs:99:22 | LL | println!("{:p}", indirect_ref); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:98:22 + --> $DIR/function-item-references.rs:102:22 | LL | println!("{:p}", &nop); | ^^^^ help: cast `nop` to obtain a function pointer: `nop as fn()` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:100:22 + --> $DIR/function-item-references.rs:104:22 | LL | println!("{:p}", &bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:102:22 + --> $DIR/function-item-references.rs:106:22 | LL | println!("{:p}", &baz); | ^^^^ help: cast `baz` to obtain a function pointer: `baz as fn(_, _) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:104:22 + --> $DIR/function-item-references.rs:108:22 | LL | println!("{:p}", &unsafe_fn); | ^^^^^^^^^^ help: cast `unsafe_fn` to obtain a function pointer: `unsafe_fn as unsafe fn()` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:106:22 + --> $DIR/function-item-references.rs:110:22 | LL | println!("{:p}", &c_fn); | ^^^^^ help: cast `c_fn` to obtain a function pointer: `c_fn as extern "C" fn()` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:108:22 + --> $DIR/function-item-references.rs:112:22 | LL | println!("{:p}", &unsafe_c_fn); | ^^^^^^^^^^^^ help: cast `unsafe_c_fn` to obtain a function pointer: `unsafe_c_fn as unsafe extern "C" fn()` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:110:22 + --> $DIR/function-item-references.rs:114:22 | LL | println!("{:p}", &variadic); | ^^^^^^^^^ help: cast `variadic` to obtain a function pointer: `variadic as unsafe extern "C" fn(_, ...)` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:112:22 + --> $DIR/function-item-references.rs:116:22 + | +LL | println!("{:p}", &take_generic_ref::); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `take_generic_ref` to obtain a function pointer: `take_generic_ref:: as fn(_)` + +warning: taking a reference to a function item does not give a function pointer + --> $DIR/function-item-references.rs:118:22 + | +LL | println!("{:p}", &take_generic_array::); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `take_generic_array` to obtain a function pointer: `take_generic_array:: as fn(_)` + +warning: taking a reference to a function item does not give a function pointer + --> $DIR/function-item-references.rs:120:22 + | +LL | println!("{:p}", &multiple_generic::); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `multiple_generic` to obtain a function pointer: `multiple_generic:: as fn(_, _)` + +warning: taking a reference to a function item does not give a function pointer + --> $DIR/function-item-references.rs:122:22 + | +LL | println!("{:p}", &multiple_generic_arrays::); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `multiple_generic_arrays` to obtain a function pointer: `multiple_generic_arrays:: as fn(_, _)` + +warning: taking a reference to a function item does not give a function pointer + --> $DIR/function-item-references.rs:124:22 | LL | println!("{:p}", &std::env::var::); - | ^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `var` to obtain a function pointer: `var as fn(_) -> _` + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `var` to obtain a function pointer: `var:: as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:115:32 + --> $DIR/function-item-references.rs:127:32 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ help: cast `nop` to obtain a function pointer: `nop as fn()` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:115:38 + --> $DIR/function-item-references.rs:127:38 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:115:44 + --> $DIR/function-item-references.rs:127:44 | LL | println!("{:p} {:p} {:p}", &nop, &foo, &bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:130:41 + --> $DIR/function-item-references.rs:142:41 | LL | std::mem::transmute::<_, usize>(&foo); | ^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:132:50 + --> $DIR/function-item-references.rs:144:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:132:50 + --> $DIR/function-item-references.rs:144:50 | LL | std::mem::transmute::<_, (usize, usize)>((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:142:15 + --> $DIR/function-item-references.rs:147:41 + | +LL | std::mem::transmute::<_, usize>(&take_generic_ref::); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: cast `take_generic_ref` to obtain a function pointer: `take_generic_ref:: as fn(_)` + +warning: taking a reference to a function item does not give a function pointer + --> $DIR/function-item-references.rs:156:15 | LL | print_ptr(&bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:144:24 + --> $DIR/function-item-references.rs:158:24 | LL | bound_by_ptr_trait(&bar); | ^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:146:30 + --> $DIR/function-item-references.rs:160:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `bar` to obtain a function pointer: `bar as fn(_) -> _` warning: taking a reference to a function item does not give a function pointer - --> $DIR/function-item-references.rs:146:30 + --> $DIR/function-item-references.rs:160:30 | LL | bound_by_ptr_trait_tuple((&foo, &bar)); | ^^^^^^^^^^^^ help: cast `foo` to obtain a function pointer: `foo as fn() -> _` -warning: 28 warnings emitted +warning: 33 warnings emitted diff --git a/src/test/ui/stability-attribute/stability-attribute-sanity.rs b/src/test/ui/stability-attribute/stability-attribute-sanity.rs index 80d7ae6dc637d..abd603b356ee6 100644 --- a/src/test/ui/stability-attribute/stability-attribute-sanity.rs +++ b/src/test/ui/stability-attribute/stability-attribute-sanity.rs @@ -59,14 +59,14 @@ fn multiple3() { } #[stable(feature = "a", since = "b")] #[rustc_deprecated(since = "b", reason = "text")] -#[rustc_deprecated(since = "b", reason = "text")] +#[rustc_deprecated(since = "b", reason = "text")] //~ ERROR multiple deprecated attributes #[rustc_const_unstable(feature = "c", issue = "none")] #[rustc_const_unstable(feature = "d", issue = "none")] //~ ERROR multiple stability levels -pub const fn multiple4() { } //~ ERROR multiple deprecated attributes +pub const fn multiple4() { } //~^ ERROR Invalid stability or deprecation version found #[rustc_deprecated(since = "a", reason = "text")] fn deprecated_without_unstable_or_stable() { } -//~^ ERROR rustc_deprecated attribute must be paired with either stable or unstable attribute +//~^^ ERROR rustc_deprecated attribute must be paired with either stable or unstable attribute fn main() { } diff --git a/src/test/ui/stability-attribute/stability-attribute-sanity.stderr b/src/test/ui/stability-attribute/stability-attribute-sanity.stderr index 134c657c62015..bf2436a535fd4 100644 --- a/src/test/ui/stability-attribute/stability-attribute-sanity.stderr +++ b/src/test/ui/stability-attribute/stability-attribute-sanity.stderr @@ -83,10 +83,12 @@ LL | #[stable(feature = "a", since = "b")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0550]: multiple deprecated attributes - --> $DIR/stability-attribute-sanity.rs:65:1 + --> $DIR/stability-attribute-sanity.rs:62:1 | -LL | pub const fn multiple4() { } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_deprecated(since = "b", reason = "text")] + | ------------------------------------------------- first deprecation attribute +LL | #[rustc_deprecated(since = "b", reason = "text")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ repeated deprecation attribute error[E0544]: multiple stability levels --> $DIR/stability-attribute-sanity.rs:64:1 @@ -101,10 +103,10 @@ LL | pub const fn multiple4() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0549]: rustc_deprecated attribute must be paired with either stable or unstable attribute - --> $DIR/stability-attribute-sanity.rs:69:1 + --> $DIR/stability-attribute-sanity.rs:68:1 | -LL | fn deprecated_without_unstable_or_stable() { } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_deprecated(since = "a", reason = "text")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 18 previous errors diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 0c52fee68a968..057b0884e287a 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -80,6 +80,7 @@ const PERMITTED_DEPENDENCIES: &[&str] = &[ "cloudabi", "cmake", "compiler_builtins", + "cpuid-bool", "crc32fast", "crossbeam-deque", "crossbeam-epoch", @@ -160,6 +161,7 @@ const PERMITTED_DEPENDENCIES: &[&str] = &[ "serde", "serde_derive", "sha-1", + "sha2", "smallvec", "snap", "stable_deref_trait",