Skip to content

[clang][Inliner] Add opt-in inliner hints and implementation-file functions - #228074

Merged
kubamracek merged 6 commits into
llvm:mainfrom
kubamracek:inliner-hints-for-linkonce-odr
Nov 3, 2026
Merged

kubamracek merged 6 commits into
llvm:mainfrom
kubamracek:inliner-hints-for-linkonce-odr

Conversation

@kubamracek

@kubamracek kubamracek commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

Today, inline functions, template instantiations and lambdas (inside those) are emitted as linkonce_odr:

  • we expect another TU may use the out-of-line copy, we want one optimized version to be shared across TUs
  • the inliner doesn't treat a call as the last one to linkonce_odr functions, even if we observe that in the TU

This patch lets Clang pass down information to the inliner about such callees, allowing lambdas, implementation-file functions (as opposed to code coming from header files), and template/inline functions from implemenation files, to be more likely to inline and optimize further. This patch just introduces the mechanism, but keeps all inlining changes off by default.

Note that placing templates/inlines/lambdas into an anonymous namespace eliminates the linkonce_odr linkage, inlines well already, and achieves the goal already. This PR is improving the situations where the source code doesn't explicitly use anonymous namespaces or other mechanisms to make the linkage internal, which is quite common in C++ code in the wild.

Motivating cases:

  • Lambdas used in STL algorithms can be just over the inline threshold (body not large, just not trivial). Inlining has large outsized benefits e.g. on captures (they can stay as local variables at the caller) or on optimizations beyond one loop iteration. Example:
// in a .cpp file
template <class V>
long foo(const V& v, int k0, int k1) {
  return std::count_if(v.begin(), v.end(), [&](int e) {
    int x = ...; // non-trivial, with some branches
    return x > e;
  });
}

Godbolt link: https://godbolt.org/z/6WWjPrPWT (GCC does inline in this case)

  • An immediately invoked lambda has exactly one call site, inlining it can't duplicate code. Example:
// in a .cpp file
template <class T>
T bar(T a, T k) {
  const T r = [&] {
    T x = ...; // non-trivial, with some branches
    return x;
  }();
  return r + a;
}

Godbolt link: https://godbolt.org/z/dz6EYnG1e (GCC does inline in this case too)

Implementation approach is:

  • Clang marks implementation-file definitions with a function attribute
  • An implementation-file linkonce_odr callee with a single call in the TU gets the last-call bonus, just like an internal function.

Assisted-by: Claude

@llvmorg-github-actions llvmorg-github-actions Bot added clang:codegen IR generation bugs: mangling, exceptions, etc. llvm:analysis Includes value tracking, cost tables and constant folding llvm:transforms labels Oct 1, 2026
@llvmorg-github-actions

llvmorg-github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-clang-driver
@llvm/pr-subscribers-llvm-ir
@llvm/pr-subscribers-llvm-transforms
@llvm/pr-subscribers-llvm-analysis

@llvm/pr-subscribers-clang-codegen

Author: Kuba (Brecka) Mracek (kubamracek)

Changes

Today, inline functions, template instantiations and lambdas (inside those) are emitted as linkonce_odr:

  • we expect another TU may use the out-of-line copy, we want one optimized version to be shared across TUs
  • the inliner doesn't treat a call as the last one to linkonce_odr functions, even if we observe that in the TU

This patch lets Clang pass down information to the inliner about such callees, allowing lambdas, main-file functions, and template/inline functions from main files, to be more likely to inline and optimize further. This patch just introduces the mechanism, the thresholds, but keeps all inlining changes off by default.

Note that placing templates/inlines/lambdas into an anonymous namespace eliminates the linkonce_odr linkage, inlines well already, and achieves the goal already. This PR is improving the situations where the source code doesn't explicitly use anonymous namespaces or other mechanisms to make the linkage internal, which is quite common in C++ code in the wild.

Motivating cases:

  • Lambdas used in STL algorithms can be just over the inline threshold (body not large, just not trivial). Inlining has large outsized benefits e.g. on captures (they can stay as local variables at the caller) or on optimizations beyond one loop iteration. Example:
