]> granicus.if.org Git - clang/commitdiff
Change struct forward declarations and definitions to use unique RecordDecls, as...
authorTed Kremenek <kremenek@apple.com>
Fri, 5 Sep 2008 17:16:31 +0000 (17:16 +0000)
committerTed Kremenek <kremenek@apple.com>
Fri, 5 Sep 2008 17:16:31 +0000 (17:16 +0000)
This change effects both RecordDecls and CXXRecordDecls, but does not effect EnumDecls (yet).

The motivation of this patch is as follows:
- Capture more source information, necessary for refactoring/rewriting clients.

- Pave the way to resolve ownership issues with RecordDecls with the forthcoming
  addition of DeclGroups.

Current caveats:
- Until DeclGroups are in place, we will leak RecordDecls not explicitly
  referenced by the AST.  For example:

    typedef struct { ... } x;

  The RecordDecl for the struct will be leaked because the TypedefDecl doesn't
  refer to it.  This will be solved with DeclGroups.

- This patch also (temporarily) breaks CodeGen.  More below.

High-level changes:
- As before, TagType still refers to a TagDecl, but it doesn't own it.  When
  a struct/union/class is first referenced, a RecordType and RecordDecl are
  created for it, and the RecordType refers to that RecordDecl.  Later, if
  a new RecordDecl is created, the pointer to a RecordDecl in RecordType is
  updated to point to the RecordDecl that defines the struct/union/class.

- TagDecl and RecordDecl now how a method 'getDefinition()' to return the
  TagDecl*/RecordDecl* that refers to the TagDecl* that defines a particular
  enum/struct/class/union. This is useful from going from a RecordDecl* that
  defines a forward declaration to the RecordDecl* that provides the actual
  definition. Note that this also works for EnumDecls, except that in this case
  there is no distinction between forward declarations and definitions (yet).

- Clients should no longer assume that 'isDefinition()' returns true from a
  RecordDecl if the corresponding struct/union/class has been defined.
  isDefinition() only returns true if a particular RecordDecl is the defining
  Decl. Use 'getDefinition()' instead to determine if a struct has been defined.

- The main changes to Sema happen in ActOnTag. To make the changes more
  incremental, I split off the processing of enums and structs et al into two
  code paths. Enums use the original code path (which is in ActOnTag) and
  structs use the ActOnTagStruct. Eventually the two code paths will be merged,
  but the idea was to preserve the original logic both for comparison and not to
  change the logic for both enums and structs all at once.

- There is NO CHAINING of RecordDecls for the same RecordType. All RecordDecls
  that correspond to the same type simply have a pointer to that type. If we
  need to figure out what are all the RecordDecls for a given type we can build
  a backmap.

- The diff in CXXRecordDecl.[cpp,h] is actually very small; it just mimics the
  changes to RecordDecl. For some reason 'svn' marks the entire file as changed.

Why is CodeGen broken:
- Codegen assumes that there is an equivalence between RecordDecl* and
  RecordType*. This was true before because we only created one RecordDecl* for
  a given RecordType*, but it is no longer true. I believe this shouldn't be too
  hard to change, but the patch was big enough as it is.

I have tested this patch on both the clang test suite, and by running the static analyzer over Postgresql and a large Apple-internal project (mix of Objective-C and C).

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@55839 91177308-0d34-0410-b5e6-96231b3b80d8

Driver/RewriteObjC.cpp
include/clang/AST/ASTContext.h
include/clang/AST/Decl.h
include/clang/AST/DeclCXX.h
include/clang/AST/Type.h
lib/AST/ASTContext.cpp
lib/AST/Decl.cpp
lib/AST/DeclCXX.cpp
lib/CodeGen/CGObjCMac.cpp
lib/Sema/Sema.h
lib/Sema/SemaDecl.cpp

index b078db3184459fde2f862c03c430e5340d7f9f2e..45ce8af6f7f60c2969d1fa74cc2b1c77d33408da 100644 (file)
@@ -1978,7 +1978,7 @@ QualType RewriteObjC::getSuperStructType() {
       FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0, 
                                         FieldTypes[i]);
   
