Skip to content

Commit

Permalink
Auto merge of #130679 - saethlin:inline-usually, r=<try>
Browse files Browse the repository at this point in the history
Add inline(usually)

I'm looking into what kind of things could recover the perf improvement detected in #121417 (comment). I think it's worth spending quite a bit of effort to figure out how to capture a 45% incr-patched improvement.

As far as I can tell, the root cause of the problem is that we have taken very deliberate steps in the compiler to ensure that `#[inline(always)]`  causes inlining where possible, even when all optimizations are disabled. Some of the reasons that was done are now outdated or were misguided. I think the only remaining use case is where the inlined body even without optimizations is cheaper to codegen or call, for example SIMD intrinsics may require a lot of code to put their arguments on the stack, which is slow to compile and run.

I'm quite sure that the majority of users applied this attribute believing it does not cause inlining in unoptimized builds, or didn't appreciate the build time regressions that implies and would prefer it didn't if they knew. (if that's you, put a heart on this or say something elsewhere, don't reply on this PR)

I am going to _try_ to use the existing benchmark suite to evaluate a number of different approaches and take notes here, and hopefully I can collect enough data to shape any conversation about what we can do to help users.

The core of this PR is `InlineAttr::Usually` (name doesn't matter) which ensures that when optimizations are enabled that the function is inlined (usual exceptions like recursion apply). I think most users believe this is what `#[inline(always)]` does.

#130685 (comment) Replaced `#[inline(always)]` with `#[inline(usually)]` in the standard library, and did not recover the same 45% incr-patched improvement in regex. It's a tidy net positive though, and I suspect that perf improvement would normally be big enough to motivate merging a change. I think that means the standard library's use of `#[inline(always)]` is imposing marginal compile time overhead on the ecosystem, but the bigger opportunities are probably in third-party crates.

#130679 (comment) Treats `#[inline(always)]` as `#[inline(usually)]` literally everywhere; this gets the desired incr-patched improvement but suffers quite a few check and doc regressions. I think that means that `alwaysinline` is more powerful than `function-inline-cost=0` in LLVM.

#130679 (comment) Treats `#[inline(always)]` as `#[inline(usually)]` when `-Copt-level=0`, which looks basically the same as #121417 (comment) (omit `alwaysinline` when doing `-Copt-level=0` codegen).

#130679 (comment) replaces `alwaysinline` with a very negative inline cost, and it still has check and doc regressions. More investigation required on what the different inlining decision is.

#130679 (comment) is a likely explanation of this, with some interesting implications; adding `inline(always)` to a function that was going to be inlined anyway can change change optimizations (usually it seems to improve things?).

#130679 (comment) makes `#[inline(usually)]` also defy instantiation mode selection and always be LocalCopy the way `#[inline(always)]` does, but still has regressions in stm32f4. I think that proves that `alwaysinline` can actually improve debug build times.

#130679 (comment) infers `alwaysinline` for extremely trivial functions, but still has regressions for stm32f4. But of course it does, I left `inline(always)` treated as `inline(usually)` which slows down the compiler 🤦 inconclusive perf run.

TODO: What happens if we infer `alwaysinline` for extremely small functions like most of those in stm32f4?
  • Loading branch information
bors committed Sep 29, 2024
2 parents ed04567 + 8c95207 commit 3a65c2b
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 4 deletions.
1 change: 1 addition & 0 deletions compiler/rustc_attr/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub enum InlineAttr {
Hint,
Always,
Never,
Usually,
}

#[derive(Clone, Encodable, Decodable, Debug, PartialEq, Eq, HashStable_Generic)]
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_gcc/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ fn inline_attr<'gcc, 'tcx>(
None
}
}
InlineAttr::Usually => Some(FnAttribute::Inline),
InlineAttr::None => None,
}
}
Expand Down
36 changes: 35 additions & 1 deletion compiler/rustc_codegen_llvm/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ fn inline_attr<'ll>(cx: &CodegenCx<'ll, '_>, inline: InlineAttr) -> Option<&'ll
}
}
InlineAttr::None => None,
InlineAttr::Usually => {
Some(llvm::CreateAttrStringValue(cx.llcx, "function-inline-cost", "0"))
}
}
}