template &lt;class V&gt;
long foo(const V&amp; v, int k0, int k1) {
  return std::count_if(v.begin(), v.end(), [&amp;](int e) {
    int x = ...; // non-trivial, with some branches
    return x &gt; e;
  });
}

Godbolt link: https://godbolt.org/z/6WWjPrPWT (GCC does inline in this case)

  • An immediately invoked lambda has exactly one call site, inlining it can't duplicate code. Example:
template &lt;class T&gt;
T bar(T a, T k) {
  const T r = [&amp;] {
    T x = ...; // non-trivial, with some branches
    return x;
  }();
  return r + a;
}

Godbolt link: https://godbolt.org/z/dz6EYnG1e (GCC does inline in this case too)

Implementation approach is:

  • Characterize certain (usually linkonce_odr) functions in Clang and pass that information as function attributes, namely:
    • "clang-lambda" for lambdas
    • "clang-main-file" when the function is defined in a main source file (and not a header file)
    • "clang-main-file"="inline-or-template" meaning it's also a function that is inline or a template instantiation)
  • Under -mllvm -inline-use-clang-hints (off by default), InlineCost raises the threshold for such callees.
  • The bonuses are tiered: lambdas defined in the main file get the largest boost, other lambdas get a smaller bonus, and main-file inline/template functions get yet a smaller bonus.
  • Main-file functions that are neither inline nor templates (plain functions) get no bonus.
  • Additionally, a linkonce_odr lambda defined in the main file is treated as a local function for the purposes of the sole-call (last-call-to-static) bonus. Ignoring unusual setups like #include-ing a .cpp file, no other TU can reuse such a lambda, so inlining its only call site is expected to leave the original dead. In the unusual setup case (e.g. "Unity builds"), such lambdas still get the pre-existing behavior of no inlining.

Assisted-by: Claude


Full diff: https://github.com/llvm/llvm-project/pull/228074.diff

4 Files Affected:

  • (modified) clang/lib/CodeGen/CodeGenModule.cpp (+16)
  • (added) clang/test/CodeGenCXX/inline-origin-hints.cpp (+29)
  • (modified) llvm/lib/Analysis/InlineCost.cpp (+53-2)
  • (added) llvm/test/Transforms/Inline/clang-hints.ll (+63)
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index d19d64e2e1c60..a2756988464a1 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3296,6 +3296,22 @@ void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   if (CodeGenOpts.DisableOutlining || D->hasAttr<NoOutlineAttr>())
     B.addAttribute(llvm::Attribute::NoOutline);
 
+  // Hints for the optimizer (see -mllvm -inline-use-clang-hints) helping with
+  // linkonce_odr C++ functions: is this a lambda, is it defined in the main
+  // source file, is it declared inline or a template instantiation.
+  if (isLambdaCallOperator(dyn_cast<DeclContext>(D)))
+    B.addAttribute("clang-lambda");
+  // D->getLocation(), for a template instantiation, is the location of the
+  // template's definition, not instantiation.
+  const SourceManager &SM = getContext().getSourceManager();
+  if (SM.isInMainFile(D->getLocation())) {
+    const auto *FD = dyn_cast<FunctionDecl>(D);
+    bool InlineOrTemplate =
+        FD && (FD->isInlineSpecified() || FD->isTemplateInstantiation());
+    B.addAttribute("clang-main-file",
+                   InlineOrTemplate ? "inline-or-template" : "");
+  }
+
   F->addFnAttrs(B);
 
   llvm::MaybeAlign ExplicitAlignment;