-    SuperStructDecl->defineBody(FieldDecls, 4);
+    SuperStructDecl->defineBody(*Context, FieldDecls, 4);
   }
   return Context->getTagDeclType(SuperStructDecl);
 }
@@ -2005,7 +2005,7 @@ QualType RewriteObjC::getConstantStringStructType() {
       FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
                                         FieldTypes[i]);
   
-    ConstantStringDecl->defineBody(FieldDecls, 4);
+    ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
   }
   return Context->getTagDeclType(ConstantStringDecl);
 }
index 658085907ce53cbe70a4c1024c1df736c50e8994..7f0a75742899460480824a836bac59f3b9127165 100644 (file)
@@ -213,7 +213,7 @@ public:
 
   /// getTypeDeclType - Return the unique reference to the type for
   /// the specified type declaration.
-  QualType getTypeDeclType(TypeDecl *Decl);
+  QualType getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl=0);
 
   /// getTypedefType - Return the unique reference to the type for the
   /// specified typename decl.
@@ -467,6 +467,12 @@ private:
   
   void InitBuiltinTypes();
   void InitBuiltinType(QualType &R, BuiltinType::Kind K);
+  
+  /// setRecordDefinition - Used by RecordDecl::defineBody to inform ASTContext
+  ///  about which RecordDecl serves as the definition of a particular
+  ///  struct/union/class.  This will eventually be used by enums as well.
+  void setTagDefinition(TagDecl* R);
+  friend class RecordDecl;
 };
   
 }  // end namespace clang
index 0e2db965f99956087dfc9a729826dd977c66bb28..a13f0532da29cb01d1572413dabcc1976e41a631 100644 (file)
@@ -690,6 +690,15 @@ public:
     return IsDefinition;
   }
   
+  /// getDefinition - Returns the TagDecl that actually defines this 
+  ///  struct/union/class/enum.  When determining whether or not a
+  ///  struct/union/class/enum is completely defined, one should use this method
+  ///  as opposed to 'isDefinition'.  'isDefinition' indicates whether or not a
+  ///  specific TagDecl is defining declaration, not whether or not the
+  ///  struct/union/class/enum type is defined.  This method returns NULL if
+  ///  there is no TagDecl that defines the struct/union/class/enum.
+  TagDecl* getDefinition(ASTContext& C) const;
+  
   const char *getKindName() const {
     switch (getTagKind()) {
     default: assert(0 && "Unknown TagKind!");
@@ -806,13 +815,25 @@ protected:
 
 public:
   static RecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC,
-                            SourceLocation L, IdentifierInfo *Id);
+                            SourceLocation L, IdentifierInfo *Id,
+                            RecordDecl* PrevDecl = 0);
 
   virtual void Destroy(ASTContext& C);
       
   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
   
+  /// getDefinition - Returns the RecordDecl that actually defines this 
+  ///  struct/union/class.  When determining whether or not a struct/union/class
+  ///  is completely defined, one should use this method as opposed to
+  ///  'isDefinition'.  'isDefinition' indicates whether or not a specific
+  ///  RecordDecl is defining declaration, not whether or not the record
+  ///  type is defined.  This method returns NULL if there is no RecordDecl
+  ///  that defines the struct/union/tag.
+  RecordDecl* getDefinition(ASTContext& C) const {
+    return cast_or_null<RecordDecl>(TagDecl::getDefinition(C));
+  }
+  
   /// getNumMembers - Return the number of members, or -1 if this is a forward
   /// definition.
   int getNumMembers() const { return NumMembers; }
@@ -844,7 +865,7 @@ public:
   /// defineBody - When created, RecordDecl's correspond to a forward declared
   /// record.  This method is used to mark the decl as being defined, with the
   /// specified contents.
-  void defineBody(FieldDecl **Members, unsigned numMembers);
+  void defineBody(ASTContext& C, FieldDecl **Members, unsigned numMembers);
 
   /// getMember - If the member doesn't exist, or there are no members, this 
   /// function will return 0;
