Skip to content

[Sema] Diagnose by-value copy constructors in template instantiations #130866

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 13, 2025

Conversation

Megan0704-1
Copy link
Contributor

Fixes #80963

This PR ensures Clang diagnoses by-value copy constructors in implicitly instantiated class templates (e.g., A<int, int>(A<int, int>)), per [class.copy.ctor].

Changes:

  • Remove TSK_ImplicitInstantiation check in SemaDeclCXX.cpp.
  • Add !isFunctionTemplateSpecialization() to skip templated constructors.
  • Add regression tests.

Fixes llvm#80963

Previously, Clang skipped diagnosing a constructor if it was implicitly
instantiated from a template class (TSK_ImplicitInstantiation). This allowed
ill-formed “copy” constructors taking the class by value (e.g. A(A)) to slip
through without a diagnostic.

However, the C++ standard mandates that copy constructors must take their
class type parameter by reference (e.g., A(const A&)). Furthermore, a
constructor template that *would* form a copy-by-value signature is not
treated as a copy constructor and should never be chosen for copying.

This patch replaces the check on TSK_ImplicitInstantiation with a check
to see if the constructor is a function template specialization (i.e.,
isFunctionTemplateSpecialization()). That ensures proper diagnosis of
non-template copy-by-value constructors, while still allowing valid
template constructors that might appear to have a copy-like signature
but should be SFINAEd out or simply not selected as a copy constructor.
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels Mar 12, 2025
@llvmbot
Copy link
Member

llvmbot commented Mar 12, 2025

@llvm/pr-subscribers-clang

Author: Kuo, Mei-Chun (Megan0704-1)

Changes

Fixes #80963

This PR ensures Clang diagnoses by-value copy constructors in implicitly instantiated class templates (e.g., A&lt;int, int&gt;(A&lt;int, int&gt;)), per [class.copy.ctor].

Changes:

  • Remove TSK_ImplicitInstantiation check in SemaDeclCXX.cpp.
  • Add !isFunctionTemplateSpecialization() to skip templated constructors.
  • Add regression tests.

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

