From 4281c2c3d5b6fe4ef4c6cf659c20da42209f2289 Mon Sep 17 00:00:00 2001 From: DianQK Date: Wed, 19 Jun 2024 21:20:38 +0800 Subject: [PATCH 01/24] patch `rust-lld` and `ld.lld` on NixOS --- src/bootstrap/bootstrap.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 9861121aac0a3..7e47b373ff9df 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -617,6 +617,9 @@ def download_toolchain(self): self.fix_bin_or_dylib("{}/bin/rustdoc".format(bin_root)) self.fix_bin_or_dylib("{}/libexec/rust-analyzer-proc-macro-srv".format(bin_root)) lib_dir = "{}/lib".format(bin_root) + rustlib_bin_dir = "{}/rustlib/{}/bin".format(lib_dir, self.build) + self.fix_bin_or_dylib("{}/rust-lld".format(rustlib_bin_dir)) + self.fix_bin_or_dylib("{}/gcc-ld/ld.lld".format(rustlib_bin_dir)) for lib in os.listdir(lib_dir): # .so is not necessarily the suffix, there can be version numbers afterwards. if ".so" in lib: @@ -731,12 +734,9 @@ def fix_bin_or_dylib(self, fname): patchelf = "{}/bin/patchelf".format(nix_deps_dir) rpath_entries = [ - # Relative default, all binary and dynamic libraries we ship - # appear to have this (even when `../lib` is redundant). - "$ORIGIN/../lib", os.path.join(os.path.realpath(nix_deps_dir), "lib") ] - patchelf_args = ["--set-rpath", ":".join(rpath_entries)] + patchelf_args = ["--add-rpath", ":".join(rpath_entries)] if ".so" not in fname: # Finally, set the correct .interp for binaries with open("{}/nix-support/dynamic-linker".format(nix_deps_dir)) as dynamic_linker: From 80e43c128cf24f143a1bf58ffa972e78633cf8e9 Mon Sep 17 00:00:00 2001 From: DianQK Date: Wed, 19 Jun 2024 21:32:18 +0800 Subject: [PATCH 02/24] patch an ELF file using `--add-rpath` --- src/bootstrap/src/core/download.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 2b11b8c3d4f2b..fd077ab2d7c7a 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -173,15 +173,10 @@ impl Config { } let mut patchelf = Command::new(nix_deps_dir.join("bin/patchelf")); - let rpath_entries = { - // ORIGIN is a relative default, all binary and dynamic libraries we ship - // appear to have this (even when `../lib` is redundant). - // NOTE: there are only two paths here, delimited by a `:` - let mut entries = OsString::from("$ORIGIN/../lib:"); - entries.push(t!(fs::canonicalize(nix_deps_dir)).join("lib")); - entries - }; - patchelf.args(&[OsString::from("--set-rpath"), rpath_entries]); + patchelf.args(&[ + OsString::from("--add-rpath"), + OsString::from(t!(fs::canonicalize(nix_deps_dir)).join("lib")), + ]); if !path_is_dylib(fname) { // Finally, set the correct .interp for binaries let dynamic_linker_path = nix_deps_dir.join("nix-support/dynamic-linker"); From 08fa5f0460c8b9a0fd5aeed0aa78a7864edf5aff Mon Sep 17 00:00:00 2001 From: onur-ozkan Date: Thu, 20 Jun 2024 11:06:32 +0300 Subject: [PATCH 03/24] bootstrap-rustdoc: use current stage if download-rustc enabled When using download-rustc, using stage 1 rustdoc results in the wrong librustc_driver being used. ```sh $ ./build/host/stage1/bin/rustdoc --version ./build/host/stage1/bin/rustdoc: error while loading shared libraries: librustc_driver-7ff02ed05016d515.so: cannot open shared object file: No such file or directory ``` This change fixes that by not cutting the stage if download-rustc is enabled. Signed-off-by: onur-ozkan --- src/bootstrap/src/core/build_steps/tool.rs | 23 +++++++++++----------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 613484788b608..abda29b790ef4 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -476,24 +476,23 @@ impl Step for Rustdoc { return builder.initial_rustc.with_file_name(exe("rustdoc", target_compiler.host)); } let target = target_compiler.host; - // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise - // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage - // compilers, which isn't what we want. Rustdoc should be linked in the same way as the - // rustc compiler it's paired with, so it must be built with the previous stage compiler. - let build_compiler = builder.compiler(target_compiler.stage - 1, builder.config.build); + + let build_compiler = if builder.download_rustc() && target_compiler.stage == 1 { + // We already have the stage 1 compiler, we don't need to cut the stage. + builder.compiler(target_compiler.stage, builder.config.build) + } else { + // Similar to `compile::Assemble`, build with the previous stage's compiler. Otherwise + // we'd have stageN/bin/rustc and stageN/bin/rustdoc be effectively different stage + // compilers, which isn't what we want. Rustdoc should be linked in the same way as the + // rustc compiler it's paired with, so it must be built with the previous stage compiler. + builder.compiler(target_compiler.stage - 1, builder.config.build) + }; // When using `download-rustc` and a stage0 build_compiler, copying rustc doesn't actually // build stage0 libstd (because the libstd in sysroot has the wrong ABI). Explicitly build // it. builder.ensure(compile::Std::new(build_compiler, target_compiler.host)); builder.ensure(compile::Rustc::new(build_compiler, target_compiler.host)); - // NOTE: this implies that `download-rustc` is pretty useless when compiling with the stage0 - // compiler, since you do just as much work. - if !builder.config.dry_run() && builder.download_rustc() && build_compiler.stage == 0 { - println!( - "WARNING: `download-rustc` does nothing when building stage1 tools; consider using `--stage 2` instead" - ); - } // The presence of `target_compiler` ensures that the necessary libraries (codegen backends, // compiler libraries, ...) are built. Rustdoc does not require the presence of any From aa30dd444b00248065d9c286527bf9168c9cfb4b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 15 May 2024 15:23:49 +1000 Subject: [PATCH 04/24] Fix a typo in a comment. --- compiler/rustc_ast/src/tokenstream.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 3d46415507def..b4ddbe20689e2 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -224,7 +224,7 @@ impl AttrTokenStream { // Inner attributes are only supported on extern blocks, functions, // impls, and modules. All of these have their inner attributes // placed at the beginning of the rightmost outermost braced group: - // e.g. fn foo() { #![my_attr} } + // e.g. fn foo() { #![my_attr] } // // Therefore, we can insert them back into the right location // without needing to do any extra position tracking. From 572ae3b22743018ea909b5f8d8a33d3d83392322 Mon Sep 17 00:00:00 2001 From: John Paul Adrian Glaubitz Date: Mon, 24 Jun 2024 16:33:24 +0200 Subject: [PATCH 05/24] rustc_data_structures: Use portable AtomicU64 on 32-bit SPARC While at it, order the list of architectures alphabetically. --- compiler/rustc_data_structures/Cargo.toml | 2 +- compiler/rustc_data_structures/src/marker.rs | 6 +++--- compiler/rustc_data_structures/src/sync.rs | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_data_structures/Cargo.toml b/compiler/rustc_data_structures/Cargo.toml index ff0a94f8e9b27..f525510030b4a 100644 --- a/compiler/rustc_data_structures/Cargo.toml +++ b/compiler/rustc_data_structures/Cargo.toml @@ -50,7 +50,7 @@ libc = "0.2" memmap2 = "0.2.1" # tidy-alphabetical-end -[target.'cfg(any(target_arch = "powerpc", target_arch = "mips"))'.dependencies] +[target.'cfg(any(target_arch = "mips", target_arch = "powerpc", target_arch = "sparc"))'.dependencies] portable-atomic = "1.5.1" [features] diff --git a/compiler/rustc_data_structures/src/marker.rs b/compiler/rustc_data_structures/src/marker.rs index a9ccfbed41165..32fad0de1aa3e 100644 --- a/compiler/rustc_data_structures/src/marker.rs +++ b/compiler/rustc_data_structures/src/marker.rs @@ -147,14 +147,14 @@ cfg_match! { [crate::owned_slice::OwnedSlice] ); - // PowerPC and MIPS platforms with 32-bit pointers do not + // MIPS, PowerPC and SPARC platforms with 32-bit pointers do not // have AtomicU64 type. - #[cfg(not(any(target_arch = "powerpc", target_arch = "mips")))] + #[cfg(not(any(target_arch = "powerpc", target_arch = "powerpc", target_arch = "sparc")))] already_sync!( [std::sync::atomic::AtomicU64] ); - #[cfg(any(target_arch = "powerpc", target_arch = "mips"))] + #[cfg(any(target_arch = "mips", target_arch = "powerpc", target_arch = "sparc"))] already_sync!( [portable_atomic::AtomicU64] ); diff --git a/compiler/rustc_data_structures/src/sync.rs b/compiler/rustc_data_structures/src/sync.rs index ecb85db33f70d..5ae79ca988f14 100644 --- a/compiler/rustc_data_structures/src/sync.rs +++ b/compiler/rustc_data_structures/src/sync.rs @@ -270,12 +270,12 @@ cfg_match! { pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32}; - // PowerPC and MIPS platforms with 32-bit pointers do not + // MIPS, PowerPC and SPARC platforms with 32-bit pointers do not // have AtomicU64 type. - #[cfg(not(any(target_arch = "powerpc", target_arch = "mips")))] + #[cfg(not(any(target_arch = "mips", target_arch = "powerpc", target_arch = "sparc")))] pub use std::sync::atomic::AtomicU64; - #[cfg(any(target_arch = "powerpc", target_arch = "mips"))] + #[cfg(any(target_arch = "mips", target_arch = "powerpc", target_arch = "sparc"))] pub use portable_atomic::AtomicU64; pub use std::sync::Arc as Lrc; From dc8ac3ec91716678aa4dfa9e8df1dceacdf3464f Mon Sep 17 00:00:00 2001 From: John Paul Adrian Glaubitz Date: Mon, 24 Jun 2024 16:36:38 +0200 Subject: [PATCH 06/24] rustc_llvm: Link against libatomic on 32-bit SPARC While at it, order the list of architectures alphabetically. --- compiler/rustc_llvm/build.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_llvm/build.rs b/compiler/rustc_llvm/build.rs index cdaabb036c2ae..3aa852c83045d 100644 --- a/compiler/rustc_llvm/build.rs +++ b/compiler/rustc_llvm/build.rs @@ -235,6 +235,7 @@ fn main() { || target.starts_with("mips-") || target.starts_with("mipsel-") || target.starts_with("powerpc-") + || target.starts_with("sparc-") { // 32-bit targets need to link libatomic. println!("cargo:rustc-link-lib=atomic"); From 8f7175c199472486756ab4432addc416e548e6d6 Mon Sep 17 00:00:00 2001 From: John Paul Adrian Glaubitz Date: Mon, 24 Jun 2024 16:41:35 +0200 Subject: [PATCH 07/24] bootstrap: Link against libatomic on 32-bit SPARC While at it, order the list of architectures alphabetically. --- src/bootstrap/src/core/build_steps/llvm.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 8b379d3be5c0b..8e6795b11bd21 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -407,18 +407,21 @@ impl Step for Llvm { cfg.define("LLVM_LINK_LLVM_DYLIB", "ON"); } - if (target.starts_with("riscv") || target.starts_with("csky")) + if (target.starts_with("csky") + || target.starts_with("riscv") + || target.starts_with("sparc-")) && !target.contains("freebsd") && !target.contains("openbsd") && !target.contains("netbsd") { - // RISC-V and CSKY GCC erroneously requires linking against + // CSKY and RISC-V GCC erroneously requires linking against // `libatomic` when using 1-byte and 2-byte C++ // atomics but the LLVM build system check cannot // detect this. Therefore it is set manually here. // Some BSD uses Clang as its system compiler and // provides no libatomic in its base system so does - // not want this. + // not want this. 32-bit SPARC requires linking against + // libatomic as well. ldflags.exe.push(" -latomic"); ldflags.shared.push(" -latomic"); } From a194f42d21cac273b9d2d44d70d02f7c7aef1304 Mon Sep 17 00:00:00 2001 From: John Paul Adrian Glaubitz Date: Mon, 24 Jun 2024 16:46:53 +0200 Subject: [PATCH 08/24] rustc_target: Rewrite sparc_unknown_linux_gnu spec to use TargetOptions --- .../spec/targets/sparc_unknown_linux_gnu.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs index c10f9d82d4636..6fa50a28c3709 100644 --- a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs @@ -1,13 +1,7 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target}; +use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; pub fn target() -> Target { - let mut base = base::linux_gnu::opts(); - base.endian = Endian::Big; - base.cpu = "v9".into(); - base.max_atomic_width = Some(32); - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-mv8plus"]); - Target { llvm_target: "sparc-unknown-linux-gnu".into(), metadata: crate::spec::TargetMetadata { @@ -19,6 +13,15 @@ pub fn target() -> Target { pointer_width: 32, data_layout: "E-m:e-p:32:32-i64:64-f128:64-n32-S64".into(), arch: "sparc".into(), - options: base, + options: TargetOptions { + cpu: "v9".into(), + endian: Endian::Big, + late_link_args: TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-mv8plus"], + ), + max_atomic_width: Some(32), + ..base::linux_gnu::opts() + }, } } From e57bbb37798ca9e3a4c3a043312b0ed30f9cfd87 Mon Sep 17 00:00:00 2001 From: John Paul Adrian Glaubitz Date: Mon, 24 Jun 2024 16:48:12 +0200 Subject: [PATCH 09/24] rustc_target: Build sparc_unknown_linux_gnu with -mcpu=v9 and -m32 The previously -mv8plus parameter is supported by GCC only, so let's use something that the SPARC backend in LLVM supports as well. --- .../rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs index 6fa50a28c3709..5cee06e4936c9 100644 --- a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs @@ -18,7 +18,7 @@ pub fn target() -> Target { endian: Endian::Big, late_link_args: TargetOptions::link_args( LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-mv8plus"], + &["-mcpu=v9", "-m32"], ), max_atomic_width: Some(32), ..base::linux_gnu::opts() From bca5cd3a9dccc166e936b21eb86e6a58d3f4b84e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 25 Jun 2024 14:14:58 +1000 Subject: [PATCH 10/24] Extend `tests/ui/macros/nonterminal-matching.rs`. To involve `macro_rules!` macros, and also a mix of fragment specifiers, some of which feature the forwaring limitation and some of which don't. --- tests/ui/macros/nonterminal-matching.rs | 30 +++++++ tests/ui/macros/nonterminal-matching.stderr | 90 ++++++++++++++++++++- 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/tests/ui/macros/nonterminal-matching.rs b/tests/ui/macros/nonterminal-matching.rs index 84fffe44d6a55..5f0d6b2f90eee 100644 --- a/tests/ui/macros/nonterminal-matching.rs +++ b/tests/ui/macros/nonterminal-matching.rs @@ -23,4 +23,34 @@ simple_nonterminal!(a, 'a, (x, y, z)); // OK complex_nonterminal!(enum E {}); +// `ident`, `lifetime`, and `tt` all work. Other fragments do not. See +// https://doc.rust-lang.org/nightly/reference/macros-by-example.html#forwarding-a-matched-fragment +macro_rules! foo { + (ident $x:ident) => { bar!(ident $x); }; + (lifetime $x:lifetime) => { bar!(lifetime $x); }; + (tt $x:tt) => { bar!(tt $x); }; + (expr $x:expr) => { bar!(expr $x); }; //~ ERROR: no rules expected the token `3` + (literal $x:literal) => { bar!(literal $x); }; //~ ERROR: no rules expected the token `4` + (path $x:path) => { bar!(path $x); }; //~ ERROR: no rules expected the token `a::b::c` + (stmt $x:stmt) => { bar!(stmt $x); }; //~ ERROR: no rules expected the token `let abc = 0` +} + +macro_rules! bar { + (ident abc) => {}; + (lifetime 'abc) => {}; + (tt 2) => {}; + (expr 3) => {}; + (literal 4) => {}; + (path a::b::c) => {}; + (stmt let abc = 0) => {}; +} + +foo!(ident abc); +foo!(lifetime 'abc); +foo!(tt 2); +foo!(expr 3); +foo!(literal 4); +foo!(path a::b::c); +foo!(stmt let abc = 0); + fn main() {} diff --git a/tests/ui/macros/nonterminal-matching.stderr b/tests/ui/macros/nonterminal-matching.stderr index d19141145fa19..3ee88b5f52ef9 100644 --- a/tests/ui/macros/nonterminal-matching.stderr +++ b/tests/ui/macros/nonterminal-matching.stderr @@ -23,5 +23,93 @@ LL | complex_nonterminal!(enum E {}); = help: try using `:tt` instead in the macro definition = note: this error originates in the macro `complex_nonterminal` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 1 previous error +error: no rules expected the token `3` + --> $DIR/nonterminal-matching.rs:32:35 + | +LL | (expr $x:expr) => { bar!(expr $x); }; + | ^^ no rules expected this token in macro call +... +LL | macro_rules! bar { + | ---------------- when calling this macro +... +LL | foo!(expr 3); + | ------------ in this macro invocation + | +note: while trying to match `3` + --> $DIR/nonterminal-matching.rs:42:11 + | +LL | (expr 3) => {}; + | ^ + = note: captured metavariables except for `:tt`, `:ident` and `:lifetime` cannot be compared to other tokens + = note: see for more information + = help: try using `:tt` instead in the macro definition + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: no rules expected the token `4` + --> $DIR/nonterminal-matching.rs:33:44 + | +LL | (literal $x:literal) => { bar!(literal $x); }; + | ^^ no rules expected this token in macro call +... +LL | macro_rules! bar { + | ---------------- when calling this macro +... +LL | foo!(literal 4); + | --------------- in this macro invocation + | +note: while trying to match `4` + --> $DIR/nonterminal-matching.rs:43:14 + | +LL | (literal 4) => {}; + | ^ + = note: captured metavariables except for `:tt`, `:ident` and `:lifetime` cannot be compared to other tokens + = note: see for more information + = help: try using `:tt` instead in the macro definition + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: no rules expected the token `a::b::c` + --> $DIR/nonterminal-matching.rs:34:35 + | +LL | (path $x:path) => { bar!(path $x); }; + | ^^ no rules expected this token in macro call +... +LL | macro_rules! bar { + | ---------------- when calling this macro +... +LL | foo!(path a::b::c); + | ------------------ in this macro invocation + | +note: while trying to match `a` + --> $DIR/nonterminal-matching.rs:44:11 + | +LL | (path a::b::c) => {}; + | ^ + = note: captured metavariables except for `:tt`, `:ident` and `:lifetime` cannot be compared to other tokens + = note: see for more information + = help: try using `:tt` instead in the macro definition + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: no rules expected the token `let abc = 0` + --> $DIR/nonterminal-matching.rs:35:35 + | +LL | (stmt $x:stmt) => { bar!(stmt $x); }; + | ^^ no rules expected this token in macro call +... +LL | macro_rules! bar { + | ---------------- when calling this macro +... +LL | foo!(stmt let abc = 0); + | ---------------------- in this macro invocation + | +note: while trying to match `let` + --> $DIR/nonterminal-matching.rs:45:11 + | +LL | (stmt let abc = 0) => {}; + | ^^^ + = note: captured metavariables except for `:tt`, `:ident` and `:lifetime` cannot be compared to other tokens + = note: see for more information + = help: try using `:tt` instead in the macro definition + = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 5 previous errors From 2e4d547d4a862aafd9b9b8382a1bbcde1a4c0d32 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 15 May 2024 09:29:11 +1000 Subject: [PATCH 11/24] Extra panic cases. Just some extra sanity checking, making explicit some values not possible in code working with token trees -- we shouldn't be seeing explicit delimiter tokens, because they should be represented as `TokenTree::Delimited`. --- compiler/rustc_ast/src/attr/mod.rs | 9 ++++++++- compiler/rustc_expand/src/config.rs | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 676a2377c3b35..593c78df3cdb8 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -327,7 +327,8 @@ impl MetaItem { I: Iterator, { // FIXME: Share code with `parse_path`. - let path = match tokens.next().map(|tt| TokenTree::uninterpolate(tt)).as_deref() { + let tt = tokens.next().map(|tt| TokenTree::uninterpolate(tt)); + let path = match tt.as_deref() { Some(&TokenTree::Token( Token { kind: ref kind @ (token::Ident(..) | token::PathSep), span }, _, @@ -368,6 +369,12 @@ impl MetaItem { token::Nonterminal::NtPath(path) => (**path).clone(), _ => return None, }, + Some(TokenTree::Token( + Token { kind: token::OpenDelim(_) | token::CloseDelim(_), .. }, + _, + )) => { + panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tt); + } _ => return None, }; let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi()); diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index badfa6d3aa323..56cbb54fcecf7 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -214,6 +214,12 @@ impl<'a> StripUnconfigured<'a> { ) => { panic!("Nonterminal should have been flattened: {:?}", tree); } + AttrTokenTree::Token( + Token { kind: TokenKind::OpenDelim(_) | TokenKind::CloseDelim(_), .. }, + _, + ) => { + panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree); + } AttrTokenTree::Token(token, spacing) => { Some(AttrTokenTree::Token(token, spacing)).into_iter() } From 9828e960ab4cccc9526fd6cc61df430588bd0487 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Sun, 23 Jun 2024 16:12:39 +1000 Subject: [PATCH 12/24] Remove `__rust_force_expr`. This was added (with a different name) to improve an error message. It is no longer needed -- removing it changes the error message, but overall I think the new message is no worse: - the mention of `#` in the first line is a little worse, - but the extra context makes it very clear what the problem is, perhaps even clearer than the old message, - and the removal of the note about the `expr` fragment (an internal detail of `__rust_force_expr`) is an improvement. Overall I think the error is quite clear and still far better than the old message that prompted #61933, which didn't even mention patterns. The motivation for this is #124141, which will cause pasted metavariables to be tokenized and reparsed instead of the AST node being cached. This change in behaviour occasionally has a non-zero perf cost, and `__rust_force_expr` causes the tokenize/reparse step to occur twice. Removing `__rust_force_expr` greatly reduces the extra overhead for the `deep-vector` benchmark. --- library/alloc/src/macros.rs | 18 ++++-------------- tests/ui/macros/vec-macro-in-pattern.rs | 2 +- tests/ui/macros/vec-macro-in-pattern.stderr | 7 +++++-- 3 files changed, 10 insertions(+), 17 deletions(-) diff --git a/library/alloc/src/macros.rs b/library/alloc/src/macros.rs index 0f767df6063a3..d5ca5c4ed27a2 100644 --- a/library/alloc/src/macros.rs +++ b/library/alloc/src/macros.rs @@ -41,18 +41,18 @@ #[allow_internal_unstable(rustc_attrs, liballoc_internals)] macro_rules! vec { () => ( - $crate::__rust_force_expr!($crate::vec::Vec::new()) + $crate::vec::Vec::new() ); ($elem:expr; $n:expr) => ( - $crate::__rust_force_expr!($crate::vec::from_elem($elem, $n)) + $crate::vec::from_elem($elem, $n) ); ($($x:expr),+ $(,)?) => ( - $crate::__rust_force_expr!(<[_]>::into_vec( + <[_]>::into_vec( // This rustc_box is not required, but it produces a dramatic improvement in compile // time when constructing arrays with many elements. #[rustc_box] $crate::boxed::Box::new([$($x),+]) - )) + ) ); } @@ -126,13 +126,3 @@ macro_rules! format { res }} } - -/// Force AST node to an expression to improve diagnostics in pattern position. -#[doc(hidden)] -#[macro_export] -#[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")] -macro_rules! __rust_force_expr { - ($e:expr) => { - $e - }; -} diff --git a/tests/ui/macros/vec-macro-in-pattern.rs b/tests/ui/macros/vec-macro-in-pattern.rs index ce4298b8bb334..26d7d4280fadb 100644 --- a/tests/ui/macros/vec-macro-in-pattern.rs +++ b/tests/ui/macros/vec-macro-in-pattern.rs @@ -4,7 +4,7 @@ fn main() { match Some(vec![42]) { - Some(vec![43]) => {} //~ ERROR arbitrary expressions aren't allowed in patterns + Some(vec![43]) => {} //~ ERROR expected pattern, found `#` _ => {} } } diff --git a/tests/ui/macros/vec-macro-in-pattern.stderr b/tests/ui/macros/vec-macro-in-pattern.stderr index 1a446b8c3edbc..f32a2cf8e4350 100644 --- a/tests/ui/macros/vec-macro-in-pattern.stderr +++ b/tests/ui/macros/vec-macro-in-pattern.stderr @@ -1,10 +1,13 @@ -error: arbitrary expressions aren't allowed in patterns +error: expected pattern, found `#` --> $DIR/vec-macro-in-pattern.rs:7:14 | LL | Some(vec![43]) => {} | ^^^^^^^^ + | | + | expected pattern + | in this macro invocation + | this macro call doesn't expand to a pattern | - = note: the `expr` fragment specifier forces the metavariable's content to be an expression = note: this error originates in the macro `vec` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error From 379b7614627b3a917a5f459388f95c4fb55c39ad Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 17 Jun 2024 14:44:55 +1000 Subject: [PATCH 13/24] Inline and remove `maybe_whole_expr!`. And remove the `NtPath` and `NtBlock` cases in `parse_literal_maybe_minus`, because they are unnecessary. --- compiler/rustc_parse/src/parser/expr.rs | 73 ++++++++++++++----------- 1 file changed, 41 insertions(+), 32 deletions(-) diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 9fad954addade..e0c70884feea3 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -39,36 +39,6 @@ use rustc_span::{BytePos, ErrorGuaranteed, Pos, Span}; use thin_vec::{thin_vec, ThinVec}; use tracing::instrument; -/// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression -/// dropped into the token stream, which happens while parsing the result of -/// macro expansion). Placement of these is not as complex as I feared it would -/// be. The important thing is to make sure that lookahead doesn't balk at -/// `token::Interpolated` tokens. -macro_rules! maybe_whole_expr { - ($p:expr) => { - if let token::Interpolated(nt) = &$p.token.kind { - match &**nt { - token::NtExpr(e) | token::NtLiteral(e) => { - let e = e.clone(); - $p.bump(); - return Ok(e); - } - token::NtPath(path) => { - let path = (**path).clone(); - $p.bump(); - return Ok($p.mk_expr($p.prev_token.span, ExprKind::Path(None, path))); - } - token::NtBlock(block) => { - let block = block.clone(); - $p.bump(); - return Ok($p.mk_expr($p.prev_token.span, ExprKind::Block(block, None))); - } - _ => {} - }; - } - }; -} - #[derive(Debug)] pub(super) enum LhsExpr { // Already parsed just the outer attributes. @@ -1421,7 +1391,27 @@ impl<'a> Parser<'a> { /// correctly if called from `parse_dot_or_call_expr()`. fn parse_expr_bottom(&mut self) -> PResult<'a, P> { maybe_recover_from_interpolated_ty_qpath!(self, true); - maybe_whole_expr!(self); + + if let token::Interpolated(nt) = &self.token.kind { + match &**nt { + token::NtExpr(e) | token::NtLiteral(e) => { + let e = e.clone(); + self.bump(); + return Ok(e); + } + token::NtPath(path) => { + let path = (**path).clone(); + self.bump(); + return Ok(self.mk_expr(self.prev_token.span, ExprKind::Path(None, path))); + } + token::NtBlock(block) => { + let block = block.clone(); + self.bump(); + return Ok(self.mk_expr(self.prev_token.span, ExprKind::Block(block, None))); + } + _ => {} + }; + } // Outer attributes are already parsed and will be // added to the return value after the fact. @@ -2190,7 +2180,26 @@ impl<'a> Parser<'a> { /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). /// Keep this in sync with `Token::can_begin_literal_maybe_minus`. pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P> { - maybe_whole_expr!(self); + if let token::Interpolated(nt) = &self.token.kind { + match &**nt { + // FIXME(nnethercote) The `NtExpr` case should only match if + // `e` is an `ExprKind::Lit` or an `ExprKind::Unary` containing + // an `UnOp::Neg` and an `ExprKind::Lit`, like how + // `can_begin_literal_maybe_minus` works. But this method has + // been over-accepting for a long time, and to make that change + // here requires also changing some `parse_literal_maybe_minus` + // call sites to accept additional expression kinds. E.g. + // `ExprKind::Path` must be accepted when parsing range + // patterns. That requires some care. So for now, we continue + // being less strict here than we should be. + token::NtExpr(e) | token::NtLiteral(e) => { + let e = e.clone(); + self.bump(); + return Ok(e); + } + _ => {} + }; + } let lo = self.token.span; let minus_present = self.eat(&token::BinOp(token::Minus)); From 57c8f6f2527ad94b2ff7f16288693c2cd6d550b5 Mon Sep 17 00:00:00 2001 From: DianQK Date: Tue, 4 Jun 2024 22:45:01 +0800 Subject: [PATCH 14/24] Add `.clang-format` --- .clang-format | 1 + .reuse/dep5 | 1 + 2 files changed, 2 insertions(+) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000..63027b8781585 --- /dev/null +++ b/.clang-format @@ -0,0 +1 @@ +BasedOnStyle: LLVM diff --git a/.reuse/dep5 b/.reuse/dep5 index 06afec2b3faec..0e2650ff2c048 100644 --- a/.reuse/dep5 +++ b/.reuse/dep5 @@ -29,6 +29,7 @@ Files: compiler/* x x.ps1 x.py + .clang-format .editorconfig .git-blame-ignore-revs .gitattributes From 9f1f6a3387e35e8368bb546fc8ec9dd0b3b1e6a4 Mon Sep 17 00:00:00 2001 From: DianQK Date: Thu, 20 Jun 2024 21:25:41 +0800 Subject: [PATCH 15/24] Add clang-format to requirements.txt in tidy --- src/tools/tidy/config/requirements.in | 1 + src/tools/tidy/config/requirements.txt | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/tools/tidy/config/requirements.in b/src/tools/tidy/config/requirements.in index 833d62a864b13..8938dc032438c 100644 --- a/src/tools/tidy/config/requirements.in +++ b/src/tools/tidy/config/requirements.in @@ -8,3 +8,4 @@ black==24.4.2 ruff==0.4.9 +clang-format==18.1.7 diff --git a/src/tools/tidy/config/requirements.txt b/src/tools/tidy/config/requirements.txt index d5236868ad17c..790eabf5cf8a8 100644 --- a/src/tools/tidy/config/requirements.txt +++ b/src/tools/tidy/config/requirements.txt @@ -28,6 +28,23 @@ black==24.4.2 \ --hash=sha256:eaea3008c281f1038edb473c1aa8ed8143a5535ff18f978a318f10302b254063 \ --hash=sha256:ef703f83fc32e131e9bcc0a5094cfe85599e7109f896fe8bc96cc402f3eb4b6e # via -r src/tools/tidy/config/requirements.in +clang-format==18.1.7 \ + --hash=sha256:035204410f65d03f98cb81c9c39d6d193f9987917cc88de9d0dbd01f2aa9c302 \ + --hash=sha256:05c482a854287a5d21f7567186c0bd4b8dbd4a871751e655a45849185f30b931 \ + --hash=sha256:0b352ec51b291fe04c25a0f0ed15ba1a55b9c9c8eaa7fdf14de3d3585aef4f72 \ + --hash=sha256:217526c8189c18fd175e19bb3e4da2d1bdf14a2bf79d97108c9b6a98d9938351 \ + --hash=sha256:42d0b580ab7a45348155944adebe0bef53d1de9357b925830a59bbc351a25560 \ + --hash=sha256:57090c40a8f0a898e0db8be150a19be2551302d5f5620d2a01de07e7c9220a53 \ + --hash=sha256:607772cf474c1ebe0de44f44c1324e57a2d5b45a1d96d4aff166645532d99b43 \ + --hash=sha256:a49c44d7cc00431be8285aa120a7a21fa0475786c03c53b04a26882c4e626a43 \ + --hash=sha256:a62fca204293893badde0ab004df8b6df1d13eac4d452051554d9684d0a8254e \ + --hash=sha256:a914592a51f77c3563563c7a8970f19bc1ed59174ab992f095a78f4e142382ac \ + --hash=sha256:b3a0a09428cdd656ed87074543222a80660bc506407ed21b8e4bcb3d6d3a5a3c \ + --hash=sha256:c151d42e6ac7c3cc03d7fec61bed3211ce8f75528e1efd8fc64bdb33840987b2 \ + --hash=sha256:d6a2f051124d6ae506ba2a68accfe4ea4c8cb90d13b422c3131bb124413bac32 \ + --hash=sha256:f4f77ac0f4f9a659213fedda0f2d216886c410132e6e7dd4b13f92b34e925554 \ + --hash=sha256:f935d34152a2e11e55120eb9182862f432bc9789ab819f680c9f6db4edebf9e3 + # via -r src/tools/tidy/config/requirements.in click==8.1.3 \ --hash=sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e \ --hash=sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48 From 457fda1701e191d9ff439d9d01ee650e6bbefee6 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Thu, 20 Jun 2024 10:49:40 +1000 Subject: [PATCH 16/24] coverage: Detach `#[coverage(..)]` from codegen attribute handling --- .../rustc_codegen_ssa/src/codegen_attrs.rs | 17 ------------ .../src/middle/codegen_fn_attrs.rs | 5 +--- compiler/rustc_middle/src/query/mod.rs | 8 ++++++ .../rustc_mir_transform/src/coverage/query.rs | 27 ++++++++++++++++++- 4 files changed, 35 insertions(+), 22 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index fb71cdaa8ff2a..d224695d1f286 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -124,22 +124,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { .emit(); } } - sym::coverage => { - let inner = attr.meta_item_list(); - match inner.as_deref() { - Some([item]) if item.has_name(sym::off) => { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_COVERAGE; - } - Some([item]) if item.has_name(sym::on) => { - // Allow #[coverage(on)] for being explicit, maybe also in future to enable - // coverage on a smaller scope within an excluded larger scope. - } - Some(_) | None => { - tcx.dcx() - .span_delayed_bug(attr.span, "unexpected value of coverage attribute"); - } - } - } sym::rustc_std_internal_symbol => { codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL } @@ -584,7 +568,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { } if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) { - codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_COVERAGE; codegen_fn_attrs.inline = InlineAttr::Never; } diff --git a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs index 3fa5054baed1e..c8f0d0795a3c5 100644 --- a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs +++ b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs @@ -87,10 +87,7 @@ bitflags::bitflags! { /// #[cmse_nonsecure_entry]: with a TrustZone-M extension, declare a /// function as an entry function from Non-Secure code. const CMSE_NONSECURE_ENTRY = 1 << 13; - /// `#[coverage(off)]`: indicates that the function should be ignored by - /// the MIR `InstrumentCoverage` pass and not added to the coverage map - /// during codegen. - const NO_COVERAGE = 1 << 14; + // (Bit 14 was used for `#[coverage(off)]`, but is now unused.) /// `#[used(linker)]`: /// indicates that neither LLVM nor the linker will eliminate this function. const USED_LINKER = 1 << 15; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index c5afecffb07af..320e21e85da0b 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -572,6 +572,14 @@ rustc_queries! { separate_provide_extern } + /// Checks for `#[coverage(off)]` or `#[coverage(on)]`. + /// + /// Returns `false` if `#[coverage(off)]` was found, or `true` if + /// either `#[coverage(on)]` or no coverage attribute was found. + query coverage_attr_on(key: LocalDefId) -> bool { + desc { |tcx| "checking for `#[coverage(..)]` on `{}`", tcx.def_path_str(key) } + } + /// Summarizes coverage IDs inserted by the `InstrumentCoverage` MIR pass /// (for compiler option `-Cinstrument-coverage`), after MIR optimizations /// have had a chance to potentially remove some of them. diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 25744009be8b8..14dcb7ef424a6 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -6,11 +6,13 @@ use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::util::Providers; use rustc_span::def_id::LocalDefId; +use rustc_span::sym; /// Registers query/hook implementations related to coverage. pub(crate) fn provide(providers: &mut Providers) { providers.hooks.is_eligible_for_coverage = |TyCtxtAt { tcx, .. }, def_id| is_eligible_for_coverage(tcx, def_id); + providers.queries.coverage_attr_on = coverage_attr_on; providers.queries.coverage_ids_info = coverage_ids_info; } @@ -38,7 +40,12 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return false; } - if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NO_COVERAGE) { + if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) { + trace!("InstrumentCoverage skipped for {def_id:?} (`#[naked]`)"); + return false; + } + + if !tcx.coverage_attr_on(def_id) { trace!("InstrumentCoverage skipped for {def_id:?} (`#[coverage(off)]`)"); return false; } @@ -46,6 +53,24 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { true } +/// Query implementation for `coverage_attr_on`. +fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { + if let Some(attr) = tcx.get_attr(def_id, sym::coverage) { + match attr.meta_item_list().as_deref() { + Some([item]) if item.has_name(sym::off) => return false, + Some([item]) if item.has_name(sym::on) => return true, + Some(_) | None => { + // Other possibilities should have been rejected by `rustc_parse::validate_attr`. + tcx.dcx().span_bug(attr.span, "unexpected value of coverage attribute"); + } + } + } + + // We didn't see an explicit coverage attribute, so + // allow coverage instrumentation by default. + true +} + /// Query implementation for `coverage_ids_info`. fn coverage_ids_info<'tcx>( tcx: TyCtxt<'tcx>, From 3262611cc5db7ce83dee4268fb1901311b24e5fc Mon Sep 17 00:00:00 2001 From: Zalathar Date: Sat, 22 Jun 2024 16:34:24 +1000 Subject: [PATCH 17/24] coverage: Apply `#[coverage(..)]` recursively to nested functions --- compiler/rustc_middle/src/query/mod.rs | 3 +- .../rustc_mir_transform/src/coverage/query.rs | 12 ++- tests/coverage/attr/nested.cov-map | 82 ------------------- tests/coverage/attr/nested.coverage | 74 ++++++++--------- tests/coverage/attr/off-on-sandwich.cov-map | 8 -- tests/coverage/attr/off-on-sandwich.coverage | 10 +-- tests/coverage/no_cov_crate.cov-map | 13 --- tests/coverage/no_cov_crate.coverage | 14 ++-- 8 files changed, 60 insertions(+), 156 deletions(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 320e21e85da0b..230a44bcf2452 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -572,7 +572,8 @@ rustc_queries! { separate_provide_extern } - /// Checks for `#[coverage(off)]` or `#[coverage(on)]`. + /// Checks for the nearest `#[coverage(off)]` or `#[coverage(on)]` on + /// this def and any enclosing defs, up to the crate root. /// /// Returns `false` if `#[coverage(off)]` was found, or `true` if /// either `#[coverage(on)]` or no coverage attribute was found. diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 14dcb7ef424a6..1fce2abbbbf73 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -55,6 +55,7 @@ fn is_eligible_for_coverage(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { /// Query implementation for `coverage_attr_on`. fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { + // Check for annotations directly on this def. if let Some(attr) = tcx.get_attr(def_id, sym::coverage) { match attr.meta_item_list().as_deref() { Some([item]) if item.has_name(sym::off) => return false, @@ -66,9 +67,14 @@ fn coverage_attr_on(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { } } - // We didn't see an explicit coverage attribute, so - // allow coverage instrumentation by default. - true + match tcx.opt_local_parent(def_id) { + // Check the parent def (and so on recursively) until we find an + // enclosing attribute or reach the crate root. + Some(parent) => tcx.coverage_attr_on(parent), + // We reached the crate root without seeing a coverage attribute, so + // allow coverage instrumentation by default. + None => true, + } } /// Query implementation for `coverage_ids_info`. diff --git a/tests/coverage/attr/nested.cov-map b/tests/coverage/attr/nested.cov-map index a613bb7f8cdf5..0f2d5542f753a 100644 --- a/tests/coverage/attr/nested.cov-map +++ b/tests/coverage/attr/nested.cov-map @@ -1,35 +1,3 @@ -Function name: <<::trait_method::MyMiddle as nested::MyTrait>::trait_method::MyInner as nested::MyTrait>::trait_method (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 39, 15, 02, 16] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 57, 21) to (start + 2, 22) - -Function name: <<::outer_method::MyMiddle>::middle_method::MyInner>::inner_method (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 23, 15, 02, 16] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 35, 21) to (start + 2, 22) - -Function name: <::trait_method::MyMiddle as nested::MyTrait>::trait_method (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 36, 0d, 08, 0e] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 54, 13) to (start + 8, 14) - -Function name: <::outer_method::MyMiddle>::middle_method (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 20, 0d, 08, 0e] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 32, 13) to (start + 8, 14) - Function name: nested::closure_expr Raw bytes (14): 0x[01, 01, 00, 02, 01, 44, 01, 01, 0f, 01, 0b, 05, 01, 02] Number of files: 1 @@ -39,23 +7,6 @@ Number of file 0 mappings: 2 - Code(Counter(0)) at (prev + 68, 1) to (start + 1, 15) - Code(Counter(0)) at (prev + 11, 5) to (start + 1, 2) -Function name: nested::closure_expr::{closure#0}::{closure#0} (unused) -Raw bytes (14): 0x[01, 01, 00, 02, 00, 47, 1a, 01, 17, 00, 04, 0d, 01, 0a] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Zero) at (prev + 71, 26) to (start + 1, 23) -- Code(Zero) at (prev + 4, 13) to (start + 1, 10) - -Function name: nested::closure_expr::{closure#0}::{closure#0}::{closure#0} (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 48, 1d, 02, 0e] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 72, 29) to (start + 2, 14) - Function name: nested::closure_tail Raw bytes (14): 0x[01, 01, 00, 02, 01, 53, 01, 01, 0f, 01, 11, 05, 01, 02] Number of files: 1 @@ -65,36 +16,3 @@ Number of file 0 mappings: 2 - Code(Counter(0)) at (prev + 83, 1) to (start + 1, 15) - Code(Counter(0)) at (prev + 17, 5) to (start + 1, 2) -Function name: nested::closure_tail::{closure#0}::{closure#0} (unused) -Raw bytes (14): 0x[01, 01, 00, 02, 00, 58, 14, 01, 1f, 00, 06, 15, 01, 12] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 2 -- Code(Zero) at (prev + 88, 20) to (start + 1, 31) -- Code(Zero) at (prev + 6, 21) to (start + 1, 18) - -Function name: nested::closure_tail::{closure#0}::{closure#0}::{closure#0} (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 5a, 1c, 02, 1a] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 90, 28) to (start + 2, 26) - -Function name: nested::outer_fn::middle_fn (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 11, 05, 05, 06] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 17, 5) to (start + 5, 6) - -Function name: nested::outer_fn::middle_fn::inner_fn (unused) -Raw bytes (9): 0x[01, 01, 00, 01, 00, 12, 09, 02, 0a] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Zero) at (prev + 18, 9) to (start + 2, 10) - diff --git a/tests/coverage/attr/nested.coverage b/tests/coverage/attr/nested.coverage index 13129572aec7d..bdd117b7dfaf5 100644 --- a/tests/coverage/attr/nested.coverage +++ b/tests/coverage/attr/nested.coverage @@ -14,12 +14,12 @@ LL| | LL| |#[coverage(off)] LL| |fn outer_fn() { - LL| 0| fn middle_fn() { - LL| 0| fn inner_fn() { - LL| 0| do_stuff(); - LL| 0| } - LL| 0| do_stuff(); - LL| 0| } + LL| | fn middle_fn() { + LL| | fn inner_fn() { + LL| | do_stuff(); + LL| | } + LL| | do_stuff(); + LL| | } LL| | do_stuff(); LL| |} LL| | @@ -29,15 +29,15 @@ LL| | fn outer_method(&self) { LL| | struct MyMiddle; LL| | impl MyMiddle { - LL| 0| fn middle_method(&self) { - LL| 0| struct MyInner; - LL| 0| impl MyInner { - LL| 0| fn inner_method(&self) { - LL| 0| do_stuff(); - LL| 0| } - LL| 0| } - LL| 0| do_stuff(); - LL| 0| } + LL| | fn middle_method(&self) { + LL| | struct MyInner; + LL| | impl MyInner { + LL| | fn inner_method(&self) { + LL| | do_stuff(); + LL| | } + LL| | } + LL| | do_stuff(); + LL| | } LL| | } LL| | do_stuff(); LL| | } @@ -51,15 +51,15 @@ LL| | fn trait_method(&self) { LL| | struct MyMiddle; LL| | impl MyTrait for MyMiddle { - LL| 0| fn trait_method(&self) { - LL| 0| struct MyInner; - LL| 0| impl MyTrait for MyInner { - LL| 0| fn trait_method(&self) { - LL| 0| do_stuff(); - LL| 0| } - LL| 0| } - LL| 0| do_stuff(); - LL| 0| } + LL| | fn trait_method(&self) { + LL| | struct MyInner; + LL| | impl MyTrait for MyInner { + LL| | fn trait_method(&self) { + LL| | do_stuff(); + LL| | } + LL| | } + LL| | do_stuff(); + LL| | } LL| | } LL| | do_stuff(); LL| | } @@ -68,12 +68,12 @@ LL| 1|fn closure_expr() { LL| 1| let _outer = #[coverage(off)] LL| | || { - LL| 0| let _middle = || { - LL| 0| let _inner = || { - LL| 0| do_stuff(); - LL| 0| }; - LL| 0| do_stuff(); - LL| 0| }; + LL| | let _middle = || { + LL| | let _inner = || { + LL| | do_stuff(); + LL| | }; + LL| | do_stuff(); + LL| | }; LL| | do_stuff(); LL| | }; LL| 1| do_stuff(); @@ -85,14 +85,14 @@ LL| | #[coverage(off)] LL| | || { LL| | let _middle = { - LL| 0| || { - LL| 0| let _inner = { - LL| 0| || { - LL| 0| do_stuff(); - LL| 0| } + LL| | || { + LL| | let _inner = { + LL| | || { + LL| | do_stuff(); + LL| | } LL| | }; - LL| 0| do_stuff(); - LL| 0| } + LL| | do_stuff(); + LL| | } LL| | }; LL| | do_stuff(); LL| | } diff --git a/tests/coverage/attr/off-on-sandwich.cov-map b/tests/coverage/attr/off-on-sandwich.cov-map index 72b96420cb562..ed77d7d17e6a7 100644 --- a/tests/coverage/attr/off-on-sandwich.cov-map +++ b/tests/coverage/attr/off-on-sandwich.cov-map @@ -6,14 +6,6 @@ Number of expressions: 0 Number of file 0 mappings: 1 - Code(Counter(0)) at (prev + 20, 5) to (start + 7, 6) -Function name: off_on_sandwich::sparse_a::sparse_b -Raw bytes (9): 0x[01, 01, 00, 01, 01, 22, 05, 10, 06] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 0 -Number of file 0 mappings: 1 -- Code(Counter(0)) at (prev + 34, 5) to (start + 16, 6) - Function name: off_on_sandwich::sparse_a::sparse_b::sparse_c Raw bytes (9): 0x[01, 01, 00, 01, 01, 26, 09, 0b, 0a] Number of files: 1 diff --git a/tests/coverage/attr/off-on-sandwich.coverage b/tests/coverage/attr/off-on-sandwich.coverage index e831b0e926e3e..58c128b834241 100644 --- a/tests/coverage/attr/off-on-sandwich.coverage +++ b/tests/coverage/attr/off-on-sandwich.coverage @@ -31,10 +31,10 @@ LL| |fn sparse_a() { LL| | sparse_b(); LL| | sparse_b(); - LL| 2| fn sparse_b() { - LL| 2| sparse_c(); - LL| 2| sparse_c(); - LL| 2| #[coverage(on)] + LL| | fn sparse_b() { + LL| | sparse_c(); + LL| | sparse_c(); + LL| | #[coverage(on)] LL| 4| fn sparse_c() { LL| 4| sparse_d(); LL| 4| sparse_d(); @@ -47,7 +47,7 @@ LL| 8| } LL| 8| } LL| 4| } - LL| 2| } + LL| | } LL| |} LL| | LL| |#[coverage(off)] diff --git a/tests/coverage/no_cov_crate.cov-map b/tests/coverage/no_cov_crate.cov-map index e623f6480b90e..281efb6d00d9c 100644 --- a/tests/coverage/no_cov_crate.cov-map +++ b/tests/coverage/no_cov_crate.cov-map @@ -59,16 +59,3 @@ Number of file 0 mappings: 4 = (c0 - c1) - Code(Counter(0)) at (prev + 3, 9) to (start + 0, 10) -Function name: no_cov_crate::nested_fns::outer_not_covered::inner -Raw bytes (26): 0x[01, 01, 01, 01, 05, 04, 01, 26, 09, 01, 17, 05, 01, 18, 02, 0e, 02, 02, 14, 02, 0e, 01, 03, 09, 00, 0a] -Number of files: 1 -- file 0 => global file 1 -Number of expressions: 1 -- expression 0 operands: lhs = Counter(0), rhs = Counter(1) -Number of file 0 mappings: 4 -- Code(Counter(0)) at (prev + 38, 9) to (start + 1, 23) -- Code(Counter(1)) at (prev + 1, 24) to (start + 2, 14) -- Code(Expression(0, Sub)) at (prev + 2, 20) to (start + 2, 14) - = (c0 - c1) -- Code(Counter(0)) at (prev + 3, 9) to (start + 0, 10) - diff --git a/tests/coverage/no_cov_crate.coverage b/tests/coverage/no_cov_crate.coverage index f5a0322bf3ee6..29ad1f979cf80 100644 --- a/tests/coverage/no_cov_crate.coverage +++ b/tests/coverage/no_cov_crate.coverage @@ -35,13 +35,13 @@ LL| |mod nested_fns { LL| | #[coverage(off)] LL| | pub fn outer_not_covered(is_true: bool) { - LL| 1| fn inner(is_true: bool) { - LL| 1| if is_true { - LL| 1| println!("called and covered"); - LL| 1| } else { - LL| 0| println!("absolutely not covered"); - LL| 0| } - LL| 1| } + LL| | fn inner(is_true: bool) { + LL| | if is_true { + LL| | println!("called and covered"); + LL| | } else { + LL| | println!("absolutely not covered"); + LL| | } + LL| | } LL| | println!("called but not covered"); LL| | inner(is_true); LL| | } From 7f37f8af5f067e0f4f8d14adb7d76f013e3c4118 Mon Sep 17 00:00:00 2001 From: Zalathar Date: Fri, 21 Jun 2024 21:59:02 +1000 Subject: [PATCH 18/24] coverage: Allow `#[coverage(..)]` on `impl` and `mod` These attributes apply to all enclosed functions/methods/closures, unless explicitly overridden by another coverage attribute. --- compiler/rustc_passes/src/check_attr.rs | 9 ++- tests/coverage/attr/impl.cov-map | 24 +++++++ tests/coverage/attr/impl.coverage | 42 +++++++++++ tests/coverage/attr/impl.rs | 41 +++++++++++ tests/coverage/attr/module.cov-map | 24 +++++++ tests/coverage/attr/module.coverage | 38 ++++++++++ tests/coverage/attr/module.rs | 37 ++++++++++ tests/ui/coverage-attr/name-value.rs | 4 -- tests/ui/coverage-attr/name-value.stderr | 87 +++++------------------ tests/ui/coverage-attr/no-coverage.rs | 4 +- tests/ui/coverage-attr/no-coverage.stderr | 22 +----- tests/ui/coverage-attr/word-only.rs | 4 -- tests/ui/coverage-attr/word-only.stderr | 87 +++++------------------ 13 files changed, 253 insertions(+), 170 deletions(-) create mode 100644 tests/coverage/attr/impl.cov-map create mode 100644 tests/coverage/attr/impl.coverage create mode 100644 tests/coverage/attr/impl.rs create mode 100644 tests/coverage/attr/module.cov-map create mode 100644 tests/coverage/attr/module.coverage create mode 100644 tests/coverage/attr/module.rs diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index d33f12a973fdc..5f8e4a8b7a761 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -369,13 +369,16 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - /// Checks that `#[coverage(..)]` is applied to a function or closure. + /// Checks that `#[coverage(..)]` is applied to a function/closure/method, + /// or to an impl block or module. fn check_coverage(&self, attr: &Attribute, span: Span, target: Target) -> bool { match target { - // #[coverage(..)] on function is fine Target::Fn | Target::Closure - | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, + | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) + | Target::Impl + | Target::Mod => true, + _ => { self.dcx().emit_err(errors::CoverageNotFnOrClosure { attr_span: attr.span, diff --git a/tests/coverage/attr/impl.cov-map b/tests/coverage/attr/impl.cov-map new file mode 100644 index 0000000000000..9b0deed8b64c0 --- /dev/null +++ b/tests/coverage/attr/impl.cov-map @@ -0,0 +1,24 @@ +Function name: ::off_on (unused) +Raw bytes (9): 0x[01, 01, 00, 01, 00, 0e, 05, 00, 13] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 14, 5) to (start + 0, 19) + +Function name: ::on_inherit (unused) +Raw bytes (9): 0x[01, 01, 00, 01, 00, 16, 05, 00, 17] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 22, 5) to (start + 0, 23) + +Function name: ::on_on (unused) +Raw bytes (9): 0x[01, 01, 00, 01, 00, 19, 05, 00, 12] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 25, 5) to (start + 0, 18) + diff --git a/tests/coverage/attr/impl.coverage b/tests/coverage/attr/impl.coverage new file mode 100644 index 0000000000000..560429fb5fe5d --- /dev/null +++ b/tests/coverage/attr/impl.coverage @@ -0,0 +1,42 @@ + LL| |#![feature(coverage_attribute)] + LL| |//@ edition: 2021 + LL| | + LL| |// Checks that `#[coverage(..)]` can be applied to impl and impl-trait blocks, + LL| |// and is inherited by any enclosed functions. + LL| | + LL| |struct MyStruct; + LL| | + LL| |#[coverage(off)] + LL| |impl MyStruct { + LL| | fn off_inherit() {} + LL| | + LL| | #[coverage(on)] + LL| 0| fn off_on() {} + LL| | + LL| | #[coverage(off)] + LL| | fn off_off() {} + LL| |} + LL| | + LL| |#[coverage(on)] + LL| |impl MyStruct { + LL| 0| fn on_inherit() {} + LL| | + LL| | #[coverage(on)] + LL| 0| fn on_on() {} + LL| | + LL| | #[coverage(off)] + LL| | fn on_off() {} + LL| |} + LL| | + LL| |trait MyTrait { + LL| | fn method(); + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |impl MyTrait for MyStruct { + LL| | fn method() {} + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |fn main() {} + diff --git a/tests/coverage/attr/impl.rs b/tests/coverage/attr/impl.rs new file mode 100644 index 0000000000000..d4d784a3502b9 --- /dev/null +++ b/tests/coverage/attr/impl.rs @@ -0,0 +1,41 @@ +#![feature(coverage_attribute)] +//@ edition: 2021 + +// Checks that `#[coverage(..)]` can be applied to impl and impl-trait blocks, +// and is inherited by any enclosed functions. + +struct MyStruct; + +#[coverage(off)] +impl MyStruct { + fn off_inherit() {} + + #[coverage(on)] + fn off_on() {} + + #[coverage(off)] + fn off_off() {} +} + +#[coverage(on)] +impl MyStruct { + fn on_inherit() {} + + #[coverage(on)] + fn on_on() {} + + #[coverage(off)] + fn on_off() {} +} + +trait MyTrait { + fn method(); +} + +#[coverage(off)] +impl MyTrait for MyStruct { + fn method() {} +} + +#[coverage(off)] +fn main() {} diff --git a/tests/coverage/attr/module.cov-map b/tests/coverage/attr/module.cov-map new file mode 100644 index 0000000000000..34898eb4ca81d --- /dev/null +++ b/tests/coverage/attr/module.cov-map @@ -0,0 +1,24 @@ +Function name: module::off::on (unused) +Raw bytes (9): 0x[01, 01, 00, 01, 00, 0c, 05, 00, 0f] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 12, 5) to (start + 0, 15) + +Function name: module::on::inherit (unused) +Raw bytes (9): 0x[01, 01, 00, 01, 00, 14, 05, 00, 14] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 20, 5) to (start + 0, 20) + +Function name: module::on::on (unused) +Raw bytes (9): 0x[01, 01, 00, 01, 00, 17, 05, 00, 0f] +Number of files: 1 +- file 0 => global file 1 +Number of expressions: 0 +Number of file 0 mappings: 1 +- Code(Zero) at (prev + 23, 5) to (start + 0, 15) + diff --git a/tests/coverage/attr/module.coverage b/tests/coverage/attr/module.coverage new file mode 100644 index 0000000000000..c1b9f0e35c0b1 --- /dev/null +++ b/tests/coverage/attr/module.coverage @@ -0,0 +1,38 @@ + LL| |#![feature(coverage_attribute)] + LL| |//@ edition: 2021 + LL| | + LL| |// Checks that `#[coverage(..)]` can be applied to modules, and is inherited + LL| |// by any enclosed functions. + LL| | + LL| |#[coverage(off)] + LL| |mod off { + LL| | fn inherit() {} + LL| | + LL| | #[coverage(on)] + LL| 0| fn on() {} + LL| | + LL| | #[coverage(off)] + LL| | fn off() {} + LL| |} + LL| | + LL| |#[coverage(on)] + LL| |mod on { + LL| 0| fn inherit() {} + LL| | + LL| | #[coverage(on)] + LL| 0| fn on() {} + LL| | + LL| | #[coverage(off)] + LL| | fn off() {} + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |mod nested_a { + LL| | mod nested_b { + LL| | fn inner() {} + LL| | } + LL| |} + LL| | + LL| |#[coverage(off)] + LL| |fn main() {} + diff --git a/tests/coverage/attr/module.rs b/tests/coverage/attr/module.rs new file mode 100644 index 0000000000000..4bfb1e7729b7d --- /dev/null +++ b/tests/coverage/attr/module.rs @@ -0,0 +1,37 @@ +#![feature(coverage_attribute)] +//@ edition: 2021 + +// Checks that `#[coverage(..)]` can be applied to modules, and is inherited +// by any enclosed functions. + +#[coverage(off)] +mod off { + fn inherit() {} + + #[coverage(on)] + fn on() {} + + #[coverage(off)] + fn off() {} +} + +#[coverage(on)] +mod on { + fn inherit() {} + + #[coverage(on)] + fn on() {} + + #[coverage(off)] + fn off() {} +} + +#[coverage(off)] +mod nested_a { + mod nested_b { + fn inner() {} + } +} + +#[coverage(off)] +fn main() {} diff --git a/tests/ui/coverage-attr/name-value.rs b/tests/ui/coverage-attr/name-value.rs index cfd78a03e438a..24a0feb0710f6 100644 --- a/tests/ui/coverage-attr/name-value.rs +++ b/tests/ui/coverage-attr/name-value.rs @@ -10,13 +10,11 @@ #[coverage = "off"] //~^ ERROR malformed `coverage` attribute input -//~| ERROR attribute should be applied to a function definition or closure mod my_mod {} mod my_mod_inner { #![coverage = "off"] //~^ ERROR malformed `coverage` attribute input - //~| ERROR attribute should be applied to a function definition or closure } #[coverage = "off"] @@ -26,7 +24,6 @@ struct MyStruct; #[coverage = "off"] //~^ ERROR malformed `coverage` attribute input -//~| ERROR attribute should be applied to a function definition or closure impl MyStruct { #[coverage = "off"] //~^ ERROR malformed `coverage` attribute input @@ -51,7 +48,6 @@ trait MyTrait { #[coverage = "off"] //~^ ERROR malformed `coverage` attribute input -//~| ERROR attribute should be applied to a function definition or closure impl MyTrait for MyStruct { #[coverage = "off"] //~^ ERROR malformed `coverage` attribute input diff --git a/tests/ui/coverage-attr/name-value.stderr b/tests/ui/coverage-attr/name-value.stderr index caac687c94d01..986467dda698e 100644 --- a/tests/ui/coverage-attr/name-value.stderr +++ b/tests/ui/coverage-attr/name-value.stderr @@ -12,7 +12,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:17:5 + --> $DIR/name-value.rs:16:5 | LL | #![coverage = "off"] | ^^^^^^^^^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL | #![coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:22:1 + --> $DIR/name-value.rs:20:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -38,7 +38,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:31:5 + --> $DIR/name-value.rs:28:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -51,7 +51,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:27:1 + --> $DIR/name-value.rs:25:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -64,7 +64,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:41:5 + --> $DIR/name-value.rs:38:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -77,7 +77,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:46:5 + --> $DIR/name-value.rs:43:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -90,7 +90,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:37:1 + --> $DIR/name-value.rs:34:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -103,7 +103,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:56:5 + --> $DIR/name-value.rs:52:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -116,7 +116,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:61:5 + --> $DIR/name-value.rs:57:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -129,7 +129,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:52:1 + --> $DIR/name-value.rs:49:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -142,7 +142,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/name-value.rs:67:1 + --> $DIR/name-value.rs:63:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -155,27 +155,7 @@ LL | #[coverage(on)] | error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:11:1 - | -LL | #[coverage = "off"] - | ^^^^^^^^^^^^^^^^^^^ -... -LL | mod my_mod {} - | ------------- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:17:5 - | -LL | / mod my_mod_inner { -LL | | #![coverage = "off"] - | | ^^^^^^^^^^^^^^^^^^^^ -LL | | -LL | | -LL | | } - | |_- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:22:1 + --> $DIR/name-value.rs:20:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -184,21 +164,7 @@ LL | struct MyStruct; | ---------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:27:1 - | -LL | #[coverage = "off"] - | ^^^^^^^^^^^^^^^^^^^ -... -LL | / impl MyStruct { -LL | | #[coverage = "off"] -LL | | -LL | | -LL | | const X: u32 = 7; -LL | | } - | |_- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:37:1 + --> $DIR/name-value.rs:34:1 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -213,22 +179,7 @@ LL | | } | |_- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:52:1 - | -LL | #[coverage = "off"] - | ^^^^^^^^^^^^^^^^^^^ -... -LL | / impl MyTrait for MyStruct { -LL | | #[coverage = "off"] -LL | | -LL | | -... | -LL | | type T = (); -LL | | } - | |_- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:41:5 + --> $DIR/name-value.rs:38:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -237,7 +188,7 @@ LL | const X: u32; | ------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:46:5 + --> $DIR/name-value.rs:43:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -246,7 +197,7 @@ LL | type T; | ------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:31:5 + --> $DIR/name-value.rs:28:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -255,7 +206,7 @@ LL | const X: u32 = 7; | ----------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:56:5 + --> $DIR/name-value.rs:52:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -264,7 +215,7 @@ LL | const X: u32 = 8; | ----------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/name-value.rs:61:5 + --> $DIR/name-value.rs:57:5 | LL | #[coverage = "off"] | ^^^^^^^^^^^^^^^^^^^ @@ -272,6 +223,6 @@ LL | #[coverage = "off"] LL | type T = (); | ------------ not a function or closure -error: aborting due to 23 previous errors +error: aborting due to 19 previous errors For more information about this error, try `rustc --explain E0788`. diff --git a/tests/ui/coverage-attr/no-coverage.rs b/tests/ui/coverage-attr/no-coverage.rs index 5290fccca6100..9545b0b55cf24 100644 --- a/tests/ui/coverage-attr/no-coverage.rs +++ b/tests/ui/coverage-attr/no-coverage.rs @@ -2,7 +2,7 @@ #![feature(coverage_attribute)] #![feature(impl_trait_in_assoc_type)] #![warn(unused_attributes)] -#![coverage(off)] //~ ERROR attribute should be applied to a function definition or closure +#![coverage(off)] #[coverage(off)] //~ ERROR attribute should be applied to a function definition or closure trait Trait { @@ -15,7 +15,7 @@ trait Trait { type U; } -#[coverage(off)] //~ ERROR attribute should be applied to a function definition or closure +#[coverage(off)] impl Trait for () { const X: u32 = 0; diff --git a/tests/ui/coverage-attr/no-coverage.stderr b/tests/ui/coverage-attr/no-coverage.stderr index c5e3b0922cb42..3897d295940ef 100644 --- a/tests/ui/coverage-attr/no-coverage.stderr +++ b/tests/ui/coverage-attr/no-coverage.stderr @@ -11,20 +11,6 @@ LL | | type U; LL | | } | |_- not a function or closure -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/no-coverage.rs:18:1 - | -LL | #[coverage(off)] - | ^^^^^^^^^^^^^^^^ -LL | / impl Trait for () { -LL | | const X: u32 = 0; -LL | | -LL | | #[coverage(off)] -... | -LL | | type U = impl Trait; -LL | | } - | |_- not a function or closure - error[E0788]: attribute should be applied to a function definition or closure --> $DIR/no-coverage.rs:39:5 | @@ -97,12 +83,6 @@ LL | #[coverage(off)] LL | type T; | ------- not a function or closure -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/no-coverage.rs:5:1 - | -LL | #![coverage(off)] - | ^^^^^^^^^^^^^^^^^ not a function or closure - error: unconstrained opaque type --> $DIR/no-coverage.rs:26:14 | @@ -111,6 +91,6 @@ LL | type U = impl Trait; | = note: `U` must be used in combination with a concrete type within the same impl -error: aborting due to 13 previous errors +error: aborting due to 11 previous errors For more information about this error, try `rustc --explain E0788`. diff --git a/tests/ui/coverage-attr/word-only.rs b/tests/ui/coverage-attr/word-only.rs index 0a61d1e709f51..ea12e7b19eeff 100644 --- a/tests/ui/coverage-attr/word-only.rs +++ b/tests/ui/coverage-attr/word-only.rs @@ -10,13 +10,11 @@ #[coverage] //~^ ERROR malformed `coverage` attribute input -//~| ERROR attribute should be applied to a function definition or closure mod my_mod {} mod my_mod_inner { #![coverage] //~^ ERROR malformed `coverage` attribute input - //~| ERROR attribute should be applied to a function definition or closure } #[coverage] @@ -26,7 +24,6 @@ struct MyStruct; #[coverage] //~^ ERROR malformed `coverage` attribute input -//~| ERROR attribute should be applied to a function definition or closure impl MyStruct { #[coverage] //~^ ERROR malformed `coverage` attribute input @@ -51,7 +48,6 @@ trait MyTrait { #[coverage] //~^ ERROR malformed `coverage` attribute input -//~| ERROR attribute should be applied to a function definition or closure impl MyTrait for MyStruct { #[coverage] //~^ ERROR malformed `coverage` attribute input diff --git a/tests/ui/coverage-attr/word-only.stderr b/tests/ui/coverage-attr/word-only.stderr index 18b5fed748476..1ce149724c6f4 100644 --- a/tests/ui/coverage-attr/word-only.stderr +++ b/tests/ui/coverage-attr/word-only.stderr @@ -12,7 +12,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:17:5 + --> $DIR/word-only.rs:16:5 | LL | #![coverage] | ^^^^^^^^^^^^ @@ -25,7 +25,7 @@ LL | #![coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:22:1 + --> $DIR/word-only.rs:20:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -38,7 +38,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:31:5 + --> $DIR/word-only.rs:28:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -51,7 +51,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:27:1 + --> $DIR/word-only.rs:25:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -64,7 +64,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:41:5 + --> $DIR/word-only.rs:38:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -77,7 +77,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:46:5 + --> $DIR/word-only.rs:43:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -90,7 +90,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:37:1 + --> $DIR/word-only.rs:34:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -103,7 +103,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:56:5 + --> $DIR/word-only.rs:52:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -116,7 +116,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:61:5 + --> $DIR/word-only.rs:57:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -129,7 +129,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:52:1 + --> $DIR/word-only.rs:49:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -142,7 +142,7 @@ LL | #[coverage(on)] | error: malformed `coverage` attribute input - --> $DIR/word-only.rs:67:1 + --> $DIR/word-only.rs:63:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -155,27 +155,7 @@ LL | #[coverage(on)] | error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:11:1 - | -LL | #[coverage] - | ^^^^^^^^^^^ -... -LL | mod my_mod {} - | ------------- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:17:5 - | -LL | / mod my_mod_inner { -LL | | #![coverage] - | | ^^^^^^^^^^^^ -LL | | -LL | | -LL | | } - | |_- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:22:1 + --> $DIR/word-only.rs:20:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -184,21 +164,7 @@ LL | struct MyStruct; | ---------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:27:1 - | -LL | #[coverage] - | ^^^^^^^^^^^ -... -LL | / impl MyStruct { -LL | | #[coverage] -LL | | -LL | | -LL | | const X: u32 = 7; -LL | | } - | |_- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:37:1 + --> $DIR/word-only.rs:34:1 | LL | #[coverage] | ^^^^^^^^^^^ @@ -213,22 +179,7 @@ LL | | } | |_- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:52:1 - | -LL | #[coverage] - | ^^^^^^^^^^^ -... -LL | / impl MyTrait for MyStruct { -LL | | #[coverage] -LL | | -LL | | -... | -LL | | type T = (); -LL | | } - | |_- not a function or closure - -error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:41:5 + --> $DIR/word-only.rs:38:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -237,7 +188,7 @@ LL | const X: u32; | ------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:46:5 + --> $DIR/word-only.rs:43:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -246,7 +197,7 @@ LL | type T; | ------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:31:5 + --> $DIR/word-only.rs:28:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -255,7 +206,7 @@ LL | const X: u32 = 7; | ----------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:56:5 + --> $DIR/word-only.rs:52:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -264,7 +215,7 @@ LL | const X: u32 = 8; | ----------------- not a function or closure error[E0788]: attribute should be applied to a function definition or closure - --> $DIR/word-only.rs:61:5 + --> $DIR/word-only.rs:57:5 | LL | #[coverage] | ^^^^^^^^^^^ @@ -272,6 +223,6 @@ LL | #[coverage] LL | type T = (); | ------------ not a function or closure -error: aborting due to 23 previous errors +error: aborting due to 19 previous errors For more information about this error, try `rustc --explain E0788`. From e5167fe7bd52a8eaebbf01d0b1469785306f4a96 Mon Sep 17 00:00:00 2001 From: ash <97464181+Borgerr@users.noreply.github.com> Date: Tue, 25 Jun 2024 23:58:43 -0600 Subject: [PATCH 19/24] set self.is_known_utf8 to false in extend_from_slice --- library/std/src/sys_common/wtf8.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys_common/wtf8.rs b/library/std/src/sys_common/wtf8.rs index 708f62f476e73..117a3e23044ea 100644 --- a/library/std/src/sys_common/wtf8.rs +++ b/library/std/src/sys_common/wtf8.rs @@ -480,7 +480,7 @@ impl Wtf8Buf { #[inline] pub(crate) fn extend_from_slice(&mut self, other: &[u8]) { self.bytes.extend_from_slice(other); - self.is_known_utf8 = self.is_known_utf8 || self.next_surrogate(0).is_none(); + self.is_known_utf8 = false; } } From 5aac24909c321dd4bb8d90380f9b2dd9f0162c68 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Tue, 25 Jun 2024 22:29:37 -0700 Subject: [PATCH 20/24] std: test a variety of ways to extend a Wtf8Buf --- library/std/src/sys_common/wtf8/tests.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/library/std/src/sys_common/wtf8/tests.rs b/library/std/src/sys_common/wtf8/tests.rs index 6a1cc41a8fb04..b57c99a8452a1 100644 --- a/library/std/src/sys_common/wtf8/tests.rs +++ b/library/std/src/sys_common/wtf8/tests.rs @@ -725,3 +725,27 @@ fn wtf8_utf8_boundary_between_surrogates() { string.push(CodePoint::from_u32(0xD800).unwrap()); check_utf8_boundary(&string, 3); } + +#[test] +fn wobbled_wtf8_plus_bytes_isnt_utf8() { + let mut string: Wtf8Buf = unsafe { Wtf8::from_bytes_unchecked(b"\xED\xA0\x80").to_owned() }; + assert!(!string.is_known_utf8); + string.extend_from_slice(b"some utf-8"); + assert!(!string.is_known_utf8); +} + +#[test] +fn wobbled_wtf8_plus_str_isnt_utf8() { + let mut string: Wtf8Buf = unsafe { Wtf8::from_bytes_unchecked(b"\xED\xA0\x80").to_owned() }; + assert!(!string.is_known_utf8); + string.push_str("some utf-8"); + assert!(!string.is_known_utf8); +} + +#[test] +fn unwobbly_wtf8_plus_utf8_is_utf8() { + let mut string: Wtf8Buf = Wtf8Buf::from_str("hello world"); + assert!(string.is_known_utf8); + string.push_str("some utf-8"); + assert!(string.is_known_utf8); +} From 518b74ec5d97317af70d3fdbc41eac903622a6b9 Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 21 Jun 2024 04:09:38 -0400 Subject: [PATCH 21/24] Remove `f16` and `f128` ICE paths from smir --- compiler/rustc_smir/src/rustc_internal/internal.rs | 2 ++ compiler/rustc_smir/src/rustc_smir/convert/ty.rs | 4 ++-- compiler/stable_mir/src/ty.rs | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index c9c1570a29a8b..7b5abcf45130d 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -188,8 +188,10 @@ impl RustcInternal for FloatTy { fn internal<'tcx>(&self, _tables: &mut Tables<'_>, _tcx: TyCtxt<'tcx>) -> Self::T<'tcx> { match self { + FloatTy::F16 => rustc_ty::FloatTy::F16, FloatTy::F32 => rustc_ty::FloatTy::F32, FloatTy::F64 => rustc_ty::FloatTy::F64, + FloatTy::F128 => rustc_ty::FloatTy::F128, } } } diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index 9cd841bba1095..74c3fcc9b9ea9 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -304,10 +304,10 @@ impl<'tcx> Stable<'tcx> for ty::FloatTy { fn stable(&self, _: &mut Tables<'_>) -> Self::T { match self { - ty::FloatTy::F16 => unimplemented!("f16_f128"), + ty::FloatTy::F16 => FloatTy::F16, ty::FloatTy::F32 => FloatTy::F32, ty::FloatTy::F64 => FloatTy::F64, - ty::FloatTy::F128 => unimplemented!("f16_f128"), + ty::FloatTy::F128 => FloatTy::F128, } } } diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index 8c120a96e75b1..01e4f1d1f33bc 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -608,8 +608,10 @@ impl UintTy { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FloatTy { + F16, F32, F64, + F128, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] From de0ece2f2935d005232a5062eeb8b916b1d8a41a Mon Sep 17 00:00:00 2001 From: DianQK Date: Sun, 23 Jun 2024 22:06:23 +0800 Subject: [PATCH 22/24] Add clang-format to the external tool check --- Cargo.lock | 1 + src/tools/tidy/Cargo.toml | 1 + src/tools/tidy/src/ext_tool_checks.rs | 134 +++++++++++++++++++++++--- 3 files changed, 124 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 241a37588b409..6d0563839aedf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5627,6 +5627,7 @@ dependencies = [ "regex", "rustc-hash", "semver", + "similar", "termcolor", "walkdir", ] diff --git a/src/tools/tidy/Cargo.toml b/src/tools/tidy/Cargo.toml index 0b05d5add52d6..1acdf9fbc7fc8 100644 --- a/src/tools/tidy/Cargo.toml +++ b/src/tools/tidy/Cargo.toml @@ -15,6 +15,7 @@ semver = "1.0" termcolor = "1.1.3" rustc-hash = "1.1.0" fluent-syntax = "0.11.1" +similar = "2.5.0" [[bin]] name = "rust-tidy" diff --git a/src/tools/tidy/src/ext_tool_checks.rs b/src/tools/tidy/src/ext_tool_checks.rs index e9dd6c66f6447..1df4921ef864a 100644 --- a/src/tools/tidy/src/ext_tool_checks.rs +++ b/src/tools/tidy/src/ext_tool_checks.rs @@ -73,6 +73,8 @@ fn check_impl( let python_fmt = lint_args.contains(&"py:fmt") || python_all; let shell_all = lint_args.contains(&"shell"); let shell_lint = lint_args.contains(&"shell:lint") || shell_all; + let cpp_all = lint_args.contains(&"cpp"); + let cpp_fmt = lint_args.contains(&"cpp:fmt") || cpp_all; let mut py_path = None; @@ -81,7 +83,7 @@ fn check_impl( .map(OsStr::new) .partition(|arg| arg.to_str().is_some_and(|s| s.starts_with('-'))); - if python_lint || python_fmt { + if python_lint || python_fmt || cpp_fmt { let venv_path = outdir.join("venv"); let mut reqs_path = root_path.to_owned(); reqs_path.extend(PIP_REQ_PATH); @@ -111,13 +113,13 @@ fn check_impl( let mut args = merge_args(&cfg_args_ruff, &file_args_ruff); args.insert(0, "check".as_ref()); - let res = py_runner(py_path.as_ref().unwrap(), "ruff", &args); + let res = py_runner(py_path.as_ref().unwrap(), true, None, "ruff", &args); if res.is_err() && show_diff { eprintln!("\npython linting failed! Printing diff suggestions:"); args.insert(1, "--diff".as_ref()); - let _ = py_runner(py_path.as_ref().unwrap(), "ruff", &args); + let _ = py_runner(py_path.as_ref().unwrap(), true, None, "ruff", &args); } // Rethrow error let _ = res?; @@ -144,13 +146,84 @@ fn check_impl( } let mut args = merge_args(&cfg_args_black, &file_args_black); - let res = py_runner(py_path.as_ref().unwrap(), "black", &args); + let res = py_runner(py_path.as_ref().unwrap(), true, None, "black", &args); if res.is_err() && show_diff { eprintln!("\npython formatting does not match! Printing diff:"); args.insert(0, "--diff".as_ref()); - let _ = py_runner(py_path.as_ref().unwrap(), "black", &args); + let _ = py_runner(py_path.as_ref().unwrap(), true, None, "black", &args); + } + // Rethrow error + let _ = res?; + } + + if cpp_fmt { + let mut cfg_args_clang_format = cfg_args.clone(); + let mut file_args_clang_format = file_args.clone(); + let config_path = root_path.join(".clang-format"); + let config_file_arg = format!("file:{}", config_path.display()); + cfg_args_clang_format.extend(&["--style".as_ref(), config_file_arg.as_ref()]); + if bless { + eprintln!("formatting C++ files"); + cfg_args_clang_format.push("-i".as_ref()); + } else { + eprintln!("checking C++ file formatting"); + cfg_args_clang_format.extend(&["--dry-run".as_ref(), "--Werror".as_ref()]); + } + let files; + if file_args_clang_format.is_empty() { + let llvm_wrapper = root_path.join("compiler/rustc_llvm/llvm-wrapper"); + files = find_with_extension( + root_path, + Some(llvm_wrapper.as_path()), + &[OsStr::new("h"), OsStr::new("cpp")], + )?; + file_args_clang_format.extend(files.iter().map(|p| p.as_os_str())); + } + let args = merge_args(&cfg_args_clang_format, &file_args_clang_format); + let res = py_runner(py_path.as_ref().unwrap(), false, None, "clang-format", &args); + + if res.is_err() && show_diff { + eprintln!("\nclang-format linting failed! Printing diff suggestions:"); + + let mut cfg_args_clang_format_diff = cfg_args.clone(); + cfg_args_clang_format_diff.extend(&["--style".as_ref(), config_file_arg.as_ref()]); + for file in file_args_clang_format { + let mut formatted = String::new(); + let mut diff_args = cfg_args_clang_format_diff.clone(); + diff_args.push(file); + let _ = py_runner( + py_path.as_ref().unwrap(), + false, + Some(&mut formatted), + "clang-format", + &diff_args, + ); + if formatted.is_empty() { + eprintln!( + "failed to obtain the formatted content for '{}'", + file.to_string_lossy() + ); + continue; + } + let actual = std::fs::read_to_string(file).unwrap_or_else(|e| { + panic!( + "failed to read the C++ file at '{}' due to '{e}'", + file.to_string_lossy() + ) + }); + if formatted != actual { + let diff = similar::TextDiff::from_lines(&actual, &formatted); + eprintln!( + "{}", + diff.unified_diff().context_radius(4).header( + &format!("{} (actual)", file.to_string_lossy()), + &format!("{} (formatted)", file.to_string_lossy()) + ) + ); + } + } } // Rethrow error let _ = res?; @@ -162,7 +235,7 @@ fn check_impl( let mut file_args_shc = file_args.clone(); let files; if file_args_shc.is_empty() { - files = find_with_extension(root_path, "sh")?; + files = find_with_extension(root_path, None, &[OsStr::new("sh")])?; file_args_shc.extend(files.iter().map(|p| p.as_os_str())); } @@ -181,8 +254,31 @@ fn merge_args<'a>(cfg_args: &[&'a OsStr], file_args: &[&'a OsStr]) -> Vec<&'a Os } /// Run a python command with given arguments. `py_path` should be a virtualenv. -fn py_runner(py_path: &Path, bin: &'static str, args: &[&OsStr]) -> Result<(), Error> { - let status = Command::new(py_path).arg("-m").arg(bin).args(args).status()?; +/// +/// Captures `stdout` to a string if provided, otherwise prints the output. +fn py_runner( + py_path: &Path, + as_module: bool, + stdout: Option<&mut String>, + bin: &'static str, + args: &[&OsStr], +) -> Result<(), Error> { + let mut cmd = Command::new(py_path); + if as_module { + cmd.arg("-m").arg(bin).args(args); + } else { + let bin_path = py_path.with_file_name(bin); + cmd.arg(bin_path).args(args); + } + let status = if let Some(stdout) = stdout { + let output = cmd.output()?; + if let Ok(s) = std::str::from_utf8(&output.stdout) { + stdout.push_str(s); + } + output.status + } else { + cmd.status()? + }; if status.success() { Ok(()) } else { Err(Error::FailedCheck(bin)) } } @@ -357,7 +453,11 @@ fn shellcheck_runner(args: &[&OsStr]) -> Result<(), Error> { } /// Check git for tracked files matching an extension -fn find_with_extension(root_path: &Path, extension: &str) -> Result, Error> { +fn find_with_extension( + root_path: &Path, + find_dir: Option<&Path>, + extensions: &[&OsStr], +) -> Result, Error> { // Untracked files show up for short status and are indicated with a leading `?` // -C changes git to be as if run from that directory let stat_output = @@ -368,15 +468,25 @@ fn find_with_extension(root_path: &Path, extension: &str) -> Result } let mut output = Vec::new(); - let binding = Command::new("git").arg("-C").arg(root_path).args(["ls-files"]).output()?; + let binding = { + let mut command = Command::new("git"); + command.arg("-C").arg(root_path).args(["ls-files"]); + if let Some(find_dir) = find_dir { + command.arg(find_dir); + } + command.output()? + }; let tracked = String::from_utf8_lossy(&binding.stdout); for line in tracked.lines() { let line = line.trim(); let path = Path::new(line); - if path.extension() == Some(OsStr::new(extension)) { - output.push(path.to_owned()); + let Some(ref extension) = path.extension() else { + continue; + }; + if extensions.contains(extension) { + output.push(root_path.join(path)); } } From e17c16d55b20b9d2702fafa017263406d1e94042 Mon Sep 17 00:00:00 2001 From: DianQK Date: Tue, 4 Jun 2024 22:46:20 +0800 Subject: [PATCH 23/24] Format C++ files in `llvm-wrapper` --- .../llvm-wrapper/ArchiveWrapper.cpp | 33 +- compiler/rustc_llvm/llvm-wrapper/Linker.cpp | 18 +- .../rustc_llvm/llvm-wrapper/PassWrapper.cpp | 470 ++++---- .../rustc_llvm/llvm-wrapper/RustWrapper.cpp | 1027 ++++++++--------- .../llvm-wrapper/SuppressLLVMWarnings.h | 14 +- .../rustc_llvm/llvm-wrapper/SymbolWrapper.cpp | 23 +- 6 files changed, 764 insertions(+), 821 deletions(-) diff --git a/compiler/rustc_llvm/llvm-wrapper/ArchiveWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/ArchiveWrapper.cpp index 8871f410e366c..a8c278741a77b 100644 --- a/compiler/rustc_llvm/llvm-wrapper/ArchiveWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/ArchiveWrapper.cpp @@ -13,10 +13,7 @@ struct RustArchiveMember { Archive::Child Child; RustArchiveMember() - : Filename(nullptr), Name(nullptr), - Child(nullptr, nullptr, nullptr) - { - } + : Filename(nullptr), Name(nullptr), Child(nullptr, nullptr, nullptr) {} ~RustArchiveMember() {} }; @@ -27,11 +24,8 @@ struct RustArchiveIterator { std::unique_ptr Err; RustArchiveIterator(Archive::child_iterator Cur, Archive::child_iterator End, - std::unique_ptr Err) - : First(true), - Cur(Cur), - End(End), - Err(std::move(Err)) {} + std::unique_ptr Err) + : First(true), Cur(Cur), End(End), Err(std::move(Err)) {} }; enum class LLVMRustArchiveKind { @@ -66,8 +60,8 @@ typedef Archive::Child const *LLVMRustArchiveChildConstRef; typedef RustArchiveIterator *LLVMRustArchiveIteratorRef; extern "C" LLVMRustArchiveRef LLVMRustOpenArchive(char *Path) { - ErrorOr> BufOr = - MemoryBuffer::getFile(Path, /*IsText*/false, /*RequiresNullTerminator=*/false); + ErrorOr> BufOr = MemoryBuffer::getFile( + Path, /*IsText*/ false, /*RequiresNullTerminator=*/false); if (!BufOr) { LLVMRustSetLastError(BufOr.getError().message().c_str()); return nullptr; @@ -146,8 +140,8 @@ extern "C" const char * LLVMRustArchiveChildName(LLVMRustArchiveChildConstRef Child, size_t *Size) { Expected NameOrErr = Child->getName(); if (!NameOrErr) { - // rustc_codegen_llvm currently doesn't use this error string, but it might be - // useful in the future, and in the meantime this tells LLVM that the + // rustc_codegen_llvm currently doesn't use this error string, but it might + // be useful in the future, and in the meantime this tells LLVM that the // error was not ignored and that it shouldn't abort the process. LLVMRustSetLastError(toString(NameOrErr.takeError()).c_str()); return nullptr; @@ -172,10 +166,9 @@ extern "C" void LLVMRustArchiveMemberFree(LLVMRustArchiveMemberRef Member) { delete Member; } -extern "C" LLVMRustResult -LLVMRustWriteArchive(char *Dst, size_t NumMembers, - const LLVMRustArchiveMemberRef *NewMembers, - bool WriteSymbtab, LLVMRustArchiveKind RustKind, bool isEC) { +extern "C" LLVMRustResult LLVMRustWriteArchive( + char *Dst, size_t NumMembers, const LLVMRustArchiveMemberRef *NewMembers, + bool WriteSymbtab, LLVMRustArchiveKind RustKind, bool isEC) { std::vector Members; auto Kind = fromRust(RustKind); @@ -206,8 +199,10 @@ LLVMRustWriteArchive(char *Dst, size_t NumMembers, #if LLVM_VERSION_LT(18, 0) auto Result = writeArchive(Dst, Members, WriteSymbtab, Kind, true, false); #else - auto SymtabMode = WriteSymbtab ? SymtabWritingMode::NormalSymtab : SymtabWritingMode::NoSymtab; - auto Result = writeArchive(Dst, Members, SymtabMode, Kind, true, false, nullptr, isEC); + auto SymtabMode = WriteSymbtab ? SymtabWritingMode::NormalSymtab + : SymtabWritingMode::NoSymtab; + auto Result = + writeArchive(Dst, Members, SymtabMode, Kind, true, false, nullptr, isEC); #endif if (!Result) return LLVMRustResult::Success; diff --git a/compiler/rustc_llvm/llvm-wrapper/Linker.cpp b/compiler/rustc_llvm/llvm-wrapper/Linker.cpp index 533df0f75f8f5..f43128ed55058 100644 --- a/compiler/rustc_llvm/llvm-wrapper/Linker.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/Linker.cpp @@ -1,5 +1,5 @@ -#include "SuppressLLVMWarnings.h" #include "llvm/Linker/Linker.h" +#include "SuppressLLVMWarnings.h" #include "LLVMWrapper.h" @@ -9,26 +9,18 @@ struct RustLinker { Linker L; LLVMContext &Ctx; - RustLinker(Module &M) : - L(M), - Ctx(M.getContext()) - {} + RustLinker(Module &M) : L(M), Ctx(M.getContext()) {} }; -extern "C" RustLinker* -LLVMRustLinkerNew(LLVMModuleRef DstRef) { +extern "C" RustLinker *LLVMRustLinkerNew(LLVMModuleRef DstRef) { Module *Dst = unwrap(DstRef); return new RustLinker(*Dst); } -extern "C" void -LLVMRustLinkerFree(RustLinker *L) { - delete L; -} +extern "C" void LLVMRustLinkerFree(RustLinker *L) { delete L; } -extern "C" bool -LLVMRustLinkerAdd(RustLinker *L, char *BC, size_t Len) { +extern "C" bool LLVMRustLinkerAdd(RustLinker *L, char *BC, size_t Len) { std::unique_ptr Buf = MemoryBuffer::getMemBufferCopy(StringRef(BC, Len)); diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index a027ddcc1508a..c4cfc0b6dc6a1 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -2,23 +2,25 @@ #include #include -#include #include +#include #include "LLVMWrapper.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" +#include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" -#include "llvm/IR/AutoUpgrade.h" #include "llvm/IR/AssemblyAnnotationWriter.h" +#include "llvm/IR/AutoUpgrade.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Verifier.h" +#include "llvm/LTO/LTO.h" #include "llvm/MC/TargetRegistry.h" -#include "llvm/Object/ObjectFile.h" #include "llvm/Object/IRObjectFile.h" +#include "llvm/Object/ObjectFile.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Passes/PassPlugin.h" #include "llvm/Passes/StandardInstrumentations.h" @@ -33,26 +35,24 @@ #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" #include "llvm/Transforms/Utils/AddDiscriminators.h" #include "llvm/Transforms/Utils/FunctionImportUtils.h" -#include "llvm/LTO/LTO.h" -#include "llvm/Bitcode/BitcodeWriter.h" #if LLVM_VERSION_GE(18, 0) #include "llvm/TargetParser/Host.h" #endif +#include "llvm/Support/TimeProfiler.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h" -#include "llvm/Support/TimeProfiler.h" #if LLVM_VERSION_GE(19, 0) #include "llvm/Support/PGOOptions.h" #endif #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" +#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" #include "llvm/Transforms/Instrumentation/InstrProfiling.h" -#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" -#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" +#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" +#include "llvm/Transforms/Utils.h" #include "llvm/Transforms/Utils/CanonicalizeAliases.h" #include "llvm/Transforms/Utils/NameAnonGlobals.h" -#include "llvm/Transforms/Utils.h" using namespace llvm; @@ -74,7 +74,7 @@ extern "C" void LLVMRustTimeTraceProfilerFinishThread() { timeTraceProfilerFinishThread(); } -extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) { +extern "C" void LLVMRustTimeTraceProfilerFinish(const char *FileName) { auto FN = StringRef(FileName); std::error_code EC; auto OS = raw_fd_ostream(FN, EC, sys::fs::CD_CreateAlways); @@ -188,7 +188,7 @@ extern "C" void LLVMRustTimeTraceProfilerFinish(const char* FileName) { SUBTARGET_HEXAGON \ SUBTARGET_XTENSA \ SUBTARGET_RISCV \ - SUBTARGET_LOONGARCH \ + SUBTARGET_LOONGARCH #define SUBTARGET(x) \ namespace llvm { \ @@ -215,8 +215,7 @@ enum class LLVMRustCodeModel { None, }; -static std::optional -fromRust(LLVMRustCodeModel Model) { +static std::optional fromRust(LLVMRustCodeModel Model) { switch (Model) { case LLVMRustCodeModel::Tiny: return CodeModel::Tiny; @@ -243,9 +242,9 @@ enum class LLVMRustCodeGenOptLevel { }; #if LLVM_VERSION_GE(18, 0) - using CodeGenOptLevelEnum = llvm::CodeGenOptLevel; +using CodeGenOptLevelEnum = llvm::CodeGenOptLevel; #else - using CodeGenOptLevelEnum = llvm::CodeGenOpt::Level; +using CodeGenOptLevelEnum = llvm::CodeGenOpt::Level; #endif static CodeGenOptLevelEnum fromRust(LLVMRustCodeGenOptLevel Level) { @@ -319,48 +318,49 @@ static Reloc::Model fromRust(LLVMRustRelocModel RustReloc) { } /// getLongestEntryLength - Return the length of the longest entry in the table. -template -static size_t getLongestEntryLength(ArrayRef Table) { +template static size_t getLongestEntryLength(ArrayRef Table) { size_t MaxLen = 0; for (auto &I : Table) MaxLen = std::max(MaxLen, std::strlen(I.Key)); return MaxLen; } -using PrintBackendInfo = void(void*, const char* Data, size_t Len); +using PrintBackendInfo = void(void *, const char *Data, size_t Len); extern "C" void LLVMRustPrintTargetCPUs(LLVMTargetMachineRef TM, - const char* TargetCPU, - PrintBackendInfo Print, - void* Out) { + const char *TargetCPU, + PrintBackendInfo Print, void *Out) { const TargetMachine *Target = unwrap(TM); - const Triple::ArchType HostArch = Triple(sys::getDefaultTargetTriple()).getArch(); + const Triple::ArchType HostArch = + Triple(sys::getDefaultTargetTriple()).getArch(); const Triple::ArchType TargetArch = Target->getTargetTriple().getArch(); std::ostringstream Buf; const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo(); - const ArrayRef CPUTable = MCInfo->getAllProcessorDescriptions(); + const ArrayRef CPUTable = + MCInfo->getAllProcessorDescriptions(); unsigned MaxCPULen = getLongestEntryLength(CPUTable); Buf << "Available CPUs for this target:\n"; // Don't print the "native" entry when the user specifies --target with a // different arch since that could be wrong or misleading. if (HostArch == TargetArch) { - MaxCPULen = std::max(MaxCPULen, (unsigned) std::strlen("native")); + MaxCPULen = std::max(MaxCPULen, (unsigned)std::strlen("native")); const StringRef HostCPU = sys::getHostCPUName(); Buf << " " << std::left << std::setw(MaxCPULen) << "native" << " - Select the CPU of the current host " - "(currently " << HostCPU.str() << ").\n"; + "(currently " + << HostCPU.str() << ").\n"; } for (auto &CPU : CPUTable) { // Compare cpu against current target to label the default if (strcmp(CPU.Key, TargetCPU) == 0) { Buf << " " << std::left << std::setw(MaxCPULen) << CPU.Key << " - This is the default target CPU for the current build target " - "(currently " << Target->getTargetTriple().str() << ")."; - } - else { + "(currently " + << Target->getTargetTriple().str() << ")."; + } else { Buf << " " << CPU.Key; } Buf << "\n"; @@ -374,7 +374,8 @@ extern "C" size_t LLVMRustGetTargetFeaturesCount(LLVMTargetMachineRef TM) { #if LLVM_VERSION_GE(18, 0) const TargetMachine *Target = unwrap(TM); const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo(); - const ArrayRef FeatTable = MCInfo->getAllProcessorFeatures(); + const ArrayRef FeatTable = + MCInfo->getAllProcessorFeatures(); return FeatTable.size(); #else return 0; @@ -382,18 +383,20 @@ extern "C" size_t LLVMRustGetTargetFeaturesCount(LLVMTargetMachineRef TM) { } extern "C" void LLVMRustGetTargetFeature(LLVMTargetMachineRef TM, size_t Index, - const char** Feature, const char** Desc) { + const char **Feature, + const char **Desc) { #if LLVM_VERSION_GE(18, 0) const TargetMachine *Target = unwrap(TM); const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo(); - const ArrayRef FeatTable = MCInfo->getAllProcessorFeatures(); + const ArrayRef FeatTable = + MCInfo->getAllProcessorFeatures(); const SubtargetFeatureKV Feat = FeatTable[Index]; *Feature = Feat.Key; *Desc = Feat.Desc; #endif } -extern "C" const char* LLVMRustGetHostCPUName(size_t *len) { +extern "C" const char *LLVMRustGetHostCPUName(size_t *len) { StringRef Name = sys::getHostCPUName(); *len = Name.size(); return Name.data(); @@ -403,19 +406,11 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( const char *TripleStr, const char *CPU, const char *Feature, const char *ABIStr, LLVMRustCodeModel RustCM, LLVMRustRelocModel RustReloc, LLVMRustCodeGenOptLevel RustOptLevel, bool UseSoftFloat, - bool FunctionSections, - bool DataSections, - bool UniqueSectionNames, - bool TrapUnreachable, - bool Singlethread, - bool AsmComments, - bool EmitStackSizeSection, - bool RelaxELFRelocations, - bool UseInitArray, - const char *SplitDwarfFile, - const char *OutputObjFile, - const char *DebugInfoCompression, - bool UseEmulatedTls, + bool FunctionSections, bool DataSections, bool UniqueSectionNames, + bool TrapUnreachable, bool Singlethread, bool AsmComments, + bool EmitStackSizeSection, bool RelaxELFRelocations, bool UseInitArray, + const char *SplitDwarfFile, const char *OutputObjFile, + const char *DebugInfoCompression, bool UseEmulatedTls, const char *ArgsCstrBuff, size_t ArgsCstrBuffLen) { auto OptLevel = fromRust(RustOptLevel); @@ -444,18 +439,20 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.MCOptions.PreserveAsmComments = AsmComments; Options.MCOptions.ABIName = ABIStr; if (SplitDwarfFile) { - Options.MCOptions.SplitDwarfFile = SplitDwarfFile; + Options.MCOptions.SplitDwarfFile = SplitDwarfFile; } if (OutputObjFile) { - Options.ObjectFilenameForDebug = OutputObjFile; + Options.ObjectFilenameForDebug = OutputObjFile; } - if (!strcmp("zlib", DebugInfoCompression) && llvm::compression::zlib::isAvailable()) { + if (!strcmp("zlib", DebugInfoCompression) && + llvm::compression::zlib::isAvailable()) { #if LLVM_VERSION_GE(19, 0) Options.MCOptions.CompressDebugSections = DebugCompressionType::Zlib; #else Options.CompressDebugSections = DebugCompressionType::Zlib; #endif - } else if (!strcmp("zstd", DebugInfoCompression) && llvm::compression::zstd::isAvailable()) { + } else if (!strcmp("zstd", DebugInfoCompression) && + llvm::compression::zstd::isAvailable()) { #if LLVM_VERSION_GE(19, 0) Options.MCOptions.CompressDebugSections = DebugCompressionType::Zstd; #else @@ -499,24 +496,21 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.EmitStackSizeSection = EmitStackSizeSection; - - if (ArgsCstrBuff != nullptr) - { + if (ArgsCstrBuff != nullptr) { int buffer_offset = 0; assert(ArgsCstrBuff[ArgsCstrBuffLen - 1] == '\0'); const size_t arg0_len = std::strlen(ArgsCstrBuff); - char* arg0 = new char[arg0_len + 1]; + char *arg0 = new char[arg0_len + 1]; memcpy(arg0, ArgsCstrBuff, arg0_len); arg0[arg0_len] = '\0'; buffer_offset += arg0_len + 1; - const int num_cmd_arg_strings = - std::count(&ArgsCstrBuff[buffer_offset], &ArgsCstrBuff[ArgsCstrBuffLen], '\0'); + const int num_cmd_arg_strings = std::count( + &ArgsCstrBuff[buffer_offset], &ArgsCstrBuff[ArgsCstrBuffLen], '\0'); - std::string* cmd_arg_strings = new std::string[num_cmd_arg_strings]; - for (int i = 0; i < num_cmd_arg_strings; ++i) - { + std::string *cmd_arg_strings = new std::string[num_cmd_arg_strings]; + for (int i = 0; i < num_cmd_arg_strings; ++i) { assert(buffer_offset < ArgsCstrBuffLen); const int len = std::strlen(ArgsCstrBuff + buffer_offset); cmd_arg_strings[i] = std::string(&ArgsCstrBuff[buffer_offset], len); @@ -527,7 +521,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.MCOptions.Argv0 = arg0; Options.MCOptions.CommandLineArgs = - llvm::ArrayRef(cmd_arg_strings, num_cmd_arg_strings); + llvm::ArrayRef(cmd_arg_strings, num_cmd_arg_strings); } TargetMachine *TM = TheTarget->createTargetMachine( @@ -537,7 +531,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) { - MCTargetOptions& MCOptions = unwrap(TM)->Options.MCOptions; + MCTargetOptions &MCOptions = unwrap(TM)->Options.MCOptions; delete[] MCOptions.Argv0; delete[] MCOptions.CommandLineArgs.data(); @@ -613,7 +607,7 @@ LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR, auto DOS = raw_fd_ostream(DwoPath, EC, sys::fs::OF_None); EC.clear(); if (EC) - ErrorInfo = EC.message(); + ErrorInfo = EC.message(); if (ErrorInfo != "") { LLVMRustSetLastError(ErrorInfo.c_str()); return LLVMRustResult::Failure; @@ -633,10 +627,12 @@ LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR, return LLVMRustResult::Success; } -extern "C" typedef void (*LLVMRustSelfProfileBeforePassCallback)(void*, // LlvmSelfProfiler - const char*, // pass name - const char*); // IR name -extern "C" typedef void (*LLVMRustSelfProfileAfterPassCallback)(void*); // LlvmSelfProfiler +extern "C" typedef void (*LLVMRustSelfProfileBeforePassCallback)( + void *, // LlvmSelfProfiler + const char *, // pass name + const char *); // IR name +extern "C" typedef void (*LLVMRustSelfProfileAfterPassCallback)( + void *); // LlvmSelfProfiler std::string LLVMRustwrappedIrGetName(const llvm::Any &WrappedIr) { if (const auto *Cast = any_cast(&WrappedIr)) @@ -650,35 +646,35 @@ std::string LLVMRustwrappedIrGetName(const llvm::Any &WrappedIr) { return ""; } - void LLVMSelfProfileInitializeCallbacks( - PassInstrumentationCallbacks& PIC, void* LlvmSelfProfiler, + PassInstrumentationCallbacks &PIC, void *LlvmSelfProfiler, LLVMRustSelfProfileBeforePassCallback BeforePassCallback, LLVMRustSelfProfileAfterPassCallback AfterPassCallback) { - PIC.registerBeforeNonSkippedPassCallback([LlvmSelfProfiler, BeforePassCallback]( - StringRef Pass, llvm::Any Ir) { - std::string PassName = Pass.str(); - std::string IrName = LLVMRustwrappedIrGetName(Ir); - BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str()); - }); + PIC.registerBeforeNonSkippedPassCallback( + [LlvmSelfProfiler, BeforePassCallback](StringRef Pass, llvm::Any Ir) { + std::string PassName = Pass.str(); + std::string IrName = LLVMRustwrappedIrGetName(Ir); + BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str()); + }); PIC.registerAfterPassCallback( - [LlvmSelfProfiler, AfterPassCallback](StringRef Pass, llvm::Any IR, - const PreservedAnalyses &Preserved) { + [LlvmSelfProfiler, AfterPassCallback]( + StringRef Pass, llvm::Any IR, const PreservedAnalyses &Preserved) { AfterPassCallback(LlvmSelfProfiler); }); PIC.registerAfterPassInvalidatedCallback( - [LlvmSelfProfiler, AfterPassCallback](StringRef Pass, const PreservedAnalyses &Preserved) { + [LlvmSelfProfiler, + AfterPassCallback](StringRef Pass, const PreservedAnalyses &Preserved) { AfterPassCallback(LlvmSelfProfiler); }); - PIC.registerBeforeAnalysisCallback([LlvmSelfProfiler, BeforePassCallback]( - StringRef Pass, llvm::Any Ir) { - std::string PassName = Pass.str(); - std::string IrName = LLVMRustwrappedIrGetName(Ir); - BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str()); - }); + PIC.registerBeforeAnalysisCallback( + [LlvmSelfProfiler, BeforePassCallback](StringRef Pass, llvm::Any Ir) { + std::string PassName = Pass.str(); + std::string IrName = LLVMRustwrappedIrGetName(Ir); + BeforePassCallback(LlvmSelfProfiler, PassName.c_str(), IrName.c_str()); + }); PIC.registerAfterAnalysisCallback( [LlvmSelfProfiler, AfterPassCallback](StringRef Pass, llvm::Any Ir) { @@ -704,7 +700,7 @@ struct LLVMRustSanitizerOptions { bool SanitizeKCFI; bool SanitizeMemory; bool SanitizeMemoryRecover; - int SanitizeMemoryTrackOrigins; + int SanitizeMemoryTrackOrigins; bool SanitizeThread; bool SanitizeHWAddress; bool SanitizeHWAddressRecover; @@ -712,31 +708,25 @@ struct LLVMRustSanitizerOptions { bool SanitizeKernelAddressRecover; }; -extern "C" LLVMRustResult -LLVMRustOptimize( - LLVMModuleRef ModuleRef, - LLVMTargetMachineRef TMRef, - LLVMRustPassBuilderOptLevel OptLevelRust, - LLVMRustOptStage OptStage, - bool IsLinkerPluginLTO, - bool NoPrepopulatePasses, bool VerifyIR, bool UseThinLTOBuffers, - bool MergeFunctions, bool UnrollLoops, bool SLPVectorize, bool LoopVectorize, - bool DisableSimplifyLibCalls, bool EmitLifetimeMarkers, - LLVMRustSanitizerOptions *SanitizerOptions, - const char *PGOGenPath, const char *PGOUsePath, - bool InstrumentCoverage, const char *InstrProfileOutput, - bool InstrumentGCOV, +extern "C" LLVMRustResult LLVMRustOptimize( + LLVMModuleRef ModuleRef, LLVMTargetMachineRef TMRef, + LLVMRustPassBuilderOptLevel OptLevelRust, LLVMRustOptStage OptStage, + bool IsLinkerPluginLTO, bool NoPrepopulatePasses, bool VerifyIR, + bool UseThinLTOBuffers, bool MergeFunctions, bool UnrollLoops, + bool SLPVectorize, bool LoopVectorize, bool DisableSimplifyLibCalls, + bool EmitLifetimeMarkers, LLVMRustSanitizerOptions *SanitizerOptions, + const char *PGOGenPath, const char *PGOUsePath, bool InstrumentCoverage, + const char *InstrProfileOutput, bool InstrumentGCOV, const char *PGOSampleUsePath, bool DebugInfoForProfiling, - void* LlvmSelfProfiler, + void *LlvmSelfProfiler, LLVMRustSelfProfileBeforePassCallback BeforePassCallback, LLVMRustSelfProfileAfterPassCallback AfterPassCallback, - const char *ExtraPasses, size_t ExtraPassesLen, - const char *LLVMPlugins, size_t LLVMPluginsLen) { + const char *ExtraPasses, size_t ExtraPassesLen, const char *LLVMPlugins, + size_t LLVMPluginsLen) { Module *TheModule = unwrap(ModuleRef); TargetMachine *TM = unwrap(TMRef); OptimizationLevel OptLevel = fromRust(OptLevelRust); - PipelineTuningOptions PTO; PTO.LoopUnrolling = UnrollLoops; PTO.LoopInterleaving = UnrollLoops; @@ -751,38 +741,39 @@ LLVMRustOptimize( StandardInstrumentations SI(TheModule->getContext(), DebugPassManager); SI.registerCallbacks(PIC); - if (LlvmSelfProfiler){ - LLVMSelfProfileInitializeCallbacks(PIC,LlvmSelfProfiler,BeforePassCallback,AfterPassCallback); + if (LlvmSelfProfiler) { + LLVMSelfProfileInitializeCallbacks(PIC, LlvmSelfProfiler, + BeforePassCallback, AfterPassCallback); } std::optional PGOOpt; auto FS = vfs::getRealFileSystem(); if (PGOGenPath) { assert(!PGOUsePath && !PGOSampleUsePath); - PGOOpt = PGOOptions(PGOGenPath, "", "", "", FS, - PGOOptions::IRInstr, PGOOptions::NoCSAction, + PGOOpt = PGOOptions(PGOGenPath, "", "", "", FS, PGOOptions::IRInstr, + PGOOptions::NoCSAction, #if LLVM_VERSION_GE(19, 0) PGOOptions::ColdFuncOpt::Default, #endif DebugInfoForProfiling); } else if (PGOUsePath) { assert(!PGOSampleUsePath); - PGOOpt = PGOOptions(PGOUsePath, "", "", "", FS, - PGOOptions::IRUse, PGOOptions::NoCSAction, + PGOOpt = PGOOptions(PGOUsePath, "", "", "", FS, PGOOptions::IRUse, + PGOOptions::NoCSAction, #if LLVM_VERSION_GE(19, 0) PGOOptions::ColdFuncOpt::Default, #endif DebugInfoForProfiling); } else if (PGOSampleUsePath) { - PGOOpt = PGOOptions(PGOSampleUsePath, "", "", "", FS, - PGOOptions::SampleUse, PGOOptions::NoCSAction, + PGOOpt = PGOOptions(PGOSampleUsePath, "", "", "", FS, PGOOptions::SampleUse, + PGOOptions::NoCSAction, #if LLVM_VERSION_GE(19, 0) PGOOptions::ColdFuncOpt::Default, #endif DebugInfoForProfiling); } else if (DebugInfoForProfiling) { - PGOOpt = PGOOptions("", "", "", "", FS, - PGOOptions::NoAction, PGOOptions::NoCSAction, + PGOOpt = PGOOptions("", "", "", "", FS, PGOOptions::NoAction, + PGOOptions::NoCSAction, #if LLVM_VERSION_GE(19, 0) PGOOptions::ColdFuncOpt::Default, #endif @@ -799,7 +790,7 @@ LLVMRustOptimize( auto PluginsStr = StringRef(LLVMPlugins, LLVMPluginsLen); SmallVector Plugins; PluginsStr.split(Plugins, ',', -1, false); - for (auto PluginPath: Plugins) { + for (auto PluginPath : Plugins) { auto Plugin = PassPlugin::Load(PluginPath.str()); if (!Plugin) { auto Err = Plugin.takeError(); @@ -814,7 +805,8 @@ LLVMRustOptimize( FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); Triple TargetTriple(TheModule->getTargetTriple()); - std::unique_ptr TLII(new TargetLibraryInfoImpl(TargetTriple)); + std::unique_ptr TLII( + new TargetLibraryInfoImpl(TargetTriple)); if (DisableSimplifyLibCalls) TLII->disableAllFunctions(); FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); @@ -825,58 +817,53 @@ LLVMRustOptimize( PB.registerLoopAnalyses(LAM); PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); - // We manually collect pipeline callbacks so we can apply them at O0, where the - // PassBuilder does not create a pipeline. + // We manually collect pipeline callbacks so we can apply them at O0, where + // the PassBuilder does not create a pipeline. std::vector> PipelineStartEPCallbacks; std::vector> OptimizerLastEPCallbacks; - if (!IsLinkerPluginLTO - && SanitizerOptions && SanitizerOptions->SanitizeCFI - && !NoPrepopulatePasses) { + if (!IsLinkerPluginLTO && SanitizerOptions && SanitizerOptions->SanitizeCFI && + !NoPrepopulatePasses) { PipelineStartEPCallbacks.push_back( - [](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, - /*ImportSummary=*/nullptr, - /*DropTypeTests=*/false)); - } - ); + [](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, + /*ImportSummary=*/nullptr, + /*DropTypeTests=*/false)); + }); } if (VerifyIR) { PipelineStartEPCallbacks.push_back( - [VerifyIR](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass(VerifierPass()); - } - ); + [VerifyIR](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(VerifierPass()); + }); } if (InstrumentGCOV) { PipelineStartEPCallbacks.push_back( - [](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass(GCOVProfilerPass(GCOVOptions::getDefault())); - } - ); + [](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(GCOVProfilerPass(GCOVOptions::getDefault())); + }); } if (InstrumentCoverage) { PipelineStartEPCallbacks.push_back( - [InstrProfileOutput](ModulePassManager &MPM, OptimizationLevel Level) { - InstrProfOptions Options; - if (InstrProfileOutput) { - Options.InstrProfileOutput = InstrProfileOutput; - } - // cargo run tests in multhreading mode by default - // so use atomics for coverage counters - Options.Atomic = true; + [InstrProfileOutput](ModulePassManager &MPM, OptimizationLevel Level) { + InstrProfOptions Options; + if (InstrProfileOutput) { + Options.InstrProfileOutput = InstrProfileOutput; + } + // cargo run tests in multhreading mode by default + // so use atomics for coverage counters + Options.Atomic = true; #if LLVM_VERSION_GE(18, 0) - MPM.addPass(InstrProfilingLoweringPass(Options, false)); + MPM.addPass(InstrProfilingLoweringPass(Options, false)); #else - MPM.addPass(InstrProfiling(Options, false)); + MPM.addPass(InstrProfiling(Options, false)); #endif - } - ); + }); } if (SanitizerOptions) { @@ -886,10 +873,9 @@ LLVMRustOptimize( SanitizerOptions->SanitizeDataFlowABIList + SanitizerOptions->SanitizeDataFlowABIListLen); OptimizerLastEPCallbacks.push_back( - [ABIListFiles](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass(DataFlowSanitizerPass(ABIListFiles)); - } - ); + [ABIListFiles](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(DataFlowSanitizerPass(ABIListFiles)); + }); } if (SanitizerOptions->SanitizeMemory) { @@ -899,54 +885,54 @@ LLVMRustOptimize( /*CompileKernel=*/false, /*EagerChecks=*/true); OptimizerLastEPCallbacks.push_back( - [Options](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass(MemorySanitizerPass(Options)); - } - ); + [Options](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(MemorySanitizerPass(Options)); + }); } if (SanitizerOptions->SanitizeThread) { - OptimizerLastEPCallbacks.push_back( - [](ModulePassManager &MPM, OptimizationLevel Level) { - MPM.addPass(ModuleThreadSanitizerPass()); - MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); - } - ); + OptimizerLastEPCallbacks.push_back([](ModulePassManager &MPM, + OptimizationLevel Level) { + MPM.addPass(ModuleThreadSanitizerPass()); + MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); + }); } - if (SanitizerOptions->SanitizeAddress || SanitizerOptions->SanitizeKernelAddress) { + if (SanitizerOptions->SanitizeAddress || + SanitizerOptions->SanitizeKernelAddress) { OptimizerLastEPCallbacks.push_back( - [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) { - auto CompileKernel = SanitizerOptions->SanitizeKernelAddress; - AddressSanitizerOptions opts = AddressSanitizerOptions{ - CompileKernel, - SanitizerOptions->SanitizeAddressRecover - || SanitizerOptions->SanitizeKernelAddressRecover, - /*UseAfterScope=*/true, - AsanDetectStackUseAfterReturnMode::Runtime, - }; - MPM.addPass(AddressSanitizerPass(opts)); - } - ); + [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) { + auto CompileKernel = SanitizerOptions->SanitizeKernelAddress; + AddressSanitizerOptions opts = AddressSanitizerOptions{ + CompileKernel, + SanitizerOptions->SanitizeAddressRecover || + SanitizerOptions->SanitizeKernelAddressRecover, + /*UseAfterScope=*/true, + AsanDetectStackUseAfterReturnMode::Runtime, + }; + MPM.addPass(AddressSanitizerPass(opts)); + }); } if (SanitizerOptions->SanitizeHWAddress) { OptimizerLastEPCallbacks.push_back( - [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) { - HWAddressSanitizerOptions opts( - /*CompileKernel=*/false, SanitizerOptions->SanitizeHWAddressRecover, - /*DisableOptimization=*/false); - MPM.addPass(HWAddressSanitizerPass(opts)); - } - ); + [SanitizerOptions](ModulePassManager &MPM, OptimizationLevel Level) { + HWAddressSanitizerOptions opts( + /*CompileKernel=*/false, + SanitizerOptions->SanitizeHWAddressRecover, + /*DisableOptimization=*/false); + MPM.addPass(HWAddressSanitizerPass(opts)); + }); } } ModulePassManager MPM; bool NeedThinLTOBufferPasses = UseThinLTOBuffers; if (!NoPrepopulatePasses) { - // The pre-link pipelines don't support O0 and require using buildO0DefaultPipeline() instead. - // At the same time, the LTO pipelines do support O0 and using them is required. - bool IsLTO = OptStage == LLVMRustOptStage::ThinLTO || OptStage == LLVMRustOptStage::FatLTO; + // The pre-link pipelines don't support O0 and require using + // buildO0DefaultPipeline() instead. At the same time, the LTO pipelines do + // support O0 and using them is required. + bool IsLTO = OptStage == LLVMRustOptStage::ThinLTO || + OptStage == LLVMRustOptStage::FatLTO; if (OptLevel == OptimizationLevel::O0 && !IsLTO) { for (const auto &C : PipelineStartEPCallbacks) PB.registerPipelineStartEPCallback(C); @@ -993,7 +979,8 @@ LLVMRustOptimize( } if (ExtraPassesLen) { - if (auto Err = PB.parsePassPipeline(MPM, StringRef(ExtraPasses, ExtraPassesLen))) { + if (auto Err = + PB.parsePassPipeline(MPM, StringRef(ExtraPasses, ExtraPassesLen))) { std::string ErrMsg = toString(std::move(Err)); LLVMRustSetLastError(ErrMsg.c_str()); return LLVMRustResult::Failure; @@ -1020,8 +1007,7 @@ LLVMRustOptimize( // * output buffer // * output buffer len // Returns len of demangled string, or 0 if demangle failed. -typedef size_t (*DemangleFn)(const char*, size_t, char*, size_t); - +typedef size_t (*DemangleFn)(const char *, size_t, char *, size_t); namespace { @@ -1064,7 +1050,7 @@ class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter { formatted_raw_ostream &OS) override { StringRef Demangled = CallDemangle(F->getName()); if (Demangled.empty()) { - return; + return; } OS << "; " << Demangled << "\n"; @@ -1077,7 +1063,7 @@ class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter { if (const CallInst *CI = dyn_cast(I)) { Name = "call"; Value = CI->getCalledOperand(); - } else if (const InvokeInst* II = dyn_cast(I)) { + } else if (const InvokeInst *II = dyn_cast(I)) { Name = "invoke"; Value = II->getCalledOperand(); } else { @@ -1101,8 +1087,8 @@ class RustAssemblyAnnotationWriter : public AssemblyAnnotationWriter { } // namespace -extern "C" LLVMRustResult -LLVMRustPrintModule(LLVMModuleRef M, const char *Path, DemangleFn Demangle) { +extern "C" LLVMRustResult LLVMRustPrintModule(LLVMModuleRef M, const char *Path, + DemangleFn Demangle) { std::string ErrorInfo; std::error_code EC; auto OS = raw_fd_ostream(Path, EC, sys::fs::OF_None); @@ -1264,11 +1250,9 @@ getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) { // The main entry point for creating the global ThinLTO analysis. The structure // here is basically the same as before threads are spawned in the `run` // function of `lib/LTO/ThinLTOCodeGenerator.cpp`. -extern "C" LLVMRustThinLTOData* -LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, - int num_modules, - const char **preserved_symbols, - int num_symbols) { +extern "C" LLVMRustThinLTOData * +LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, int num_modules, + const char **preserved_symbols, int num_symbols) { auto Ret = std::make_unique(); // Load each module's summary and merge it into one combined index @@ -1290,7 +1274,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, } // Collect for each module the list of function it defines (GUID -> Summary) - Ret->Index.collectDefinedGVSummariesPerModule(Ret->ModuleToDefinedGVSummaries); + Ret->Index.collectDefinedGVSummariesPerModule( + Ret->ModuleToDefinedGVSummaries); // Convert the preserved symbols set from string to GUID, this is then needed // for internalization. @@ -1310,7 +1295,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, // crate, so we need `ImportEnabled = false` to limit internalization. // Otherwise, we sometimes lose `static` values -- see #60184. computeDeadSymbolsWithConstProp(Ret->Index, Ret->GUIDPreservedSymbols, - deadIsPrevailing, /* ImportEnabled = */ false); + deadIsPrevailing, + /* ImportEnabled = */ false); // Resolve LinkOnce/Weak symbols, this has to be computed early be cause it // impacts the caching. // @@ -1319,7 +1305,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, DenseMap PrevailingCopy; for (auto &I : Ret->Index) { if (I.second.SummaryList.size() > 1) - PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second.SummaryList); + PrevailingCopy[I.first] = + getFirstDefinitionForLinker(I.second.SummaryList); } auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) { const auto &Prevailing = PrevailingCopy.find(GUID); @@ -1327,13 +1314,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, return true; return Prevailing->second == S; }; - ComputeCrossModuleImport( - Ret->Index, - Ret->ModuleToDefinedGVSummaries, - isPrevailing, - Ret->ImportLists, - Ret->ExportLists - ); + ComputeCrossModuleImport(Ret->Index, Ret->ModuleToDefinedGVSummaries, + isPrevailing, Ret->ImportLists, Ret->ExportLists); auto recordNewLinkage = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID, @@ -1345,8 +1327,8 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, // formats. We probably could and should use ELF visibility scheme for many of // our targets, however. lto::Config conf; - thinLTOResolvePrevailingInIndex(conf, Ret->Index, isPrevailing, recordNewLinkage, - Ret->GUIDPreservedSymbols); + thinLTOResolvePrevailingInIndex(conf, Ret->Index, isPrevailing, + recordNewLinkage, Ret->GUIDPreservedSymbols); // Here we calculate an `ExportedGUIDs` set for use in the `isExported` // callback below. This callback below will dictate the linkage for all @@ -1355,7 +1337,7 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, // linkage will stay as external, and internal will stay as internal. std::set ExportedGUIDs; for (auto &List : Ret->Index) { - for (auto &GVS: List.second.SummaryList) { + for (auto &GVS : List.second.SummaryList) { if (GlobalValue::isLocalLinkage(GVS->linkage())) continue; auto GUID = GVS->getOriginalName(); @@ -1366,16 +1348,15 @@ LLVMRustCreateThinLTOData(LLVMRustThinLTOModule *modules, auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) { const auto &ExportList = Ret->ExportLists.find(ModuleIdentifier); return (ExportList != Ret->ExportLists.end() && - ExportList->second.count(VI)) || - ExportedGUIDs.count(VI.getGUID()); + ExportList->second.count(VI)) || + ExportedGUIDs.count(VI.getGUID()); }; thinLTOInternalizeAndPromoteInIndex(Ret->Index, isExported, isPrevailing); return Ret.release(); } -extern "C" void -LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) { +extern "C" void LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) { delete Data; } @@ -1387,20 +1368,18 @@ LLVMRustFreeThinLTOData(LLVMRustThinLTOData *Data) { // `ProcessThinLTOModule` function. Here they're split up into separate steps // so rustc can save off the intermediate bytecode between each step. -static bool -clearDSOLocalOnDeclarations(Module &Mod, TargetMachine &TM) { +static bool clearDSOLocalOnDeclarations(Module &Mod, TargetMachine &TM) { // When linking an ELF shared object, dso_local should be dropped. We // conservatively do this for -fpic. - bool ClearDSOLocalOnDeclarations = - TM.getTargetTriple().isOSBinFormatELF() && - TM.getRelocationModel() != Reloc::Static && - Mod.getPIELevel() == PIELevel::Default; + bool ClearDSOLocalOnDeclarations = TM.getTargetTriple().isOSBinFormatELF() && + TM.getRelocationModel() != Reloc::Static && + Mod.getPIELevel() == PIELevel::Default; return ClearDSOLocalOnDeclarations; } -extern "C" bool -LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M, - LLVMTargetMachineRef TM) { +extern "C" bool LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, + LLVMModuleRef M, + LLVMTargetMachineRef TM) { Module &Mod = *unwrap(M); TargetMachine &Target = *unwrap(TM); @@ -1415,24 +1394,28 @@ LLVMRustPrepareThinLTORename(const LLVMRustThinLTOData *Data, LLVMModuleRef M, } extern "C" bool -LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, LLVMModuleRef M) { +LLVMRustPrepareThinLTOResolveWeak(const LLVMRustThinLTOData *Data, + LLVMModuleRef M) { Module &Mod = *unwrap(M); - const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier()); + const auto &DefinedGlobals = + Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier()); thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true); return true; } extern "C" bool -LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, LLVMModuleRef M) { +LLVMRustPrepareThinLTOInternalize(const LLVMRustThinLTOData *Data, + LLVMModuleRef M) { Module &Mod = *unwrap(M); - const auto &DefinedGlobals = Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier()); + const auto &DefinedGlobals = + Data->ModuleToDefinedGVSummaries.lookup(Mod.getModuleIdentifier()); thinLTOInternalizeModule(Mod, DefinedGlobals); return true; } -extern "C" bool -LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M, - LLVMTargetMachineRef TM) { +extern "C" bool LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, + LLVMModuleRef M, + LLVMTargetMachineRef TM) { Module &Mod = *unwrap(M); TargetMachine &Target = *unwrap(TM); @@ -1464,7 +1447,8 @@ LLVMRustPrepareThinLTOImport(const LLVMRustThinLTOData *Data, LLVMModuleRef M, return Ret; } - auto *WasmCustomSections = (*MOrErr)->getNamedMetadata("wasm.custom_sections"); + auto *WasmCustomSections = + (*MOrErr)->getNamedMetadata("wasm.custom_sections"); if (WasmCustomSections) WasmCustomSections->eraseFromParent(); @@ -1498,7 +1482,7 @@ struct LLVMRustThinLTOBuffer { std::string thin_link_data; }; -extern "C" LLVMRustThinLTOBuffer* +extern "C" LLVMRustThinLTOBuffer * LLVMRustThinLTOBufferCreate(LLVMModuleRef M, bool is_thin, bool emit_summary) { auto Ret = std::make_unique(); { @@ -1520,7 +1504,8 @@ LLVMRustThinLTOBufferCreate(LLVMModuleRef M, bool is_thin, bool emit_summary) { // We only pass ThinLinkOS to be filled in if we want the summary, // because otherwise LLVM does extra work and may double-emit some // errors or warnings. - MPM.addPass(ThinLTOBitcodeWriterPass(OS, emit_summary ? &ThinLinkOS : nullptr)); + MPM.addPass( + ThinLTOBitcodeWriterPass(OS, emit_summary ? &ThinLinkOS : nullptr)); MPM.run(*unwrap(M), MAM); } else { WriteBitcodeToFile(*unwrap(M), OS); @@ -1530,12 +1515,11 @@ LLVMRustThinLTOBufferCreate(LLVMModuleRef M, bool is_thin, bool emit_summary) { return Ret.release(); } -extern "C" void -LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) { +extern "C" void LLVMRustThinLTOBufferFree(LLVMRustThinLTOBuffer *Buffer) { delete Buffer; } -extern "C" const void* +extern "C" const void * LLVMRustThinLTOBufferPtr(const LLVMRustThinLTOBuffer *Buffer) { return Buffer->data.data(); } @@ -1545,7 +1529,7 @@ LLVMRustThinLTOBufferLen(const LLVMRustThinLTOBuffer *Buffer) { return Buffer->data.length(); } -extern "C" const void* +extern "C" const void * LLVMRustThinLTOBufferThinLinkDataPtr(const LLVMRustThinLTOBuffer *Buffer) { return Buffer->thin_link_data.data(); } @@ -1558,11 +1542,10 @@ LLVMRustThinLTOBufferThinLinkDataLen(const LLVMRustThinLTOBuffer *Buffer) { // This is what we used to parse upstream bitcode for actual ThinLTO // processing. We'll call this once per module optimized through ThinLTO, and // it'll be called concurrently on many threads. -extern "C" LLVMModuleRef -LLVMRustParseBitcodeForLTO(LLVMContextRef Context, - const char *data, - size_t len, - const char *identifier) { +extern "C" LLVMModuleRef LLVMRustParseBitcodeForLTO(LLVMContextRef Context, + const char *data, + size_t len, + const char *identifier) { auto Data = StringRef(data, len); auto Buffer = MemoryBufferRef(Data, identifier); unwrap(Context)->enableDebugTypeODRUniquing(); @@ -1614,8 +1597,9 @@ extern "C" const char *LLVMRustGetSliceFromObjectDataByName(const char *data, // of access globals, etc). // The precise details are determined by LLVM in `computeLTOCacheKey`, which is // used during the normal linker-plugin incremental thin-LTO process. -extern "C" void -LLVMRustComputeLTOCacheKey(RustStringRef KeyOut, const char *ModId, LLVMRustThinLTOData *Data) { +extern "C" void LLVMRustComputeLTOCacheKey(RustStringRef KeyOut, + const char *ModId, + LLVMRustThinLTOData *Data) { SmallString<40> Key; llvm::lto::Config conf; const auto &ImportList = Data->ImportLists.lookup(ModId); @@ -1633,9 +1617,9 @@ LLVMRustComputeLTOCacheKey(RustStringRef KeyOut, const char *ModId, LLVMRustThin CfiFunctionDecls.insert( GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); - llvm::computeLTOCacheKey(Key, conf, Data->Index, ModId, - ImportList, ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls - ); + llvm::computeLTOCacheKey(Key, conf, Data->Index, ModId, ImportList, + ExportList, ResolvedODR, DefinedGlobals, + CfiFunctionDefs, CfiFunctionDecls); LLVMRustStringWriteImpl(KeyOut, Key.c_str(), Key.size()); } diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 20167a4b45ee2..b6790b7df500b 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1,5 +1,6 @@ #include "LLVMWrapper.h" #include "llvm/ADT/Statistic.h" +#include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DiagnosticHandler.h" #include "llvm/IR/DiagnosticInfo.h" @@ -11,17 +12,16 @@ #include "llvm/IR/LLVMRemarkStreamer.h" #include "llvm/IR/Mangler.h" #include "llvm/IR/Value.h" -#include "llvm/Remarks/RemarkStreamer.h" -#include "llvm/Remarks/RemarkSerializer.h" -#include "llvm/Remarks/RemarkFormat.h" -#include "llvm/Support/ToolOutputFile.h" -#include "llvm/Support/ModRef.h" #include "llvm/Object/Archive.h" #include "llvm/Object/COFFImportFile.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Pass.h" -#include "llvm/Bitcode/BitcodeWriter.h" +#include "llvm/Remarks/RemarkFormat.h" +#include "llvm/Remarks/RemarkSerializer.h" +#include "llvm/Remarks/RemarkStreamer.h" +#include "llvm/Support/ModRef.h" #include "llvm/Support/Signals.h" +#include "llvm/Support/ToolOutputFile.h" #include @@ -71,12 +71,12 @@ static LLVM_THREAD_LOCAL char *LastError; // Custom error handler for fatal LLVM errors. // // Notably it exits the process with code 101, unlike LLVM's default of 1. -static void FatalErrorHandler(void *UserData, - const char* Reason, +static void FatalErrorHandler(void *UserData, const char *Reason, bool GenCrashDiag) { // Once upon a time we emitted "LLVM ERROR:" specifically to mimic LLVM. Then, - // we developed crater and other tools which only expose logs, not error codes. - // Use a more greppable prefix that will still match the "LLVM ERROR:" prefix. + // we developed crater and other tools which only expose logs, not error + // codes. Use a more greppable prefix that will still match the "LLVM ERROR:" + // prefix. std::cerr << "rustc-LLVM ERROR: " << Reason << std::endl; // Since this error handler exits the process, we have to run any cleanup that @@ -99,8 +99,7 @@ static void FatalErrorHandler(void *UserData, // // It aborts the process without any further allocations, similar to LLVM's // default except that may be configured to `throw std::bad_alloc()` instead. -static void BadAllocErrorHandler(void *UserData, - const char* Reason, +static void BadAllocErrorHandler(void *UserData, const char *Reason, bool GenCrashDiag) { const char *OOM = "rustc-LLVM ERROR: out of memory\n"; (void)!::write(2, OOM, strlen(OOM)); @@ -190,7 +189,8 @@ static CallInst::TailCallKind fromRust(LLVMRustTailCallKind Kind) { } } -extern "C" void LLVMRustSetTailCallKind(LLVMValueRef Call, LLVMRustTailCallKind TCK) { +extern "C" void LLVMRustSetTailCallKind(LLVMValueRef Call, + LLVMRustTailCallKind TCK) { unwrap(Call)->setTailCallKind(fromRust(TCK)); } @@ -201,12 +201,13 @@ extern "C" LLVMValueRef LLVMRustGetOrInsertFunction(LLVMModuleRef M, return wrap(unwrap(M) ->getOrInsertFunction(StringRef(Name, NameLen), unwrap(FunctionTy)) - .getCallee() - ); + .getCallee()); } -extern "C" LLVMValueRef -LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, size_t NameLen, LLVMTypeRef Ty) { +extern "C" LLVMValueRef LLVMRustGetOrInsertGlobal(LLVMModuleRef M, + const char *Name, + size_t NameLen, + LLVMTypeRef Ty) { Module *Mod = unwrap(M); auto NameRef = StringRef(Name, NameLen); @@ -221,13 +222,10 @@ LLVMRustGetOrInsertGlobal(LLVMModuleRef M, const char *Name, size_t NameLen, LLV return wrap(GV); } -extern "C" LLVMValueRef -LLVMRustInsertPrivateGlobal(LLVMModuleRef M, LLVMTypeRef Ty) { - return wrap(new GlobalVariable(*unwrap(M), - unwrap(Ty), - false, - GlobalValue::PrivateLinkage, - nullptr)); +extern "C" LLVMValueRef LLVMRustInsertPrivateGlobal(LLVMModuleRef M, + LLVMTypeRef Ty) { + return wrap(new GlobalVariable(*unwrap(M), unwrap(Ty), false, + GlobalValue::PrivateLinkage, nullptr)); } static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) { @@ -326,8 +324,9 @@ static Attribute::AttrKind fromRust(LLVMRustAttribute Kind) { report_fatal_error("bad AttributeKind"); } -template static inline void AddAttributes(T *t, unsigned Index, - LLVMAttributeRef *Attrs, size_t AttrsLen) { +template +static inline void AddAttributes(T *t, unsigned Index, LLVMAttributeRef *Attrs, + size_t AttrsLen) { AttributeList PAL = t->getAttributes(); auto B = AttrBuilder(t->getContext()); for (LLVMAttributeRef Attr : ArrayRef(Attrs, AttrsLen)) @@ -337,19 +336,22 @@ template static inline void AddAttributes(T *t, unsigned Index, } extern "C" void LLVMRustAddFunctionAttributes(LLVMValueRef Fn, unsigned Index, - LLVMAttributeRef *Attrs, size_t AttrsLen) { + LLVMAttributeRef *Attrs, + size_t AttrsLen) { Function *F = unwrap(Fn); AddAttributes(F, Index, Attrs, AttrsLen); } -extern "C" void LLVMRustAddCallSiteAttributes(LLVMValueRef Instr, unsigned Index, - LLVMAttributeRef *Attrs, size_t AttrsLen) { +extern "C" void LLVMRustAddCallSiteAttributes(LLVMValueRef Instr, + unsigned Index, + LLVMAttributeRef *Attrs, + size_t AttrsLen) { CallBase *Call = unwrap(Instr); AddAttributes(Call, Index, Attrs, AttrsLen); } -extern "C" LLVMAttributeRef LLVMRustCreateAttrNoValue(LLVMContextRef C, - LLVMRustAttribute RustAttr) { +extern "C" LLVMAttributeRef +LLVMRustCreateAttrNoValue(LLVMContextRef C, LLVMRustAttribute RustAttr) { return wrap(Attribute::get(*unwrap(C), fromRust(RustAttr))); } @@ -363,30 +365,36 @@ extern "C" LLVMAttributeRef LLVMRustCreateDereferenceableAttr(LLVMContextRef C, return wrap(Attribute::getWithDereferenceableBytes(*unwrap(C), Bytes)); } -extern "C" LLVMAttributeRef LLVMRustCreateDereferenceableOrNullAttr(LLVMContextRef C, - uint64_t Bytes) { +extern "C" LLVMAttributeRef +LLVMRustCreateDereferenceableOrNullAttr(LLVMContextRef C, uint64_t Bytes) { return wrap(Attribute::getWithDereferenceableOrNullBytes(*unwrap(C), Bytes)); } -extern "C" LLVMAttributeRef LLVMRustCreateByValAttr(LLVMContextRef C, LLVMTypeRef Ty) { +extern "C" LLVMAttributeRef LLVMRustCreateByValAttr(LLVMContextRef C, + LLVMTypeRef Ty) { return wrap(Attribute::getWithByValType(*unwrap(C), unwrap(Ty))); } -extern "C" LLVMAttributeRef LLVMRustCreateStructRetAttr(LLVMContextRef C, LLVMTypeRef Ty) { +extern "C" LLVMAttributeRef LLVMRustCreateStructRetAttr(LLVMContextRef C, + LLVMTypeRef Ty) { return wrap(Attribute::getWithStructRetType(*unwrap(C), unwrap(Ty))); } -extern "C" LLVMAttributeRef LLVMRustCreateElementTypeAttr(LLVMContextRef C, LLVMTypeRef Ty) { +extern "C" LLVMAttributeRef LLVMRustCreateElementTypeAttr(LLVMContextRef C, + LLVMTypeRef Ty) { return wrap(Attribute::get(*unwrap(C), Attribute::ElementType, unwrap(Ty))); } -extern "C" LLVMAttributeRef LLVMRustCreateUWTableAttr(LLVMContextRef C, bool Async) { +extern "C" LLVMAttributeRef LLVMRustCreateUWTableAttr(LLVMContextRef C, + bool Async) { return wrap(Attribute::getWithUWTableKind( *unwrap(C), Async ? UWTableKind::Async : UWTableKind::Sync)); } -extern "C" LLVMAttributeRef LLVMRustCreateAllocSizeAttr(LLVMContextRef C, uint32_t ElementSizeArg) { - return wrap(Attribute::getWithAllocSizeArgs(*unwrap(C), ElementSizeArg, std::nullopt)); +extern "C" LLVMAttributeRef +LLVMRustCreateAllocSizeAttr(LLVMContextRef C, uint32_t ElementSizeArg) { + return wrap(Attribute::getWithAllocSizeArgs(*unwrap(C), ElementSizeArg, + std::nullopt)); } // These values **must** match ffi::AllocKindFlags. @@ -403,12 +411,15 @@ enum class LLVMRustAllocKindFlags : uint64_t { Aligned = 1 << 5, }; -static LLVMRustAllocKindFlags operator&(LLVMRustAllocKindFlags A, LLVMRustAllocKindFlags B) { +static LLVMRustAllocKindFlags operator&(LLVMRustAllocKindFlags A, + LLVMRustAllocKindFlags B) { return static_cast(static_cast(A) & - static_cast(B)); + static_cast(B)); } -static bool isSet(LLVMRustAllocKindFlags F) { return F != LLVMRustAllocKindFlags::Unknown; } +static bool isSet(LLVMRustAllocKindFlags F) { + return F != LLVMRustAllocKindFlags::Unknown; +} static llvm::AllocFnKind allocKindFromRust(LLVMRustAllocKindFlags F) { llvm::AllocFnKind AFK = llvm::AllocFnKind::Unknown; @@ -433,40 +444,47 @@ static llvm::AllocFnKind allocKindFromRust(LLVMRustAllocKindFlags F) { return AFK; } -extern "C" LLVMAttributeRef LLVMRustCreateAllocKindAttr(LLVMContextRef C, uint64_t AllocKindArg) { - return wrap(Attribute::get(*unwrap(C), Attribute::AllocKind, - static_cast(allocKindFromRust(static_cast(AllocKindArg))))); +extern "C" LLVMAttributeRef LLVMRustCreateAllocKindAttr(LLVMContextRef C, + uint64_t AllocKindArg) { + return wrap( + Attribute::get(*unwrap(C), Attribute::AllocKind, + static_cast(allocKindFromRust( + static_cast(AllocKindArg))))); } // Simplified representation of `MemoryEffects` across the FFI boundary. // -// Each variant corresponds to one of the static factory methods on `MemoryEffects`. +// Each variant corresponds to one of the static factory methods on +// `MemoryEffects`. enum class LLVMRustMemoryEffects { None, ReadOnly, InaccessibleMemOnly, }; -extern "C" LLVMAttributeRef LLVMRustCreateMemoryEffectsAttr(LLVMContextRef C, - LLVMRustMemoryEffects Effects) { +extern "C" LLVMAttributeRef +LLVMRustCreateMemoryEffectsAttr(LLVMContextRef C, + LLVMRustMemoryEffects Effects) { switch (Effects) { - case LLVMRustMemoryEffects::None: - return wrap(Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::none())); - case LLVMRustMemoryEffects::ReadOnly: - return wrap(Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::readOnly())); - case LLVMRustMemoryEffects::InaccessibleMemOnly: - return wrap(Attribute::getWithMemoryEffects(*unwrap(C), - MemoryEffects::inaccessibleMemOnly())); - default: - report_fatal_error("bad MemoryEffects."); - } -} - -// Enable all fast-math flags, including those which will cause floating-point operations -// to return poison for some well-defined inputs. This function can only be used to build -// unsafe Rust intrinsics. That unsafety does permit additional optimizations, but at the -// time of writing, their value is not well-understood relative to those enabled by -// LLVMRustSetAlgebraicMath. + case LLVMRustMemoryEffects::None: + return wrap( + Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::none())); + case LLVMRustMemoryEffects::ReadOnly: + return wrap( + Attribute::getWithMemoryEffects(*unwrap(C), MemoryEffects::readOnly())); + case LLVMRustMemoryEffects::InaccessibleMemOnly: + return wrap(Attribute::getWithMemoryEffects( + *unwrap(C), MemoryEffects::inaccessibleMemOnly())); + default: + report_fatal_error("bad MemoryEffects."); + } +} + +// Enable all fast-math flags, including those which will cause floating-point +// operations to return poison for some well-defined inputs. This function can +// only be used to build unsafe Rust intrinsics. That unsafety does permit +// additional optimizations, but at the time of writing, their value is not +// well-understood relative to those enabled by LLVMRustSetAlgebraicMath. // // https://llvm.org/docs/LangRef.html#fast-math-flags extern "C" void LLVMRustSetFastMath(LLVMValueRef V) { @@ -475,14 +493,12 @@ extern "C" void LLVMRustSetFastMath(LLVMValueRef V) { } } -// Enable fast-math flags which permit algebraic transformations that are not allowed by -// IEEE floating point. For example: -// a + (b + c) = (a + b) + c -// and -// a / b = a * (1 / b) -// Note that this does NOT enable any flags which can cause a floating-point operation on -// well-defined inputs to return poison, and therefore this function can be used to build -// safe Rust intrinsics (such as fadd_algebraic). +// Enable fast-math flags which permit algebraic transformations that are not +// allowed by IEEE floating point. For example: a + (b + c) = (a + b) + c and a +// / b = a * (1 / b) Note that this does NOT enable any flags which can cause a +// floating-point operation on well-defined inputs to return poison, and +// therefore this function can be used to build safe Rust intrinsics (such as +// fadd_algebraic). // // https://llvm.org/docs/LangRef.html#fast-math-flags extern "C" void LLVMRustSetAlgebraicMath(LLVMValueRef V) { @@ -497,9 +513,9 @@ extern "C" void LLVMRustSetAlgebraicMath(LLVMValueRef V) { // Enable the reassoc fast-math flag, allowing transformations that pretend // floating-point addition and multiplication are associative. // -// Note that this does NOT enable any flags which can cause a floating-point operation on -// well-defined inputs to return poison, and therefore this function can be used to build -// safe Rust intrinsics (such as fadd_algebraic). +// Note that this does NOT enable any flags which can cause a floating-point +// operation on well-defined inputs to return poison, and therefore this +// function can be used to build safe Rust intrinsics (such as fadd_algebraic). // // https://llvm.org/docs/LangRef.html#fast-math-flags extern "C" void LLVMRustSetAllowReassoc(LLVMValueRef V) { @@ -547,11 +563,10 @@ LLVMRustInlineAsm(LLVMTypeRef Ty, char *AsmString, size_t AsmStringLen, char *Constraints, size_t ConstraintsLen, LLVMBool HasSideEffects, LLVMBool IsAlignStack, LLVMRustAsmDialect Dialect, LLVMBool CanThrow) { - return wrap(InlineAsm::get(unwrap(Ty), - StringRef(AsmString, AsmStringLen), - StringRef(Constraints, ConstraintsLen), - HasSideEffects, IsAlignStack, - fromRust(Dialect), CanThrow)); + return wrap(InlineAsm::get( + unwrap(Ty), StringRef(AsmString, AsmStringLen), + StringRef(Constraints, ConstraintsLen), HasSideEffects, IsAlignStack, + fromRust(Dialect), CanThrow)); } extern "C" bool LLVMRustInlineAsmVerify(LLVMTypeRef Ty, char *Constraints, @@ -705,19 +720,22 @@ enum class LLVMRustDISPFlags : uint32_t { inline LLVMRustDISPFlags operator&(LLVMRustDISPFlags A, LLVMRustDISPFlags B) { return static_cast(static_cast(A) & - static_cast(B)); + static_cast(B)); } inline LLVMRustDISPFlags operator|(LLVMRustDISPFlags A, LLVMRustDISPFlags B) { return static_cast(static_cast(A) | - static_cast(B)); + static_cast(B)); } -inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A, LLVMRustDISPFlags B) { +inline LLVMRustDISPFlags &operator|=(LLVMRustDISPFlags &A, + LLVMRustDISPFlags B) { return A = A | B; } -inline bool isSet(LLVMRustDISPFlags F) { return F != LLVMRustDISPFlags::SPFlagZero; } +inline bool isSet(LLVMRustDISPFlags F) { + return F != LLVMRustDISPFlags::SPFlagZero; +} inline LLVMRustDISPFlags virtuality(LLVMRustDISPFlags F) { return static_cast(static_cast(F) & 0x3); @@ -761,7 +779,8 @@ enum class LLVMRustDebugEmissionKind { DebugDirectivesOnly, }; -static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind) { +static DICompileUnit::DebugEmissionKind +fromRust(LLVMRustDebugEmissionKind Kind) { switch (Kind) { case LLVMRustDebugEmissionKind::NoDebug: return DICompileUnit::DebugEmissionKind::NoDebug; @@ -777,12 +796,13 @@ static DICompileUnit::DebugEmissionKind fromRust(LLVMRustDebugEmissionKind Kind) } enum class LLVMRustDebugNameTableKind { - Default, - GNU, - None, + Default, + GNU, + None, }; -static DICompileUnit::DebugNameTableKind fromRust(LLVMRustDebugNameTableKind Kind) { +static DICompileUnit::DebugNameTableKind +fromRust(LLVMRustDebugNameTableKind Kind) { switch (Kind) { case LLVMRustDebugNameTableKind::Default: return DICompileUnit::DebugNameTableKind::Default; @@ -827,22 +847,18 @@ extern "C" uint32_t LLVMRustVersionMinor() { return LLVM_VERSION_MINOR; } extern "C" uint32_t LLVMRustVersionMajor() { return LLVM_VERSION_MAJOR; } -extern "C" void LLVMRustAddModuleFlagU32( - LLVMModuleRef M, - Module::ModFlagBehavior MergeBehavior, - const char *Name, - uint32_t Value) { +extern "C" void LLVMRustAddModuleFlagU32(LLVMModuleRef M, + Module::ModFlagBehavior MergeBehavior, + const char *Name, uint32_t Value) { unwrap(M)->addModuleFlag(MergeBehavior, Name, Value); } extern "C" void LLVMRustAddModuleFlagString( - LLVMModuleRef M, - Module::ModFlagBehavior MergeBehavior, - const char *Name, - const char *Value, - size_t ValueLen) { - unwrap(M)->addModuleFlag(MergeBehavior, Name, - MDString::get(unwrap(M)->getContext(), StringRef(Value, ValueLen))); + LLVMModuleRef M, Module::ModFlagBehavior MergeBehavior, const char *Name, + const char *Value, size_t ValueLen) { + unwrap(M)->addModuleFlag( + MergeBehavior, Name, + MDString::get(unwrap(M)->getContext(), StringRef(Value, ValueLen))); } extern "C" bool LLVMRustHasModuleFlag(LLVMModuleRef M, const char *Name, @@ -850,8 +866,8 @@ extern "C" bool LLVMRustHasModuleFlag(LLVMModuleRef M, const char *Name, return unwrap(M)->getModuleFlag(StringRef(Name, Len)) != nullptr; } -extern "C" void LLVMRustGlobalAddMetadata( - LLVMValueRef Global, unsigned Kind, LLVMMetadataRef MD) { +extern "C" void LLVMRustGlobalAddMetadata(LLVMValueRef Global, unsigned Kind, + LLVMMetadataRef MD) { unwrap(Global)->addMetadata(Kind, *unwrap(MD)); } @@ -870,33 +886,29 @@ extern "C" void LLVMRustDIBuilderFinalize(LLVMRustDIBuilderRef Builder) { extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateCompileUnit( LLVMRustDIBuilderRef Builder, unsigned Lang, LLVMMetadataRef FileRef, const char *Producer, size_t ProducerLen, bool isOptimized, - const char *Flags, unsigned RuntimeVer, - const char *SplitName, size_t SplitNameLen, - LLVMRustDebugEmissionKind Kind, - uint64_t DWOId, bool SplitDebugInlining, - LLVMRustDebugNameTableKind TableKind) { + const char *Flags, unsigned RuntimeVer, const char *SplitName, + size_t SplitNameLen, LLVMRustDebugEmissionKind Kind, uint64_t DWOId, + bool SplitDebugInlining, LLVMRustDebugNameTableKind TableKind) { auto *File = unwrapDI(FileRef); - return wrap(Builder->createCompileUnit(Lang, File, StringRef(Producer, ProducerLen), - isOptimized, Flags, RuntimeVer, - StringRef(SplitName, SplitNameLen), - fromRust(Kind), DWOId, SplitDebugInlining, - false, fromRust(TableKind))); + return wrap(Builder->createCompileUnit( + Lang, File, StringRef(Producer, ProducerLen), isOptimized, Flags, + RuntimeVer, StringRef(SplitName, SplitNameLen), fromRust(Kind), DWOId, + SplitDebugInlining, false, fromRust(TableKind))); } -extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFile( - LLVMRustDIBuilderRef Builder, - const char *Filename, size_t FilenameLen, - const char *Directory, size_t DirectoryLen, LLVMRustChecksumKind CSKind, - const char *Checksum, size_t ChecksumLen) { +extern "C" LLVMMetadataRef +LLVMRustDIBuilderCreateFile(LLVMRustDIBuilderRef Builder, const char *Filename, + size_t FilenameLen, const char *Directory, + size_t DirectoryLen, LLVMRustChecksumKind CSKind, + const char *Checksum, size_t ChecksumLen) { std::optional llvmCSKind = fromRust(CSKind); std::optional> CSInfo{}; if (llvmCSKind) CSInfo.emplace(*llvmCSKind, StringRef{Checksum, ChecksumLen}); return wrap(Builder->createFile(StringRef(Filename, FilenameLen), - StringRef(Directory, DirectoryLen), - CSInfo)); + StringRef(Directory, DirectoryLen), CSInfo)); } extern "C" LLVMMetadataRef @@ -907,63 +919,59 @@ LLVMRustDIBuilderCreateSubroutineType(LLVMRustDIBuilderRef Builder, } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateFunction( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - const char *LinkageName, size_t LinkageNameLen, - LLVMMetadataRef File, unsigned LineNo, - LLVMMetadataRef Ty, unsigned ScopeLine, LLVMRustDIFlags Flags, - LLVMRustDISPFlags SPFlags, LLVMValueRef MaybeFn, LLVMMetadataRef TParam, - LLVMMetadataRef Decl) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, const char *LinkageName, size_t LinkageNameLen, + LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, + unsigned ScopeLine, LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, + LLVMValueRef MaybeFn, LLVMMetadataRef TParam, LLVMMetadataRef Decl) { DITemplateParameterArray TParams = DITemplateParameterArray(unwrap(TParam)); DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags); DINode::DIFlags llvmFlags = fromRust(Flags); DISubprogram *Sub = Builder->createFunction( - unwrapDI(Scope), - StringRef(Name, NameLen), - StringRef(LinkageName, LinkageNameLen), - unwrapDI(File), LineNo, - unwrapDI(Ty), ScopeLine, llvmFlags, - llvmSPFlags, TParams, unwrapDIPtr(Decl)); + unwrapDI(Scope), StringRef(Name, NameLen), + StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, + unwrapDI(Ty), ScopeLine, llvmFlags, llvmSPFlags, + TParams, unwrapDIPtr(Decl)); if (MaybeFn) unwrap(MaybeFn)->setSubprogram(Sub); return wrap(Sub); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMethod( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - const char *LinkageName, size_t LinkageNameLen, - LLVMMetadataRef File, unsigned LineNo, - LLVMMetadataRef Ty, LLVMRustDIFlags Flags, - LLVMRustDISPFlags SPFlags, LLVMMetadataRef TParam) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, const char *LinkageName, size_t LinkageNameLen, + LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, + LLVMRustDIFlags Flags, LLVMRustDISPFlags SPFlags, LLVMMetadataRef TParam) { DITemplateParameterArray TParams = DITemplateParameterArray(unwrap(TParam)); DISubprogram::DISPFlags llvmSPFlags = fromRust(SPFlags); DINode::DIFlags llvmFlags = fromRust(Flags); DISubprogram *Sub = Builder->createMethod( - unwrapDI(Scope), - StringRef(Name, NameLen), - StringRef(LinkageName, LinkageNameLen), - unwrapDI(File), LineNo, - unwrapDI(Ty), - 0, 0, nullptr, // VTable params aren't used + unwrapDI(Scope), StringRef(Name, NameLen), + StringRef(LinkageName, LinkageNameLen), unwrapDI(File), LineNo, + unwrapDI(Ty), 0, 0, + nullptr, // VTable params aren't used llvmFlags, llvmSPFlags, TParams); return wrap(Sub); } -extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateBasicType( - LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, - uint64_t SizeInBits, unsigned Encoding) { - return wrap(Builder->createBasicType(StringRef(Name, NameLen), SizeInBits, Encoding)); +extern "C" LLVMMetadataRef +LLVMRustDIBuilderCreateBasicType(LLVMRustDIBuilderRef Builder, const char *Name, + size_t NameLen, uint64_t SizeInBits, + unsigned Encoding) { + return wrap( + Builder->createBasicType(StringRef(Name, NameLen), SizeInBits, Encoding)); } -extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTypedef( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Type, const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Scope) { +extern "C" LLVMMetadataRef +LLVMRustDIBuilderCreateTypedef(LLVMRustDIBuilderRef Builder, + LLVMMetadataRef Type, const char *Name, + size_t NameLen, LLVMMetadataRef File, + unsigned LineNo, LLVMMetadataRef Scope) { return wrap(Builder->createTypedef( - unwrap(Type), StringRef(Name, NameLen), unwrap(File), - LineNo, unwrapDIPtr(Scope))); + unwrap(Type), StringRef(Name, NameLen), unwrap(File), + LineNo, unwrapDIPtr(Scope))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType( @@ -971,118 +979,98 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreatePointerType( uint64_t SizeInBits, uint32_t AlignInBits, unsigned AddressSpace, const char *Name, size_t NameLen) { return wrap(Builder->createPointerType(unwrapDI(PointeeTy), - SizeInBits, AlignInBits, - AddressSpace, + SizeInBits, AlignInBits, AddressSpace, StringRef(Name, NameLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStructType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, - uint32_t AlignInBits, LLVMRustDIFlags Flags, - LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements, - unsigned RunTimeLang, LLVMMetadataRef VTableHolder, - const char *UniqueId, size_t UniqueIdLen) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, + uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, + LLVMMetadataRef DerivedFrom, LLVMMetadataRef Elements, unsigned RunTimeLang, + LLVMMetadataRef VTableHolder, const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createStructType( unwrapDI(Scope), StringRef(Name, NameLen), - unwrapDI(File), LineNumber, - SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(DerivedFrom), + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, + fromRust(Flags), unwrapDI(DerivedFrom), DINodeArray(unwrapDI(Elements)), RunTimeLang, unwrapDI(VTableHolder), StringRef(UniqueId, UniqueIdLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantPart( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, - uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Discriminator, - LLVMMetadataRef Elements, const char *UniqueId, size_t UniqueIdLen) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, + uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, + LLVMMetadataRef Discriminator, LLVMMetadataRef Elements, + const char *UniqueId, size_t UniqueIdLen) { return wrap(Builder->createVariantPart( unwrapDI(Scope), StringRef(Name, NameLen), - unwrapDI(File), LineNumber, - SizeInBits, AlignInBits, fromRust(Flags), unwrapDI(Discriminator), - DINodeArray(unwrapDI(Elements)), StringRef(UniqueId, UniqueIdLen))); + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, + fromRust(Flags), unwrapDI(Discriminator), + DINodeArray(unwrapDI(Elements)), + StringRef(UniqueId, UniqueIdLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateMemberType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { - return wrap(Builder->createMemberType(unwrapDI(Scope), - StringRef(Name, NameLen), - unwrapDI(File), LineNo, - SizeInBits, AlignInBits, OffsetInBits, - fromRust(Flags), unwrapDI(Ty))); + return wrap(Builder->createMemberType( + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, + fromRust(Flags), unwrapDI(Ty))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariantMemberType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, - uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNo, uint64_t SizeInBits, + uint32_t AlignInBits, uint64_t OffsetInBits, LLVMValueRef Discriminant, LLVMRustDIFlags Flags, LLVMMetadataRef Ty) { - llvm::ConstantInt* D = nullptr; + llvm::ConstantInt *D = nullptr; if (Discriminant) { D = unwrap(Discriminant); } - return wrap(Builder->createVariantMemberType(unwrapDI(Scope), - StringRef(Name, NameLen), - unwrapDI(File), LineNo, - SizeInBits, AlignInBits, OffsetInBits, D, - fromRust(Flags), unwrapDI(Ty))); + return wrap(Builder->createVariantMemberType( + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNo, SizeInBits, AlignInBits, OffsetInBits, D, + fromRust(Flags), unwrapDI(Ty))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticMemberType( - LLVMRustDIBuilderRef Builder, - LLVMMetadataRef Scope, - const char *Name, - size_t NameLen, - LLVMMetadataRef File, - unsigned LineNo, - LLVMMetadataRef Ty, - LLVMRustDIFlags Flags, - LLVMValueRef val, - uint32_t AlignInBits -) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, + LLVMRustDIFlags Flags, LLVMValueRef val, uint32_t AlignInBits) { return wrap(Builder->createStaticMemberType( - unwrapDI(Scope), - StringRef(Name, NameLen), - unwrapDI(File), - LineNo, - unwrapDI(Ty), - fromRust(Flags), - unwrap(val), + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNo, unwrapDI(Ty), fromRust(Flags), + unwrap(val), #if LLVM_VERSION_GE(18, 0) - llvm::dwarf::DW_TAG_member, + llvm::dwarf::DW_TAG_member, #endif - AlignInBits - )); + AlignInBits)); } -extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlock( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - LLVMMetadataRef File, unsigned Line, unsigned Col) { +extern "C" LLVMMetadataRef +LLVMRustDIBuilderCreateLexicalBlock(LLVMRustDIBuilderRef Builder, + LLVMMetadataRef Scope, LLVMMetadataRef File, + unsigned Line, unsigned Col) { return wrap(Builder->createLexicalBlock(unwrapDI(Scope), unwrapDI(File), Line, Col)); } -extern "C" LLVMMetadataRef -LLVMRustDIBuilderCreateLexicalBlockFile(LLVMRustDIBuilderRef Builder, - LLVMMetadataRef Scope, - LLVMMetadataRef File) { +extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateLexicalBlockFile( + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, LLVMMetadataRef File) { return wrap(Builder->createLexicalBlockFile(unwrapDI(Scope), unwrapDI(File))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, - const char *Name, size_t NameLen, - const char *LinkageName, size_t LinkageNameLen, - LLVMMetadataRef File, unsigned LineNo, - LLVMMetadataRef Ty, bool IsLocalToUnit, LLVMValueRef V, - LLVMMetadataRef Decl = nullptr, uint32_t AlignInBits = 0) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Context, const char *Name, + size_t NameLen, const char *LinkageName, size_t LinkageNameLen, + LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, + bool IsLocalToUnit, LLVMValueRef V, LLVMMetadataRef Decl = nullptr, + uint32_t AlignInBits = 0) { llvm::GlobalVariable *InitVal = cast(unwrap(V)); llvm::DIExpression *InitExpr = nullptr; @@ -1095,14 +1083,13 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( FPVal->getValueAPF().bitcastToAPInt().getZExtValue()); } - llvm::DIGlobalVariableExpression *VarExpr = Builder->createGlobalVariableExpression( - unwrapDI(Context), StringRef(Name, NameLen), - StringRef(LinkageName, LinkageNameLen), - unwrapDI(File), LineNo, unwrapDI(Ty), IsLocalToUnit, - /* isDefined */ true, - InitExpr, unwrapDIPtr(Decl), - /* templateParams */ nullptr, - AlignInBits); + llvm::DIGlobalVariableExpression *VarExpr = + Builder->createGlobalVariableExpression( + unwrapDI(Context), StringRef(Name, NameLen), + StringRef(LinkageName, LinkageNameLen), unwrapDI(File), + LineNo, unwrapDI(Ty), IsLocalToUnit, + /* isDefined */ true, InitExpr, unwrapDIPtr(Decl), + /* templateParams */ nullptr, AlignInBits); InitVal->setMetadata("dbg", VarExpr); @@ -1111,20 +1098,19 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateStaticVariable( extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateVariable( LLVMRustDIBuilderRef Builder, unsigned Tag, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNo, + const char *Name, size_t NameLen, LLVMMetadataRef File, unsigned LineNo, LLVMMetadataRef Ty, bool AlwaysPreserve, LLVMRustDIFlags Flags, unsigned ArgNo, uint32_t AlignInBits) { if (Tag == 0x100) { // DW_TAG_auto_variable return wrap(Builder->createAutoVariable( unwrapDI(Scope), StringRef(Name, NameLen), - unwrapDI(File), LineNo, - unwrapDI(Ty), AlwaysPreserve, fromRust(Flags), AlignInBits)); + unwrapDI(File), LineNo, unwrapDI(Ty), AlwaysPreserve, + fromRust(Flags), AlignInBits)); } else { return wrap(Builder->createParameterVariable( unwrapDI(Scope), StringRef(Name, NameLen), ArgNo, - unwrapDI(File), LineNo, - unwrapDI(Ty), AlwaysPreserve, fromRust(Flags))); + unwrapDI(File), LineNo, unwrapDI(Ty), AlwaysPreserve, + fromRust(Flags))); } } @@ -1157,9 +1143,9 @@ extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd( LLVMBasicBlockRef InsertAtEnd) { auto Result = Builder->insertDeclare( unwrap(V), unwrap(VarInfo), - Builder->createExpression(llvm::ArrayRef(AddrOps, AddrOpsCount)), - DebugLoc(cast(unwrap(DL))), - unwrap(InsertAtEnd)); + Builder->createExpression( + llvm::ArrayRef(AddrOps, AddrOpsCount)), + DebugLoc(cast(unwrap(DL))), unwrap(InsertAtEnd)); #if LLVM_VERSION_GE(19, 0) return wrap(Result.get()); #else @@ -1170,21 +1156,20 @@ extern "C" LLVMValueRef LLVMRustDIBuilderInsertDeclareAtEnd( extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerator( LLVMRustDIBuilderRef Builder, const char *Name, size_t NameLen, const uint64_t Value[2], unsigned SizeInBits, bool IsUnsigned) { - return wrap(Builder->createEnumerator(StringRef(Name, NameLen), + return wrap(Builder->createEnumerator( + StringRef(Name, NameLen), APSInt(APInt(SizeInBits, ArrayRef(Value, 2)), IsUnsigned))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, - uint32_t AlignInBits, LLVMMetadataRef Elements, + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, + uint64_t SizeInBits, uint32_t AlignInBits, LLVMMetadataRef Elements, LLVMMetadataRef ClassTy, bool IsScoped) { return wrap(Builder->createEnumerationType( unwrapDI(Scope), StringRef(Name, NameLen), - unwrapDI(File), LineNumber, - SizeInBits, AlignInBits, DINodeArray(unwrapDI(Elements)), - unwrapDI(ClassTy), + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, + DINodeArray(unwrapDI(Elements)), unwrapDI(ClassTy), #if LLVM_VERSION_GE(18, 0) /* RunTimeLang */ 0, #endif @@ -1192,39 +1177,38 @@ extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateEnumerationType( } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateUnionType( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, - LLVMMetadataRef File, unsigned LineNumber, uint64_t SizeInBits, - uint32_t AlignInBits, LLVMRustDIFlags Flags, LLVMMetadataRef Elements, - unsigned RunTimeLang, const char *UniqueId, size_t UniqueIdLen) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef File, unsigned LineNumber, + uint64_t SizeInBits, uint32_t AlignInBits, LLVMRustDIFlags Flags, + LLVMMetadataRef Elements, unsigned RunTimeLang, const char *UniqueId, + size_t UniqueIdLen) { return wrap(Builder->createUnionType( - unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(File), - LineNumber, SizeInBits, AlignInBits, fromRust(Flags), - DINodeArray(unwrapDI(Elements)), RunTimeLang, + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(File), LineNumber, SizeInBits, AlignInBits, + fromRust(Flags), DINodeArray(unwrapDI(Elements)), RunTimeLang, StringRef(UniqueId, UniqueIdLen))); } extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateTemplateTypeParameter( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, LLVMMetadataRef Ty) { + LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, const char *Name, + size_t NameLen, LLVMMetadataRef Ty) { bool IsDefault = false; // FIXME: should we ever set this true? return wrap(Builder->createTemplateTypeParameter( - unwrapDI(Scope), StringRef(Name, NameLen), unwrapDI(Ty), IsDefault)); + unwrapDI(Scope), StringRef(Name, NameLen), + unwrapDI(Ty), IsDefault)); } -extern "C" LLVMMetadataRef LLVMRustDIBuilderCreateNameSpace( - LLVMRustDIBuilderRef Builder, LLVMMetadataRef Scope, - const char *Name, size_t NameLen, bool ExportSymbols) { +extern "C" LLVMMetadataRef +LLVMRustDIBuilderCreateNameSpace(LLVMRustDIBuilderRef Builder, + LLVMMetadataRef Scope, const char *Name, + size_t NameLen, bool ExportSymbols) { return wrap(Builder->createNameSpace( - unwrapDI(Scope), StringRef(Name, NameLen), ExportSymbols - )); + unwrapDI(Scope), StringRef(Name, NameLen), ExportSymbols)); } -extern "C" void -LLVMRustDICompositeTypeReplaceArrays(LLVMRustDIBuilderRef Builder, - LLVMMetadataRef CompositeTy, - LLVMMetadataRef Elements, - LLVMMetadataRef Params) { +extern "C" void LLVMRustDICompositeTypeReplaceArrays( + LLVMRustDIBuilderRef Builder, LLVMMetadataRef CompositeTy, + LLVMMetadataRef Elements, LLVMMetadataRef Params) { DICompositeType *Tmp = unwrapDI(CompositeTy); Builder->replaceArrays(Tmp, DINodeArray(unwrap(Elements)), DINodeArray(unwrap(Params))); @@ -1235,9 +1219,8 @@ LLVMRustDIBuilderCreateDebugLocation(unsigned Line, unsigned Column, LLVMMetadataRef ScopeRef, LLVMMetadataRef InlinedAt) { MDNode *Scope = unwrapDIPtr(ScopeRef); - DILocation *Loc = DILocation::get( - Scope->getContext(), Line, Column, Scope, - unwrapDIPtr(InlinedAt)); + DILocation *Loc = DILocation::get(Scope->getContext(), Line, Column, Scope, + unwrapDIPtr(InlinedAt)); return wrap(Loc); } @@ -1258,8 +1241,7 @@ extern "C" void LLVMRustWriteTypeToString(LLVMTypeRef Ty, RustStringRef Str) { unwrap(Ty)->print(OS); } -extern "C" void LLVMRustWriteValueToString(LLVMValueRef V, - RustStringRef Str) { +extern "C" void LLVMRustWriteValueToString(LLVMValueRef V, RustStringRef Str) { auto OS = RawRustStringOstream(Str); if (!V) { OS << "(null)"; @@ -1281,7 +1263,7 @@ extern "C" void LLVMRustWriteTwineToString(LLVMTwineRef T, RustStringRef Str) { extern "C" void LLVMRustUnpackOptimizationDiagnostic( LLVMDiagnosticInfoRef DI, RustStringRef PassNameOut, - LLVMValueRef *FunctionOut, unsigned* Line, unsigned* Column, + LLVMValueRef *FunctionOut, unsigned *Line, unsigned *Column, RustStringRef FilenameOut, RustStringRef MessageOut) { // Undefined to call this not on an optimization diagnostic! llvm::DiagnosticInfoOptimizationBase *Opt = @@ -1304,17 +1286,15 @@ extern "C" void LLVMRustUnpackOptimizationDiagnostic( } enum class LLVMRustDiagnosticLevel { - Error, - Warning, - Note, - Remark, + Error, + Warning, + Note, + Remark, }; -extern "C" void -LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, - LLVMRustDiagnosticLevel *LevelOut, - uint64_t *CookieOut, - LLVMTwineRef *MessageOut) { +extern "C" void LLVMRustUnpackInlineAsmDiagnostic( + LLVMDiagnosticInfoRef DI, LLVMRustDiagnosticLevel *LevelOut, + uint64_t *CookieOut, LLVMTwineRef *MessageOut) { // Undefined to call this not on an inline assembly diagnostic! llvm::DiagnosticInfoInlineAsm *IA = static_cast(unwrap(DI)); @@ -1323,20 +1303,20 @@ LLVMRustUnpackInlineAsmDiagnostic(LLVMDiagnosticInfoRef DI, *MessageOut = wrap(&IA->getMsgStr()); switch (IA->getSeverity()) { - case DS_Error: - *LevelOut = LLVMRustDiagnosticLevel::Error; - break; - case DS_Warning: - *LevelOut = LLVMRustDiagnosticLevel::Warning; - break; - case DS_Note: - *LevelOut = LLVMRustDiagnosticLevel::Note; - break; - case DS_Remark: - *LevelOut = LLVMRustDiagnosticLevel::Remark; - break; - default: - report_fatal_error("Invalid LLVMRustDiagnosticLevel value!"); + case DS_Error: + *LevelOut = LLVMRustDiagnosticLevel::Error; + break; + case DS_Warning: + *LevelOut = LLVMRustDiagnosticLevel::Warning; + break; + case DS_Note: + *LevelOut = LLVMRustDiagnosticLevel::Note; + break; + case DS_Remark: + *LevelOut = LLVMRustDiagnosticLevel::Remark; + break; + default: + report_fatal_error("Invalid LLVMRustDiagnosticLevel value!"); } } @@ -1454,61 +1434,61 @@ extern "C" LLVMTypeKind LLVMRustGetTypeKind(LLVMTypeRef Ty) { return LLVMBFloatTypeKind; case Type::X86_AMXTyID: return LLVMX86_AMXTypeKind; - default: - { - std::string error; - auto stream = llvm::raw_string_ostream(error); - stream << "Rust does not support the TypeID: " << unwrap(Ty)->getTypeID() - << " for the type: " << *unwrap(Ty); - stream.flush(); - report_fatal_error(error.c_str()); - } + default: { + std::string error; + auto stream = llvm::raw_string_ostream(error); + stream << "Rust does not support the TypeID: " << unwrap(Ty)->getTypeID() + << " for the type: " << *unwrap(Ty); + stream.flush(); + report_fatal_error(error.c_str()); + } } } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(SMDiagnostic, LLVMSMDiagnosticRef) -extern "C" LLVMSMDiagnosticRef LLVMRustGetSMDiagnostic( - LLVMDiagnosticInfoRef DI, unsigned *Cookie) { - llvm::DiagnosticInfoSrcMgr *SM = static_cast(unwrap(DI)); +extern "C" LLVMSMDiagnosticRef LLVMRustGetSMDiagnostic(LLVMDiagnosticInfoRef DI, + unsigned *Cookie) { + llvm::DiagnosticInfoSrcMgr *SM = + static_cast(unwrap(DI)); *Cookie = SM->getLocCookie(); return wrap(&SM->getSMDiag()); } -extern "C" bool LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef, - RustStringRef MessageOut, - RustStringRef BufferOut, - LLVMRustDiagnosticLevel* LevelOut, - unsigned* LocOut, - unsigned* RangesOut, - size_t* NumRanges) { - SMDiagnostic& D = *unwrap(DRef); +extern "C" bool +LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef, RustStringRef MessageOut, + RustStringRef BufferOut, + LLVMRustDiagnosticLevel *LevelOut, unsigned *LocOut, + unsigned *RangesOut, size_t *NumRanges) { + SMDiagnostic &D = *unwrap(DRef); auto MessageOS = RawRustStringOstream(MessageOut); MessageOS << D.getMessage(); switch (D.getKind()) { - case SourceMgr::DK_Error: - *LevelOut = LLVMRustDiagnosticLevel::Error; - break; - case SourceMgr::DK_Warning: - *LevelOut = LLVMRustDiagnosticLevel::Warning; - break; - case SourceMgr::DK_Note: - *LevelOut = LLVMRustDiagnosticLevel::Note; - break; - case SourceMgr::DK_Remark: - *LevelOut = LLVMRustDiagnosticLevel::Remark; - break; - default: - report_fatal_error("Invalid LLVMRustDiagnosticLevel value!"); + case SourceMgr::DK_Error: + *LevelOut = LLVMRustDiagnosticLevel::Error; + break; + case SourceMgr::DK_Warning: + *LevelOut = LLVMRustDiagnosticLevel::Warning; + break; + case SourceMgr::DK_Note: + *LevelOut = LLVMRustDiagnosticLevel::Note; + break; + case SourceMgr::DK_Remark: + *LevelOut = LLVMRustDiagnosticLevel::Remark; + break; + default: + report_fatal_error("Invalid LLVMRustDiagnosticLevel value!"); } if (D.getLoc() == SMLoc()) return false; const SourceMgr &LSM = *D.getSourceMgr(); - const MemoryBuffer *LBuf = LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); - LLVMRustStringWriteImpl(BufferOut, LBuf->getBufferStart(), LBuf->getBufferSize()); + const MemoryBuffer *LBuf = + LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); + LLVMRustStringWriteImpl(BufferOut, LBuf->getBufferStart(), + LBuf->getBufferSize()); *LocOut = D.getLoc().getPointer() - LBuf->getBufferStart(); @@ -1525,7 +1505,8 @@ extern "C" bool LLVMRustUnpackSMDiagnostic(LLVMSMDiagnosticRef DRef, extern "C" OperandBundleDef *LLVMRustBuildOperandBundleDef(const char *Name, LLVMValueRef *Inputs, unsigned NumInputs) { - return new OperandBundleDef(Name, ArrayRef(unwrap(Inputs), NumInputs)); + return new OperandBundleDef(Name, + ArrayRef(unwrap(Inputs), NumInputs)); } extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) { @@ -1533,8 +1514,9 @@ extern "C" void LLVMRustFreeOperandBundleDef(OperandBundleDef *Bundle) { } // OpBundlesIndirect is an array of pointers (*not* a pointer to an array). -extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn, - LLVMValueRef *Args, unsigned NumArgs, +extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, + LLVMValueRef Fn, LLVMValueRef *Args, + unsigned NumArgs, OperandBundleDef **OpBundlesIndirect, unsigned NumOpBundles) { Value *Callee = unwrap(Fn); @@ -1547,17 +1529,19 @@ extern "C" LLVMValueRef LLVMRustBuildCall(LLVMBuilderRef B, LLVMTypeRef Ty, LLVM OpBundles.push_back(*OpBundlesIndirect[i]); } - return wrap(unwrap(B)->CreateCall( - FTy, Callee, ArrayRef(unwrap(Args), NumArgs), - ArrayRef(OpBundles))); + return wrap(unwrap(B)->CreateCall(FTy, Callee, + ArrayRef(unwrap(Args), NumArgs), + ArrayRef(OpBundles))); } -extern "C" LLVMValueRef LLVMRustGetInstrProfIncrementIntrinsic(LLVMModuleRef M) { +extern "C" LLVMValueRef +LLVMRustGetInstrProfIncrementIntrinsic(LLVMModuleRef M) { return wrap(llvm::Intrinsic::getDeclaration( unwrap(M), llvm::Intrinsic::instrprof_increment)); } -extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRef M) { +extern "C" LLVMValueRef +LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRef M) { #if LLVM_VERSION_GE(18, 0) return wrap(llvm::Intrinsic::getDeclaration( unwrap(M), llvm::Intrinsic::instrprof_mcdc_parameters)); @@ -1566,7 +1550,8 @@ extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCParametersIntrinsic(LLVMModuleRe #endif } -extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModuleRef M) { +extern "C" LLVMValueRef +LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModuleRef M) { #if LLVM_VERSION_GE(18, 0) return wrap(llvm::Intrinsic::getDeclaration( unwrap(M), llvm::Intrinsic::instrprof_mcdc_tvbitmap_update)); @@ -1575,7 +1560,8 @@ extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCTVBitmapUpdateIntrinsic(LLVMModu #endif } -extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRef M) { +extern "C" LLVMValueRef +LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRef M) { #if LLVM_VERSION_GE(18, 0) return wrap(llvm::Intrinsic::getDeclaration( unwrap(M), llvm::Intrinsic::instrprof_mcdc_condbitmap_update)); @@ -1584,32 +1570,31 @@ extern "C" LLVMValueRef LLVMRustGetInstrProfMCDCCondBitmapIntrinsic(LLVMModuleRe #endif } -extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B, - LLVMValueRef Dst, unsigned DstAlign, - LLVMValueRef Src, unsigned SrcAlign, - LLVMValueRef Size, bool IsVolatile) { - return wrap(unwrap(B)->CreateMemCpy( - unwrap(Dst), MaybeAlign(DstAlign), - unwrap(Src), MaybeAlign(SrcAlign), - unwrap(Size), IsVolatile)); +extern "C" LLVMValueRef LLVMRustBuildMemCpy(LLVMBuilderRef B, LLVMValueRef Dst, + unsigned DstAlign, LLVMValueRef Src, + unsigned SrcAlign, + LLVMValueRef Size, + bool IsVolatile) { + return wrap(unwrap(B)->CreateMemCpy(unwrap(Dst), MaybeAlign(DstAlign), + unwrap(Src), MaybeAlign(SrcAlign), + unwrap(Size), IsVolatile)); } -extern "C" LLVMValueRef LLVMRustBuildMemMove(LLVMBuilderRef B, - LLVMValueRef Dst, unsigned DstAlign, - LLVMValueRef Src, unsigned SrcAlign, - LLVMValueRef Size, bool IsVolatile) { - return wrap(unwrap(B)->CreateMemMove( - unwrap(Dst), MaybeAlign(DstAlign), - unwrap(Src), MaybeAlign(SrcAlign), - unwrap(Size), IsVolatile)); +extern "C" LLVMValueRef +LLVMRustBuildMemMove(LLVMBuilderRef B, LLVMValueRef Dst, unsigned DstAlign, + LLVMValueRef Src, unsigned SrcAlign, LLVMValueRef Size, + bool IsVolatile) { + return wrap(unwrap(B)->CreateMemMove(unwrap(Dst), MaybeAlign(DstAlign), + unwrap(Src), MaybeAlign(SrcAlign), + unwrap(Size), IsVolatile)); } -extern "C" LLVMValueRef LLVMRustBuildMemSet(LLVMBuilderRef B, - LLVMValueRef Dst, unsigned DstAlign, - LLVMValueRef Val, - LLVMValueRef Size, bool IsVolatile) { - return wrap(unwrap(B)->CreateMemSet( - unwrap(Dst), unwrap(Val), unwrap(Size), MaybeAlign(DstAlign), IsVolatile)); +extern "C" LLVMValueRef LLVMRustBuildMemSet(LLVMBuilderRef B, LLVMValueRef Dst, + unsigned DstAlign, LLVMValueRef Val, + LLVMValueRef Size, + bool IsVolatile) { + return wrap(unwrap(B)->CreateMemSet(unwrap(Dst), unwrap(Val), unwrap(Size), + MaybeAlign(DstAlign), IsVolatile)); } // OpBundlesIndirect is an array of pointers (*not* a pointer to an array). @@ -1630,7 +1615,7 @@ LLVMRustBuildInvoke(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn, } return wrap(unwrap(B)->CreateInvoke(FTy, Callee, unwrap(Then), unwrap(Catch), - ArrayRef(unwrap(Args), NumArgs), + ArrayRef(unwrap(Args), NumArgs), ArrayRef(OpBundles), Name)); } @@ -1647,7 +1632,7 @@ LLVMRustBuildCallBr(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn, FunctionType *FTy = unwrap(Ty); // FIXME: Is there a way around this? - std::vector IndirectDestsUnwrapped; + std::vector IndirectDestsUnwrapped; IndirectDestsUnwrapped.reserve(NumIndirectDests); for (unsigned i = 0; i < NumIndirectDests; ++i) { IndirectDestsUnwrapped.push_back(unwrap(IndirectDests[i])); @@ -1660,12 +1645,11 @@ LLVMRustBuildCallBr(LLVMBuilderRef B, LLVMTypeRef Ty, LLVMValueRef Fn, OpBundles.push_back(*OpBundlesIndirect[i]); } - return wrap(unwrap(B)->CreateCallBr( - FTy, Callee, unwrap(DefaultDest), - ArrayRef(IndirectDestsUnwrapped), - ArrayRef(unwrap(Args), NumArgs), - ArrayRef(OpBundles), - Name)); + return wrap( + unwrap(B)->CreateCallBr(FTy, Callee, unwrap(DefaultDest), + ArrayRef(IndirectDestsUnwrapped), + ArrayRef(unwrap(Args), NumArgs), + ArrayRef(OpBundles), Name)); } extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B, @@ -1765,28 +1749,30 @@ extern "C" void LLVMRustSetLinkage(LLVMValueRef V, } extern "C" bool LLVMRustConstIntGetZExtValue(LLVMValueRef CV, uint64_t *value) { - auto C = unwrap(CV); - if (C->getBitWidth() > 64) - return false; - *value = C->getZExtValue(); - return true; + auto C = unwrap(CV); + if (C->getBitWidth() > 64) + return false; + *value = C->getZExtValue(); + return true; } -// Returns true if both high and low were successfully set. Fails in case constant wasn’t any of -// the common sizes (1, 8, 16, 32, 64, 128 bits) -extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, uint64_t *high, uint64_t *low) -{ - auto C = unwrap(CV); - if (C->getBitWidth() > 128) { return false; } - APInt AP; - if (sext) { - AP = C->getValue().sext(128); - } else { - AP = C->getValue().zext(128); - } - *low = AP.getLoBits(64).getZExtValue(); - *high = AP.getHiBits(64).getZExtValue(); - return true; +// Returns true if both high and low were successfully set. Fails in case +// constant wasn’t any of the common sizes (1, 8, 16, 32, 64, 128 bits) +extern "C" bool LLVMRustConstInt128Get(LLVMValueRef CV, bool sext, + uint64_t *high, uint64_t *low) { + auto C = unwrap(CV); + if (C->getBitWidth() > 128) { + return false; + } + APInt AP; + if (sext) { + AP = C->getValue().sext(128); + } else { + AP = C->getValue().zext(128); + } + *low = AP.getLoBits(64).getZExtValue(); + *high = AP.getHiBits(64).getZExtValue(); + return true; } enum class LLVMRustVisibility { @@ -1836,8 +1822,7 @@ struct LLVMRustModuleBuffer { std::string data; }; -extern "C" LLVMRustModuleBuffer* -LLVMRustModuleBufferCreate(LLVMModuleRef M) { +extern "C" LLVMRustModuleBuffer *LLVMRustModuleBufferCreate(LLVMModuleRef M) { auto Ret = std::make_unique(); { auto OS = raw_string_ostream(Ret->data); @@ -1846,30 +1831,26 @@ LLVMRustModuleBufferCreate(LLVMModuleRef M) { return Ret.release(); } -extern "C" void -LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) { +extern "C" void LLVMRustModuleBufferFree(LLVMRustModuleBuffer *Buffer) { delete Buffer; } -extern "C" const void* +extern "C" const void * LLVMRustModuleBufferPtr(const LLVMRustModuleBuffer *Buffer) { return Buffer->data.data(); } -extern "C" size_t -LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) { +extern "C" size_t LLVMRustModuleBufferLen(const LLVMRustModuleBuffer *Buffer) { return Buffer->data.length(); } -extern "C" uint64_t -LLVMRustModuleCost(LLVMModuleRef M) { +extern "C" uint64_t LLVMRustModuleCost(LLVMModuleRef M) { auto f = unwrap(M)->functions(); return std::distance(std::begin(f), std::end(f)); } -extern "C" void -LLVMRustModuleInstructionStats(LLVMModuleRef M, RustStringRef Str) -{ +extern "C" void LLVMRustModuleInstructionStats(LLVMModuleRef M, + RustStringRef Str) { auto OS = RawRustStringOstream(Str); auto JOS = llvm::json::OStream(OS); auto Module = unwrap(M); @@ -1881,41 +1862,45 @@ LLVMRustModuleInstructionStats(LLVMModuleRef M, RustStringRef Str) } // Vector reductions: -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc),unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, LLVMValueRef Acc, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc),unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateAddReduce(unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateMulReduce(unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateAndReduce(unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateOrReduce(unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, LLVMValueRef Src) { - return wrap(unwrap(B)->CreateXorReduce(unwrap(Src))); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) { - return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned)); -} -extern "C" LLVMValueRef -LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, LLVMValueRef Src, bool IsSigned) { - return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned)); +extern "C" LLVMValueRef LLVMRustBuildVectorReduceFAdd(LLVMBuilderRef B, + LLVMValueRef Acc, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateFAddReduce(unwrap(Acc), unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceFMul(LLVMBuilderRef B, + LLVMValueRef Acc, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateFMulReduce(unwrap(Acc), unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceAdd(LLVMBuilderRef B, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateAddReduce(unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceMul(LLVMBuilderRef B, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateMulReduce(unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceAnd(LLVMBuilderRef B, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateAndReduce(unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceOr(LLVMBuilderRef B, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateOrReduce(unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceXor(LLVMBuilderRef B, + LLVMValueRef Src) { + return wrap(unwrap(B)->CreateXorReduce(unwrap(Src))); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceMin(LLVMBuilderRef B, + LLVMValueRef Src, + bool IsSigned) { + return wrap(unwrap(B)->CreateIntMinReduce(unwrap(Src), IsSigned)); +} +extern "C" LLVMValueRef LLVMRustBuildVectorReduceMax(LLVMBuilderRef B, + LLVMValueRef Src, + bool IsSigned) { + return wrap(unwrap(B)->CreateIntMaxReduce(unwrap(Src), IsSigned)); } extern "C" LLVMValueRef LLVMRustBuildVectorReduceFMin(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) { @@ -1930,32 +1915,28 @@ LLVMRustBuildVectorReduceFMax(LLVMBuilderRef B, LLVMValueRef Src, bool NoNaN) { return wrap(I); } -extern "C" LLVMValueRef -LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) { - return wrap(unwrap(B)->CreateMinNum(unwrap(LHS),unwrap(RHS))); +extern "C" LLVMValueRef LLVMRustBuildMinNum(LLVMBuilderRef B, LLVMValueRef LHS, + LLVMValueRef RHS) { + return wrap(unwrap(B)->CreateMinNum(unwrap(LHS), unwrap(RHS))); } -extern "C" LLVMValueRef -LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, LLVMValueRef RHS) { - return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS),unwrap(RHS))); +extern "C" LLVMValueRef LLVMRustBuildMaxNum(LLVMBuilderRef B, LLVMValueRef LHS, + LLVMValueRef RHS) { + return wrap(unwrap(B)->CreateMaxNum(unwrap(LHS), unwrap(RHS))); } // This struct contains all necessary info about a symbol exported from a DLL. struct LLVMRustCOFFShortExport { - const char* name; + const char *name; bool ordinal_present; // The value of `ordinal` is only meaningful if `ordinal_present` is true. uint16_t ordinal; }; // Machine must be a COFF machine type, as defined in PE specs. -extern "C" LLVMRustResult LLVMRustWriteImportLibrary( - const char* ImportName, - const char* Path, - const LLVMRustCOFFShortExport* Exports, - size_t NumExports, - uint16_t Machine, - bool MinGW) -{ +extern "C" LLVMRustResult +LLVMRustWriteImportLibrary(const char *ImportName, const char *Path, + const LLVMRustCOFFShortExport *Exports, + size_t NumExports, uint16_t Machine, bool MinGW) { std::vector ConvertedExports; ConvertedExports.reserve(NumExports); @@ -1963,27 +1944,24 @@ extern "C" LLVMRustResult LLVMRustWriteImportLibrary( bool ordinal_present = Exports[i].ordinal_present; uint16_t ordinal = ordinal_present ? Exports[i].ordinal : 0; ConvertedExports.push_back(llvm::object::COFFShortExport{ - Exports[i].name, // Name - std::string{}, // ExtName - std::string{}, // SymbolName - std::string{}, // AliasTarget + Exports[i].name, // Name + std::string{}, // ExtName + std::string{}, // SymbolName + std::string{}, // AliasTarget #if LLVM_VERSION_GE(19, 0) - std::string{}, // ExportAs + std::string{}, // ExportAs #endif - ordinal, // Ordinal - ordinal_present, // Noname - false, // Data - false, // Private - false // Constant + ordinal, // Ordinal + ordinal_present, // Noname + false, // Data + false, // Private + false // Constant }); } auto Error = llvm::object::writeImportLibrary( - ImportName, - Path, - ConvertedExports, - static_cast(Machine), - MinGW); + ImportName, Path, ConvertedExports, + static_cast(Machine), MinGW); if (Error) { std::string errorString; auto stream = llvm::raw_string_ostream(errorString); @@ -2019,27 +1997,23 @@ using LLVMDiagnosticHandlerTy = DiagnosticHandler::DiagnosticHandlerTy; // the RemarkPasses array specifies individual passes for which remarks will be // enabled. // -// If RemarkFilePath is not NULL, optimization remarks will be streamed directly into this file, -// bypassing the diagnostics handler. +// If RemarkFilePath is not NULL, optimization remarks will be streamed directly +// into this file, bypassing the diagnostics handler. extern "C" void LLVMRustContextConfigureDiagnosticHandler( LLVMContextRef C, LLVMDiagnosticHandlerTy DiagnosticHandlerCallback, void *DiagnosticHandlerContext, bool RemarkAllPasses, - const char * const * RemarkPasses, size_t RemarkPassesLen, - const char * RemarkFilePath, - bool PGOAvailable -) { + const char *const *RemarkPasses, size_t RemarkPassesLen, + const char *RemarkFilePath, bool PGOAvailable) { class RustDiagnosticHandler final : public DiagnosticHandler { public: RustDiagnosticHandler( - LLVMDiagnosticHandlerTy DiagnosticHandlerCallback, - void *DiagnosticHandlerContext, - bool RemarkAllPasses, - std::vector RemarkPasses, - std::unique_ptr RemarksFile, - std::unique_ptr RemarkStreamer, - std::unique_ptr LlvmRemarkStreamer - ) + LLVMDiagnosticHandlerTy DiagnosticHandlerCallback, + void *DiagnosticHandlerContext, bool RemarkAllPasses, + std::vector RemarkPasses, + std::unique_ptr RemarksFile, + std::unique_ptr RemarkStreamer, + std::unique_ptr LlvmRemarkStreamer) : DiagnosticHandlerCallback(DiagnosticHandlerCallback), DiagnosticHandlerContext(DiagnosticHandlerContext), RemarkAllPasses(RemarkAllPasses), @@ -2049,11 +2023,13 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler( LlvmRemarkStreamer(std::move(LlvmRemarkStreamer)) {} virtual bool handleDiagnostics(const DiagnosticInfo &DI) override { - // If this diagnostic is one of the optimization remark kinds, we can check if it's enabled - // before emitting it. This can avoid many short-lived allocations when unpacking the - // diagnostic and converting its various C++ strings into rust strings. - // FIXME: some diagnostic infos still allocate before we get here, and avoiding that would be - // good in the future. That will require changing a few call sites in LLVM. + // If this diagnostic is one of the optimization remark kinds, we can + // check if it's enabled before emitting it. This can avoid many + // short-lived allocations when unpacking the diagnostic and converting + // its various C++ strings into rust strings. + // FIXME: some diagnostic infos still allocate before we get here, and + // avoiding that would be good in the future. That will require changing a + // few call sites in LLVM. if (auto *OptDiagBase = dyn_cast(&DI)) { if (OptDiagBase->isEnabled()) { if (this->LlvmRemarkStreamer) { @@ -2109,16 +2085,15 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler( bool RemarkAllPasses = false; std::vector RemarkPasses; - // Since LlvmRemarkStreamer contains a pointer to RemarkStreamer, the ordering of the three - // members below is important. + // Since LlvmRemarkStreamer contains a pointer to RemarkStreamer, the + // ordering of the three members below is important. std::unique_ptr RemarksFile; std::unique_ptr RemarkStreamer; std::unique_ptr LlvmRemarkStreamer; }; std::vector Passes; - for (size_t I = 0; I != RemarkPassesLen; ++I) - { + for (size_t I = 0; I != RemarkPassesLen; ++I) { Passes.push_back(RemarkPasses[I]); } @@ -2135,13 +2110,10 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler( std::error_code EC; RemarkFile = std::make_unique( - RemarkFilePath, - EC, - llvm::sys::fs::OF_TextWithCRLF - ); + RemarkFilePath, EC, llvm::sys::fs::OF_TextWithCRLF); if (EC) { std::string Error = std::string("Cannot create remark file: ") + - toString(errorCodeToError(EC)); + toString(errorCodeToError(EC)); report_fatal_error(Twine(Error)); } @@ -2149,28 +2121,22 @@ extern "C" void LLVMRustContextConfigureDiagnosticHandler( RemarkFile->keep(); auto RemarkSerializer = remarks::createRemarkSerializer( - llvm::remarks::Format::YAML, - remarks::SerializerMode::Separate, - RemarkFile->os() - ); - if (Error E = RemarkSerializer.takeError()) - { - std::string Error = std::string("Cannot create remark serializer: ") + toString(std::move(E)); + llvm::remarks::Format::YAML, remarks::SerializerMode::Separate, + RemarkFile->os()); + if (Error E = RemarkSerializer.takeError()) { + std::string Error = std::string("Cannot create remark serializer: ") + + toString(std::move(E)); report_fatal_error(Twine(Error)); } - RemarkStreamer = std::make_unique(std::move(*RemarkSerializer)); + RemarkStreamer = std::make_unique( + std::move(*RemarkSerializer)); LlvmRemarkStreamer = std::make_unique(*RemarkStreamer); } unwrap(C)->setDiagnosticHandler(std::make_unique( - DiagnosticHandlerCallback, - DiagnosticHandlerContext, - RemarkAllPasses, - Passes, - std::move(RemarkFile), - std::move(RemarkStreamer), - std::move(LlvmRemarkStreamer) - )); + DiagnosticHandlerCallback, DiagnosticHandlerContext, RemarkAllPasses, + Passes, std::move(RemarkFile), std::move(RemarkStreamer), + std::move(LlvmRemarkStreamer))); } extern "C" void LLVMRustGetMangledName(LLVMValueRef V, RustStringRef Str) { @@ -2180,14 +2146,14 @@ extern "C" void LLVMRustGetMangledName(LLVMValueRef V, RustStringRef Str) { } extern "C" int32_t LLVMRustGetElementTypeArgIndex(LLVMValueRef CallSite) { - auto *CB = unwrap(CallSite); - switch (CB->getIntrinsicID()) { - case Intrinsic::arm_ldrex: - return 0; - case Intrinsic::arm_strex: - return 1; - } - return -1; + auto *CB = unwrap(CallSite); + switch (CB->getIntrinsicID()) { + case Intrinsic::arm_ldrex: + return 0; + case Intrinsic::arm_strex: + return 1; + } + return -1; } extern "C" bool LLVMRustIsBitcode(char *ptr, size_t len) { @@ -2214,10 +2180,10 @@ extern "C" bool LLVMRustLLVMHasZstdCompressionForDebugSymbols() { } // Operations on composite constants. -// These are clones of LLVM api functions that will become available in future releases. -// They can be removed once Rust's minimum supported LLVM version supports them. -// See https://github.com/rust-lang/rust/issues/121868 -// See https://llvm.org/doxygen/group__LLVMCCoreValueConstantComposite.html +// These are clones of LLVM api functions that will become available in future +// releases. They can be removed once Rust's minimum supported LLVM version +// supports them. See https://github.com/rust-lang/rust/issues/121868 See +// https://llvm.org/doxygen/group__LLVMCCoreValueConstantComposite.html // FIXME: Remove when Rust's minimum supported LLVM version reaches 19. // https://github.com/llvm/llvm-project/commit/e1405e4f71c899420ebf8262d5e9745598419df8 @@ -2226,6 +2192,7 @@ extern "C" LLVMValueRef LLVMConstStringInContext2(LLVMContextRef C, const char *Str, size_t Length, bool DontNullTerminate) { - return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length), !DontNullTerminate)); + return wrap(ConstantDataArray::getString(*unwrap(C), StringRef(Str, Length), + !DontNullTerminate)); } #endif diff --git a/compiler/rustc_llvm/llvm-wrapper/SuppressLLVMWarnings.h b/compiler/rustc_llvm/llvm-wrapper/SuppressLLVMWarnings.h index 56964e4eaa702..09ecfd54cd8e9 100644 --- a/compiler/rustc_llvm/llvm-wrapper/SuppressLLVMWarnings.h +++ b/compiler/rustc_llvm/llvm-wrapper/SuppressLLVMWarnings.h @@ -1,13 +1,17 @@ #ifndef _rustc_llvm_SuppressLLVMWarnings_h #define _rustc_llvm_SuppressLLVMWarnings_h -// LLVM currently generates many warnings when compiled using MSVC. These warnings make it difficult -// to diagnose real problems when working on C++ code, so we suppress them. +// LLVM currently generates many warnings when compiled using MSVC. These +// warnings make it difficult to diagnose real problems when working on C++ +// code, so we suppress them. #ifdef _MSC_VER -#pragma warning(disable:4530) // C++ exception handler used, but unwind semantics are not enabled. -#pragma warning(disable:4624) // 'xxx': destructor was implicitly defined as deleted -#pragma warning(disable:4244) // conversion from 'xxx' to 'yyy', possible loss of data +#pragma warning(disable : 4530) // C++ exception handler used, but unwind + // semantics are not enabled. +#pragma warning( \ + disable : 4624) // 'xxx': destructor was implicitly defined as deleted +#pragma warning( \ + disable : 4244) // conversion from 'xxx' to 'yyy', possible loss of data #endif #endif // _rustc_llvm_SuppressLLVMWarnings_h diff --git a/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp index ee8239ef8e79d..a9d1362a338d0 100644 --- a/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp @@ -34,14 +34,15 @@ static bool isArchiveSymbol(const object::BasicSymbolRef &S) { typedef void *(*LLVMRustGetSymbolsCallback)(void *, const char *); typedef void *(*LLVMRustGetSymbolsErrorCallback)(const char *); -// Note: This is implemented in C++ instead of using the C api from Rust as IRObjectFile doesn't -// implement getSymbolName, only printSymbolName, which is inaccessible from the C api. -extern "C" void *LLVMRustGetSymbols( - char *BufPtr, size_t BufLen, void *State, LLVMRustGetSymbolsCallback Callback, - LLVMRustGetSymbolsErrorCallback ErrorCallback) { - std::unique_ptr Buf = - MemoryBuffer::getMemBuffer(StringRef(BufPtr, BufLen), StringRef("LLVMRustGetSymbolsObject"), - false); +// Note: This is implemented in C++ instead of using the C api from Rust as +// IRObjectFile doesn't implement getSymbolName, only printSymbolName, which is +// inaccessible from the C api. +extern "C" void * +LLVMRustGetSymbols(char *BufPtr, size_t BufLen, void *State, + LLVMRustGetSymbolsCallback Callback, + LLVMRustGetSymbolsErrorCallback ErrorCallback) { + std::unique_ptr Buf = MemoryBuffer::getMemBuffer( + StringRef(BufPtr, BufLen), StringRef("LLVMRustGetSymbolsObject"), false); SmallString<0> SymNameBuf; auto SymName = raw_svector_ostream(SymNameBuf); @@ -57,7 +58,7 @@ extern "C" void *LLVMRustGetSymbols( if (Type == file_magic::bitcode) { auto ObjOrErr = object::SymbolicFile::createSymbolicFile( - Buf->getMemBufferRef(), file_magic::bitcode, &Context); + Buf->getMemBufferRef(), file_magic::bitcode, &Context); if (!ObjOrErr) { Error E = ObjOrErr.takeError(); SmallString<0> ErrorBuf; @@ -67,7 +68,8 @@ extern "C" void *LLVMRustGetSymbols( } Obj = std::move(*ObjOrErr); } else { - auto ObjOrErr = object::SymbolicFile::createSymbolicFile(Buf->getMemBufferRef()); + auto ObjOrErr = + object::SymbolicFile::createSymbolicFile(Buf->getMemBufferRef()); if (!ObjOrErr) { Error E = ObjOrErr.takeError(); SmallString<0> ErrorBuf; @@ -78,7 +80,6 @@ extern "C" void *LLVMRustGetSymbols( Obj = std::move(*ObjOrErr); } - for (const object::BasicSymbolRef &S : Obj->symbols()) { if (!isArchiveSymbol(S)) continue; From c163d5c99d381efb74c02182996b69b32ecfcff1 Mon Sep 17 00:00:00 2001 From: DianQK Date: Tue, 25 Jun 2024 18:37:15 +0800 Subject: [PATCH 24/24] Add `cpp:fmt` to mingw-check-tidy --- src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile b/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile index 0a49eab4d5028..cb17592b201cc 100644 --- a/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile +++ b/src/ci/docker/host-x86_64/mingw-check-tidy/Dockerfile @@ -35,4 +35,4 @@ COPY host-x86_64/mingw-check/validate-error-codes.sh /scripts/ # NOTE: intentionally uses python2 for x.py so we can test it still works. # validate-toolstate only runs in our CI, so it's ok for it to only support python3. ENV SCRIPT TIDY_PRINT_DIFF=1 python2.7 ../x.py test \ - --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint + --stage 0 src/tools/tidy tidyselftest --extra-checks=py:lint,cpp:fmt