diff --git a/clang/test/CodeGenCXX/inline-origin-hints.cpp b/clang/test/CodeGenCXX/inline-origin-hints.cpp
new file mode 100644
index 0000000000000..f73708a8309c0
--- /dev/null
+++ b/clang/test/CodeGenCXX/inline-origin-hints.cpp
@@ -0,0 +1,29 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -triple arm64-apple-macosx14.0.0 -std=c++20 -emit-llvm -o - %t/main.cpp | FileCheck %s
+
+//--- hdr.h
+inline int hdr_inline(int x) { return x * 3; }
+template <class F> int hdr_call(F f) { return f(); }
+
+//--- main.cpp
+#include "hdr.h"
+
+int main_plain(int x) { return x + 1; }
+inline int main_inline(int x) { return x * 7; }
+template <class T> int main_tmpl(T x) { return hdr_call([&] { return x * 2; }); }
+
+int use(int x) { return main_plain(x) + main_inline(x) + main_tmpl(x) + hdr_inline(x); }
+
+// CHECK: define{{.*}} i32 @_Z10main_plaini({{.*}}) #[[PLAIN:[0-9]+]]
+// CHECK: define{{.*}} i32 @_Z3usei({{.*}}) #[[PLAIN]]
+// CHECK: define{{.*}} i32 @_Z11main_inlinei({{.*}}) #[[INL:[0-9]+]]
+// CHECK: define{{.*}} i32 @_Z9main_tmplIiEiT_({{.*}}) #[[INL]]
+// CHECK: define{{.*}} i32 @_Z10hdr_inlinei({{.*}}) #[[HDR:[0-9]+]]
+// CHECK: define{{.*}} i32 @_ZZ9main_tmplIiEiT_ENKUlvE_clEv({{.*}}) #[[LAMBDA:[0-9]+]]
+
+// CHECK: attributes #[[PLAIN]] = { {{.*}}"clang-main-file" {{.*}} }
+// CHECK: attributes #[[INL]] = { {{.*}}"clang-main-file"="inline-or-template"{{.*}} }
+// CHECK: attributes #[[HDR]] = {
+// CHECK-NOT: clang-
+// CHECK: attributes #[[LAMBDA]] = { {{.*}}"clang-lambda" "clang-main-file"="inline-or-template"{{.*}} }
diff --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp
index 0a540c1b8fb67..53bcde650c65c 100644
--- a/llvm/lib/Analysis/InlineCost.cpp
+++ b/llvm/lib/Analysis/InlineCost.cpp
@@ -183,6 +183,27 @@ static cl::opt<bool> InlineAllViableCalls(
     "inline-all-viable-calls", cl::Hidden, cl::init(false),
     cl::desc("Inline all viable calls, even if they exceed the inlining "
              "threshold"));
