diff --git a/clang-tools-extra/clangd/FindTarget.cpp b/clang-tools-extra/clangd/FindTarget.cpp --- a/clang-tools-extra/clangd/FindTarget.cpp +++ b/clang-tools-extra/clangd/FindTarget.cpp @@ -31,6 +31,7 @@ #include "clang/Basic/LangOptions.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/SourceLocation.h" +#include "clang/Basic/Specifiers.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" @@ -139,7 +140,14 @@ const NamedDecl *getTemplatePattern(const NamedDecl *D) { if (const CXXRecordDecl *CRD = dyn_cast(D)) { - return CRD->getTemplateInstantiationPattern(); + if (const auto *Result = CRD->getTemplateInstantiationPattern()) + return Result; + // getTemplateInstantiationPattern returns null if the Specialization is + // incomplete (e.g. the type didn't need to be complete), fall back to the + // primary template. + if (CRD->getTemplateSpecializationKind() == TSK_Undeclared) + if (const auto *Spec = dyn_cast(CRD)) + return Spec->getSpecializedTemplate()->getTemplatedDecl(); } else if (const FunctionDecl *FD = dyn_cast(D)) { return FD->getTemplateInstantiationPattern(); } else if (auto *VD = dyn_cast(D)) { diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp --- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp +++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp @@ -310,6 +310,16 @@ {"class Foo", Rel::TemplatePattern}); Code = R"cpp( + template class Foo {}; + // The "Foo" SpecializationDecl is incomplete, there is no + // instantiation happening. + void func([[Foo]] *); + )cpp"; + EXPECT_DECLS("TemplateSpecializationTypeLoc", + {"class Foo", Rel::TemplatePattern}, + {"template<> class Foo", Rel::TemplateInstantiation}); + + Code = R"cpp( // Explicit specialization. template class Foo{}; template<> class Foo<42>{}; diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp --- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp +++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp @@ -954,6 +954,12 @@ class [[Fo^o]] {}; void func([[Foo]]); )cpp", + + R"cpp( + template + class [[Foo]] {}; + void func([[Fo^o]]); + )cpp", }; for (const char *Test : Tests) { Annotations T(Test);