Expand Down Expand Up @@ -324,6 +327,27 @@ fn create_alloc_family_attr(llcx: &llvm::Context) -> &llvm::Attribute {
llvm::CreateAttrStringValue(llcx, "alloc-family", "__rust_alloc")
}

fn should_always_inline(body: &rustc_middle::mir::Body<'_>) -> bool {
use rustc_middle::mir::*;
match body.basic_blocks.len() {
0 => return true,
1 => {}
2.. => return false,
}
let block = &body.basic_blocks[START_BLOCK];
match block.statements.len() {
0 => {
matches!(block.terminator().kind, TerminatorKind::Return)
}
1 => {
let statement = &block.statements[0];
matches!(statement.kind, StatementKind::Assign(_))
&& matches!(block.terminator().kind, TerminatorKind::Return)
}
2.. => return false,
}
}

/// Helper for `FnAbi::apply_attrs_llfn`:
/// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
/// attributes.
Expand Down Expand Up @@ -353,7 +377,17 @@ pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>(
} else {
codegen_fn_attrs.inline
};
to_add.extend(inline_attr(cx, inline));

if cx.tcx.is_mir_available(instance.def_id()) {
let body = cx.tcx.instance_mir(instance.def);
if should_always_inline(body) {
to_add.push(AttributeKind::AlwaysInline.create_attr(cx.llcx));
} else {
to_add.extend(inline_attr(cx, inline));
}
} else {
to_add.extend(inline_attr(cx, inline));
}

// The `uwtable` attribute according to LLVM is:
//
Expand Down
9 changes: 8 additions & 1 deletion compiler/rustc_codegen_ssa/src/codegen_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use rustc_middle::middle::codegen_fn_attrs::{
use rustc_middle::mir::mono::Linkage;
use rustc_middle::query::Providers;
use rustc_middle::ty::{self as ty, TyCtxt};
use rustc_session::config::OptLevel;
use rustc_session::lint;
use rustc_session::parse::feature_err;
use rustc_span::symbol::Ident;
Expand Down Expand Up @@ -525,9 +526,15 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
.emit();
InlineAttr::None
} else if list_contains_name(items, sym::always) {
InlineAttr::Always
if tcx.sess.opts.optimize == OptLevel::No {
InlineAttr::Usually
} else {
InlineAttr::Always
}
} else if list_contains_name(items, sym::never) {
InlineAttr::Never
} else if list_contains_name(items, sym::usually) {
InlineAttr::Usually
} else {
struct_span_code_err!(tcx.dcx(), items[0].span(), E0535, "invalid argument")
.with_help("valid inline arguments are `always` and `never`")
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/cross_crate_inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
// #[inline(never)] to force code generation.
match codegen_fn_attrs.inline {
InlineAttr::Never => return false,
InlineAttr::Hint | InlineAttr::Always => return true,
InlineAttr::Hint | InlineAttr::Always | InlineAttr::Usually => return true,
_ => {}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_transform/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ fn inline<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
changed: false,
caller_is_inline_forwarder: matches!(
codegen_fn_attrs.inline,
InlineAttr::Hint | InlineAttr::Always
InlineAttr::Hint | InlineAttr::Always | InlineAttr::Usually
) && body_is_forwarder(body),
};
let blocks = START_BLOCK..body.basic_blocks.next_index();
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2102,6 +2102,7 @@ symbols! {
usize_legacy_fn_max_value,
usize_legacy_fn_min_value,
usize_legacy_mod,
usually,
va_arg,
va_copy,
va_end,
Expand Down

0 comments on commit 3a65c2b

Please sign in to comment.