index 614e8ef93c5b6daf16ebe1d27816ad11213a2fdd..dc72267554ea6d8565162ee63424889fd65d5cb1 100644 (file)
@@ -49,7 +49,8 @@ protected:
   }
 public:
   static CXXRecordDecl *Create(ASTContext &C, TagKind TK, DeclContext *DC,
-                               SourceLocation L, IdentifierInfo *Id);
+                               SourceLocation L, IdentifierInfo *Id,
+                               CXXRecordDecl* PrevDecl=0);
   
   const CXXFieldDecl *getMember(unsigned i) const {
     return cast<const CXXFieldDecl>(RecordDecl::getMember(i));
index 3eb28a86c0c2bec7c739b4a14d2643fd4118b7e1..50ea6f083638453932a61527a6d27238284b978d 100644 (file)
@@ -1070,6 +1070,7 @@ public:
 
 class TagType : public Type {
   TagDecl *decl;
+  friend class ASTContext;
 
 protected:
   TagType(TagDecl *D, QualType can) : Type(Tagged, can), decl(D) {}
index 5a6aa1ae3120514b5bb57eacf9f41ee432708fa5..4caf16c4b095cd54b70b6e959e218097fe9edc40 100644 (file)
@@ -483,7 +483,8 @@ ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
 /// specified record (struct/union/class), which indicates its size and field
 /// position information.
 const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
-  assert(D->isDefinition() && "Cannot get layout of forward declarations!");
+  D = D->getDefinition(*this);
+  assert(D && "Cannot get layout of forward declarations!");
 
   // Look up this layout, if already laid out, return what we have.
   const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
@@ -898,7 +899,7 @@ QualType ASTContext::getFunctionType(QualType ResultTy, const QualType *ArgArray
 
 /// getTypeDeclType - Return the unique reference to the type for the
 /// specified type declaration.
-QualType ASTContext::getTypeDeclType(TypeDecl *Decl) {
+QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
   
   if (TypedefDecl *Typedef = dyn_cast_or_null<TypedefDecl>(Decl))
@@ -907,19 +908,31 @@ QualType ASTContext::getTypeDeclType(TypeDecl *Decl) {
              = dyn_cast_or_null<ObjCInterfaceDecl>(Decl))
     return getObjCInterfaceType(ObjCInterface);
 
-  if (CXXRecordDecl *CXXRecord = dyn_cast_or_null<CXXRecordDecl>(Decl))
-    Decl->TypeForDecl = new CXXRecordType(CXXRecord);
-  else if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Decl))
-    Decl->TypeForDecl = new RecordType(Record);
+  if (CXXRecordDecl *CXXRecord = dyn_cast_or_null<CXXRecordDecl>(Decl)) {
+    Decl->TypeForDecl = PrevDecl ? PrevDecl->TypeForDecl
+                                 : new CXXRecordType(CXXRecord);
+  }
+  else if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Decl)) {
+    Decl->TypeForDecl = PrevDecl ? PrevDecl->TypeForDecl
+                                 : new RecordType(Record);
+  }
   else if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Decl))
     Decl->TypeForDecl = new EnumType(Enum);
   else
     assert(false && "TypeDecl without a type?");
 
-  Types.push_back(Decl->TypeForDecl);
+  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
   return QualType(Decl->TypeForDecl, 0);
 }
 
+/// setTagDefinition - Used by RecordDecl::defineBody to inform ASTContext
+///  about which RecordDecl serves as the definition of a particular
+///  struct/union/class.  This will eventually be used by enums as well.
+void ASTContext::setTagDefinition(TagDecl* D) {
+  assert (D->isDefinition());
+  cast<TagType>(D->TypeForDecl)->decl = D;  
+}
+
 /// getTypedefType - Return the unique reference to the type for the
 /// specified typename decl.
 QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
@@ -1366,7 +1379,7 @@ QualType ASTContext::getCFConstantStringType() {
       FieldDecls[i] = FieldDecl::Create(*this, SourceLocation(), 0,
                                         FieldTypes[i]);
   
-    CFConstantStringTypeDecl->defineBody(FieldDecls, 4);
+    CFConstantStringTypeDecl->defineBody(*this, FieldDecls, 4);
   }
   
   return getTagDeclType(CFConstantStringTypeDecl);
@@ -1392,7 +1405,7 @@ QualType ASTContext::getObjCFastEnumerationStateType()
       RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
                          &Idents.get("__objcFastEnumerationState"));
     