+
+static cl::opt<bool> UseClangHints(
+    "inline-use-clang-hints", cl::Hidden, cl::init(false),
+    cl::desc("Use clang's lambda/main-file hints to raise thresholds"));
+
+static cl::opt<int> ClangHintsLambdaBonus(
+    "clang-hints-lambda-bonus", cl::Hidden, cl::init(500),
+    cl::desc("Threshold bonus for lambdas"));
+
+static cl::opt<int> ClangHintsMainFileTemplateBonus(
+    "clang-hints-main-file-template-bonus", cl::Hidden, cl::init(150),
+    cl::desc("Threshold bonus for main-file inline/template functions"));
+
+static cl::opt<int> ClangHintsLambdaMainFileBonus(
+    "clang-hints-lambda-main-file-bonus", cl::Hidden, cl::init(3000),
+    cl::desc("Threshold bonus for lambdas in the main file"));
+
+static cl::opt<bool> ClangHintsLocalLambdas(
+    "clang-hints-local-lambdas", cl::Hidden, cl::init(true),
+    cl::desc("Treat main-file linkonce_odr lambdas as local functions"));
+
 namespace llvm {
 std::optional<int> getStringFnAttrAsInt(const Attribute &Attr) {
   if (Attr.isValid()) {
@@ -1247,10 +1268,20 @@ class InlineCostCallAnalyzer final : public CallAnalyzer {
 };
 
 // Return true if CB is the sole call to local function Callee.
+//
+// With UseClangHints and ClangHintsLocalLambdas, a linkonce_odr function
+// that's (1) a lambda, and (2) defined in the main source file, we count as
+// local too. Ignoring very unusual setups (#include-ing a .cpp file), no other
+// translation unit can reuse such lambda, so we expect inlining it turns the
+// original dead.
 static bool isSoleCallToLocalFunction(const CallBase &CB,
                                       const Function &Callee) {
-  return Callee.hasLocalLinkage() && Callee.hasOneLiveUse() &&
-         &Callee == CB.getCalledFunction();
+  bool Local = Callee.hasLocalLinkage() ||
+               (UseClangHints && ClangHintsLocalLambdas &&
+                Callee.hasLinkOnceODRLinkage() &&
+                Callee.hasFnAttribute("clang-lambda") &&
+                Callee.hasFnAttribute("clang-main-file"));
+  return Local && Callee.hasOneLiveUse() && &Callee == CB.getCalledFunction();
 }
 
 class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
@@ -2104,12 +2135,14 @@ void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
   int SingleBBBonusPercent = 50;
   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
   int LastCallToStaticBonus = TTI.getInliningLastCallToStaticBonus();
+  bool ClangHintBonusAllowed = true;
 
   // Lambda to set all the above bonus and bonus percentages to 0.
   auto DisallowAllBonuses = [&]() {
     SingleBBBonusPercent = 0;
     VectorBonusPercent = 0;
     LastCallToStaticBonus = 0;
+    ClangHintBonusAllowed = false;
   };
 
   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
@@ -2122,6 +2155,7 @@ void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
     // call/return instructions.
     SingleBBBonusPercent = 0;
     VectorBonusPercent = 0;
+    ClangHintBonusAllowed = false;
   } else if (Caller->hasOptSize())
     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
 
@@ -2194,6 +2228,23 @@ void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
   VectorBonus = Threshold * VectorBonusPercent / 100;
 
+  // A lambda is usually specific to its call sites, very often there's only
+  // one call site, and inlining is especially benefitial: Captured variables
+  // turn back into the caller's locals. A function defined in the main source
+  // file (very typically) isn't used in other translation unit, inlining it
+  // cannot multiply copies across them (that's what linkonce_odr tries to
+  // prevent). Boost those situations.
+  if (UseClangHints && ClangHintBonusAllowed) {
+    bool IsLambda = Callee.hasFnAttribute("clang-lambda");
+    Attribute MainFile = Callee.getFnAttribute("clang-main-file");
+    if (IsLambda && MainFile.isValid())
+      Threshold += ClangHintsLambdaMainFileBonus;
+    else if (IsLambda)
+      Threshold += ClangHintsLambdaBonus;
+    else if (MainFile.getValueAsString() == "inline-or-template")
+      Threshold += ClangHintsMainFileTemplateBonus;
+  }
+
   // If there is only one call of the function, and it has internal linkage,
   // the cost of inlining it drops dramatically. It may seem odd to update
   // Cost in updateThreshold, but the bonus depends on the logic in this method.
diff --git a/llvm/test/Transforms/Inline/clang-hints.ll b/llvm/test/Transforms/Inline/clang-hints.ll
new file mode 100644
index 0000000000000..01b3719ce31f8
--- /dev/null
+++ b/llvm/test/Transforms/Inline/clang-hints.ll
@@ -0,0 +1,63 @@
+; RUN: opt -passes=inline -inline-threshold=0 -S < %s | FileCheck %s --check-prefix=OFF
+; RUN: opt -passes=inline -inline-threshold=0 -inline-use-clang-hints -S < %s | FileCheck %s --check-prefix=HINTS
+; RUN: opt -passes=inline -inline-threshold=0 -inline-use-clang-hints -clang-hints-lambda-main-file-bonus=0 -S < %s | FileCheck %s --check-prefix=LOCAL
+; RUN: opt -passes=inline -inline-threshold=0 -inline-use-clang-hints -clang-hints-lambda-main-file-bonus=0 -clang-hints-local-lambdas=false -S < %s | FileCheck %s --check-prefix=NOLOCAL
+
+; OFF-LABEL: define i32 @caller(
+; OFF-COUNT-2: call i32 @lambda(
+; OFF-COUNT-2: call i32 @main_template(
+; OFF-COUNT-2: call i32 @main_plain(
+; OFF: call i32 @sole_main_inline(
+
+; HINTS-LABEL: define i32 @caller(
+; HINTS-NOT: call i32 @lambda(
+; HINTS-COUNT-2: call i32 @main_template(
+; HINTS-COUNT-2: call i32 @main_plain(
+; HINTS-NOT: call i32 @sole_main_inline(
+; HINTS: ret i32
+
+; LOCAL-LABEL: define i32 @caller(
+; LOCAL-NOT: call i32 @sole_main_inline(
+; LOCAL: ret i32
+
+; NOLOCAL-LABEL: define i32 @caller(
+; NOLOCAL: call i32 @sole_main_inline(
+define i32 @caller(i32 %x) {
+  %a1 = call i32 @lambda(i32 %x)
+  %a2 = call i32 @lambda(i32 %a1)
+  %b1 = call i32 @main_template(i32 %a2)
+  %b2 = call i32 @main_template(i32 %b1)
+  %c1 = call i32 @main_plain(i32 %b2)
+  %c2 = call i32 @main_plain(i32 %c1)
+  %d = call i32 @sole_main_inline(i32 %c2)
+  ret i32 %d
+}
+
+define linkonce_odr i32 @lambda(i32 %x) "clang-lambda" "function-inline-cost"="300" {
+  %r = add i32 %x, 1
+  ret i32 %r
+}
+
+define linkonce_odr i32 @main_template(i32 %x) "clang-main-file"="inline-or-template" "function-inline-cost"="300" {
+  %r = add i32 %x, 2
+  ret i32 %r
+}
+
+define linkonce_odr i32 @main_plain(i32 %x) "clang-main-file" "function-inline-cost"="300" {
+  %r = add i32 %x, 3
+  ret i32 %r
+}
+
+define linkonce_odr i32 @sole_main_inline(i32 %x) "clang-lambda" "clang-main-file" {
+  %v1 = mul i32 %x, 3
+  %v2 = mul i32 %v1, 5
+  %v3 = mul i32 %v2, 7
+  %v4 = mul i32 %v3, 11
+  %v5 = mul i32 %v4, 13
+  %v6 = mul i32 %v5, 17
+  %v7 = mul i32 %v6, 19
+  %v8 = mul i32 %v7, 23
+  %v9 = mul i32 %v8, 29
+  %v10 = mul i32 %v9, 31
+  ret i32 %v10
+}

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

✅ With the latest revision this PR passed the C/C++ code formatter.

@cofibrant cofibrant left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very cool. I had a couple of minor things but otherwise makes sense to me. I definitely shouldn't be the last person to sign off on this, though.

Comment thread llvm/lib/Analysis/InlineCost.cpp Outdated
VectorBonus = Threshold * VectorBonusPercent / 100;

// A lambda is usually specific to its call sites, very often there's only
// one call site, and inlining is especially benefitial: Captured variables

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo beneficial

Comment thread llvm/lib/Analysis/InlineCost.cpp Outdated
int SingleBBBonusPercent = 50;
int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
int LastCallToStaticBonus = TTI.getInliningLastCallToStaticBonus();
bool ClangHintBonusAllowed = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this want to be a scalable bonus percent like the others?

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

🐧 Linux x64 Test Results

  • 190615 tests passed
  • 5856 tests skipped

✅ The build succeeded and all tests passed.

@boomanaiden154 boomanaiden154 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced this is something we want to do for "main-file" functions. What kind of inlining behavior you want for "main-file" functions is going to heavily depend upon how you write your application. For something like a server application, people generally do not care about what's in the main file.

LLVM is also supposed to be generic infrastructure for multiple frontends. This means metadata should also be general purpose and not specific to clang (or at least not named clang-* even if clang is the only emitter in practice).

I haven't given that much thought to what a proper design would be here. I think some attribute for lambdas might be helpful. I think it's also good to note that ThinLTO should already cover this case. It will mark GVs internal that are not referenced outside of the current module.

Numbers on real applications would also help for motivation.

@kubamracek

Copy link
Copy Markdown
Member Author

I'm not convinced this is something we want to do for "main-file" functions. What kind of inlining behavior you want for "main-file" functions is going to heavily depend upon how you write your application. For something like a server application, people generally do not care about what's in the main file.

I think I might have managed to introduce a confusion here (and I'll rename the PR and description to avoid that confusion) -- code being from "main-file" in this PR means it's coming from any .cpp file and it's not coming from a #include'd .h file. It's not about anything like main.cpp or "the file that contains main()".

@kubamracek kubamracek changed the title [clang][Inliner] Add opt-in inliner hints for lambdas and main-file functions [clang][Inliner] Add opt-in inliner hints for lambdas and implementation-file functions Oct 1, 2026
@kubamracek

Copy link
Copy Markdown
Member Author

LLVM is also supposed to be generic infrastructure for multiple frontends. This means metadata should also be general purpose and not specific to clang (or at least not named clang-* even if clang is the only emitter in practice).

I agree, that makes sense. The general phrasing of the same concept is "header files" vs "implementation files". This distinction exists in multiple frontends/languages (but not all), and where it exists, the same idea of boosting inlineability/optimizatibility of implementation-file content should apply the same way. Languages without header files don't suffer from this problem in the first place (no over-used linkonce_odr linkage).

@kubamracek
kubamracek requested a review from osa1 October 1, 2026 17:31
@efriedma-quic

Copy link
Copy Markdown
Contributor

I think we need to come up with names that actually describe the relevant properties, so it's clear what the contract is.

If I'm understanding correctly, the interesting property of lambdas, specifically, is that they only have one "use": the caller function. clang-main-file sounds like it's basically "make heuristics assume we don't actually have any other definitions of this function for even though it's technically required to be weak".

@kubamracek
kubamracek requested a review from rjmccall October 1, 2026 19:29
@rjmccall

rjmccall commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

I generally recommend that conceptually rich ideas be brought up as an RFC on the forums; patch review threads can be hard to find, and IME they're not great places to have extended conversations, especially when the conversation doesn't really need to refer to the actual patch.

As I understand it, what you're trying to do is to heuristically guess that certain functions are probably unique to the current translation unit so that the compiler will treat them like internal functions for the purposes of inlining/cloning. This seems reasonable enough; certainly you're right that most C++ programmers don't know to use anonymous namespaces in their .cpp files in order to force internal-ness to all of the types defined there. And if the heuristic is wrong because two translation units have redundant definitions in their .cpp files, I mean, it's just a code-size loss, and quite possibly balanced out by better optimization elsewhere.

I do think you need more of a discussion about the limits of this. Most importantly, this does not enable full IPO with the target function, because we still have the familiar problem that the ODR doesn't guarantee instruction-for-instruction equivalence. For example, a parameter that's dead in our copy of the function will not necessarily be dead in the copy of the function selected by the linker. However, the heuristic does suggest that it would be acceptable to "clone" (internalize) the function because we have a reasonable belief that there are no other uses of it. This is semantically allowed by the ODR as long as the program can't depend on the uniqueness of the function address. Once the function is internalized, of course, full IPO is allowed.

Most of your examples are cases where we have a reasonable belief that all of the uses of the function are likely to come from the current translation unit:

  • inline functions and template instantiations that are only declared in non-header files
  • templates specialized for types that are only declared in non-header files
  • lambda bodies from such contexts, whether they are called immediately or not

Immediately-called lambdas from functions defined in headers feel like a different case. I believe you are trying to make an argument about transitive references: inlining the function doesn't increase code size because the code is simply transferred to our copy of its caller; if the linker selects a different copy of the caller, our entire merged function will be eliminated. This doesn't strictly hold, however, because the caller might be inlined prior to the inlining of the lambda, creating references to the lambda from arbitrary other functions. In fact, this could easily be the desired result if the lambda is cold.

@kubamracek kubamracek changed the title [clang][Inliner] Add opt-in inliner hints for lambdas and implementation-file functions [clang][Inliner] Add opt-in inliner hints and implementation-file functions Oct 5, 2026
@kubamracek

Copy link
Copy Markdown
Member Author

I dropped the lambda part of this PR, I agree that that's unrelated. Updated the PR to use frontend-neutral naming of the attribute, and simplified it only to apply the sole-call rule change, not any threshold changes. I posted the RFC about implementation-file hints to LLVM Discourse: https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

🪟 Windows x64 Test Results

  • 148612 tests passed
  • 3711 tests skipped

✅ The build succeeded and all tests passed.

@kubamracek

Copy link
Copy Markdown
Member Author

Based on the discussion on the RFC and here, I'd like to go ahead and merge this PR. Currently, it's only doing anything new under a flag, and that's useful for further evaluations and experiments. @rjmccall @efriedma-quic WDYT?

Comment thread llvm/lib/Analysis/InlineCost.cpp Resolved
…cl::opt with -fmodule-local-hints

Turn the "likely-module-local" string attribute into the enum attribute
likely_module_local (bitcode, CodeExtractor, LangRef, editor syntax files),
and replace Clang's -mllvm -clang-emit-module-local-hints cl::opt with the
cc1 option -fmodule-local-hints backed by CodeGenOptions::ModuleLocalHints.
@kubamracek
kubamracek force-pushed the inliner-hints-for-linkonce-odr branch from df33b11 to 0392fd5 Compare November 2, 2026 20:01
@kubamracek
kubamracek merged commit 932a5ca into llvm:main Nov 3, 2026
12 checks passed
@kubamracek

Copy link
Copy Markdown
Member Author

Thanks everyone for the help and reviews!

llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Nov 3, 2026
…zer hints for linkonce_odr non-header-file definitions (#228074)

Clang can now mark function definitions with a `likely_module_local` function
attribute when the function is defined in the main source file (as opposed to
in a header-file). Currently off-by-default but intended to be enabled by
default soon, to help an optimization gap that we currently have on all
linkonce_odr code (typically C++ templates) due to inhibited IPO.

When the attribute is present, LLVM's inliner now lifts the restriction that
linkonce_odr functions never get the "sole call bonus" in the cost model.

PR: llvm/llvm-project#228074

RFC: https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

Assisted-by: Claude
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Nov 3, 2026
…zer hints for linkonce_odr non-header-file definitions (#228074)

Clang can now mark function definitions with a `likely_module_local` function
attribute when the function is defined in the main source file (as opposed to
in a header-file). Currently off-by-default but intended to be enabled by
default soon, to help an optimization gap that we currently have on all
linkonce_odr code (typically C++ templates) due to inhibited IPO.

When the attribute is present, LLVM's inliner now lifts the restriction that
linkonce_odr functions never get the "sole call bonus" in the cost model.

PR: llvm/llvm-project#228074

RFC: https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

Assisted-by: Claude
kubamracek added a commit to kubamracek/llvm-project that referenced this pull request Nov 3, 2026
For reference, see:
- llvm@932a5ca
- llvm#228074
- https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

This enables emitting the `likely-module-local` function attr in Clang, as an
LLVM optimizer hint that the linkonce_odr function, which would normally be
subject to inlining and IPO restrictions, is in fact likely to be TU-local.
Hence inlining and cloning should be considered benefitial.
kubamracek added a commit to kubamracek/llvm-project that referenced this pull request Nov 7, 2026
For reference, see:
- llvm@932a5ca
- llvm#228074
- https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

This enables emitting the `likely-module-local` function attr in Clang, as an
LLVM optimizer hint that the linkonce_odr function, which would normally be
subject to inlining and IPO restrictions, is in fact likely to be TU-local.
Hence inlining and cloning should be considered benefitial.
kubamracek added a commit to kubamracek/llvm-project that referenced this pull request Nov 19, 2026
For reference, see:
- llvm@932a5ca
- llvm#228074
- https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

This enables emitting the `likely-module-local` function attr in Clang, as an
LLVM optimizer hint that the linkonce_odr function, which would normally be
subject to inlining and IPO restrictions, is in fact likely to be TU-local.
Hence inlining and cloning should be considered benefitial.
kubamracek added a commit that referenced this pull request Nov 19, 2026
)

This enables emitting the `likely-module-local` function attr in Clang, as an
LLVM optimizer hint that the linkonce_odr function, which would normally be
subject to inlining and IPO restrictions, is in fact likely to be TU-local.
Hence inlining and cloning should be considered benefitial.

For more context, see:
- 932a5ca
- #228074
- https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

PR: #238529

Assisted-by: Claude
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Nov 19, 2026
…fault (#238529)

This enables emitting the `likely-module-local` function attr in Clang, as an
LLVM optimizer hint that the linkonce_odr function, which would normally be
subject to inlining and IPO restrictions, is in fact likely to be TU-local.
Hence inlining and cloning should be considered benefitial.

For more context, see:
- llvm/llvm-project@932a5ca
- llvm/llvm-project#228074
- https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

PR: llvm/llvm-project#238529

Assisted-by: Claude
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Nov 19, 2026
…fault (#238529)

This enables emitting the `likely-module-local` function attr in Clang, as an
LLVM optimizer hint that the linkonce_odr function, which would normally be
subject to inlining and IPO restrictions, is in fact likely to be TU-local.
Hence inlining and cloning should be considered benefitial.

For more context, see:
- llvm/llvm-project@932a5ca
- llvm/llvm-project#228074
- https://discourse.llvm.org/t/rfc-optimizing-linkonce-odr-functions-frontend-hints-inlining-and-internal-cloning/92423

PR: llvm/llvm-project#238529

Assisted-by: Claude
nikic added a commit that referenced this pull request Nov 25, 2026
Inlining was dropping functions that become unused as a result of
inlining eagerly, as this impacts the single-call bonus. However, this
is not done for functions in comdats, as this requires all functions in
the comdat to be dead.

This adds a special case for trivial comdats, where the function is the
only member. This has become more relevant after the introduction of
module-local hints in #228074,
as linkonce_odr functions (which will typically have a comdat) can now
be subject to the single-call bonus.

This gives a 1.2% compile-time improvement on tramp3d-v4. This is
because we end up inlining a call earlier and do less redundant
simplification. In other cases, it could probably also regress
compile-time by enabling more inlining overall.
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Nov 25, 2026
…rly (#245935)

Inlining was dropping functions that become unused as a result of
inlining eagerly, as this impacts the single-call bonus. However, this
is not done for functions in comdats, as this requires all functions in
the comdat to be dead.

This adds a special case for trivial comdats, where the function is the
only member. This has become more relevant after the introduction of
module-local hints in llvm/llvm-project#228074,
as linkonce_odr functions (which will typically have a comdat) can now
be subject to the single-call bonus.

This gives a 1.2% compile-time improvement on tramp3d-v4. This is
because we end up inlining a call earlier and do less redundant
simplification. In other cases, it could probably also regress
compile-time by enabling more inlining overall.
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Nov 25, 2026
…rly (#245935)

Inlining was dropping functions that become unused as a result of
inlining eagerly, as this impacts the single-call bonus. However, this
is not done for functions in comdats, as this requires all functions in
the comdat to be dead.

This adds a special case for trivial comdats, where the function is the
only member. This has become more relevant after the introduction of
module-local hints in llvm/llvm-project#228074,
as linkonce_odr functions (which will typically have a comdat) can now
be subject to the single-call bonus.

This gives a 1.2% compile-time improvement on tramp3d-v4. This is
because we end up inlining a call earlier and do less redundant
simplification. In other cases, it could probably also regress
compile-time by enabling more inlining overall.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:codegen IR generation bugs: mangling, exceptions, etc. clang:driver 'clang' and 'clang++' user-facing binaries. Not 'clang-cl' clang:frontend Language frontend issues, e.g. anything involving "Sema" llvm:analysis Includes value tracking, cost tables and constant folding llvm:ir llvm:transforms

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants