Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resurrect: rustc_llvm: Add a -Z print-codegen-stats option to expose LLVM statistics. #113723

Merged
merged 4 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions compiler/rustc_codegen_gcc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ impl WriteBackendMethods for GccCodegenBackend {
unimplemented!();
}

fn print_statistics(&self) {
unimplemented!()
}

unsafe fn optimize(_cgcx: &CodegenContext<Self>, _diag_handler: &Handler, module: &ModuleCodegen<Self::Module>, config: &ModuleConfig) -> Result<(), FatalError> {
module.module_llvm.context.set_optimization_level(to_gcc_opt_level(config.opt_level));
Ok(())
Expand Down
29 changes: 26 additions & 3 deletions compiler/rustc_codegen_llvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,32 @@ impl WriteBackendMethods for LlvmCodegenBackend {
type ThinData = back::lto::ThinData;
type ThinBuffer = back::lto::ThinBuffer;
fn print_pass_timings(&self) {
unsafe {
llvm::LLVMRustPrintPassTimings();
}
let msg = unsafe {
let cstr = llvm::LLVMRustPrintPassTimings();
if cstr.is_null() {
"failed to get pass timings".into()
} else {
let timings = CStr::from_ptr(cstr).to_bytes();
let timings = String::from_utf8_lossy(timings).to_string();
libc::free(cstr as *mut _);
timings
}
};
println!("{}", msg);
}
fn print_statistics(&self) {
let msg = unsafe {
let cstr = llvm::LLVMRustPrintStatistics();
if cstr.is_null() {
"failed to get stats".into()
} else {
let stats = CStr::from_ptr(cstr).to_bytes();
let stats = String::from_utf8_lossy(stats).to_string();
khei4 marked this conversation as resolved.
Show resolved Hide resolved
libc::free(cstr as *mut _);
stats
}
};
println!("{}", msg);
}
fn run_link(
cgcx: &CodegenContext<Self>,
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_codegen_llvm/src/llvm/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1868,7 +1868,10 @@ extern "C" {
pub fn LLVMRustGetLastError() -> *const c_char;

/// Print the pass timings since static dtors aren't picking them up.
pub fn LLVMRustPrintPassTimings();
pub fn LLVMRustPrintPassTimings() -> *const c_char;

/// Print the statistics since static dtors aren't picking them up.
pub fn LLVMRustPrintStatistics() -> *const c_char;

pub fn LLVMStructCreateNamed(C: &Context, Name: *const c_char) -> &Type;

Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_codegen_llvm/src/llvm_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ unsafe fn configure_llvm(sess: &Session) {
// Use non-zero `import-instr-limit` multiplier for cold callsites.
add("-import-cold-multiplier=0.1", false);

if sess.print_llvm_stats() {
add("-stats", false);
}

for arg in sess_args {
add(&(*arg), true);
}
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1945,6 +1945,10 @@ impl<B: ExtraBackendMethods> OngoingCodegen<B> {
self.backend.print_pass_timings()
}

if sess.print_llvm_stats() {
self.backend.print_statistics()
}

(
CodegenResults {
metadata: self.metadata,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_ssa/src/traits/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub trait WriteBackendMethods: 'static + Sized + Clone {
cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError>;
fn print_pass_timings(&self);
fn print_statistics(&self);
unsafe fn optimize(
cgcx: &CodegenContext<Self>,
diag_handler: &Handler,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,7 @@ fn test_unstable_options_tracking_hash() {
untracked!(perf_stats, true);
// `pre_link_arg` is omitted because it just forwards to `pre_link_args`.
untracked!(pre_link_args, vec![String::from("abc"), String::from("def")]);
untracked!(print_codegen_stats, true);
untracked!(print_llvm_passes, true);
untracked!(print_mono_items, Some(String::from("abc")));
untracked!(print_type_sizes, true);
Expand Down
22 changes: 19 additions & 3 deletions compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "LLVMWrapper.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DiagnosticHandler.h"
#include "llvm/IR/DiagnosticInfo.h"
Expand Down Expand Up @@ -111,9 +112,24 @@ extern "C" void LLVMRustSetNormalizedTarget(LLVMModuleRef M,
unwrap(M)->setTargetTriple(Triple::normalize(Triple));
}

extern "C" void LLVMRustPrintPassTimings() {
raw_fd_ostream OS(2, false); // stderr.
TimerGroup::printAll(OS);
extern "C" const char *LLVMRustPrintPassTimings(void) {
std::string buf;
raw_string_ostream SS(buf);
TimerGroup::printAll(SS);
SS.flush();
char* CStr = (char*) malloc((buf.length() + 1) * sizeof(char));
strcpy(CStr, buf.c_str());
return CStr;
}
khei4 marked this conversation as resolved.
Show resolved Hide resolved

extern "C" const char *LLVMRustPrintStatistics(void) {
std::string buf;
raw_string_ostream SS(buf);
llvm::PrintStatistics(SS);
SS.flush();
char* CStr = (char*) malloc((buf.length() + 1) * sizeof(char));
strcpy(CStr, buf.c_str());
return CStr;
}

extern "C" LLVMValueRef LLVMRustGetNamedValue(LLVMModuleRef M, const char *Name,
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1668,6 +1668,9 @@ options! {
"use a more precise version of drop elaboration for matches on enums (default: yes). \
This results in better codegen, but has caused miscompilations on some tier 2 platforms. \
See #77382 and #74551."),
#[rustc_lint_opt_deny_field_access("use `Session::print_codegen_stats` instead of this field")]
print_codegen_stats: bool = (false, parse_bool, [UNTRACKED],
"print codegen statistics (default: no)"),
print_fuel: Option<String> = (None, parse_opt_string, [TRACKED],
"make rustc print the total optimization fuel used by a crate"),
print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,10 @@ impl Session {
self.opts.unstable_opts.verbose
}

pub fn print_llvm_stats(&self) -> bool {
self.opts.unstable_opts.print_codegen_stats
}

pub fn verify_llvm_ir(&self) -> bool {
self.opts.unstable_opts.verify_llvm_ir || option_env!("RUSTC_VERIFY_LLVM_IR").is_some()
}
Expand Down
Loading