-    ObjCFastEnumerationStateTypeDecl->defineBody(FieldDecls, 4);
+    ObjCFastEnumerationStateTypeDecl->defineBody(*this, FieldDecls, 4);
   }
   
   return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
index eb9d0efdb483078139c6c259457ed709e2f75d88..8bc212d302d341db26d0fc9298c010443c2f978f 100644 (file)
@@ -199,6 +199,16 @@ unsigned FunctionDecl::getMinRequiredArguments() const {
   return NumRequiredArgs;
 }
 
+//===----------------------------------------------------------------------===//
+// TagdDecl Implementation
+//===----------------------------------------------------------------------===//
+
+TagDecl* TagDecl::getDefinition(ASTContext& C) const {
+  QualType T = C.getTypeDeclType(const_cast<TagDecl*>(this));
+  TagDecl* D = cast<TagDecl>(cast<TagType>(T)->getDecl());  
+  return D->isDefinition() ? D : 0;
+}
+
 //===----------------------------------------------------------------------===//
 // RecordDecl Implementation
 //===----------------------------------------------------------------------===//
@@ -214,7 +224,8 @@ RecordDecl::RecordDecl(Kind DK, DeclContext *DC, SourceLocation L,
 }
 
 RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
-                               SourceLocation L, IdentifierInfo *Id) {
+                               SourceLocation L, IdentifierInfo *Id,
+                               RecordDecl* PrevDecl) {
   
   void *Mem = C.getAllocator().Allocate<RecordDecl>();
   Kind DK;
@@ -225,7 +236,10 @@ RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
     case TK_union:  DK = Union;  break;
     case TK_class:  DK = Class;  break;
   }
-  return new (Mem) RecordDecl(DK, DC, L, Id);
+  
+  RecordDecl* R = new (Mem) RecordDecl(DK, DC, L, Id);
+  C.getTypeDeclType(R, PrevDecl);
+  return R;
 }
 
 RecordDecl::~RecordDecl() {
@@ -243,7 +257,8 @@ void RecordDecl::Destroy(ASTContext& C) {
 /// defineBody - When created, RecordDecl's correspond to a forward declared
 /// record.  This method is used to mark the decl as being defined, with the
 /// specified contents.
-void RecordDecl::defineBody(FieldDecl **members, unsigned numMembers) {
+void RecordDecl::defineBody(ASTContext& C, FieldDecl **members,
+                            unsigned numMembers) {
   assert(!isDefinition() && "Cannot redefine record!");
   setDefinition(true);
   NumMembers = numMembers;
@@ -251,8 +266,12 @@ void RecordDecl::defineBody(FieldDecl **members, unsigned numMembers) {
     Members = new FieldDecl*[numMembers];
     memcpy(Members, members, numMembers*sizeof(Decl*));
   }
+  
+  // Let ASTContext know that this is the defining RecordDecl this type.
+  C.setTagDefinition(this);
 }
 
+
 FieldDecl *RecordDecl::getMember(IdentifierInfo *II) {
   if (Members == 0 || NumMembers < 0)
     return 0;
index 0cce7db1d687c6b2575a1477651f93a951e5f2d8..0a65ab34f0eedc041c2ab18a3adc8cb2da35f4a8 100644 (file)
@@ -1,65 +1,68 @@
-//===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//\r
-//\r
-//                     The LLVM Compiler Infrastructure\r
-//\r
-// This file is distributed under the University of Illinois Open Source\r
-// License. See LICENSE.TXT for details.\r
-//\r
-//===----------------------------------------------------------------------===//\r
-//\r
-// This file implements the C++ related Decl classes.\r
-//\r
-//===----------------------------------------------------------------------===//\r
-\r
-#include "clang/AST/DeclCXX.h"\r
-#include "clang/AST/ASTContext.h"\r
-using namespace clang;\r
-\r
-//===----------------------------------------------------------------------===//\r
-// Decl Allocation/Deallocation Method Implementations\r
-//===----------------------------------------------------------------------===//\r
\r
-CXXFieldDecl *CXXFieldDecl::Create(ASTContext &C, CXXRecordDecl *RD,\r
-                                   SourceLocation L, IdentifierInfo *Id,\r
-                                   QualType T, Expr *BW) {\r
-  void *Mem = C.getAllocator().Allocate<CXXFieldDecl>();\r
-  return new (Mem) CXXFieldDecl(RD, L, Id, T, BW);\r
-}\r
-\r
-CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,\r
-                                     SourceLocation L, IdentifierInfo *Id) {\r
-  Kind DK;\r
-  switch (TK) {\r
-    default: assert(0 && "Invalid TagKind!");\r
-    case TK_enum:   assert(0 && "Enum TagKind passed for Record!");\r
-    case TK_struct: DK = CXXStruct; break;\r
-    case TK_union:  DK = CXXUnion;  break;\r
-    case TK_class:  DK = CXXClass;  break;\r
-  }\r
-  void *Mem = C.getAllocator().Allocate<CXXRecordDecl>();\r
-  return new (Mem) CXXRecordDecl(DK, DC, L, Id);\r
-}\r
-\r
-CXXMethodDecl *\r
-CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,\r
-                      SourceLocation L, IdentifierInfo *Id,\r
-                      QualType T, bool isStatic, bool isInline,\r
-                      ScopedDecl *PrevDecl) {\r
-  void *Mem = C.getAllocator().Allocate<CXXMethodDecl>();\r
-  return new (Mem) CXXMethodDecl(RD, L, Id, T, isStatic, isInline, PrevDecl);\r
-}\r
-\r
-QualType CXXMethodDecl::getThisType(ASTContext &C) const {\r
-  assert(isInstance() && "No 'this' for static methods!");\r
-  QualType ClassTy = C.getTagDeclType(cast<CXXRecordDecl>(getParent()));\r
-  QualType ThisTy = C.getPointerType(ClassTy);\r
-  ThisTy.addConst();\r
-  return ThisTy;\r
-}\r
-\r
-CXXClassVarDecl *CXXClassVarDecl::Create(ASTContext &C, CXXRecordDecl *RD,\r
-                                   SourceLocation L, IdentifierInfo *Id,\r
-                                   QualType T, ScopedDecl *PrevDecl) {\r
-  void *Mem = C.getAllocator().Allocate<CXXClassVarDecl>();\r
-  return new (Mem) CXXClassVarDecl(RD, L, Id, T, PrevDecl);\r
-}\r
+//===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements the C++ related Decl classes.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/ASTContext.h"
+using namespace clang;
+
+//===----------------------------------------------------------------------===//
+// Decl Allocation/Deallocation Method Implementations
+//===----------------------------------------------------------------------===//
+CXXFieldDecl *CXXFieldDecl::Create(ASTContext &C, CXXRecordDecl *RD,
+                                   SourceLocation L, IdentifierInfo *Id,
+                                   QualType T, Expr *BW) {
+  void *Mem = C.getAllocator().Allocate<CXXFieldDecl>();
+  return new (Mem) CXXFieldDecl(RD, L, Id, T, BW);
+}
+
+CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
+                                     SourceLocation L, IdentifierInfo *Id,
+                                     CXXRecordDecl* PrevDecl) {
+  Kind DK;
+  switch (TK) {
+    default: assert(0 && "Invalid TagKind!");
+    case TK_enum:   assert(0 && "Enum TagKind passed for Record!");
+    case TK_struct: DK = CXXStruct; break;
+    case TK_union:  DK = CXXUnion;  break;
+    case TK_class:  DK = CXXClass;  break;
+  }
+  void *Mem = C.getAllocator().Allocate<CXXRecordDecl>();
+  CXXRecordDecl* R = new (Mem) CXXRecordDecl(DK, DC, L, Id);
+  C.getTypeDeclType(R, PrevDecl);  
+  return R;
+}
+
+CXXMethodDecl *
+CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
+                      SourceLocation L, IdentifierInfo *Id,
+                      QualType T, bool isStatic, bool isInline,
+                      ScopedDecl *PrevDecl) {
+  void *Mem = C.getAllocator().Allocate<CXXMethodDecl>();
+  return new (Mem) CXXMethodDecl(RD, L, Id, T, isStatic, isInline, PrevDecl);
+}
+
+QualType CXXMethodDecl::getThisType(ASTContext &C) const {
+  assert(isInstance() && "No 'this' for static methods!");
+  QualType ClassTy = C.getTagDeclType(cast<CXXRecordDecl>(getParent()));
+  QualType ThisTy = C.getPointerType(ClassTy);
+  ThisTy.addConst();
+  return ThisTy;
+}
+
+CXXClassVarDecl *CXXClassVarDecl::Create(ASTContext &C, CXXRecordDecl *RD,
+                                   SourceLocation L, IdentifierInfo *Id,
+                                   QualType T, ScopedDecl *PrevDecl) {
+  void *Mem = C.getAllocator().Allocate<CXXClassVarDecl>();
+  return new (Mem) CXXClassVarDecl(RD, L, Id, T, PrevDecl);
+}
index a535ea254ee5deeca73cc0ed085026b455fda248..3922ae66a3d736f93d181148a3bde592c6e7f205 100644 (file)
@@ -1872,7 +1872,7 @@ ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
                                     Ctx.getObjCIdType());
   FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
                                     Ctx.getObjCClassType());
