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

>From eda7a8377c8cb1cdb90e3ee901ca793dfd9cc45f Mon Sep 17 00:00:00 2001
From: Kuba Mracek <[email protected]>
Date: Sun, 8 Nov 2026 09:20:08 +0000
Subject: [PATCH 1/2] [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 d825aa1e7bb193..b2b6eee0a5c403 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -547,7 +547,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, 1, 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 304a0f1bcb44ab..53c2fcbe3bf453 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -3801,7 +3801,8 @@ defm module_local_hints : 
BoolFOption<"module-local-hints",
   PosFlag<SetTrue, [], [ClangOption], "Mark">,
   NegFlag<SetFalse, [], [ClangOption, CC1Option], "Don't mark">,
   BothFlags<[], [ClangOption], " inline functions and template instantiations "
-            "defined in the main source file as likely_module_local">>;
+            "defined in the main source file, or instantiated with a template "
+            "argument declared in it, as likely_module_local">>;
 
 def fmodules_embed_all_files : Joined<["-"], "fmodules-embed-all-files">,
   Visibility<[ClangOption, CC1Option, CLOption]>,
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index f0ea493e172229..a279faa5fbaf52 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -3217,6 +3217,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());
@@ -3367,9 +3452,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 89234fa483497e..4088dbc7af6aa3 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

>From b8035d8376fc9ecbf6f14397577083fec89894b2 Mon Sep 17 00:00:00 2001
From: Kuba Mracek <[email protected]>
Date: Thu, 19 Nov 2026 14:26:11 +0000
Subject: [PATCH 2/2] Add tests for likely_module_local with compound types and
 nested template specializations

---
 .../likely-module-local-template-args.cpp     | 51 ++++++++++++++++++-
 1 file changed, 49 insertions(+), 2 deletions(-)

diff --git a/clang/test/CodeGenCXX/likely-module-local-template-args.cpp 
b/clang/test/CodeGenCXX/likely-module-local-template-args.cpp
index bbcd1f380faba0..6b25de2852d319 100644
--- a/clang/test/CodeGenCXX/likely-module-local-template-args.cpp
+++ b/clang/test/CodeGenCXX/likely-module-local-template-args.cpp
@@ -1,24 +1,34 @@
 // 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
+// RUN: %clang_cc1 -triple arm64-apple-macosx14.0.0 -std=c++20 -emit-llvm -o - 
%t/main.cpp | FileCheck %s
+// RUN: %clang_cc1 -triple arm64-apple-macosx14.0.0 -std=c++20 -emit-llvm 
-fno-module-local-hints -o - %t/main.cpp | FileCheck %s --check-prefix=NOHINTS
 
 //--- hdr.h
 struct HdrStruct {};
+enum class HdrEnum { X };
 template <class T> int hdr_size(T) { return sizeof(T); }
+template <class T> int hdr_ty() { return 1; }
 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> int hdr_inner(T) {
+  return [] { return (int)sizeof(T); }();
+}
 template <class T> struct HdrBox {
   T t;
   int get() { return sizeof(t); }
+  struct Inner {
+    int f() { return sizeof(T); }
+  };
 };
+template <class T> struct HdrWrap {};
 
 //--- main.cpp
 #include "hdr.h"
 
 struct Local {};
+enum class LocalEnum { A };
 int local_fn() { return 1; }
 template <class T> struct LocalBox { T t; };
 inline int main_inline() { return hdr_call([] { return 2; }); }
@@ -30,6 +40,22 @@ int use() {
          hdr_size(HdrStruct()) + HdrBox<int>().get();
 }
 
+int use_more() {
+  return
+      // Types looked through: enum, array, reference, function, member
+      // pointer, and nested class template specializations.
+      hdr_ty<LocalEnum>() + hdr_ty<Local[2]>() + hdr_ty<Local &>() +
+      hdr_ty<int(Local)>() + hdr_ty<int Local::*>() +
+      hdr_ty<Local HdrStruct::*>() + hdr_ty<HdrWrap<HdrBox<Local>>>() +
+      // A lambda and a nested class's member in a header template instantiated
+      // with a main-file class.
+      hdr_inner(Local()) + HdrBox<Local>::Inner().f() +
+      // Header-only arguments, never marked.
+      hdr_ty<HdrEnum>() + hdr_ty<int HdrStruct::*>() +
+      hdr_ty<HdrWrap<HdrBox<int>>>() +
+      hdr_inner(HdrStruct()) + HdrBox<int>::Inner().f();
+}
+
 // A plain function, never marked.
 // CHECK: define {{.*}} @_Z8local_fnv() #[[OFF:[0-9]+]]
 
@@ -55,6 +81,27 @@ int use() {
 // CHECK-DAG: define linkonce_odr {{.*}} @_Z8hdr_sizeI9HdrStructEiT_({{.*}}) 
#[[OFF]]
 // CHECK-DAG: define linkonce_odr {{.*}} @_ZN6HdrBoxIiE3getEv({{.*}}) #[[OFF]]
 
+// Explicit type arguments from main.cpp, looked through compound types.
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyI9LocalEnumEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyIA2_5LocalEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyIR5LocalEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyIFi5LocalEEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyIM5LocaliEiv() #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyIM9HdrStruct5LocalEiv() 
#[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} 
@_Z6hdr_tyI7HdrWrapI6HdrBoxI5LocalEEEiv() #[[ON]]
+
+// A lambda inside, and a nested class's member of, a header template
+// instantiated with a main.cpp class.
+// CHECK-DAG: define linkonce_odr {{.*}} 
@_ZZ9hdr_innerI5LocalEiT_ENKUlvE_clEv({{.*}}) #[[ON]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_ZN6HdrBoxI5LocalE5Inner1fEv({{.*}}) 
#[[ON]]
+
+// The same shapes with only header and builtin arguments.
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyI7HdrEnumEiv() #[[OFF]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyIM9HdrStructiEiv() #[[OFF]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_Z6hdr_tyI7HdrWrapI6HdrBoxIiEEEiv() 
#[[OFF]]
+// CHECK-DAG: define linkonce_odr {{.*}} 
@_ZZ9hdr_innerI9HdrStructEiT_ENKUlvE_clEv({{.*}}) #[[OFF]]
+// CHECK-DAG: define linkonce_odr {{.*}} @_ZN6HdrBoxIiE5Inner1fEv({{.*}}) 
#[[OFF]]
+
 // CHECK: attributes #[[OFF]] = {
 // CHECK-NOT: likely_module_local
 // CHECK-SAME: }

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to