Fix crash in BuildCXXDefaultInitExpr.
authorReid Kleckner <rnk@google.com>
Fri, 29 Apr 2016 18:06:53 +0000 (18:06 +0000)
committerReid Kleckner <rnk@google.com>
Fri, 29 Apr 2016 18:06:53 +0000 (18:06 +0000)
Fix crash in BuildCXXDefaultInitExpr when member of template class has
same name as the class itself.

Based on patch by Raphael "Teemperor" Isemann!

Differential Revision: http://reviews.llvm.org/D19721

llvm-svn: 268082

clang/lib/Sema/SemaDeclCXX.cpp
clang/test/SemaCXX/pr27047-default-init-expr-name-conflict.cpp [new file with mode: 0644]

index 40be8d6..21db3be 100644 (file)
@@ -11412,8 +11412,19 @@ ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
     DeclContext::lookup_result Lookup =
         ClassPattern->lookup(Field->getDeclName());
-    assert(Lookup.size() == 1);
-    FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
+
+    // Lookup can return at most two results: the pattern for the field, or the
+    // injected class name of the parent record. No other member can have the
+    // same name as the field.
+    assert(!Lookup.empty() && Lookup.size() <= 2 &&
+           "more than two lookup results for field name");
+    FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
+    if (!Pattern) {
+      assert(isa<CXXRecordDecl>(Lookup[0]) &&
+             "cannot have other non-field member with same name");
+      Pattern = cast<FieldDecl>(Lookup[1]);
+    }
+
     if (InstantiateInClassInitializer(Loc, Field, Pattern,
                                       getTemplateInstantiationArgs(Field)))
       return ExprError();
diff --git a/clang/test/SemaCXX/pr27047-default-init-expr-name-conflict.cpp b/clang/test/SemaCXX/pr27047-default-init-expr-name-conflict.cpp
new file mode 100644 (file)
index 0000000..772db99
--- /dev/null
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++11 %s
+
+template <typename T>
+struct A {
+  // Used to crash when field was named after class.
+  int A = 0;
+};
+A<int> a;