-  RD->defineBody(FieldDecls, 2);
+  RD->defineBody(Ctx, FieldDecls, 2);
 
   SuperCTy = Ctx.getTagDeclType(RD);
   SuperPtrCTy = Ctx.getPointerType(SuperCTy);
index f5a85a5fc9ed6c8c1114c315791081b7b9d30a76..96f6e53c618b926a23df31c5284bb918a19e6b1a 100644 (file)
@@ -251,6 +251,11 @@ private:
   virtual DeclTy *ActOnTag(Scope *S, unsigned TagType, TagKind TK,
                            SourceLocation KWLoc, IdentifierInfo *Name,
                            SourceLocation NameLoc, AttributeList *Attr);
+  
+  DeclTy* ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
+                         SourceLocation KWLoc, IdentifierInfo *Name,
+                         SourceLocation NameLoc, AttributeList *Attr);  
+  
   virtual void ActOnDefs(Scope *S, SourceLocation DeclStart,
                          IdentifierInfo *ClassName,
                          llvm::SmallVectorImpl<DeclTy*> &Decls);
index 467da813050e1f14d72e1c93d00986d2eb1ef2a5..df9118238337bc164baa22c36d280845aea089b1 100644 (file)
@@ -1682,6 +1682,12 @@ Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
   case DeclSpec::TST_enum:   Kind = TagDecl::TK_enum; break;
   }
   
+  // Two code paths: a new one for structs/unions/classes where we create
+  //   separate decls for forward declarations, and an old (eventually to
+  //   be removed) code path for enums.
+  if (Kind != TagDecl::TK_enum)
+    return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
+  
   // If this is a named struct, check to see if there was a previous forward
   // declaration or definition.
   // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
@@ -1781,6 +1787,121 @@ Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
   return New;
 }
 
