Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Do not inline function calls into cold blocks (#15236)

Nick Fitzgerald266d7946f778
diff --git a/crates/cranelift/src/compiler.rs b/crates/cranelift/src/compiler.rs
index 13eaa5dccd..76fcc180bb 100644
--- a/crates/cranelift/src/compiler.rs
+++ b/crates/cranelift/src/compiler.rs
@@ -38,12 +38,12 @@ use wasmparser::{FuncValidatorAllocations, FunctionBody};
use wasmtime_environ::error::{Context as _, Result};
use wasmtime_environ::obj::{ELF_WASMTIME_EXCEPTIONS, ELF_WASMTIME_FRAMES};
use wasmtime_environ::{
- Abi, AddressMapSection, BuiltinFunctionIndex, CacheStore, CompileError, CompiledFunctionBody,
- DefinedFuncIndex, FlagValue, FrameInstPos, FrameStackShape, FrameStateSlotBuilder,
- FrameTableBuilder, FuncKey, FunctionBodyData, FunctionLoc, GetPtrSize, HostCall,
- InliningCompiler, ModulePC, ModuleStartup, ModuleTranslation, ModuleTypesBuilder, PtrSize,
- StackMapSection, StaticModuleIndex, TrapEncodingBuilder, TrapSentinel, TripleExt, Tunables,
- WasmFuncType, WasmValType, prelude::*,
+ Abi, AddressMapSection, BuiltinFunctionIndex, CacheStore, CallSite, CompileError,
+ CompiledFunctionBody, DefinedFuncIndex, FlagValue, FrameInstPos, FrameStackShape,
+ FrameStateSlotBuilder, FrameTableBuilder, FuncKey, FunctionBodyData, FunctionLoc, GetPtrSize,
+ HostCall, InliningCompiler, ModulePC, ModuleStartup, ModuleTranslation, ModuleTypesBuilder,
+ PtrSize, StackMapSection, StaticModuleIndex, TrapEncodingBuilder, TrapSentinel, TripleExt,
+ Tunables, WasmFuncType, WasmValType, prelude::*,
};
use wasmtime_unwinder::ExceptionTableBuilder;
@@ -1001,7 +1001,7 @@ impl InliningCompiler for Compiler {
fn inline<'a>(
&self,
func_body: &mut CompiledFunctionBody,
- get_callee: &'a mut dyn FnMut(FuncKey) -> Option<&'a CompiledFunctionBody>,
+ get_callee: &'a mut dyn FnMut(FuncKey, CallSite) -> Option<&'a CompiledFunctionBody>,
) -> Result<()> {
debug_assert!(!func_body.code.is::<CompiledFunction>());
debug_assert!(func_body.code.is::<Option<Box<CompilerContext>>>());
@@ -1014,13 +1014,15 @@ impl InliningCompiler for Compiler {
cx.codegen_context.inline(Inliner(get_callee))?;
return Ok(());
- struct Inliner<'a>(&'a mut dyn FnMut(FuncKey) -> Option<&'a CompiledFunctionBody>);
+ struct Inliner<'a>(
+ &'a mut dyn FnMut(FuncKey, CallSite) -> Option<&'a CompiledFunctionBody>,
+ );
impl cranelift_codegen::inline::Inline for Inliner<'_> {
fn inline(
&mut self,
caller: &ir::Function,
- _call_inst: ir::Inst,
+ call_inst: ir::Inst,
_call_opcode: ir::Opcode,
callee: ir::FuncRef,
_call_args: &[ir::Value],
@@ -1039,7 +1041,11 @@ impl InliningCompiler for Compiler {
FuncKey::UnsafeIntrinsic(..) => {}
_ => return InlineCommand::KeepCall,
}
- match (self.0)(callee) {
+ let is_cold = caller
+ .layout
+ .inst_block(call_inst)
+ .is_some_and(|block| caller.layout.is_cold(block));
+ match (self.0)(callee, CallSite { is_cold }) {
None => InlineCommand::KeepCall,
Some(func_body) => {
debug_assert!(!func_body.code.is::<CompiledFunction>());
diff --git a/crates/environ/src/compile/mod.rs b/crates/environ/src/compile/mod.rs
index 78c5cc1a31..0c57a0a23b 100644
--- a/crates/environ/src/compile/mod.rs
+++ b/crates/environ/src/compile/mod.rs
@@ -467,6 +467,14 @@ pub trait Compiler: Send + Sync {
fn release_caches(&self);
}
+/// Information about a call site, for use in inlining heuristics.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct CallSite {
+ /// Whether this call site is in cold code (e.g. a block that has been
+ /// hinted as unlikely to execute).
+ pub is_cold: bool,
+}
+
/// An inlining compiler.
pub trait InliningCompiler: Sync + Send {
/// Enumerate the function calls that the given `func` makes.
@@ -479,12 +487,13 @@ pub trait InliningCompiler: Sync + Send {
/// Process this function for inlining.
///
/// Implementations should call `get_callee` for each of their direct
- /// function call sites and if `get_callee` returns `Some(_)`, they should
- /// inline the given function body into that call site.
+ /// function call sites, passing the callee and information about the call
+ /// site, and if `get_callee` returns `Some(_)`, they should inline the
+ /// given function body into that call site.
fn inline<'a>(
&self,
func: &mut CompiledFunctionBody,
- get_callee: &'a mut dyn FnMut(FuncKey) -> Option<&'a CompiledFunctionBody>,
+ get_callee: &'a mut dyn FnMut(FuncKey, CallSite) -> Option<&'a CompiledFunctionBody>,
) -> Result<()>;
/// Finish compiling the given function.
diff --git a/crates/wasmtime/src/compile.rs b/crates/wasmtime/src/compile.rs
index adba68a130..bd6a64581c 100644
--- a/crates/wasmtime/src/compile.rs
+++ b/crates/wasmtime/src/compile.rs
@@ -28,7 +28,7 @@ use crate::hash_set::HashSet;
use crate::prelude::*;
use std::{any::Any, borrow::Cow, mem, ops::Range};
use wasmtime_environ::{
- Abi, CompiledFunctionBody, CompiledFunctionsTable, CompiledFunctionsTableBuilder,
+ Abi, CallSite, CompiledFunctionBody, CompiledFunctionsTable, CompiledFunctionsTableBuilder,
CompiledModuleInfo, Compiler, DefinedFuncIndex, FilePos, FinishedObject, FuncKey,
FunctionBodyData, Inlining, InliningCompiler, ModuleEnvironment, ModuleTranslation,
ModuleTypes, ModuleTypesBuilder, ObjectKind, PrimaryMap, StaticModuleIndex, Tunables,
@@ -288,6 +288,7 @@ struct InlineHeuristicParams<'a> {
callee_size: u32,
callee_key: FuncKey,
callee_needs_gc_heap: bool,
+ call_site_is_cold: bool,
}
/// The collection of things we need to compile for a Wasm module or component.
@@ -773,42 +774,46 @@ the use case.
let mut caller_size = inlining_compiler.size(caller);
- inlining_compiler.inline(caller, &mut |callee_key: FuncKey| {
- log::trace!(" --> considering call to {callee_key:?}");
- let callee_output_index: OutputIndex = key_to_output[&callee_key];
-
- // NB: If the callee is not inside `outputs`, then it is
- // in the same `Strata` layer as the caller (and
- // therefore is in the same strongly-connected component
- // as the caller, and they mutually recursive). In this
- // case, we do not do any inlining; communicate this
- // command via `?`-propagation.
- let callee_output = outputs[callee_output_index].as_ref()?;
-
- debug_assert_eq!(callee_output.key, callee_key);
-
- let callee = &callee_output.function;
- let callee_size = inlining_compiler.size(callee);
-
- let callee_needs_gc_heap = callee_output
- .translation
- .is_some_and(|t| t.module.needs_gc_heap);
-
- if Self::should_inline(InlineHeuristicParams {
- tunables: engine.tunables(),
- caller_size,
- caller_key,
- caller_needs_gc_heap,
- callee_size,
- callee_key,
- callee_needs_gc_heap,
- }) {
- caller_size = caller_size.saturating_add(callee_size);
- Some(callee)
- } else {
- None
- }
- })
+ inlining_compiler.inline(
+ caller,
+ &mut |callee_key: FuncKey, call_site: CallSite| {
+ log::trace!(" --> considering call to {callee_key:?}");
+ let callee_output_index: OutputIndex = key_to_output[&callee_key];
+
+ // NB: If the callee is not inside `outputs`, then it is
+ // in the same `Strata` layer as the caller (and
+ // therefore is in the same strongly-connected component
+ // as the caller, and they mutually recursive). In this
+ // case, we do not do any inlining; communicate this
+ // command via `?`-propagation.
+ let callee_output = outputs[callee_output_index].as_ref()?;
+
+ debug_assert_eq!(callee_output.key, callee_key);
+
+ let callee = &callee_output.function;
+ let callee_size = inlining_compiler.size(callee);
+
+ let callee_needs_gc_heap = callee_output
+ .translation
+ .is_some_and(|t| t.module.needs_gc_heap);
+
+ if Self::should_inline(InlineHeuristicParams {
+ tunables: engine.tunables(),
+ caller_size,
+ caller_key,
+ caller_needs_gc_heap,
+ callee_size,
+ callee_key,
+ callee_needs_gc_heap,
+ call_site_is_cold: call_site.is_cold,
+ }) {
+ caller_size = caller_size.saturating_add(callee_size);
+ Some(callee)
+ } else {
+ None
+ }
+ },
+ )
},
)?;
@@ -861,6 +866,7 @@ the use case.
callee_size,
callee_key,
callee_needs_gc_heap,
+ call_site_is_cold,
}: InlineHeuristicParams,
) -> bool {
log::trace!(
@@ -870,7 +876,8 @@ the use case.
\t\tneeds_gc_heap = {caller_needs_gc_heap}\n\
\tcallee = {callee_key:?}\n\
\t\tsize = {callee_size}\n\
- \t\tneeds_gc_heap = {callee_needs_gc_heap}"
+ \t\tneeds_gc_heap = {callee_needs_gc_heap}\n\
+ \tcall_site_is_cold = {call_site_is_cold}"
);
debug_assert!(
@@ -879,6 +886,13 @@ the use case.
);
debug_assert_ne!(caller_key, callee_key, "we never inline recursion");
+ // Don't inline into cold call sites: doing so bloats code that is
+ // rarely executed and provides little benefit.
+ if call_site_is_cold {
+ log::trace!(" --> not inlining: call site is cold");
+ return false;
+ }
+
// Put a limit on how large we can make a function via inlining to cap
// code bloat.
let sum_size = caller_size.saturating_add(callee_size);
diff --git a/tests/disas/inlining-cold-call-site.wat b/tests/disas/inlining-cold-call-site.wat
new file mode 100644
index 0000000000..47f9f98e27
--- /dev/null
+++ b/tests/disas/inlining-cold-call-site.wat
@@ -0,0 +1,67 @@
+;;! target = "x86_64"
+;;! test = "optimize"
+;;! filter = "wasm[0]--function[2]"
+;;! flags = "-Cinlining=y -Wbranch-hinting"
+
+;; Calls in cold blocks are not inlined.
+
+(module
+ (func $hot_callee (result i32)
+ (i32.const 42)
+ )
+
+ (func $cold_callee (result i32)
+ (i32.const 36)
+ )
+
+ (func (param i32) (result i32)
+ local.get 0
+ (@metadata.code.branch_hint "\01")
+ if (result i32)
+ call $hot_callee
+ else
+ call $cold_callee
+ end
+ )
+)
+
+;; function u0:2(i64 vmctx, i64, i32) -> i32 tail {
+;; region0 = 123 ""
+;; region1 = 160 ""
+;; gv0 = vmctx
+;; gv1 = load.i64 notrap aligned readonly can_move region0 gv0+8
+;; gv2 = load.i64 notrap aligned region1 gv1+24
+;; gv3 = vmctx
+;; gv4 = load.i64 notrap aligned readonly can_move region0 gv3+8
+;; gv5 = load.i64 notrap aligned region1 gv4+24
+;; sig0 = (i64 vmctx, i64) -> i32 tail
+;; fn0 = colocated u0:0 sig0
+;; fn1 = colocated u0:1 sig0
+;; stack_limit = gv2
+;;
+;; block0(v0: i64, v1: i64, v2: i32):
+;; @004d brif v2, block2, block4
+;;
+;; block2:
+;; @004f jump block5
+;;
+;; block5:
+;; jump block6
+;;
+;; block6:
+;; jump block7
+;;
+;; block7:
+;; v7 = iconst.i32 42
+;; @0051 jump block3(v7) ; v7 = 42
+;;
+;; block4 cold:
+;; @0052 v4 = call fn1(v0, v0)
+;; @0054 jump block3(v4)
+;;
+;; block3(v5: i32):
+;; @0055 jump block1
+;;
+;; block1:
+;; @0055 return v5
+;; }