[clang] Fix ICE on invalid when defining a friend function in a template (PR #181890)

via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 17 11:58:34 PST 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: None (Iasonaskrpr)

<details>
<summary>Changes</summary>

This PR fixes #<!-- -->181603 

The logic added in #<!-- -->125266 failed to account for cases where a function template is instantiated from a friend definition that is not a TSK_ExplicitSpecialization. In these scenarios the find_if search on the primary template redeclaration chain would fail because the definition is hidden within the lexical context of the class.

Updated the assertion logic to check if the function is a friend object and isThisDeclarationADefinition() returns true before asserting.

ICE is fixed and all clang tests pass

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+12-8) 


``````````diff
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index e74c41517ecbf..b7d6e786f4616 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -5894,14 +5894,18 @@ void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
                                 return cast<FunctionTemplateDecl>(RTD)
                                     ->isCompatibleWithDefinition();
                               });
-      assert(It != Primary->redecls().end() &&
-             "Should't get here without a definition");
-      if (FunctionDecl *Def = cast<FunctionTemplateDecl>(*It)
-                                  ->getTemplatedDecl()
-                                  ->getDefinition())
-        DC = Def->getLexicalDeclContext();
-      else
-        DC = (*It)->getLexicalDeclContext();
+      if (It != Primary->redecls().end()) {
+        if (FunctionDecl *Def = cast<FunctionTemplateDecl>(*It)
+                                    ->getTemplatedDecl()
+                                    ->getDefinition())
+          DC = Def->getLexicalDeclContext();
+        else
+          DC = (*It)->getLexicalDeclContext();
+      } else {
+        assert((Function->getFriendObjectKind() != Decl::FOK_None &&
+                Function->isThisDeclarationADefinition()) &&
+               "Should't get here without a definition");
+      }
       Innermost.emplace(Function->getTemplateSpecializationArgs()->asArray());
     }
     MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(

``````````

</details>


https://github.com/llvm/llvm-project/pull/181890


More information about the cfe-commits mailing list