2 Files Affected:

  • (modified) clang/lib/Sema/SemaDeclCXX.cpp (+2-2)
  • (added) clang/test/SemaCXX/copy-ctor-template.cpp (+22)
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 96aac7871db1e..1c62a551ee732 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -10921,8 +10921,8 @@ void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
   //   parameters have default arguments.
   if (!Constructor->isInvalidDecl() &&
       Constructor->hasOneParamOrDefaultArgs() &&
-      Constructor->getTemplateSpecializationKind() !=
-          TSK_ImplicitInstantiation) {
+      !Constructor->isFunctionTemplateSpecialization()
+          ) {
     QualType ParamType = Constructor->getParamDecl(0)->getType();
     QualType ClassTy = Context.getTagDeclType(ClassDecl);
     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
diff --git a/clang/test/SemaCXX/copy-ctor-template.cpp b/clang/test/SemaCXX/copy-ctor-template.cpp
new file mode 100644
index 0000000000000..a46a167038cf7
--- /dev/null
+++ b/clang/test/SemaCXX/copy-ctor-template.cpp
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+template<class T, class V>
+struct A{
+    A();
+    A(A&);
+    A(A<V, T>); // expected-error{{copy constructor must pass its first argument by reference}}
+};
+
+void f() {
+    A<int, int> a = A<int, int>(); // expected-note{{in instantiation of template class 'A<int, int>'}}
+}
+
+template<class T, class V>
+struct B{
+    B();
+    template<class U> B(U); // No error (templated constructor)
+};
+
+void g() {
+    B<int, int> b = B<int, int>(); // should use implicit copy constructor
+}

@Megan0704-1
Copy link
Contributor Author

@erichkeane, @shafik
Could you please take a look and let me know if it looks good to you? Thank you very much!

Copy link
Contributor

@cor3ntin cor3ntin left a comment

Choose a reason for hiding this comment

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

Thanks for working on this

Can you add a changelog entry in clang/docs/ReleaseNotes.rst (in the bug fixes to c++ section)?

Thanks


void g() {
B<int, int> b = B<int, int>(); // should use implicit copy constructor
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you add a test for @hubert-reinterpretcast comment here
#80963 (comment)

Can you add tests for something like
A<int, double> a = A<double, int>(); // not a copy constructor

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the review! I’ll add tests for the A<int, double> case and update the PR shortly.

@Megan0704-1
Copy link
Contributor Author

Megan0704-1 commented Mar 12, 2025

Thanks for your feedback and review!! I’ve updated the changelog and the test file to include the rvalue-to-lvalue case and converting constructor scenario. Please let me know if there’s anything else!

Copy link
Contributor

@cor3ntin cor3ntin left a comment

Choose a reason for hiding this comment

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

LGTM. Thanks for fixing this issue!

Will you need me to merge this for you?

@Megan0704-1
Copy link
Contributor Author

Thank you for reviewing and approving the PR!
Yes, please merge it for me. Thanks again for all your help!

@cor3ntin
Copy link
Contributor

@Megan0704-1 Can you look into the test failures? thanks

Adjust the test to account for new diagnostics emitted when a class template constructor takes the class by value after instantiation.
- Add expected-error annotations to lines 142, 159, 172 (invalid by-value constructors when T = U).
- Add expected-note annotations to lines 147, 164, 176 (template instantiation points).
- Remove expected-error from line 76 (valid template specialization).
@Megan0704-1
Copy link
Contributor Author

@cor3ntin
Thank you for flagging the test failures!

I’ve investigated them, and here’s what I found:
Failed Tests in constructor-template.cpp:

  • The failures occurred because the test wasn’t annotated to expect the new diagnostics introduced by the fix (e.g., A<int, int> instantiations now emit errors for invalid by-value copy constructors).

Fix it by updating the test to:

  • Add expected-error to lines 142, 159, 172 (invalid by-value constructors when T = U).
  • Add expected-note to lines 147, 164, 176 (template instantiation points).
  • Remove an incorrect expected-error from line 76 (valid template specialization).

Please Let me know if further adjustments are needed~

@cor3ntin cor3ntin merged commit fe0d3e3 into llvm:main Mar 13, 2025
7 of 11 checks passed
Copy link

@Megan0704-1 Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

Copy link

⚠️ C/C++ code formatter, clang-format found issues in your code. ⚠️

You can test this locally with the following command:
git-clang-format --diff c2ed840ed94d3412c7c0bdd9ed84cac6fe0afb57 790d151975c9ce4f5f823484d100d9460077b971 --extensions cpp -- clang/test/SemaCXX/copy-ctor-template.cpp clang/lib/Sema/SemaDeclCXX.cpp clang/test/SemaTemplate/constructor-template.cpp
View the diff from clang-format here.
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 1c62a551ee..00b4006b5e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -10921,8 +10921,7 @@ void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
   //   parameters have default arguments.
   if (!Constructor->isInvalidDecl() &&
       Constructor->hasOneParamOrDefaultArgs() &&
-      !Constructor->isFunctionTemplateSpecialization()
-          ) {
+      !Constructor->isFunctionTemplateSpecialization()) {
     QualType ParamType = Constructor->getParamDecl(0)->getType();
     QualType ClassTy = Context.getTagDeclType(ClassDecl);
     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {

@Megan0704-1 Megan0704-1 deleted the fix-80963 branch March 13, 2025 05:11
Constructor->getTemplateSpecializationKind() !=
TSK_ImplicitInstantiation) {
!Constructor->isFunctionTemplateSpecialization()
) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Did you run clang-format on this? I am surprised it would leave the ) on the line like that but maybe I am off.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thank you for catching this, and I am so sorry for the oversight.
I forgot to run clang-format before merging.
Should I submitt a follow-up PR to fix the formatting issues?

Copy link
Contributor

Choose a reason for hiding this comment

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

I missed it too, sorry.

yes, feel free to submit a new pr. thanks

@Megan0704-1 Megan0704-1 restored the fix-80963 branch March 13, 2025 05:27
cor3ntin pushed a commit that referenced this pull request Mar 13, 2025
This PR fixes formatting issues in `constructor-template.cpp` introduced
in #130866.

Changes:  
- Ran `clang-format` to adhere to LLVM style guidelines.  
- No functional changes.  

CC: @cor3ntin @shafik 
Thanks
frederik-h pushed a commit to frederik-h/llvm-project that referenced this pull request Mar 18, 2025
…llvm#130866)

Fixes llvm#80963 

This PR ensures Clang diagnoses by-value copy constructors in implicitly
instantiated class templates (e.g., `A<int, int>(A<int, int>)`), per
[class.copy.ctor].

Changes: 
- Remove `TSK_ImplicitInstantiation` check in `SemaDeclCXX.cpp`.
- Add `!isFunctionTemplateSpecialization()` to skip templated
constructors.
- Add regression tests.
frederik-h pushed a commit to frederik-h/llvm-project that referenced this pull request Mar 18, 2025
This PR fixes formatting issues in `constructor-template.cpp` introduced
in llvm#130866.

Changes:  
- Ran `clang-format` to adhere to LLVM style guidelines.  
- No functional changes.  

CC: @cor3ntin @shafik 
Thanks
@zygoloid
Copy link
Collaborator

zygoloid commented Mar 24, 2025

This error is produced for the following code:

template <typename KeyT>
class SetView {
  SetView(SetView<std::remove_const_t<KeyT>> other_view)
    requires(!std::same_as<KeyT, std::remove_const_t<KeyT>>);
};

... which is never an eligible copy constructor. Is that intended? If this is in line with the language rules, perhaps we should file a core issue.

[Edit: I've mailed the core reflector.]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Clang fails to detect illegal copy constructor with template class as its parameter
5 participants