[clang] [Clang] Mark template instantiations with main-file template arguments as likely_module_local (PR #240113)

Kuba Mracek via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 8 01:49:21 PST 2026


https://github.com/kubamracek created https://github.com/llvm/llvm-project/pull/240113

None

>From 443ac3f381ed8b6cd48bae1cc8a58d5e0499230f Mon Sep 17 00:00:00 2001
From: Kuba Mracek <mracek at apple.com>
Date: Sun, 8 Nov 2026 09:20:08 +0000
Subject: [PATCH] [Clang] Mark template instantiations with main-file template
 arguments as likely_module_local

With -fmodule-local-hints, Clang marks inline functions and template
instantiations defined in the main source file as likely_module_local. A
template defined in a header but instantiated with an entity declared in the
main file (e.g. std::sort with a main-file comparator or lambda) isn't marked,
even though such an instantiation can't be referenced or emitted by any other
translation unit either.

Also mark a function template instantiation if its template arguments, or
those of the enclosing class and function template specializations, name a
class, enum, lambda closure type, function or template declared in the main
file. Pointer, reference, array, member pointer and function types are looked
through, as are the template arguments of class template specializations used
as arguments. The walk is bounded to avoid blowup on deeply nested arguments.
---
 clang/include/clang/Basic/CodeGenOptions.def  |  3 +-
 clang/include/clang/Options/Options.td        |  3 +-
 clang/lib/CodeGen/CodeGenModule.cpp           | 91 ++++++++++++++++++-
 .../likely-module-local-template-args.cpp     | 63 +++++++++++++
 clang/test/CodeGenCXX/likely-module-local.cpp |  6 +-
 5 files changed, 158 insertions(+), 8 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/likely-module-local-template-args.cpp

diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def
index ff33f5be424ecd..03f154447cc066 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -545,7 +545,8 @@ ENUM_CODEGENOPT(WinControlFlowGuardMechanism, ControlFlowGuardMechanism,
 CODEGENOPT(DisableOutlining, 1, 0, Benign)
 
 /// Marks inline functions and template instantiations defined in the main
-/// source file as likely_module_local (`-fmodule-local-hints`)
+/// source file, or instantiated with a template argument declared in it, as
+/// likely_module_local (`-fmodule-local-hints`)
 CODEGENOPT(ModuleLocalHints, 1, 0, Benign)
 
 /// Controlls the emission of function name in PPA1 on z/OS.
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index 9c266b1bdaf7be..6a280416d2af3f 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -3791,7 +3791,8 @@ defm module_local_hints : BoolFOption<"module-local-hints",
   CodeGenOpts<"ModuleLocalHints">, DefaultFalse,
   PosFlag<SetTrue, [], [ClangOption, CC1Option],
           "Mark inline functions and template instantiations defined in the "
-          "main source file as likely_module_local">,
+          "main source file, or instantiated with a template argument "
+          "declared in it, as likely_module_local">,
   NegFlag<SetFalse>>;
 
 def fmodules_embed_all_files : Joined<["-"], "fmodules-embed-all-files">,
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp
index ab13a6ab9446fb..f266c738c19557 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3199,6 +3199,91 @@ CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
   return MostBases.takeVector();
 }
 
+namespace {
+/// Finds whether the template arguments of a function template instantiation,
+/// or of the class and function templates it is nested in, name an entity
+/// (class, enum, lambda closure type, function or template) declared in the
+/// main source file. Such an instantiation (ignoring unusual setups, and ODR
+/// equivalent definitions in multiple main files) can't be referenced or
+/// emitted by any other translation unit.
+class MainFileTemplateArgFinder {
+  const SourceManager &SM;
+  // Bound the walk over deeply nested template arguments.
+  unsigned Budget = 128;
+
+  bool inMainFile(const Decl *D) {
+    return D && SM.isInMainFile(D->getLocation());
+  }
+
+  bool visitType(QualType T) {
+    if (T.isNull() || Budget == 0)
+      return false;
+    --Budget;
+    const Type *Ty = T.getCanonicalType().getTypePtr();
+    if (const auto *PT = dyn_cast<PointerType>(Ty))
+      return visitType(PT->getPointeeType());
+    if (const auto *RT = dyn_cast<ReferenceType>(Ty))
+      return visitType(RT->getPointeeType());
+    if (const auto *AT = dyn_cast<ArrayType>(Ty))
+      return visitType(AT->getElementType());
+    if (const auto *MPT = dyn_cast<MemberPointerType>(Ty))
+      return inMainFile(MPT->getMostRecentCXXRecordDecl()) ||
+             visitType(MPT->getPointeeType());
+    if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty))
+      return visitType(FPT->getReturnType()) ||
+             llvm::any_of(FPT->param_types(),
+                          [&](QualType P) { return visitType(P); });
+    if (const TagDecl *TD = Ty->getAsTagDecl())
+      return inMainFile(TD) || visitContext(TD);
+    return false;
+  }
+
+  bool visitArg(const TemplateArgument &A) {
+    switch (A.getKind()) {
+    case TemplateArgument::Type:
+      return visitType(A.getAsType());
+    case TemplateArgument::Declaration:
+      return inMainFile(A.getAsDecl());
+    case TemplateArgument::Template:
+    case TemplateArgument::TemplateExpansion:
+      return inMainFile(A.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
+    case TemplateArgument::Pack:
+      return visitArgs(A.pack_elements());
+    default:
+      return false;
+    }
+  }
+
+  bool visitArgs(ArrayRef<TemplateArgument> Args) {
+    return llvm::any_of(Args,
+                        [&](const TemplateArgument &A) { return visitArg(A); });
+  }
+
+  // Template arguments of D itself (if a specialization) and of the class and
+  // function template specializations enclosing it, e.g. a member function of
+  // std::vector<T>, or a lambda inside std::sort<It, Cmp>.
+  bool visitContext(const Decl *D) {
+    for (const DeclContext *DC = dyn_cast<DeclContext>(D); DC;
+         DC = DC->getParent()) {
+      if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
+        if (visitArgs(CTSD->getTemplateArgs().asArray()))
+          return true;
+      } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
+        if (const TemplateArgumentList *Args =
+                FD->getTemplateSpecializationArgs())
+          if (visitArgs(Args->asArray()))
+            return true;
+      }
+    }
+    return false;
+  }
+
+public:
+  MainFileTemplateArgFinder(const SourceManager &SM) : SM(SM) {}
+  bool find(const FunctionDecl *FD) { return visitContext(FD); }
+};
+} // namespace
+
 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
                                                            llvm::Function *F) {
   llvm::AttrBuilder B(F->getContext());
@@ -3349,9 +3434,11 @@ void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
     const SourceManager &SM = getContext().getSourceManager();
     // D->getLocation(), for a template instantiation, is the location of the
     // template's definition, not instantiation.
-    // TODO: Also consider template instantiations where a template argument is
-    // a class declared in the main file.
     bool InMainFile = SM.isInMainFile(D->getLocation());
+    // A template defined in a header but instantiated with a main-file class,
+    // e.g. std::sort with a main-file comparator or lambda.
+    if (FD && !InMainFile && FD->isTemplateInstantiation())
+      InMainFile = MainFileTemplateArgFinder(SM).find(FD);
     if (FD && (FD->isInlined() || FD->isTemplateInstantiation()) && InMainFile)
       B.addAttribute(llvm::Attribute::LikelyModuleLocal);
   }
