Files
wasmtime/cranelift/codegen/src/timing.rs
Benjamin Bouvier 8a9b1a9025 Implement an incremental compilation cache for Cranelift (#4551)
This is the implementation of https://github.com/bytecodealliance/wasmtime/issues/4155, using the "inverted API" approach suggested by @cfallin (thanks!) in Cranelift, and trait object to provide a backend for an all-included experience in Wasmtime. 

After the suggestion of Chris, `Function` has been split into mostly two parts:

- on the one hand, `FunctionStencil` contains all the fields required during compilation, and that act as a compilation cache key: if two function stencils are the same, then the result of their compilation (`CompiledCodeBase<Stencil>`) will be the same. This makes caching trivial, as the only thing to cache is the `FunctionStencil`.
- on the other hand, `FunctionParameters` contain the... function parameters that are required to finalize the result of compilation into a `CompiledCode` (aka `CompiledCodeBase<Final>`) with proper final relocations etc., by applying fixups and so on.

Most changes are here to accomodate those requirements, in particular that `FunctionStencil` should be `Hash`able to be used as a key in the cache:

- most source locations are now relative to a base source location in the function, and as such they're encoded as `RelSourceLoc` in the `FunctionStencil`. This required changes so that there's no need to explicitly mark a `SourceLoc` as the base source location, it's automatically detected instead the first time a non-default `SourceLoc` is set.
- user-defined external names in the `FunctionStencil` (aka before this patch `ExternalName::User { namespace, index }`) are now references into an external table of `UserExternalNameRef -> UserExternalName`, present in the `FunctionParameters`, and must be explicitly declared using `Function::declare_imported_user_function`.
- some refactorings have been made for function names:
  - `ExternalName` was used as the type for a `Function`'s name; while it thus allowed `ExternalName::Libcall` in this place, this would have been quite confusing to use it there. Instead, a new enum `UserFuncName` is introduced for this name, that's either a user-defined function name (the above `UserExternalName`) or a test case name.
  - The future of `ExternalName` is likely to become a full reference into the `FunctionParameters`'s mapping, instead of being "either a handle for user-defined external names, or the thing itself for other variants". I'm running out of time to do this, and this is not trivial as it implies touching ISLE which I'm less familiar with.

The cache computes a sha256 hash of the `FunctionStencil`, and uses this as the cache key. No equality check (using `PartialEq`) is performed in addition to the hash being the same, as we hope that this is sufficient data to avoid collisions.

A basic fuzz target has been introduced that tries to do the bare minimum:

- check that a function successfully compiled and cached will be also successfully reloaded from the cache, and returns the exact same function.
- check that a trivial modification in the external mapping of `UserExternalNameRef -> UserExternalName` hits the cache, and that other modifications don't hit the cache.
  - This last check is less efficient and less likely to happen, so probably should be rethought a bit.

Thanks to both @alexcrichton and @cfallin for your very useful feedback on Zulip.

Some numbers show that for a large wasm module we're using internally, this is a 20% compile-time speedup, because so many `FunctionStencil`s are the same, even within a single module. For a group of modules that have a lot of code in common, we get hit rates up to 70% when they're used together. When a single function changes in a wasm module, every other function is reloaded; that's still slower than I expect (between 10% and 50% of the overall compile time), so there's likely room for improvement. 

Fixes #4155.
2022-08-12 16:47:43 +00:00

265 lines
8.5 KiB
Rust

//! Pass timing.
//!
//! This modules provides facilities for timing the execution of individual compilation passes.
use core::fmt;
pub use self::details::{add_to_current, take_current, PassTimes, TimingToken};
// Each pass that can be timed is predefined with the `define_passes!` macro. Each pass has a
// snake_case name and a plain text description used when printing out the timing report.
//
// This macro defines:
//
// - A C-style enum containing all the pass names and a `None` variant.
// - A usize constant with the number of defined passes.
// - A const array of pass descriptions.
// - A public function per pass used to start the timing of that pass.
macro_rules! define_passes {
{ $enum:ident, $num_passes:ident, $descriptions:ident;
$($pass:ident: $desc:expr,)+
} => {
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum $enum { $($pass,)+ None}
const $num_passes: usize = $enum::None as usize;
const $descriptions: [&str; $num_passes] = [ $($desc),+ ];
$(
#[doc=$desc]
#[must_use]
pub fn $pass() -> TimingToken {
details::start_pass($enum::$pass)
}
)+
}
}
// Pass definitions.
define_passes! {
Pass, NUM_PASSES, DESCRIPTIONS;
// All these are used in other crates but defined here so they appear in the unified
// `PassTimes` output.
process_file: "Processing test file",
parse_text: "Parsing textual Cranelift IR",
wasm_translate_module: "Translate WASM module",
wasm_translate_function: "Translate WASM function",
verifier: "Verify Cranelift IR",
verify_flags: "Verify CPU flags",
compile: "Compilation passes",
try_incremental_cache: "Try loading from incremental cache",
store_incremental_cache: "Store in incremental cache",
flowgraph: "Control flow graph",
domtree: "Dominator tree",
loop_analysis: "Loop analysis",
preopt: "Pre-legalization rewriting",
dce: "Dead code elimination",
gvn: "Global value numbering",
licm: "Loop invariant code motion",
unreachable_code: "Remove unreachable blocks",
remove_constant_phis: "Remove constant phi-nodes",
vcode_lower: "VCode lowering",
vcode_emit: "VCode emission",
vcode_emit_finish: "VCode emission finalization",
regalloc: "Register allocation",
regalloc_checker: "Register allocation symbolic verification",
layout_renumber: "Layout full renumbering",
canonicalize_nans: "Canonicalization of NaNs",
}
impl Pass {
pub fn idx(self) -> usize {
self as usize
}
}
impl fmt::Display for Pass {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match DESCRIPTIONS.get(self.idx()) {
Some(s) => f.write_str(s),
None => f.write_str("<no pass>"),
}
}
}
/// Implementation details.
///
/// This whole module can be gated on a `cfg` feature to provide a dummy implementation for
/// performance-sensitive builds or restricted environments. The dummy implementation must provide
/// `TimingToken` and `PassTimes` types and `take_current`, `add_to_current`, and `start_pass` funcs
#[cfg(feature = "std")]
mod details {
use super::{Pass, DESCRIPTIONS, NUM_PASSES};
use std::cell::{Cell, RefCell};
use std::fmt;
use std::mem;
use std::time::{Duration, Instant};
/// A timing token is responsible for timing the currently running pass. Timing starts when it
/// is created and ends when it is dropped.
///
/// Multiple passes can be active at the same time, but they must be started and stopped in a
/// LIFO fashion.
pub struct TimingToken {
/// Start time for this pass.
start: Instant,
// Pass being timed by this token.
pass: Pass,
// The previously active pass which will be restored when this token is dropped.
prev: Pass,
}
/// Accumulated timing information for a single pass.
#[derive(Default, Copy, Clone)]
struct PassTime {
/// Total time spent running this pass including children.
total: Duration,
/// Time spent running in child passes.
child: Duration,
}
/// Accumulated timing for all passes.
pub struct PassTimes {
pass: [PassTime; NUM_PASSES],
}
impl PassTimes {
/// Returns the total amount of time taken by all the passes measured.
pub fn total(&self) -> Duration {
self.pass.iter().map(|p| p.total - p.child).sum()
}
}
impl Default for PassTimes {
fn default() -> Self {
Self {
pass: [Default::default(); NUM_PASSES],
}
}
}
impl fmt::Display for PassTimes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "======== ======== ==================================")?;
writeln!(f, " Total Self Pass")?;
writeln!(f, "-------- -------- ----------------------------------")?;
for (time, desc) in self.pass.iter().zip(&DESCRIPTIONS[..]) {
// Omit passes that haven't run.
if time.total == Duration::default() {
continue;
}
// Write a duration as secs.millis, trailing space.
fn fmtdur(mut dur: Duration, f: &mut fmt::Formatter) -> fmt::Result {
// Round to nearest ms by adding 500us.
dur += Duration::new(0, 500_000);
let ms = dur.subsec_millis();
write!(f, "{:4}.{:03} ", dur.as_secs(), ms)
}
fmtdur(time.total, f)?;
if let Some(s) = time.total.checked_sub(time.child) {
fmtdur(s, f)?;
}
writeln!(f, " {}", desc)?;
}
writeln!(f, "======== ======== ==================================")
}
}
// Information about passes in a single thread.
thread_local! {
static CURRENT_PASS: Cell<Pass> = const { Cell::new(Pass::None) };
static PASS_TIME: RefCell<PassTimes> = RefCell::new(Default::default());
}
/// Start timing `pass` as a child of the currently running pass, if any.
///
/// This function is called by the publicly exposed pass functions.
pub(super) fn start_pass(pass: Pass) -> TimingToken {
let prev = CURRENT_PASS.with(|p| p.replace(pass));
log::debug!("timing: Starting {}, (during {})", pass, prev);
TimingToken {
start: Instant::now(),
pass,
prev,
}
}
/// Dropping a timing token indicated the end of the pass.
impl Drop for TimingToken {
fn drop(&mut self) {
let duration = self.start.elapsed();
log::debug!("timing: Ending {}", self.pass);
let old_cur = CURRENT_PASS.with(|p| p.replace(self.prev));
debug_assert_eq!(self.pass, old_cur, "Timing tokens dropped out of order");
PASS_TIME.with(|rc| {
let mut table = rc.borrow_mut();
table.pass[self.pass.idx()].total += duration;
if let Some(parent) = table.pass.get_mut(self.prev.idx()) {
parent.child += duration;
}
})
}
}
/// Take the current accumulated pass timings and reset the timings for the current thread.
pub fn take_current() -> PassTimes {
PASS_TIME.with(|rc| mem::replace(&mut *rc.borrow_mut(), Default::default()))
}
/// Add `timings` to the accumulated timings for the current thread.
pub fn add_to_current(times: &PassTimes) {
PASS_TIME.with(|rc| {
for (a, b) in rc.borrow_mut().pass.iter_mut().zip(&times.pass[..]) {
a.total += b.total;
a.child += b.child;
}
})
}
}
/// Dummy `debug` implementation
#[cfg(not(feature = "std"))]
mod details {
use super::Pass;
/// Dummy `TimingToken`
pub struct TimingToken;
/// Dummy `PassTimes`
pub struct PassTimes;
/// Returns dummy `PassTimes`
pub fn take_current() -> PassTimes {
PassTimes
}
/// does nothing
pub fn add_to_current(_times: PassTimes) {}
/// does nothing
pub(super) fn start_pass(_pass: Pass) -> TimingToken {
TimingToken
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
#[test]
fn display() {
assert_eq!(Pass::None.to_string(), "<no pass>");
assert_eq!(Pass::regalloc.to_string(), "Register allocation");
}
}