+/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes.  Unlike
+///  the logic for enums, we create separate decls for forward declarations.
+///  This is called by ActOnTag, but eventually will replace its logic.
+Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
+                             SourceLocation KWLoc, IdentifierInfo *Name,
+                             SourceLocation NameLoc, AttributeList *Attr) {
+  
+  // If this is a named struct, check to see if there was a previous forward
+  // declaration or definition.
+  // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
+  ScopedDecl *PrevDecl = 
+    dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
+  
+  if (PrevDecl) {    
+    assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
+           "unexpected Decl type");
+    
+    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
+      // If this is a use of a previous tag, or if the tag is already declared
+      // in the same scope (so that the definition/declaration completes or
+      // rementions the tag), reuse the decl.
+      if (TK == TK_Reference ||
+          IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
+        // Make sure that this wasn't declared as an enum and now used as a
+        // struct or something similar.
+        if (PrevTagDecl->getTagKind() != Kind) {
+          Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
+          Diag(PrevDecl->getLocation(), diag::err_previous_use);
+          // Recover by making this an anonymous redefinition.
+          Name = 0;
+          PrevDecl = 0;
+        } else {
+          // If this is a use, return the original decl.
+          
+          // FIXME: In the future, return a variant or some other clue
+          //  for the consumer of this Decl to know it doesn't own it.
+          //  For our current ASTs this shouldn't be a problem, but will
+          //  need to be changed with DeclGroups.
+          if (TK == TK_Reference)
+            return PrevDecl;
+          
+          // The new decl is a definition?
+          if (TK == TK_Definition) {
+            // Diagnose attempts to redefine a tag.
+            if (RecordDecl* DefRecord =
+                cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
+              Diag(NameLoc, diag::err_redefinition, Name->getName());
+              Diag(DefRecord->getLocation(), diag::err_previous_definition);
+              // If this is a redefinition, recover by making this struct be
+              // anonymous, which will make any later references get the previous
+              // definition.
+              Name = 0;
+              PrevDecl = 0;
+            }
+            // Okay, this is definition of a previously declared or referenced
+            // tag.  We're going to create a new Decl.
+          }
+        }
+        // If we get here we have (another) forward declaration.  Just create
+        // a new decl.        
+      }
+      else {
+        // If we get here, this is a definition of a new struct type in a nested
+        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 
+        // new decl/type.  We set PrevDecl to NULL so that the Records
+        // have distinct types.
+        PrevDecl = 0;
+      }
+    } else {
+      // PrevDecl is a namespace.
+      if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
+        // The tag name clashes with a namespace name, issue an error and
+        // recover by making this tag be anonymous.
+        Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
+        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
+        Name = 0;
+      }
+    }
+  }
+  
+  // If there is an identifier, use the location of the identifier as the
+  // location of the decl, otherwise use the location of the struct/union
+  // keyword.
+  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
+  
+  // Otherwise, if this is the first time we've seen this tag, create the decl.
+  TagDecl *New;
+    
+  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
+  // struct X { int A; } D;    D should chain to X.
+  if (getLangOptions().CPlusPlus)
+    New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
+                                dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
+  else
+    New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
+                             dyn_cast_or_null<RecordDecl>(PrevDecl));
+  
+  // If this has an identifier, add it to the scope stack.
+  if ((TK == TK_Definition || !PrevDecl) && Name) {
+    // The scope passed in may not be a decl scope.  Zip up the scope tree until
+    // we find one that is.
+    while ((S->getFlags() & Scope::DeclScope) == 0)
+      S = S->getParent();
+    
+    // Add it to the decl chain.
+    PushOnScopeChains(New, S);
+  }
+  
+  if (Attr)
+    ProcessDeclAttributeList(New, Attr);
+
+  return New;
+}
+
+
 /// Collect the instance variables declared in an Objective-C object.  Used in
 /// the creation of structures from objects using the @defs directive.
 static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
@@ -1977,17 +2098,19 @@ void Sema::ActOnFields(Scope* S,
   assert(EnclosingDecl && "missing record or interface decl");
   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
   
-  if (Record && Record->isDefinition()) {
-    // Diagnose code like:
-    //     struct S { struct S {} X; };
-    // We discover this when we complete the outer S.  Reject and ignore the
-    // outer S.
-    Diag(Record->getLocation(), diag::err_nested_redefinition,
-         Record->getKindName());
-    Diag(RecLoc, diag::err_previous_definition);
-    Record->setInvalidDecl();
-    return;
-  }
+  if (Record)
+    if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
+      // Diagnose code like:
+      //     struct S { struct S {} X; };
+      // We discover this when we complete the outer S.  Reject and ignore the
+      // outer S.
+      Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
+           DefRecord->getKindName());
+      Diag(RecLoc, diag::err_previous_definition);
+      Record->setInvalidDecl();
+      return;
+    }
+  
   // Verify that all the fields are okay.
   unsigned NumNamedMembers = 0;
   llvm::SmallVector<FieldDecl*, 32> RecFields;
@@ -2099,7 +2222,7 @@ void Sema::ActOnFields(Scope* S,
  
   // Okay, we successfully defined 'Record'.
   if (Record) {
-    Record->defineBody(&RecFields[0], RecFields.size());
+    Record->defineBody(Context, &RecFields[0], RecFields.size());
     // If this is a C++ record, HandleTagDeclDefinition will be invoked in
     // Sema::ActOnFinishCXXClassDef.
     if (!isa<CXXRecordDecl>(Record))