diff --git a/clang/test/CodeGenCXX/likely-module-local-template-args.cpp b/clang/test/CodeGenCXX/likely-module-local-template-args.cpp
new file mode 100644
index 00000000000000..bbcd1f380faba0
--- /dev/null
+++ b/clang/test/CodeGenCXX/likely-module-local-template-args.cpp
@@ -0,0 +1,63 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: %clang_cc1 -triple arm64-apple-macosx14.0.0 -std=c++20 -emit-llvm -fmodule-local-hints -o - %t/main.cpp | FileCheck %s
+// RUN: %clang_cc1 -triple arm64-apple-macosx14.0.0 -std=c++20 -emit-llvm -o - %t/main.cpp | FileCheck %s --check-prefix=NOHINTS
+
+//--- hdr.h
+struct HdrStruct {};
+template <class T> int hdr_size(T) { return sizeof(T); }
+template <class F> int hdr_call(F f) { return f(); }
+template <int (*F)()> int hdr_callp() { return F(); }
+template <template <class> class C> int hdr_tt() { return sizeof(C<int>); }
+template <class... Ts> int hdr_pack(Ts...) { return sizeof...(Ts); }
+template <class T> struct HdrBox {
+  T t;
+  int get() { return sizeof(t); }
+};
+
+//--- main.cpp
+#include "hdr.h"
+
+struct Local {};
+int local_fn() { return 1; }
+template <class T> struct LocalBox { T t; };
+inline int main_inline() { return hdr_call([] { return 2; }); }
+
+int use() {
+  return hdr_size(Local()) + hdr_size((Local *)nullptr) +
+         hdr_size(HdrBox<Local>()) + main_inline() + hdr_callp<local_fn>() +
+         hdr_tt<LocalBox>() + hdr_pack(1, Local()) + HdrBox<Local>().get() +
+         hdr_size(HdrStruct()) + HdrBox<int>().get();
+}
+
+// A plain function, never marked.
+// CHECK: define {{.*}} @_Z8local_fnv() #[[OFF:[0-9]+]]
+
+// The inline function defined in main.cpp is marked either way.
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z11main_inlinev() #[[ON:[0-9]+]]
+
+// Templates defined in hdr.h, instantiated with an entity from main.cpp: a
+// class type, a pointer to one, a header class template specialized with one,
+// a lambda closure type, a function, a class template, and a pack element.
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_sizeI5LocalEiT_({{.*}}) #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_sizeIP5LocalEiT_({{.*}}) #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_sizeI6HdrBoxI5LocalEEiT_({{.*}}) #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_callIZ11main_inlinevEUlvE_EiT_({{.*}}) #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z9hdr_callpIXadL_Z8local_fnvEEEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_ttI8LocalBoxEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_packIJi5LocalEEiDpT_({{.*}}) #[[ON]]
+
+// A member function of a header class template specialized with a main.cpp
+// class.
+// CHECK-DAG: define linkonce_odr {{.*}} @_ZN6HdrBoxI5LocalE3getEv({{.*}}) #[[ON]]
+
+// Instantiations with only header and builtin types are never marked.
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_sizeI9HdrStructEiT_({{.*}}) #[[OFF]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_ZN6HdrBoxIiE3getEv({{.*}}) #[[OFF]]
+
+// CHECK: attributes #[[OFF]] = {
+// CHECK-NOT: likely_module_local
+// CHECK-SAME: }
+// CHECK: attributes #[[ON]] = { {{.*}}likely_module_local{{.*}} }
+
+// NOHINTS-NOT: likely_module_local
diff --git a/clang/test/CodeGenCXX/likely-module-local.cpp b/clang/test/CodeGenCXX/likely-module-local.cpp
index 3cdace5a83ac41..6b15fd30e0bf70 100644
--- a/clang/test/CodeGenCXX/likely-module-local.cpp
+++ b/clang/test/CodeGenCXX/likely-module-local.cpp
@@ -66,10 +66,8 @@ int use(int x) {
 // HDR-NOT: likely_module_local
 // HDR-SAME: }
 
-// Template defined in hdr.h, instantiated (with a main.cpp lambda) in main.cpp.
+// Template defined in hdr.h, instantiated with a main.cpp lambda in main.cpp.
 // HDRTMPL: define{{.*}} i32 @_Z8hdr_call{{.*}}) #[[HDRTMPL:[0-9]+]]
-// HDRTMPL: attributes #[[HDRTMPL]] = {
-// HDRTMPL-NOT: likely_module_local
-// HDRTMPL-SAME: }
+// HDRTMPL: attributes #[[HDRTMPL]] = { {{.*}}likely_module_local{{.*}} }
 
 // OFF-NOT: likely_module_local



More information about the cfe-commits mailing list