SemaDecl.cpp revision aaf87162c5fbfbf320072da3a8e83392e1bbf041
169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// 369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// The LLVM Compiler Infrastructure 469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// 569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// This file is distributed under the University of Illinois Open Source 669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// License. See LICENSE.TXT for details. 769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// 869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal//===----------------------------------------------------------------------===// 969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// 1069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// This file implements semantic analysis for declarations. 1169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// 1269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal//===----------------------------------------------------------------------===// 1369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 1469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "Sema.h" 1569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "SemaInit.h" 1669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "Lookup.h" 1769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/APValue.h" 1869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/ASTConsumer.h" 1969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/ASTContext.h" 2069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/CXXInheritance.h" 2169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/DeclTemplate.h" 2269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/ExprCXX.h" 2369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/AST/StmtCXX.h" 2469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Parse/DeclSpec.h" 2569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Parse/ParseDiagnostic.h" 2669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Parse/Template.h" 2769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Basic/PartialDiagnostic.h" 2869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Basic/SourceManager.h" 2969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Basic/TargetInfo.h" 3069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 3169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Lex/Preprocessor.h" 3269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "clang/Lex/HeaderSearch.h" 3369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include "llvm/ADT/Triple.h" 3469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include <algorithm> 3569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include <cstring> 3669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#include <functional> 3769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalusing namespace clang; 3869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 3969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// getDeclName - Return a pretty name for the specified decl if possible, or 4069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// an empty string if not. This is used for pretty crash reporting. 4169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstd::string Sema::getDeclName(DeclPtrTy d) { 4269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Decl *D = d.getAs<Decl>(); 4369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D)) 4469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DN->getQualifiedNameAsString(); 4569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return ""; 4669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 4769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 4869e17611504376e4d4603925f8528dfc890fd2c6Luis SigalSema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) { 4969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>())); 5069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 5169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 5269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \brief If the identifier refers to a type name within this scope, 5369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// return the declaration of that type. 5469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 5569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// This routine performs ordinary name lookup of the identifier II 5669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// within the given scope, with optional C++ scope specifier SS, to 5769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// determine whether the name refers to a type. If so, returns an 5869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// opaque pointer (actually a QualType) corresponding to that 5969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// type. Otherwise, returns NULL. 6069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 6169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// If name lookup results in an ambiguity, this routine will complain 6269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// and then return NULL. 6369e17611504376e4d4603925f8528dfc890fd2c6Luis SigalSema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 6469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Scope *S, CXXScopeSpec *SS, 6569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal bool isClassName, 6669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TypeTy *ObjectTypePtr) { 6769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Determine where we will perform name lookup. 6869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclContext *LookupCtx = 0; 6969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ObjectTypePtr) { 7069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr); 7169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ObjectType->isRecordType()) 7269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupCtx = computeDeclContext(ObjectType); 7369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (SS && SS->isNotEmpty()) { 7469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupCtx = computeDeclContext(*SS, false); 7569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 7669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!LookupCtx) { 7769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isDependentScopeSpecifier(*SS)) { 7869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [temp.res]p3: 7969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // A qualified-id that refers to a type and in which the 8069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // nested-name-specifier depends on a template-parameter (14.6.2) 8169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // shall be prefixed by the keyword typename to indicate that the 8269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // qualified-id denotes a type, forming an 8369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // elaborated-type-specifier (7.1.5.3). 8469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 8569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We therefore do not perform any name lookup if the result would 8669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // refer to a member of an unknown specialization. 8769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isClassName) 8869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 8969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 9069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We know from the grammar that this name refers to a type, so build a 9169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // DependentNameType node to describe the type. 9269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Record somewhere that this DependentNameType node has no "typename" 9369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // keyword associated with it. 9469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return CheckTypenameType((NestedNameSpecifier *)SS->getScopeRep(), 9569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal II, SS->getRange()).getAsOpaquePtr(); 9669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 9769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 9869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 9969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 10069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 10169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS)) 10269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 10369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 10469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 10569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: LookupNestedNameSpecifierName isn't the right kind of 10669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // lookup for class-names. 10769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 10869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupOrdinaryName; 10969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult Result(*this, &II, NameLoc, Kind); 11069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (LookupCtx) { 11169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Perform "qualified" name lookup into the declaration context we 11269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // computed, which is either the type of the base of a member access 11369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // expression or the declaration context associated with a prior 11469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // nested-name-specifier. 11569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupQualifiedName(Result, LookupCtx); 11669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 11769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ObjectTypePtr && Result.empty()) { 11869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [basic.lookup.classref]p3: 11969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If the unqualified-id is ~type-name, the type-name is looked up 12069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // in the context of the entire postfix-expression. If the type T of 12169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the object expression is of a class type C, the type-name is also 12269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // looked up in the scope of class C. At least one of the lookups shall 12369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // find a name that refers to (possibly cv-qualified) T. 12469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupName(Result, S); 12569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 12669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 12769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Perform unqualified name lookup. 12869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupName(Result, S); 12969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 13069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 13169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *IIDecl = 0; 13269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal switch (Result.getResultKind()) { 13369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case LookupResult::NotFound: 13469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case LookupResult::NotFoundInCurrentInstantiation: 13569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case LookupResult::FoundOverloaded: 13669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case LookupResult::FoundUnresolvedValue: 13769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Result.suppressDiagnostics(); 13869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 13969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 14069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case LookupResult::Ambiguous: 14169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Recover from type-hiding ambiguities by hiding the type. We'll 14269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // do the lookup again when looking for an object, and we can 14369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // diagnose the error then. If we don't do this, then the error 14469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // about hiding the type will be immediately followed by an error 14569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // that only makes sense if the identifier was treated like a type. 14669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 14769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Result.suppressDiagnostics(); 14869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 14969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 15069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 15169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Look to see if we have a type anywhere in the list of results. 15269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 15369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Res != ResEnd; ++Res) { 15469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 15569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!IIDecl || 15669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (*Res)->getLocation().getRawEncoding() < 15769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IIDecl->getLocation().getRawEncoding()) 15869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IIDecl = *Res; 15969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 16069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 16169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 16269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!IIDecl) { 16369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // None of the entities we found is a type, so there is no way 16469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // to even assume that the result is a type. In this case, don't 16569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // complain about the ambiguity. The parser will either try to 16669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // perform this lookup again (e.g., as an object name), which 16769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // will produce the ambiguity, or will complain that it expected 16869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // a type name. 16969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Result.suppressDiagnostics(); 17069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 17169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 17269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 17369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We found a type within the ambiguous lookup; diagnose the 17469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // ambiguity and then return that type. This might be the right 17569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // answer, or it might not be, but it suppresses any attempt to 17669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // perform the name lookup again. 17769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 17869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 17969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case LookupResult::Found: 18069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IIDecl = Result.getFoundDecl(); 18169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 18269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 18369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 18469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(IIDecl && "Didn't find decl"); 18569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 18669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType T; 18769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 18869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DiagnoseUseOfDecl(IIDecl, NameLoc); 18969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 19069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (T.isNull()) 19169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal T = Context.getTypeDeclType(TD); 19269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 19369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (SS) 19469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal T = getQualifiedNameType(*SS, T); 19569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 19669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 19769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal T = Context.getObjCInterfaceType(IDecl); 19869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (UnresolvedUsingTypenameDecl *UUDecl = 19969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) { 20069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: preserve source structure information. 20169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal T = Context.getDependentNameType(ETK_None, 20269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal UUDecl->getTargetNestedNameSpecifier(), 20369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal &II); 20469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 20569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If it's not plausibly a type, suppress diagnostics. 20669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Result.suppressDiagnostics(); 20769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 20869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 20969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 21069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return T.getAsOpaquePtr(); 21169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 21269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 21369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// isTagName() - This method is called *for error recovery purposes only* 21469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// to determine if the specified name is a valid tag name ("struct foo"). If 21569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// so, this returns the TST for the tag corresponding to it (TST_enum, 21669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 21769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// where the user forgot to specify the tag. 21869e17611504376e4d4603925f8528dfc890fd2c6Luis SigalDeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 21969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Do a tag name lookup in this scope. 22069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult R(*this, &II, SourceLocation(), LookupTagName); 22169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupName(R, S, false); 22269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal R.suppressDiagnostics(); 22369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (R.getResultKind() == LookupResult::Found) 22469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 22569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal switch (TD->getTagKind()) { 22669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case TagDecl::TK_struct: return DeclSpec::TST_struct; 22769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case TagDecl::TK_union: return DeclSpec::TST_union; 22869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case TagDecl::TK_class: return DeclSpec::TST_class; 22969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case TagDecl::TK_enum: return DeclSpec::TST_enum; 23069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 23169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 23269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 23369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclSpec::TST_unspecified; 23469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 23569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 23669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalbool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 23769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SourceLocation IILoc, 23869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Scope *S, 23969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CXXScopeSpec *SS, 24069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TypeTy *&SuggestedType) { 24169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We don't have anything to suggest (yet). 24269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SuggestedType = 0; 24369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 24469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // There may have been a typo in the name of the type. Look up typo 24569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // results, in case we have something that we can suggest. 24669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName, 24769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NotForRedeclaration); 24869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 24969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) { 25069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) { 25169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) && 25269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !Result->isInvalidDecl()) { 25369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We found a similarly-named type or interface; suggest that. 25469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!SS || !SS->isSet()) 25569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IILoc, diag::err_unknown_typename_suggest) 25669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << &II << Lookup.getLookupName() 25769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << FixItHint::CreateReplacement(SourceRange(IILoc), 25869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Result->getNameAsString()); 25969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (DeclContext *DC = computeDeclContext(*SS, false)) 26069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IILoc, diag::err_unknown_nested_typename_suggest) 26169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << &II << DC << Lookup.getLookupName() << SS->getRange() 26269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << FixItHint::CreateReplacement(SourceRange(IILoc), 26369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Result->getNameAsString()); 26469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else 26569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal llvm_unreachable("could not have corrected a typo here"); 26669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 26769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Result->getLocation(), diag::note_previous_decl) 26869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Result->getDeclName(); 26969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 27069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS); 27169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 27269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 27369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (Lookup.empty()) { 27469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We corrected to a keyword. 27569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 27669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IILoc, diag::err_unknown_typename_suggest) 27769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << &II << Corrected; 27869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 27969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 28069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 28169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 28269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus) { 28369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // See if II is a class template that the user forgot to pass arguments to. 28469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal UnqualifiedId Name; 28569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Name.setIdentifier(&II, IILoc); 28669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CXXScopeSpec EmptySS; 28769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TemplateTy TemplateResult; 28869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isTemplateName(S, SS ? *SS : EmptySS, Name, 0, true, TemplateResult) 28969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal == TNK_Type_template) { 29069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 29169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IILoc, diag::err_template_missing_args) << TplName; 29269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 29369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(TplDecl->getLocation(), diag::note_template_decl_here) 29469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << TplDecl->getTemplateParameters()->getSourceRange(); 29569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 29669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 29769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 29869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 29969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 30069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Should we move the logic that tries to recover from a missing tag 30169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 30269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 30369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!SS || (!SS->isSet() && !SS->isInvalid())) 30469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IILoc, diag::err_unknown_typename) << &II; 30569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (DeclContext *DC = computeDeclContext(*SS, false)) 30669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IILoc, diag::err_typename_nested_not_found) 30769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << &II << DC << SS->getRange(); 30869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (isDependentScopeSpecifier(*SS)) { 30969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(SS->getRange().getBegin(), diag::err_typename_missing) 31069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 31169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << SourceRange(SS->getRange().getBegin(), IILoc) 31269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 31369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get(); 31469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 31569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(SS && SS->isInvalid() && 31669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal "Invalid scope specifier has already been diagnosed"); 31769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 31869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 31969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 32069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 32169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 32269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// Determines the context to return to after temporarily entering a 32369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// context. This depends in an unnecessarily complicated way on the 32469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal// exact ordering of callbacks from the parser. 32569e17611504376e4d4603925f8528dfc890fd2c6Luis SigalDeclContext *Sema::getContainingDC(DeclContext *DC) { 32669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 32769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Functions defined inline within classes aren't parsed until we've 32869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // finished parsing the top-level class, so the top-level class is 32969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the context we'll need to return to. 33069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<FunctionDecl>(DC)) { 33169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DC = DC->getLexicalParent(); 33269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 33369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // A function not defined within a class will always return to its 33469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // lexical context. 33569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isa<CXXRecordDecl>(DC)) 33669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DC; 33769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 33869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // A C++ inline method/friend is parsed *after* the topmost class 33969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // it was declared in is fully parsed ("complete"); the topmost 34069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // class is the context we need to return to. 34169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 34269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DC = RD; 34369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 34469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Return the declaration context of the topmost class the inline method is 34569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // declared in. 34669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DC; 34769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 34869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 34969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<ObjCMethodDecl>(DC)) 35069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return Context.getTranslationUnitDecl(); 35169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 35269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DC->getLexicalParent(); 35369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 35469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 35569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::PushDeclContext(Scope *S, DeclContext *DC) { 35669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(getContainingDC(DC) == CurContext && 35769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal "The next DeclContext should be lexically contained in the current one."); 35869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext = DC; 35969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S->setEntity(DC); 36069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 36169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 36269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::PopDeclContext() { 36369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(CurContext && "DeclContext imbalance!"); 36469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 36569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext = getContainingDC(CurContext); 36669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 36769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 36869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// EnterDeclaratorContext - Used when we must lookup names in the context 36969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// of a declarator's nested name specifier. 37069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 37169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 37269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++0x [basic.lookup.unqual]p13: 37369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // A name used in the definition of a static data member of class 37469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // X (after the qualified-id of the static member) is looked up as 37569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // if the name was used in a member function of X. 37669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++0x [basic.lookup.unqual]p14: 37769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If a variable member of a namespace is defined outside of the 37869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // scope of its namespace then any name used in the definition of 37969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the variable member (after the declarator-id) is looked up as 38069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // if the definition of the variable member occurred in its 38169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // namespace. 38269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Both of these imply that we should push a scope whose context 38369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // is the semantic context of the declaration. We can't use 38469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // PushDeclContext here because that context is not necessarily 38569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // lexically contained in the current context. Fortunately, 38669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the containing scope should have the appropriate information. 38769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 38869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(!S->getEntity() && "scope already has entity"); 38969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 39069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#ifndef NDEBUG 39169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Scope *Ancestor = S->getParent(); 39269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 39369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 39469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal#endif 39569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 39669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext = DC; 39769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S->setEntity(DC); 39869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 39969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 40069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::ExitDeclaratorContext(Scope *S) { 40169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(S->getEntity() == CurContext && "Context imbalance!"); 40269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 40369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Switch back to the lexical context. The safety of this is 40469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // enforced by an assert in EnterDeclaratorContext. 40569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Scope *Ancestor = S->getParent(); 40669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 40769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext = (DeclContext*) Ancestor->getEntity(); 40869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 40969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We don't need to do anything with the scope, which is going to 41069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // disappear. 41169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 41269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 41369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \brief Determine whether we allow overloading of the function 41469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// PrevDecl with another declaration. 41569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 41669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// This routine determines whether overloading is possible, not 41769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// whether some new function is actually an overload. It will return 41869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// true in C++ (where we can always provide overloads) or, as an 41969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// extension, in C when the previous function is already an 42069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// overloaded function declaration or has the "overloadable" 42169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// attribute. 42269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool AllowOverloadingOfFunction(LookupResult &Previous, 42369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ASTContext &Context) { 42469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.getLangOptions().CPlusPlus) 42569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 42669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 42769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Previous.getResultKind() == LookupResult::FoundOverloaded) 42869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 42969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 43069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return (Previous.getResultKind() == LookupResult::Found 43169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 43269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 43369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 43469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// Add this decl to the scope shadowed decl chains. 43569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 43669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Move up the scope chain until we find the nearest enclosing 43769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // non-transparent context. The declaration will be introduced into this 43869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // scope. 43969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (S->getEntity() && 44069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ((DeclContext *)S->getEntity())->isTransparentContext()) 44169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S = S->getParent(); 44269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 44369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Add scoped declarations into their context, so that they can be 44469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // found later. Declarations without a context won't be inserted 44569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // into any context. 44669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (AddToContext) 44769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext->addDecl(D); 44869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 44969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Out-of-line definitions shouldn't be pushed into scope in C++. 45069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Out-of-line variable and function definitions shouldn't even in C. 45169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 45269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal D->isOutOfLine()) 45369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 45469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 45569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Template instantiations should also not be pushed into scope. 45669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<FunctionDecl>(D) && 45769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 45869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 45969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 46069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If this replaces anything in the current scope, 46169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 46269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IEnd = IdResolver.end(); 46369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (; I != IEnd; ++I) { 46469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) { 46569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S->RemoveDecl(DeclPtrTy::make(*I)); 46669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IdResolver.RemoveDecl(*I); 46769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 46869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Should only need to replace one decl. 46969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 47069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 47169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 47269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 47369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S->AddDecl(DeclPtrTy::make(D)); 47469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IdResolver.AddDecl(D); 47569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 47669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 47769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalbool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) { 47869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return IdResolver.isDeclInScope(D, Ctx, Context, S); 47969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 48069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 48169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool isOutOfScopePreviousDeclaration(NamedDecl *, 48269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclContext*, 48369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ASTContext&); 48469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 48569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// Filters out lookup results that don't fall within the given scope 48669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// as determined by isDeclInScope. 48769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic void FilterLookupForScope(Sema &SemaRef, LookupResult &R, 48869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclContext *Ctx, Scope *S, 48969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal bool ConsiderLinkage) { 49069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult::Filter F = R.makeFilter(); 49169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (F.hasNext()) { 49269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *D = F.next(); 49369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 49469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (SemaRef.isDeclInScope(D, Ctx, S)) 49569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal continue; 49669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 49769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ConsiderLinkage && 49869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context)) 49969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal continue; 50069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 50169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal F.erase(); 50269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 50369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 50469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal F.done(); 50569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 50669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 50769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool isUsingDecl(NamedDecl *D) { 50869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return isa<UsingShadowDecl>(D) || 50969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal isa<UnresolvedUsingTypenameDecl>(D) || 51069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal isa<UnresolvedUsingValueDecl>(D); 51169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 51269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 51369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// Removes using shadow declarations from the lookup results. 51469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic void RemoveUsingDecls(LookupResult &R) { 51569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult::Filter F = R.makeFilter(); 51669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (F.hasNext()) 51769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isUsingDecl(F.next())) 51869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal F.erase(); 51969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 52069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal F.done(); 52169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 52269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 52369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 52469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (D->isInvalidDecl()) 52569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 52669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 52769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (D->isUsed() || D->hasAttr<UnusedAttr>()) 52869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 52969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 53069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // White-list anything that isn't a local variable. 53169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 53269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !D->getDeclContext()->isFunctionOrMethod()) 53369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 53469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 53569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Types of valid local variables should be complete, so this should succeed. 53669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 53769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 53869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // White-list anything with an __attribute__((unused)) type. 53969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType Ty = VD->getType(); 54069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 54169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Only look at the outermost level of typedef. 54269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 54369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (TT->getDecl()->hasAttr<UnusedAttr>()) 54469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 54569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 54669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 54769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const TagType *TT = Ty->getAs<TagType>()) { 54869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const TagDecl *Tag = TT->getDecl(); 54969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Tag->hasAttr<UnusedAttr>()) 55069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 55169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 55269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 55369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!RD->hasTrivialConstructor()) 55469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 55569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!RD->hasTrivialDestructor()) 55669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 55769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 55869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 55969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 56069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // TODO: __attribute__((unused)) templates? 56169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 56269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 56369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 56469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 56569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 56669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 56769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (S->decl_empty()) return; 56869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 56969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal "Scope shouldn't contain decls!"); 57069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 57169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 57269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal I != E; ++I) { 57369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Decl *TmpD = (*I).getAs<Decl>(); 57469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(TmpD && "This decl didn't get pushed??"); 57569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 57669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 57769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *D = cast<NamedDecl>(TmpD); 57869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 57969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!D->getDeclName()) continue; 58069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 58169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Diagnose unused variables in this scope. 58269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ShouldDiagnoseUnusedDecl(D) && 58369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S->getNumErrorsAtStart() == getDiagnostics().getNumErrors()) 58469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName(); 58569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 58669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Remove this name from our lexical scope. 58769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IdResolver.RemoveDecl(D); 58869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 58969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 59069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 59169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 59269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// return 0 if one not found. 59369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 59469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \param Id the name of the Objective-C class we're looking for. If 59569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// typo-correction fixes this name, the Id will be updated 59669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// to the fixed name. 59769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 59869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \param RecoverLoc if provided, this routine will attempt to 59969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// recover from a typo in the name of an existing Objective-C class 60069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// and, if successful, will return the lookup that results from 60169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// typo-correction. 60269e17611504376e4d4603925f8528dfc890fd2c6Luis SigalObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 60369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SourceLocation RecoverLoc) { 60469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The third "scope" argument is 0 since we aren't enabling lazy built-in 60569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // creation from this context. 60669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *IDecl = LookupSingleName(TUScope, Id, LookupOrdinaryName); 60769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 60869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!IDecl && !RecoverLoc.isInvalid()) { 60969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Perform typo correction at the given location, but only if we 61069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // find an Objective-C class name. 61169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult R(*this, Id, RecoverLoc, LookupOrdinaryName); 61269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) && 61369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) { 61469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(RecoverLoc, diag::err_undef_interface_suggest) 61569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Id << IDecl->getDeclName() 61669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << FixItHint::CreateReplacement(RecoverLoc, IDecl->getNameAsString()); 61769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(IDecl->getLocation(), diag::note_previous_decl) 61869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << IDecl->getDeclName(); 61969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 62069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Id = IDecl->getIdentifier(); 62169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 62269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 62369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 62469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 62569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 62669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 62769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// getNonFieldDeclScope - Retrieves the innermost scope, starting 62869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// from S, where a non-field would be declared. This routine copes 62969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// with the difference between C and C++ scoping rules in structs and 63069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// unions. For example, the following code is well-formed in C but 63169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// ill-formed in C++: 63269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// @code 63369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// struct S6 { 63469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// enum { BAR } e; 63569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// }; 63669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 63769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// void test_S6() { 63869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// struct S6 a; 63969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// a.e = BAR; 64069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// } 64169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// @endcode 64269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// For the declaration of BAR, this routine will return a different 64369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// scope. The scope S will be the scope of the unnamed enumeration 64469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// within S6. In C++, this routine will return the scope associated 64569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// with S6, because the enumeration's scope is a transparent 64669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// context but structures can contain non-field names. In C, this 64769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// routine will return the translation unit scope, since the 64869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// enumeration's scope is a transparent context and structures cannot 64969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// contain non-field names. 65069e17611504376e4d4603925f8528dfc890fd2c6Luis SigalScope *Sema::getNonFieldDeclScope(Scope *S) { 65169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal while (((S->getFlags() & Scope::DeclScope) == 0) || 65269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (S->getEntity() && 65369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ((DeclContext *)S->getEntity())->isTransparentContext()) || 65469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (S->isClassScope() && !getLangOptions().CPlusPlus)) 65569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S = S->getParent(); 65669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return S; 65769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 65869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 65969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::InitBuiltinVaListType() { 66069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!Context.getBuiltinVaListType().isNull()) 66169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 66269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 66369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 66469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, LookupOrdinaryName); 66569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 66669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 66769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 66869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 66969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// LazilyCreateBuiltin - The specified Builtin-ID was first used at 67069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// file scope. lazily create a decl for it. ForRedeclaration is true 67169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// if we're creating this built-in in anticipation of redeclaring the 67269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// built-in. 67369e17611504376e4d4603925f8528dfc890fd2c6Luis SigalNamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 67469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Scope *S, bool ForRedeclaration, 67569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SourceLocation Loc) { 67669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Builtin::ID BID = (Builtin::ID)bid; 67769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 67869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.BuiltinInfo.hasVAListUse(BID)) 67969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal InitBuiltinVaListType(); 68069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 68169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ASTContext::GetBuiltinTypeError Error; 68269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType R = Context.GetBuiltinType(BID, Error); 68369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal switch (Error) { 68469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case ASTContext::GE_None: 68569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Okay 68669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 68769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 68869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case ASTContext::GE_Missing_stdio: 68969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ForRedeclaration) 69069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Loc, diag::err_implicit_decl_requires_stdio) 69169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Context.BuiltinInfo.GetName(BID); 69269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 69369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 69469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case ASTContext::GE_Missing_setjmp: 69569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (ForRedeclaration) 69669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Loc, diag::err_implicit_decl_requires_setjmp) 69769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Context.BuiltinInfo.GetName(BID); 69869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return 0; 69969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 70069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 70169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 70269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Loc, diag::ext_implicit_lib_function_decl) 70369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Context.BuiltinInfo.GetName(BID) 70469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << R; 70569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.BuiltinInfo.getHeaderName(BID) && 70669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl) 70769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal != Diagnostic::Ignored) 70869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Loc, diag::note_please_include_header) 70969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Context.BuiltinInfo.getHeaderName(BID) 71069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Context.BuiltinInfo.GetName(BID); 71169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 71269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 71369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FunctionDecl *New = FunctionDecl::Create(Context, 71469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.getTranslationUnitDecl(), 71569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Loc, II, R, /*TInfo=*/0, 71669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FunctionDecl::Extern, false, 71769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal /*hasPrototype=*/true); 71869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setImplicit(); 71969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 72069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Create Decl objects for each parameter, adding them to the 72169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FunctionDecl. 72269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 72369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal llvm::SmallVector<ParmVarDecl*, 16> Params; 72469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 72569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 72669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FT->getArgType(i), /*TInfo=*/0, 72769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal VarDecl::None, 0)); 72869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setParams(Params.data(), Params.size()); 72969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 73069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 73169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal AddKnownFunctionAttributes(New); 73269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 73369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // TUScope is the translation-unit scope to insert this function into. 73469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: This is hideous. We need to teach PushOnScopeChains to 73569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // relate Scopes to DeclContexts, and probably eliminate CurContext 73669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // entirely, but we're not there yet. 73769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclContext *SavedContext = CurContext; 73869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext = Context.getTranslationUnitDecl(); 73969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PushOnScopeChains(New, TUScope); 74069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CurContext = SavedContext; 74169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New; 74269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 74369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 74469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the 74569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// same name and scope as a previous declaration 'Old'. Figure out 74669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// how to resolve this situation, merging decls or emitting 74769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// diagnostics as appropriate. If there was an error, set New to be invalid. 74869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 74969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) { 75069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If the new decl is known invalid already, don't bother doing any 75169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // merging checks. 75269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (New->isInvalidDecl()) return; 75369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 75469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Allow multiple definitions for ObjC built-in typedefs. 75569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Verify the underlying types are equivalent! 75669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().ObjC1) { 75769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const IdentifierInfo *TypeID = New->getIdentifier(); 75869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal switch (TypeID->getLength()) { 75969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal default: break; 76069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case 2: 76169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!TypeID->isStr("id")) 76269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 76369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.ObjCIdRedefinitionType = New->getUnderlyingType(); 76469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Install the built-in type for 'id', ignoring the current definition. 76569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 76669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 76769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case 5: 76869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!TypeID->isStr("Class")) 76969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 77069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.ObjCClassRedefinitionType = New->getUnderlyingType(); 77169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Install the built-in type for 'Class', ignoring the current definition. 77269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 77369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 77469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case 3: 77569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!TypeID->isStr("SEL")) 77669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 77769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.ObjCSelRedefinitionType = New->getUnderlyingType(); 77869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Install the built-in type for 'SEL', ignoring the current definition. 77969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 78069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 78169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal case 8: 78269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!TypeID->isStr("Protocol")) 78369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal break; 78469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.setObjCProtoType(New->getUnderlyingType()); 78569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 78669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 78769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Fall through - the typedef name was not a builtin type. 78869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 78969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 79069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Verify the old decl was also a type. 79169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 79269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!Old) { 79369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition_different_kind) 79469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 79569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 79669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 79769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldD->getLocation().isValid()) 79869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(OldD->getLocation(), diag::note_previous_definition); 79969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 80069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 80169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 80269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 80369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If the old declaration is invalid, just give up here. 80469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Old->isInvalidDecl()) 80569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 80669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 80769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Determine the "old" type we'll use for checking and diagnostics. 80869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType OldType; 80969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 81069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldType = OldTypedef->getUnderlyingType(); 81169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else 81269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldType = Context.getTypeDeclType(Old); 81369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 81469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If the typedef types are not identical, reject them in all languages and 81569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // with any extensions enabled. 81669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 81769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldType != New->getUnderlyingType() && 81869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.getCanonicalType(OldType) != 81969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.getCanonicalType(New->getUnderlyingType())) { 82069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition_different_typedef) 82169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getUnderlyingType() << OldType; 82269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Old->getLocation().isValid()) 82369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 82469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 82569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 82669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 82769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The types match. Link up the redeclaration chain if the old 82869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // declaration was a typedef. 82969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: this is a potential source of wierdness if the type 83069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // spellings don't match exactly. 83169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<TypedefDecl>(Old)) 83269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setPreviousDeclaration(cast<TypedefDecl>(Old)); 83369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 83469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().Microsoft) 83569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 83669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 83769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus) { 83869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [dcl.typedef]p2: 83969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // In a given non-class scope, a typedef specifier can be used to 84069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // redefine the name of any type declared in that scope to refer 84169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // to the type to which it already refers. 84269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isa<CXXRecordDecl>(CurContext)) 84369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 84469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 84569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++0x [dcl.typedef]p4: 84669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // In a given class scope, a typedef specifier can be used to redefine 84769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // any class-name declared in that scope that is not also a typedef-name 84869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // to refer to the type to which it already refers. 84969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 85069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // This wording came in via DR424, which was a correction to the 85169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // wording in DR56, which accidentally banned code like: 85269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 85369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // struct S { 85469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // typedef struct A { } A; 85569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // }; 85669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 85769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // in the C++03 standard. We implement the C++0x semantics, which 85869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // allow the above but disallow 85969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 86069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // struct S { 86169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // typedef int I; 86269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // typedef int I; 86369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // }; 86469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 86569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // since that was the intent of DR56. 86669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isa<TypedefDecl >(Old)) 86769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 86869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 86969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition) 87069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 87169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 87269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 87369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 87469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 87569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If we have a redefinition of a typedef in C, emit a warning. This warning 87669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // is normally mapped to an error, but can be controlled with 87769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // -Wtypedef-redefinition. If either the original or the redefinition is 87869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // in a system header, don't emit this for compatibility with GCC. 87969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getDiagnostics().getSuppressSystemWarnings() && 88069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 88169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.getSourceManager().isInSystemHeader(New->getLocation()))) 88269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 88369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 88469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 88569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 88669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 88769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 88869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 88969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 89069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// DeclhasAttr - returns true if decl Declaration already has the target 89169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// attribute. 89269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool 89369e17611504376e4d4603925f8528dfc890fd2c6Luis SigalDeclHasAttr(const Decl *decl, const Attr *target) { 89469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 89569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (attr->getKind() == target->getKind()) 89669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 89769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 89869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 89969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 90069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 90169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// MergeAttributes - append attributes from the Old decl to the New one. 90269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) { 90369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) { 90469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!DeclHasAttr(New, attr) && attr->isMerged()) { 90569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Attr *NewAttr = attr->clone(C); 90669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewAttr->setInherited(true); 90769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->addAttr(NewAttr); 90869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 90969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 91069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 91169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 91269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// Used in MergeFunctionDecl to keep track of function parameters in 91369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// C. 91469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstruct GNUCompatibleParamWarning { 91569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParmVarDecl *OldParm; 91669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParmVarDecl *NewParm; 91769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType PromotedType; 91869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal}; 91969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 92069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 92169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// getSpecialMember - get the special member enum for a method. 92269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic Sema::CXXSpecialMember getSpecialMember(ASTContext &Ctx, 92369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const CXXMethodDecl *MD) { 92469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 92569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Ctor->isDefaultConstructor()) 92669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return Sema::CXXDefaultConstructor; 92769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Ctor->isCopyConstructor()) 92869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return Sema::CXXCopyConstructor; 92969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 93069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 93169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<CXXDestructorDecl>(MD)) 93269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return Sema::CXXDestructor; 93369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 93469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(MD->isCopyAssignment() && "Must have copy assignment operator"); 93569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return Sema::CXXCopyAssignment; 93669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 93769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 93869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// canREdefineFunction - checks if a function can be redefined. Currently, 93969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// only extern inline functions can be redefined, and even then only in 94069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// GNU89 mode. 94169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool canRedefineFunction(const FunctionDecl *FD, 94269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const LangOptions& LangOpts) { 94369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus && 94469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FD->isInlineSpecified() && 94569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FD->getStorageClass() == FunctionDecl::Extern); 94669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 94769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 94869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// MergeFunctionDecl - We just parsed a function 'New' from 94969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// declarator D which has the same name and scope as a previous 95069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// declaration 'Old'. Figure out how to resolve this situation, 95169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// merging decls or emitting diagnostics as appropriate. 95269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 95369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// In C++, New and Old must be declarations that are not 95469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// overloaded. Use IsOverload to determine whether New and Old are 95569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// overloaded, and to select the Old declaration that New should be 95669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// merged with. 95769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 95869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// Returns true if there was an error, false otherwise. 95969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalbool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) { 96069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Verify the old decl was also a function. 96169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FunctionDecl *Old = 0; 96269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (FunctionTemplateDecl *OldFunctionTemplate 96369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = dyn_cast<FunctionTemplateDecl>(OldD)) 96469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old = OldFunctionTemplate->getTemplatedDecl(); 96569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else 96669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old = dyn_cast<FunctionDecl>(OldD); 96769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!Old) { 96869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 96969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 97069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Shadow->getTargetDecl()->getLocation(), 97169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::note_using_decl_target); 97269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Shadow->getUsingDecl()->getLocation(), 97369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::note_using_decl) << 0; 97469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 97569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 97669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 97769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition_different_kind) 97869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 97969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(OldD->getLocation(), diag::note_previous_definition); 98069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 98169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 98269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 98369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Determine whether the previous declaration was a definition, 98469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // implicit declaration, or a declaration. 98569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::kind PrevDiag; 98669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Old->isThisDeclarationADefinition()) 98769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PrevDiag = diag::note_previous_definition; 98869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (Old->isImplicit()) 98969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PrevDiag = diag::note_previous_implicit_declaration; 99069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else 99169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PrevDiag = diag::note_previous_declaration; 99269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 99369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType OldQType = Context.getCanonicalType(Old->getType()); 99469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType NewQType = Context.getCanonicalType(New->getType()); 99569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 99669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Don't complain about this if we're in GNU89 mode and the old function 99769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // is an extern inline function. 99869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 99969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->getStorageClass() == FunctionDecl::Static && 100069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old->getStorageClass() != FunctionDecl::Static && 100169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !canRedefineFunction(Old, getLangOptions())) { 100269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_static_non_static) 100369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New; 100469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), PrevDiag); 100569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 100669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 100769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 100869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If a function is first declared with a calling convention, but is 100969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // later declared or defined without one, the second decl assumes the 101069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // calling convention of the first. 101169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 101269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // For the new decl, we have to look at the NON-canonical type to tell the 101369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // difference between a function that really doesn't have a calling 101469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // convention and one that is declared cdecl. That's because in 101569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 101669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // because it is the default calling convention. 101769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 101869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Note also that we DO NOT return at this point, because we still have 101969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // other tests to run. 102069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionType *OldType = OldQType->getAs<FunctionType>(); 102169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 102269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 102369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 102469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldTypeInfo.getCC() != CC_Default && 102569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewTypeInfo.getCC() == CC_Default) { 102669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC()); 102769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setType(NewQType); 102869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewQType = Context.getCanonicalType(NewQType); 102969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 103069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewTypeInfo.getCC())) { 103169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Calling conventions really aren't compatible, so complain. 103269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_cconv_change) 103369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 103469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (OldTypeInfo.getCC() == CC_Default) 103569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (OldTypeInfo.getCC() == CC_Default ? "" : 103669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 103769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_declaration); 103869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 103969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 104069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 104169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: diagnose the other way around? 104269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldType->getNoReturnAttr() && 104369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !NewType->getNoReturnAttr()) { 104469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewQType = Context.getNoReturnType(NewQType); 104569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setType(NewQType); 104669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(NewQType.isCanonical()); 104769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 104869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 104969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus) { 105069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // (C++98 13.1p2): 105169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Certain function declarations cannot be overloaded: 105269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // -- Function declarations that differ only in the return type 105369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // cannot be overloaded. 105469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType OldReturnType 105569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 105669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType NewReturnType 105769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 105869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldReturnType != NewReturnType) { 105969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_ovl_diff_return_type); 106069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 106169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 106269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 106369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 106469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 106569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 106669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldMethod && NewMethod) { 106769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Preserve triviality. 106869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewMethod->setTrivial(OldMethod->isTrivial()); 106969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 107069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal bool isFriend = NewMethod->getFriendObjectKind(); 107169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 107269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) { 107369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // -- Member function declarations with the same name and the 107469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // same parameter types cannot be overloaded if any of them 107569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // is a static member function declaration. 107669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldMethod->isStatic() || NewMethod->isStatic()) { 107769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 107869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 107969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 108069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 108169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 108269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.mem]p1: 108369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // [...] A member shall not be declared twice in the 108469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // member-specification, except that a nested class or member 108569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // class template can be declared and then later defined. 108669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal unsigned NewDiag; 108769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<CXXConstructorDecl>(OldMethod)) 108869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewDiag = diag::err_constructor_redeclared; 108969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (isa<CXXDestructorDecl>(NewMethod)) 109069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewDiag = diag::err_destructor_redeclared; 109169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (isa<CXXConversionDecl>(NewMethod)) 109269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewDiag = diag::err_conv_function_redeclared; 109369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else 109469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewDiag = diag::err_member_redeclared; 109569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 109669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), NewDiag); 109769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 109869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 109969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Complain if this is an explicit declaration of a special 110069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // member that was initially declared implicitly. 110169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 110269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // As an exception, it's okay to befriend such methods in order 110369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // to permit the implicit constructor/destructor/operator calls. 110469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (OldMethod->isImplicit()) { 110569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isFriend) { 110669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewMethod->setImplicit(); 110769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 110869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(NewMethod->getLocation(), 110969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::err_definition_of_implicitly_declared_member) 111069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New << getSpecialMember(Context, OldMethod); 111169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 111269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 111369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 111469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 111569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 111669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // (C++98 8.3.5p3): 111769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // All declarations for a function shall agree exactly in both the 111869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // return type and the parameter-type-list. 111969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // attributes should be ignored when comparing. 112069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.getNoReturnType(OldQType, false) == 112169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.getNoReturnType(NewQType, false)) 112269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return MergeCompatibleFunctionDecls(New, Old); 112369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 112469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Fall through for conflicting redeclarations and redefinitions. 112569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 112669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 112769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C: Function types need to be compatible, not identical. This handles 112869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // duplicate function decls like "void f(int); void f(enum X);" properly. 112969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!getLangOptions().CPlusPlus && 113069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Context.typesAreCompatible(OldQType, NewQType)) { 113169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 113269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 113369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionProtoType *OldProto = 0; 113469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<FunctionNoProtoType>(NewFuncType) && 113569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 113669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The old declaration provided a function prototype, but the 113769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // new declaration does not. Merge in the prototype. 113869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 113969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 114069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldProto->arg_type_end()); 114169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewQType = Context.getFunctionType(NewFuncType->getResultType(), 114269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParamTypes.data(), ParamTypes.size(), 114369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldProto->isVariadic(), 114469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldProto->getTypeQuals(), 114569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal false, false, 0, 0, 114669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldProto->getExtInfo()); 114769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setType(NewQType); 114869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setHasInheritedPrototype(); 114969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 115069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Synthesize a parameter for each argument type. 115169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal llvm::SmallVector<ParmVarDecl*, 16> Params; 115269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (FunctionProtoType::arg_type_iterator 115369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParamType = OldProto->arg_type_begin(), 115469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParamEnd = OldProto->arg_type_end(); 115569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParamType != ParamEnd; ++ParamType) { 115669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 115769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SourceLocation(), 0, 115869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal *ParamType, /*TInfo=*/0, 115969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal VarDecl::None, 0); 116069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Param->setImplicit(); 116169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Params.push_back(Param); 116269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 116369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 116469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setParams(Params.data(), Params.size()); 116569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 116669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 116769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return MergeCompatibleFunctionDecls(New, Old); 116869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 116969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 117069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // GNU C permits a K&R definition to follow a prototype declaration 117169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // if the declared types of the parameters in the K&R definition 117269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // match the types in the prototype declaration, even when the 117369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // promoted types of the parameters from the K&R definition differ 117469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // from the types in the prototype. GCC then keeps the types from 117569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the prototype. 117669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // 117769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If a variadic prototype is followed by a non-variadic K&R definition, 117869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the K&R definition becomes variadic. This is sort of an edge case, but 117969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 118069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C99 6.9.1p8. 118169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!getLangOptions().CPlusPlus && 118269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old->hasPrototype() && !New->hasPrototype() && 118369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->getType()->getAs<FunctionProtoType>() && 118469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old->getNumParams() == New->getNumParams()) { 118569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal llvm::SmallVector<QualType, 16> ArgTypes; 118669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings; 118769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionProtoType *OldProto 118869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = Old->getType()->getAs<FunctionProtoType>(); 118969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const FunctionProtoType *NewProto 119069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = New->getType()->getAs<FunctionProtoType>(); 119169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 119269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Determine whether this is the GNU C extension. 119369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 119469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewProto->getResultType()); 119569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal bool LooseCompatible = !MergedReturn.isNull(); 119669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (unsigned Idx = 0, End = Old->getNumParams(); 119769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LooseCompatible && Idx != End; ++Idx) { 119869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParmVarDecl *OldParm = Old->getParamDecl(Idx); 119969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ParmVarDecl *NewParm = New->getParamDecl(Idx); 120069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.typesAreCompatible(OldParm->getType(), 120169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewProto->getArgType(Idx))) { 120269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ArgTypes.push_back(NewParm->getType()); 120369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (Context.typesAreCompatible(OldParm->getType(), 120469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NewParm->getType())) { 120569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal GNUCompatibleParamWarning Warn 120669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = { OldParm, NewParm, NewProto->getArgType(Idx) }; 120769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Warnings.push_back(Warn); 120869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ArgTypes.push_back(NewParm->getType()); 120969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else 121069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LooseCompatible = false; 121169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 121269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 121369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (LooseCompatible) { 121469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 121569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Warnings[Warn].NewParm->getLocation(), 121669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::ext_param_promoted_not_compatible_with_prototype) 121769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Warnings[Warn].PromotedType 121869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Warnings[Warn].OldParm->getType(); 121969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Warnings[Warn].OldParm->getLocation(), 122069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::note_previous_declaration); 122169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 122269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 122369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 122469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ArgTypes.size(), 122569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldProto->isVariadic(), 0, 122669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal false, false, 0, 0, 122769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal OldProto->getExtInfo())); 122869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return MergeCompatibleFunctionDecls(New, Old); 122969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 123069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 123169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Fall through to diagnose conflicting types. 123269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 123369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 123469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // A function that has already been declared has been redeclared or defined 123569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // with a different type- show appropriate diagnostic 123669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (unsigned BuiltinID = Old->getBuiltinID()) { 123769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The user has declared a builtin function with an incompatible 123869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // signature. 123969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 124069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The function the user is redeclaring is a library-defined 124169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // function like 'malloc' or 'printf'. Warn about the 124269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // redeclaration, then pretend that we don't know about this 124369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // library built-in. 124469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 124569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 124669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << Old << Old->getType(); 124769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 124869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old->setInvalidDecl(); 124969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 125069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 125169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 125269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PrevDiag = diag::note_previous_builtin_declaration; 125369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 125469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 125569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 125669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 125769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 125869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 125969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 126069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \brief Completes the merge of two function declarations that are 126169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// known to be compatible. 126269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 126369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// This routine handles the merging of attributes and other 126469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// properties of function declarations form the old declaration to 126569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// the new declaration, once we know that New is in fact a 126669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// redeclaration of Old. 126769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 126869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \returns false 126969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalbool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) { 127069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Merge the attributes 127169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MergeAttributes(New, Old, Context); 127269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 127369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Merge the storage class. 127469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Old->getStorageClass() != FunctionDecl::Extern && 127569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old->getStorageClass() != FunctionDecl::None) 127669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setStorageClass(Old->getStorageClass()); 127769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 127869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Merge "pure" flag. 127969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Old->isPure()) 128069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setPure(); 128169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 128269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Merge the "deleted" flag. 128369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Old->isDeleted()) 128469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setDeleted(); 128569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 128669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus) 128769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return MergeCXXFunctionDecl(New, Old); 128869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 128969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 129069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 129169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 129269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// MergeVarDecl - We just parsed a variable 'New' which has the same name 129369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// and scope as a previous declaration 'Old'. Figure out how to resolve this 129469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// situation, merging decls or emitting diagnostics as appropriate. 129569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 129669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// Tentative definition rules (C99 6.9.2p2) are checked by 129769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 129869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// definitions here, since the initializer hasn't been attached. 129969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 130069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalvoid Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 130169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If the new decl is already invalid, don't do any other checking. 130269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (New->isInvalidDecl()) 130369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 130469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 130569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Verify the old decl was also a variable. 130669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal VarDecl *Old = 0; 130769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!Previous.isSingleResult() || 130869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 130969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition_different_kind) 131069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 131169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Previous.getRepresentativeDecl()->getLocation(), 131269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::note_previous_definition); 131369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 131469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 131569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 131669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MergeAttributes(New, Old, Context); 131769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 131869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Merge the types 131969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal QualType MergedT; 132069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus) { 132169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Context.hasSameType(New->getType(), Old->getType())) 132269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MergedT = New->getType(); 132369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [basic.link]p10: 132469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // [...] the types specified by all declarations referring to a given 132569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // object or function shall be identical, except that declarations for an 132669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // array object can specify array types that differ by the presence or 132769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // absence of a major array bound (8.3.4). 132869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (Old->getType()->isIncompleteArrayType() && 132969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->getType()->isArrayType()) { 133069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CanQual<ArrayType> OldArray 133169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 133269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CanQual<ArrayType> NewArray 133369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 133469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldArray->getElementType() == NewArray->getElementType()) 133569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MergedT = New->getType(); 133669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (Old->getType()->isArrayType() && 133769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->getType()->isIncompleteArrayType()) { 133869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CanQual<ArrayType> OldArray 133969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 134069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal CanQual<ArrayType> NewArray 134169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 134269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (OldArray->getElementType() == NewArray->getElementType()) 134369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MergedT = Old->getType(); 134469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 134569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 134669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MergedT = Context.mergeTypes(New->getType(), Old->getType()); 134769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 134869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (MergedT.isNull()) { 134969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition_different_type) 135069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 135169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 135269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 135369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 135469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setType(MergedT); 135569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 135669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 135769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (New->getStorageClass() == VarDecl::Static && 135869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) { 135969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 136069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 136169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 136269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 136369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C99 6.2.2p4: 136469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // For an identifier declared with the storage-class specifier 136569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // extern in a scope in which a prior declaration of that 136669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // identifier is visible,23) if the prior declaration specifies 136769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // internal or external linkage, the linkage of the identifier at 136869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the later declaration is the same as the linkage specified at 136969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // the prior declaration. If no prior declaration is visible, or 137069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // if the prior declaration specifies no linkage, then the 137169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // identifier has external linkage. 137269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (New->hasExternalStorage() && Old->hasLinkage()) 137369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal /* Okay */; 137469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (New->getStorageClass() != VarDecl::Static && 137569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Old->getStorageClass() == VarDecl::Static) { 137669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 137769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 137869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 137969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 138069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 138169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 138269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 138369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: The test for external storage here seems wrong? We still 138469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // need to check for mismatches. 138569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!New->hasExternalStorage() && !New->isFileVarDecl() && 138669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Don't complain about out-of-line definitions of static members. 138769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !(Old->getLexicalDeclContext()->isRecord() && 138869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal !New->getLexicalDeclContext()->isRecord())) { 138969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 139069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 139169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return New->setInvalidDecl(); 139269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 139369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 139469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 139569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 139669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 139769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 139869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 139969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Old->getLocation(), diag::note_previous_definition); 140069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 140169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 140269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ doesn't have tentative definitions, so go right ahead and check here. 140369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const VarDecl *Def; 140469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus && 140569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->isThisDeclarationADefinition() == VarDecl::Definition && 140669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (Def = Old->getDefinition())) { 140769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(New->getLocation(), diag::err_redefinition) 140869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << New->getDeclName(); 140969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Def->getLocation(), diag::note_previous_definition); 141069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setInvalidDecl(); 141169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return; 141269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 141369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 141469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Keep a chain of previous declarations. 141569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setPreviousDeclaration(Old); 141669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 141769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Inherit access appropriately. 141869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal New->setAccess(Old->getAccess()); 141969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 142069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 142169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 142269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// no declarator (e.g. "struct foo;") is parsed. 142369e17611504376e4d4603925f8528dfc890fd2c6Luis SigalSema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 142469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Error on auto/register at file scope 142569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Error on inline/virtual/explicit 142669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Warn on useless __thread 142769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Warn on useless const/volatile 142869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Warn on useless static/extern/typedef/private_extern/mutable 142969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Warn on useless attributes 143069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Decl *TagD = 0; 143169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TagDecl *Tag = 0; 143269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (DS.getTypeSpecType() == DeclSpec::TST_class || 143369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.getTypeSpecType() == DeclSpec::TST_struct || 143469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.getTypeSpecType() == DeclSpec::TST_union || 143569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.getTypeSpecType() == DeclSpec::TST_enum) { 143669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TagD = static_cast<Decl *>(DS.getTypeRep()); 143769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 143869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!TagD) // We probably had an error 143969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclPtrTy(); 144069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 144169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Note that the above type specs guarantee that the 144269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // type rep is a Decl, whereas in many of the others 144369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // it's a Type. 144469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Tag = dyn_cast<TagDecl>(TagD); 144569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 144669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 144769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (unsigned TypeQuals = DS.getTypeQualifiers()) { 144869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 144969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // or incomplete types shall not be restrict-qualified." 145069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (TypeQuals & DeclSpec::TQ_restrict) 145169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(DS.getRestrictSpecLoc(), 145269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::err_typecheck_invalid_restrict_not_pointer_noarg) 145369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << DS.getSourceRange(); 145469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 145569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 145669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (DS.isFriendSpecified()) { 145769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If we're dealing with a class template decl, assume that the 145869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // template routines are handling it. 145969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (TagD && isa<ClassTemplateDecl>(TagD)) 146069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclPtrTy(); 146169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0)); 146269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 146369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 146469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 146569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // If there are attributes in the DeclSpec, apply them to the record. 146669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (const AttributeList *AL = DS.getAttributes()) 146769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal ProcessDeclAttributeList(S, Record, AL); 146869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 146969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!Record->getDeclName() && Record->isDefinition() && 147069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 147169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus || 147269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Record->getDeclContext()->isRecord()) 147369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return BuildAnonymousStructOrUnion(S, DS, Record); 147469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 147569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 147669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << DS.getSourceRange(); 147769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 147869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 147969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Microsoft allows unnamed struct/union fields. Don't complain 148069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // about them. 148169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // FIXME: Should we support Microsoft's extensions in this area? 148269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Record->getDeclName() && getLangOptions().Microsoft) 148369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclPtrTy::make(Tag); 148469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 148569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 148669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!DS.isMissingDeclaratorOk() && 148769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.getTypeSpecType() != DeclSpec::TST_error) { 148869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Warn about typedefs of enums without names, since this is an 148969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // extension in both Microsoft an GNU. 149069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 149169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Tag && isa<EnumDecl>(Tag)) { 149269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 149369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << DS.getSourceRange(); 149469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclPtrTy::make(Tag); 149569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 149669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 149769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators) 149869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << DS.getSourceRange(); 149969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 150069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 150169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return DeclPtrTy::make(Tag); 150269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 150369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 150469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// We are trying to inject an anonymous member into the given scope; 150569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// check if there's an existing declaration that can't be overloaded. 150669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 150769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// \return true if this is a forbidden redeclaration 150869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalstatic bool CheckAnonMemberRedeclaration(Sema &SemaRef, 150969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Scope *S, 151069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclContext *Owner, 151169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclarationName Name, 151269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SourceLocation NameLoc, 151369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal unsigned diagnostic) { 151469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 151569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Sema::ForRedeclaration); 151669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!SemaRef.LookupName(R, S)) return false; 151769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 151869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (R.getAsSingle<TagDecl>()) 151969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 152069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 152169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Pick a representative declaration. 152269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 152369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (PrevDecl && Owner->isRecord()) { 152469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal RecordDecl *Record = cast<RecordDecl>(Owner); 152569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!SemaRef.isDeclInScope(PrevDecl, Record, S)) 152669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return false; 152769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 152869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 152969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SemaRef.Diag(NameLoc, diagnostic) << Name; 153069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 153169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 153269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return true; 153369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 153469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 153569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// InjectAnonymousStructOrUnionMembers - Inject the members of the 153669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// anonymous struct or union AnonRecord into the owning context Owner 153769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// and scope S. This routine will be invoked just after we realize 153869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// that an unnamed union or struct is actually an anonymous union or 153969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// struct, e.g., 154069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 154169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// @code 154269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// union { 154369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// int i; 154469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// float f; 154569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 154669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// // f into the surrounding scope.x 154769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// @endcode 154869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// 154969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// This routine is recursive, injecting the names of nested anonymous 155069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// structs/unions into the owning context and scope as well. 155169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigalbool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner, 155269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal RecordDecl *AnonRecord) { 155369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal unsigned diagKind 155469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 155569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal : diag::err_anonymous_struct_member_redecl; 155669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 155769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal bool Invalid = false; 155869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (RecordDecl::field_iterator F = AnonRecord->field_begin(), 155969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal FEnd = AnonRecord->field_end(); 156069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal F != FEnd; ++F) { 156169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if ((*F)->getDeclName()) { 156269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(), 156369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (*F)->getLocation(), diagKind)) { 156469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.union]p2: 156569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The names of the members of an anonymous union shall be 156669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // distinct from the names of any other entity in the 156769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // scope in which the anonymous union is declared. 156869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 156969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 157069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.union]p2: 157169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // For the purpose of name lookup, after the anonymous union 157269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // definition, the members of the anonymous union are 157369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // considered to have been defined in the scope in which the 157469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // anonymous union is declared. 157569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Owner->makeDeclVisibleInContext(*F); 157669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal S->AddDecl(DeclPtrTy::make(*F)); 157769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal IdResolver.AddDecl(*F); 157869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 157969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (const RecordType *InnerRecordType 158069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal = (*F)->getType()->getAs<RecordType>()) { 158169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal RecordDecl *InnerRecord = InnerRecordType->getDecl(); 158269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (InnerRecord->isAnonymousStructOrUnion()) 158369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = Invalid || 158469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord); 158569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 158669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 158769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 158869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal return Invalid; 158969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal} 159069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 159169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// ActOnAnonymousStructOrUnion - Handle the declaration of an 159269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// anonymous structure or union. Anonymous unions are a C++ feature 159369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// (C++ [class.union]) and a GNU C extension; anonymous structures 159469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal/// are a GNU C and GNU C++ extension. 159569e17611504376e4d4603925f8528dfc890fd2c6Luis SigalSema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 159669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal RecordDecl *Record) { 159769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DeclContext *Owner = Record->getDeclContext(); 159869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 159969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Diagnose whether this anonymous struct/union is an extension. 160069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (Record->isUnion() && !getLangOptions().CPlusPlus) 160169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Record->getLocation(), diag::ext_anonymous_union); 160269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (!Record->isUnion()) 160369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Record->getLocation(), diag::ext_anonymous_struct); 160469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 160569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C and C++ require different kinds of checks for anonymous 160669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // structs/unions. 160769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal bool Invalid = false; 160869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (getLangOptions().CPlusPlus) { 160969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal const char* PrevSpec = 0; 161069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal unsigned DiagID; 161169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.union]p3: 161269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Anonymous unions declared in a named namespace or in the 161369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // global namespace shall be declared static. 161469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 161569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (isa<TranslationUnitDecl>(Owner) || 161669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal (isa<NamespaceDecl>(Owner) && 161769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal cast<NamespaceDecl>(Owner)->getDeclName()))) { 161869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 161969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 162069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 162169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Recover by adding 'static'. 162269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), 162369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PrevSpec, DiagID); 162469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 162569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.union]p3: 162669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // A storage class is not allowed in a declaration of an 162769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // anonymous union in a class scope. 162869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 162969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal isa<RecordDecl>(Owner)) { 163069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(DS.getStorageClassSpecLoc(), 163169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal diag::err_anonymous_union_with_storage_spec); 163269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 163369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 163469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Recover by removing the storage specifier. 163569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 163669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal PrevSpec, DiagID); 163769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 163869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 163969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.union]p2: 164069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // The member-specification of an anonymous union shall only 164169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // define non-static data members. [Note: nested types and 164269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // functions cannot be declared within an anonymous union. ] 164369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal for (DeclContext::decl_iterator Mem = Record->decls_begin(), 164469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MemEnd = Record->decls_end(); 164569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Mem != MemEnd; ++Mem) { 164669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 164769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // C++ [class.union]p3: 164869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // An anonymous union shall not have private or protected 164969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // members (clause 11). 165069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) { 165169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 165269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 165369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 165469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 165569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if ((*Mem)->isImplicit()) { 165669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Any implicit members are fine. 165769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 165869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // This is a type that showed up in an 165969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // elaborated-type-specifier inside the anonymous struct or 166069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // union, but which actually declares a type outside of the 166169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // anonymous struct or union. It's okay. 166269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 166369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!MemRecord->isAnonymousStructOrUnion() && 166469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal MemRecord->getDeclName()) { 166569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // This is a nested type declaration. 166669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 166769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (int)Record->isUnion(); 166869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 166969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 167069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } else { 167169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // We have something that isn't a non-static data 167269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // member. Complain about it. 167369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal unsigned DK = diag::err_anonymous_record_bad_member; 167469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (isa<TypeDecl>(*Mem)) 167569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DK = diag::err_anonymous_record_with_type; 167669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (isa<FunctionDecl>(*Mem)) 167769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DK = diag::err_anonymous_record_with_function; 167869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal else if (isa<VarDecl>(*Mem)) 167969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal DK = diag::err_anonymous_record_with_static; 168069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag((*Mem)->getLocation(), DK) 168169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (int)Record->isUnion(); 168269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 168369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 168469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 168569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 168669e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 168769e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal if (!Record->isUnion() && !Owner->isRecord()) { 168869e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 168969e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal << (int)getLangOptions().CPlusPlus; 169069e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Invalid = true; 169169e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal } 169269e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal 169369e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal // Mock up a declarator. 169469e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal Declarator Dc(DS, Declarator::TypeNameContext); 169569e17611504376e4d4603925f8528dfc890fd2c6Luis Sigal TypeSourceInfo *TInfo = 0; 1696 GetTypeForDeclarator(Dc, S, &TInfo); 1697 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 1698 1699 // Create a declaration for this anonymous struct/union. 1700 NamedDecl *Anon = 0; 1701 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 1702 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 1703 /*IdentifierInfo=*/0, 1704 Context.getTypeDeclType(Record), 1705 TInfo, 1706 /*BitWidth=*/0, /*Mutable=*/false); 1707 Anon->setAccess(AS_public); 1708 if (getLangOptions().CPlusPlus) 1709 FieldCollector->Add(cast<FieldDecl>(Anon)); 1710 } else { 1711 VarDecl::StorageClass SC; 1712 switch (DS.getStorageClassSpec()) { 1713 default: assert(0 && "Unknown storage class!"); 1714 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1715 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1716 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1717 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1718 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1719 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1720 case DeclSpec::SCS_mutable: 1721 // mutable can only appear on non-static class members, so it's always 1722 // an error here 1723 Diag(Record->getLocation(), diag::err_mutable_nonmember); 1724 Invalid = true; 1725 SC = VarDecl::None; 1726 break; 1727 } 1728 1729 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 1730 /*IdentifierInfo=*/0, 1731 Context.getTypeDeclType(Record), 1732 TInfo, 1733 SC); 1734 } 1735 Anon->setImplicit(); 1736 1737 // Add the anonymous struct/union object to the current 1738 // context. We'll be referencing this object when we refer to one of 1739 // its members. 1740 Owner->addDecl(Anon); 1741 1742 // Inject the members of the anonymous struct/union into the owning 1743 // context and into the identifier resolver chain for name lookup 1744 // purposes. 1745 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record)) 1746 Invalid = true; 1747 1748 // Mark this as an anonymous struct/union type. Note that we do not 1749 // do this until after we have already checked and injected the 1750 // members of this anonymous struct/union type, because otherwise 1751 // the members could be injected twice: once by DeclContext when it 1752 // builds its lookup table, and once by 1753 // InjectAnonymousStructOrUnionMembers. 1754 Record->setAnonymousStructOrUnion(true); 1755 1756 if (Invalid) 1757 Anon->setInvalidDecl(); 1758 1759 return DeclPtrTy::make(Anon); 1760} 1761 1762 1763/// GetNameForDeclarator - Determine the full declaration name for the 1764/// given Declarator. 1765DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 1766 return GetNameFromUnqualifiedId(D.getName()); 1767} 1768 1769/// \brief Retrieves the canonicalized name from a parsed unqualified-id. 1770DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 1771 switch (Name.getKind()) { 1772 case UnqualifiedId::IK_Identifier: 1773 return DeclarationName(Name.Identifier); 1774 1775 case UnqualifiedId::IK_OperatorFunctionId: 1776 return Context.DeclarationNames.getCXXOperatorName( 1777 Name.OperatorFunctionId.Operator); 1778 1779 case UnqualifiedId::IK_LiteralOperatorId: 1780 return Context.DeclarationNames.getCXXLiteralOperatorName( 1781 Name.Identifier); 1782 1783 case UnqualifiedId::IK_ConversionFunctionId: { 1784 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId); 1785 if (Ty.isNull()) 1786 return DeclarationName(); 1787 1788 return Context.DeclarationNames.getCXXConversionFunctionName( 1789 Context.getCanonicalType(Ty)); 1790 } 1791 1792 case UnqualifiedId::IK_ConstructorName: { 1793 QualType Ty = GetTypeFromParser(Name.ConstructorName); 1794 if (Ty.isNull()) 1795 return DeclarationName(); 1796 1797 return Context.DeclarationNames.getCXXConstructorName( 1798 Context.getCanonicalType(Ty)); 1799 } 1800 1801 case UnqualifiedId::IK_ConstructorTemplateId: { 1802 // In well-formed code, we can only have a constructor 1803 // template-id that refers to the current context, so go there 1804 // to find the actual type being constructed. 1805 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 1806 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 1807 return DeclarationName(); 1808 1809 // Determine the type of the class being constructed. 1810 QualType CurClassType = Context.getTypeDeclType(CurClass); 1811 1812 // FIXME: Check two things: that the template-id names the same type as 1813 // CurClassType, and that the template-id does not occur when the name 1814 // was qualified. 1815 1816 return Context.DeclarationNames.getCXXConstructorName( 1817 Context.getCanonicalType(CurClassType)); 1818 } 1819 1820 case UnqualifiedId::IK_DestructorName: { 1821 QualType Ty = GetTypeFromParser(Name.DestructorName); 1822 if (Ty.isNull()) 1823 return DeclarationName(); 1824 1825 return Context.DeclarationNames.getCXXDestructorName( 1826 Context.getCanonicalType(Ty)); 1827 } 1828 1829 case UnqualifiedId::IK_TemplateId: { 1830 TemplateName TName 1831 = TemplateName::getFromVoidPointer(Name.TemplateId->Template); 1832 return Context.getNameForTemplate(TName); 1833 } 1834 } 1835 1836 assert(false && "Unknown name kind"); 1837 return DeclarationName(); 1838} 1839 1840/// isNearlyMatchingFunction - Determine whether the C++ functions 1841/// Declaration and Definition are "nearly" matching. This heuristic 1842/// is used to improve diagnostics in the case where an out-of-line 1843/// function definition doesn't match any declaration within 1844/// the class or namespace. 1845static bool isNearlyMatchingFunction(ASTContext &Context, 1846 FunctionDecl *Declaration, 1847 FunctionDecl *Definition) { 1848 if (Declaration->param_size() != Definition->param_size()) 1849 return false; 1850 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 1851 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 1852 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 1853 1854 if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(), 1855 DefParamTy.getNonReferenceType())) 1856 return false; 1857 } 1858 1859 return true; 1860} 1861 1862Sema::DeclPtrTy 1863Sema::HandleDeclarator(Scope *S, Declarator &D, 1864 MultiTemplateParamsArg TemplateParamLists, 1865 bool IsFunctionDefinition) { 1866 DeclarationName Name = GetNameForDeclarator(D); 1867 1868 // All of these full declarators require an identifier. If it doesn't have 1869 // one, the ParsedFreeStandingDeclSpec action should be used. 1870 if (!Name) { 1871 if (!D.isInvalidType()) // Reject this if we think it is valid. 1872 Diag(D.getDeclSpec().getSourceRange().getBegin(), 1873 diag::err_declarator_need_ident) 1874 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 1875 return DeclPtrTy(); 1876 } 1877 1878 // The scope passed in may not be a decl scope. Zip up the scope tree until 1879 // we find one that is. 1880 while ((S->getFlags() & Scope::DeclScope) == 0 || 1881 (S->getFlags() & Scope::TemplateParamScope) != 0) 1882 S = S->getParent(); 1883 1884 // If this is an out-of-line definition of a member of a class template 1885 // or class template partial specialization, we may need to rebuild the 1886 // type specifier in the declarator. See RebuildTypeInCurrentInstantiation() 1887 // for more information. 1888 // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can 1889 // handle expressions properly. 1890 DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec()); 1891 if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() && 1892 isDependentScopeSpecifier(D.getCXXScopeSpec()) && 1893 (DS.getTypeSpecType() == DeclSpec::TST_typename || 1894 DS.getTypeSpecType() == DeclSpec::TST_typeofType || 1895 DS.getTypeSpecType() == DeclSpec::TST_typeofExpr || 1896 DS.getTypeSpecType() == DeclSpec::TST_decltype)) { 1897 if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) { 1898 // FIXME: Preserve type source info. 1899 QualType T = GetTypeFromParser(DS.getTypeRep()); 1900 1901 DeclContext *SavedContext = CurContext; 1902 CurContext = DC; 1903 T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name); 1904 CurContext = SavedContext; 1905 1906 if (T.isNull()) 1907 return DeclPtrTy(); 1908 DS.UpdateTypeRep(T.getAsOpaquePtr()); 1909 } 1910 } 1911 1912 DeclContext *DC; 1913 NamedDecl *New; 1914 1915 TypeSourceInfo *TInfo = 0; 1916 QualType R = GetTypeForDeclarator(D, S, &TInfo); 1917 1918 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 1919 ForRedeclaration); 1920 1921 // See if this is a redefinition of a variable in the same scope. 1922 if (D.getCXXScopeSpec().isInvalid()) { 1923 DC = CurContext; 1924 D.setInvalidType(); 1925 } else if (!D.getCXXScopeSpec().isSet()) { 1926 bool IsLinkageLookup = false; 1927 1928 // If the declaration we're planning to build will be a function 1929 // or object with linkage, then look for another declaration with 1930 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 1931 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1932 /* Do nothing*/; 1933 else if (R->isFunctionType()) { 1934 if (CurContext->isFunctionOrMethod() || 1935 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1936 IsLinkageLookup = true; 1937 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 1938 IsLinkageLookup = true; 1939 else if (CurContext->getLookupContext()->isTranslationUnit() && 1940 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 1941 IsLinkageLookup = true; 1942 1943 if (IsLinkageLookup) 1944 Previous.clear(LookupRedeclarationWithLinkage); 1945 1946 DC = CurContext; 1947 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 1948 } else { // Something like "int foo::x;" 1949 DC = computeDeclContext(D.getCXXScopeSpec(), true); 1950 1951 if (!DC) { 1952 // If we could not compute the declaration context, it's because the 1953 // declaration context is dependent but does not refer to a class, 1954 // class template, or class template partial specialization. Complain 1955 // and return early, to avoid the coming semantic disaster. 1956 Diag(D.getIdentifierLoc(), 1957 diag::err_template_qualified_declarator_no_match) 1958 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 1959 << D.getCXXScopeSpec().getRange(); 1960 return DeclPtrTy(); 1961 } 1962 1963 if (!DC->isDependentContext() && 1964 RequireCompleteDeclContext(D.getCXXScopeSpec())) 1965 return DeclPtrTy(); 1966 1967 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 1968 Diag(D.getIdentifierLoc(), 1969 diag::err_member_def_undefined_record) 1970 << Name << DC << D.getCXXScopeSpec().getRange(); 1971 D.setInvalidType(); 1972 } 1973 1974 LookupQualifiedName(Previous, DC); 1975 1976 // Don't consider using declarations as previous declarations for 1977 // out-of-line members. 1978 RemoveUsingDecls(Previous); 1979 1980 // C++ 7.3.1.2p2: 1981 // Members (including explicit specializations of templates) of a named 1982 // namespace can also be defined outside that namespace by explicit 1983 // qualification of the name being defined, provided that the entity being 1984 // defined was already declared in the namespace and the definition appears 1985 // after the point of declaration in a namespace that encloses the 1986 // declarations namespace. 1987 // 1988 // Note that we only check the context at this point. We don't yet 1989 // have enough information to make sure that PrevDecl is actually 1990 // the declaration we want to match. For example, given: 1991 // 1992 // class X { 1993 // void f(); 1994 // void f(float); 1995 // }; 1996 // 1997 // void X::f(int) { } // ill-formed 1998 // 1999 // In this case, PrevDecl will point to the overload set 2000 // containing the two f's declared in X, but neither of them 2001 // matches. 2002 2003 // First check whether we named the global scope. 2004 if (isa<TranslationUnitDecl>(DC)) { 2005 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope) 2006 << Name << D.getCXXScopeSpec().getRange(); 2007 } else { 2008 DeclContext *Cur = CurContext; 2009 while (isa<LinkageSpecDecl>(Cur)) 2010 Cur = Cur->getParent(); 2011 if (!Cur->Encloses(DC)) { 2012 // The qualifying scope doesn't enclose the original declaration. 2013 // Emit diagnostic based on current scope. 2014 SourceLocation L = D.getIdentifierLoc(); 2015 SourceRange R = D.getCXXScopeSpec().getRange(); 2016 if (isa<FunctionDecl>(Cur)) 2017 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 2018 else 2019 Diag(L, diag::err_invalid_declarator_scope) 2020 << Name << cast<NamedDecl>(DC) << R; 2021 D.setInvalidType(); 2022 } 2023 } 2024 } 2025 2026 if (Previous.isSingleResult() && 2027 Previous.getFoundDecl()->isTemplateParameter()) { 2028 // Maybe we will complain about the shadowed template parameter. 2029 if (!D.isInvalidType()) 2030 if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 2031 Previous.getFoundDecl())) 2032 D.setInvalidType(); 2033 2034 // Just pretend that we didn't see the previous declaration. 2035 Previous.clear(); 2036 } 2037 2038 // In C++, the previous declaration we find might be a tag type 2039 // (class or enum). In this case, the new declaration will hide the 2040 // tag type. Note that this does does not apply if we're declaring a 2041 // typedef (C++ [dcl.typedef]p4). 2042 if (Previous.isSingleTagDecl() && 2043 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 2044 Previous.clear(); 2045 2046 bool Redeclaration = false; 2047 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 2048 if (TemplateParamLists.size()) { 2049 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 2050 return DeclPtrTy(); 2051 } 2052 2053 New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration); 2054 } else if (R->isFunctionType()) { 2055 New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous, 2056 move(TemplateParamLists), 2057 IsFunctionDefinition, Redeclaration); 2058 } else { 2059 New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous, 2060 move(TemplateParamLists), 2061 Redeclaration); 2062 } 2063 2064 if (New == 0) 2065 return DeclPtrTy(); 2066 2067 // If this has an identifier and is not an invalid redeclaration or 2068 // function template specialization, add it to the scope stack. 2069 if (Name && !(Redeclaration && New->isInvalidDecl())) 2070 PushOnScopeChains(New, S); 2071 2072 return DeclPtrTy::make(New); 2073} 2074 2075/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 2076/// types into constant array types in certain situations which would otherwise 2077/// be errors (for GCC compatibility). 2078static QualType TryToFixInvalidVariablyModifiedType(QualType T, 2079 ASTContext &Context, 2080 bool &SizeIsNegative) { 2081 // This method tries to turn a variable array into a constant 2082 // array even when the size isn't an ICE. This is necessary 2083 // for compatibility with code that depends on gcc's buggy 2084 // constant expression folding, like struct {char x[(int)(char*)2];} 2085 SizeIsNegative = false; 2086 2087 QualifierCollector Qs; 2088 const Type *Ty = Qs.strip(T); 2089 2090 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 2091 QualType Pointee = PTy->getPointeeType(); 2092 QualType FixedType = 2093 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative); 2094 if (FixedType.isNull()) return FixedType; 2095 FixedType = Context.getPointerType(FixedType); 2096 return Qs.apply(FixedType); 2097 } 2098 2099 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 2100 if (!VLATy) 2101 return QualType(); 2102 // FIXME: We should probably handle this case 2103 if (VLATy->getElementType()->isVariablyModifiedType()) 2104 return QualType(); 2105 2106 Expr::EvalResult EvalResult; 2107 if (!VLATy->getSizeExpr() || 2108 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) || 2109 !EvalResult.Val.isInt()) 2110 return QualType(); 2111 2112 llvm::APSInt &Res = EvalResult.Val.getInt(); 2113 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) { 2114 // TODO: preserve the size expression in declarator info 2115 return Context.getConstantArrayType(VLATy->getElementType(), 2116 Res, ArrayType::Normal, 0); 2117 } 2118 2119 SizeIsNegative = true; 2120 return QualType(); 2121} 2122 2123/// \brief Register the given locally-scoped external C declaration so 2124/// that it can be found later for redeclarations 2125void 2126Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 2127 const LookupResult &Previous, 2128 Scope *S) { 2129 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 2130 "Decl is not a locally-scoped decl!"); 2131 // Note that we have a locally-scoped external with this name. 2132 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 2133 2134 if (!Previous.isSingleResult()) 2135 return; 2136 2137 NamedDecl *PrevDecl = Previous.getFoundDecl(); 2138 2139 // If there was a previous declaration of this variable, it may be 2140 // in our identifier chain. Update the identifier chain with the new 2141 // declaration. 2142 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 2143 // The previous declaration was found on the identifer resolver 2144 // chain, so remove it from its scope. 2145 while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl))) 2146 S = S->getParent(); 2147 2148 if (S) 2149 S->RemoveDecl(DeclPtrTy::make(PrevDecl)); 2150 } 2151} 2152 2153/// \brief Diagnose function specifiers on a declaration of an identifier that 2154/// does not identify a function. 2155void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 2156 // FIXME: We should probably indicate the identifier in question to avoid 2157 // confusion for constructs like "inline int a(), b;" 2158 if (D.getDeclSpec().isInlineSpecified()) 2159 Diag(D.getDeclSpec().getInlineSpecLoc(), 2160 diag::err_inline_non_function); 2161 2162 if (D.getDeclSpec().isVirtualSpecified()) 2163 Diag(D.getDeclSpec().getVirtualSpecLoc(), 2164 diag::err_virtual_non_function); 2165 2166 if (D.getDeclSpec().isExplicitSpecified()) 2167 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2168 diag::err_explicit_non_function); 2169} 2170 2171NamedDecl* 2172Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2173 QualType R, TypeSourceInfo *TInfo, 2174 LookupResult &Previous, bool &Redeclaration) { 2175 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 2176 if (D.getCXXScopeSpec().isSet()) { 2177 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 2178 << D.getCXXScopeSpec().getRange(); 2179 D.setInvalidType(); 2180 // Pretend we didn't see the scope specifier. 2181 DC = CurContext; 2182 Previous.clear(); 2183 } 2184 2185 if (getLangOptions().CPlusPlus) { 2186 // Check that there are no default arguments (C++ only). 2187 CheckExtraCXXDefaultArguments(D); 2188 } 2189 2190 DiagnoseFunctionSpecifiers(D); 2191 2192 if (D.getDeclSpec().isThreadSpecified()) 2193 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2194 2195 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo); 2196 if (!NewTD) return 0; 2197 2198 // Handle attributes prior to checking for duplicates in MergeVarDecl 2199 ProcessDeclAttributes(S, NewTD, D); 2200 2201 // Merge the decl with the existing one if appropriate. If the decl is 2202 // in an outer scope, it isn't the same thing. 2203 FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false); 2204 if (!Previous.empty()) { 2205 Redeclaration = true; 2206 MergeTypeDefDecl(NewTD, Previous); 2207 } 2208 2209 // C99 6.7.7p2: If a typedef name specifies a variably modified type 2210 // then it shall have block scope. 2211 QualType T = NewTD->getUnderlyingType(); 2212 if (T->isVariablyModifiedType()) { 2213 FunctionNeedsScopeChecking() = true; 2214 2215 if (S->getFnParent() == 0) { 2216 bool SizeIsNegative; 2217 QualType FixedTy = 2218 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 2219 if (!FixedTy.isNull()) { 2220 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size); 2221 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 2222 } else { 2223 if (SizeIsNegative) 2224 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size); 2225 else if (T->isVariableArrayType()) 2226 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 2227 else 2228 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 2229 NewTD->setInvalidDecl(); 2230 } 2231 } 2232 } 2233 2234 // If this is the C FILE type, notify the AST context. 2235 if (IdentifierInfo *II = NewTD->getIdentifier()) 2236 if (!NewTD->isInvalidDecl() && 2237 NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) { 2238 if (II->isStr("FILE")) 2239 Context.setFILEDecl(NewTD); 2240 else if (II->isStr("jmp_buf")) 2241 Context.setjmp_bufDecl(NewTD); 2242 else if (II->isStr("sigjmp_buf")) 2243 Context.setsigjmp_bufDecl(NewTD); 2244 } 2245 2246 return NewTD; 2247} 2248 2249/// \brief Determines whether the given declaration is an out-of-scope 2250/// previous declaration. 2251/// 2252/// This routine should be invoked when name lookup has found a 2253/// previous declaration (PrevDecl) that is not in the scope where a 2254/// new declaration by the same name is being introduced. If the new 2255/// declaration occurs in a local scope, previous declarations with 2256/// linkage may still be considered previous declarations (C99 2257/// 6.2.2p4-5, C++ [basic.link]p6). 2258/// 2259/// \param PrevDecl the previous declaration found by name 2260/// lookup 2261/// 2262/// \param DC the context in which the new declaration is being 2263/// declared. 2264/// 2265/// \returns true if PrevDecl is an out-of-scope previous declaration 2266/// for a new delcaration with the same name. 2267static bool 2268isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 2269 ASTContext &Context) { 2270 if (!PrevDecl) 2271 return 0; 2272 2273 if (!PrevDecl->hasLinkage()) 2274 return false; 2275 2276 if (Context.getLangOptions().CPlusPlus) { 2277 // C++ [basic.link]p6: 2278 // If there is a visible declaration of an entity with linkage 2279 // having the same name and type, ignoring entities declared 2280 // outside the innermost enclosing namespace scope, the block 2281 // scope declaration declares that same entity and receives the 2282 // linkage of the previous declaration. 2283 DeclContext *OuterContext = DC->getLookupContext(); 2284 if (!OuterContext->isFunctionOrMethod()) 2285 // This rule only applies to block-scope declarations. 2286 return false; 2287 else { 2288 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 2289 if (PrevOuterContext->isRecord()) 2290 // We found a member function: ignore it. 2291 return false; 2292 else { 2293 // Find the innermost enclosing namespace for the new and 2294 // previous declarations. 2295 while (!OuterContext->isFileContext()) 2296 OuterContext = OuterContext->getParent(); 2297 while (!PrevOuterContext->isFileContext()) 2298 PrevOuterContext = PrevOuterContext->getParent(); 2299 2300 // The previous declaration is in a different namespace, so it 2301 // isn't the same function. 2302 if (OuterContext->getPrimaryContext() != 2303 PrevOuterContext->getPrimaryContext()) 2304 return false; 2305 } 2306 } 2307 } 2308 2309 return true; 2310} 2311 2312static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 2313 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2314 if (!SS.isSet()) return; 2315 DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 2316 SS.getRange()); 2317} 2318 2319NamedDecl* 2320Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2321 QualType R, TypeSourceInfo *TInfo, 2322 LookupResult &Previous, 2323 MultiTemplateParamsArg TemplateParamLists, 2324 bool &Redeclaration) { 2325 DeclarationName Name = GetNameForDeclarator(D); 2326 2327 // Check that there are no default arguments (C++ only). 2328 if (getLangOptions().CPlusPlus) 2329 CheckExtraCXXDefaultArguments(D); 2330 2331 VarDecl *NewVD; 2332 VarDecl::StorageClass SC; 2333 switch (D.getDeclSpec().getStorageClassSpec()) { 2334 default: assert(0 && "Unknown storage class!"); 2335 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 2336 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 2337 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 2338 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 2339 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 2340 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 2341 case DeclSpec::SCS_mutable: 2342 // mutable can only appear on non-static class members, so it's always 2343 // an error here 2344 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 2345 D.setInvalidType(); 2346 SC = VarDecl::None; 2347 break; 2348 } 2349 2350 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2351 if (!II) { 2352 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 2353 << Name.getAsString(); 2354 return 0; 2355 } 2356 2357 DiagnoseFunctionSpecifiers(D); 2358 2359 if (!DC->isRecord() && S->getFnParent() == 0) { 2360 // C99 6.9p2: The storage-class specifiers auto and register shall not 2361 // appear in the declaration specifiers in an external declaration. 2362 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 2363 2364 // If this is a register variable with an asm label specified, then this 2365 // is a GNU extension. 2366 if (SC == VarDecl::Register && D.getAsmLabel()) 2367 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 2368 else 2369 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 2370 D.setInvalidType(); 2371 } 2372 } 2373 if (DC->isRecord() && !CurContext->isRecord()) { 2374 // This is an out-of-line definition of a static data member. 2375 if (SC == VarDecl::Static) { 2376 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2377 diag::err_static_out_of_line) 2378 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 2379 } else if (SC == VarDecl::None) 2380 SC = VarDecl::Static; 2381 } 2382 if (SC == VarDecl::Static) { 2383 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 2384 if (RD->isLocalClass()) 2385 Diag(D.getIdentifierLoc(), 2386 diag::err_static_data_member_not_allowed_in_local_class) 2387 << Name << RD->getDeclName(); 2388 } 2389 } 2390 2391 // Match up the template parameter lists with the scope specifier, then 2392 // determine whether we have a template or a template specialization. 2393 bool isExplicitSpecialization = false; 2394 if (TemplateParameterList *TemplateParams 2395 = MatchTemplateParametersToScopeSpecifier( 2396 D.getDeclSpec().getSourceRange().getBegin(), 2397 D.getCXXScopeSpec(), 2398 (TemplateParameterList**)TemplateParamLists.get(), 2399 TemplateParamLists.size(), 2400 /*never a friend*/ false, 2401 isExplicitSpecialization)) { 2402 if (TemplateParams->size() > 0) { 2403 // There is no such thing as a variable template. 2404 Diag(D.getIdentifierLoc(), diag::err_template_variable) 2405 << II 2406 << SourceRange(TemplateParams->getTemplateLoc(), 2407 TemplateParams->getRAngleLoc()); 2408 return 0; 2409 } else { 2410 // There is an extraneous 'template<>' for this variable. Complain 2411 // about it, but allow the declaration of the variable. 2412 Diag(TemplateParams->getTemplateLoc(), 2413 diag::err_template_variable_noparams) 2414 << II 2415 << SourceRange(TemplateParams->getTemplateLoc(), 2416 TemplateParams->getRAngleLoc()); 2417 2418 isExplicitSpecialization = true; 2419 } 2420 } 2421 2422 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 2423 II, R, TInfo, SC); 2424 2425 if (D.isInvalidType()) 2426 NewVD->setInvalidDecl(); 2427 2428 SetNestedNameSpecifier(NewVD, D); 2429 2430 if (D.getDeclSpec().isThreadSpecified()) { 2431 if (NewVD->hasLocalStorage()) 2432 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 2433 else if (!Context.Target.isTLSSupported()) 2434 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 2435 else 2436 NewVD->setThreadSpecified(true); 2437 } 2438 2439 // Set the lexical context. If the declarator has a C++ scope specifier, the 2440 // lexical context will be different from the semantic context. 2441 NewVD->setLexicalDeclContext(CurContext); 2442 2443 // Handle attributes prior to checking for duplicates in MergeVarDecl 2444 ProcessDeclAttributes(S, NewVD, D); 2445 2446 // Handle GNU asm-label extension (encoded as an attribute). 2447 if (Expr *E = (Expr*) D.getAsmLabel()) { 2448 // The parser guarantees this is a string. 2449 StringLiteral *SE = cast<StringLiteral>(E); 2450 NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString())); 2451 } 2452 2453 // Diagnose shadowed variables before filtering for scope. 2454 if (!D.getCXXScopeSpec().isSet()) 2455 CheckShadow(S, NewVD, Previous); 2456 2457 // Don't consider existing declarations that are in a different 2458 // scope and are out-of-semantic-context declarations (if the new 2459 // declaration has linkage). 2460 FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage()); 2461 2462 // Merge the decl with the existing one if appropriate. 2463 if (!Previous.empty()) { 2464 if (Previous.isSingleResult() && 2465 isa<FieldDecl>(Previous.getFoundDecl()) && 2466 D.getCXXScopeSpec().isSet()) { 2467 // The user tried to define a non-static data member 2468 // out-of-line (C++ [dcl.meaning]p1). 2469 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 2470 << D.getCXXScopeSpec().getRange(); 2471 Previous.clear(); 2472 NewVD->setInvalidDecl(); 2473 } 2474 } else if (D.getCXXScopeSpec().isSet()) { 2475 // No previous declaration in the qualifying scope. 2476 Diag(D.getIdentifierLoc(), diag::err_no_member) 2477 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 2478 << D.getCXXScopeSpec().getRange(); 2479 NewVD->setInvalidDecl(); 2480 } 2481 2482 CheckVariableDeclaration(NewVD, Previous, Redeclaration); 2483 2484 // This is an explicit specialization of a static data member. Check it. 2485 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 2486 CheckMemberSpecialization(NewVD, Previous)) 2487 NewVD->setInvalidDecl(); 2488 2489 // attributes declared post-definition are currently ignored 2490 if (Previous.isSingleResult()) { 2491 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl()); 2492 if (Def && (Def = Def->getDefinition()) && 2493 Def != NewVD && D.hasAttributes()) { 2494 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition); 2495 Diag(Def->getLocation(), diag::note_previous_definition); 2496 } 2497 } 2498 2499 // If this is a locally-scoped extern C variable, update the map of 2500 // such variables. 2501 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 2502 !NewVD->isInvalidDecl()) 2503 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 2504 2505 return NewVD; 2506} 2507 2508/// \brief Diagnose variable or built-in function shadowing. Implements 2509/// -Wshadow. 2510/// 2511/// This method is called whenever a VarDecl is added to a "useful" 2512/// scope. 2513/// 2514/// \param S the scope in which the shadowing name is being declared 2515/// \param R the lookup of the name 2516/// 2517void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 2518 // Return if warning is ignored. 2519 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored) 2520 return; 2521 2522 // Don't diagnose declarations at file scope. The scope might not 2523 // have a DeclContext if (e.g.) we're parsing a function prototype. 2524 DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity()); 2525 if (NewDC && NewDC->isFileContext()) 2526 return; 2527 2528 // Only diagnose if we're shadowing an unambiguous field or variable. 2529 if (R.getResultKind() != LookupResult::Found) 2530 return; 2531 2532 NamedDecl* ShadowedDecl = R.getFoundDecl(); 2533 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 2534 return; 2535 2536 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 2537 2538 // Only warn about certain kinds of shadowing for class members. 2539 if (NewDC && NewDC->isRecord()) { 2540 // In particular, don't warn about shadowing non-class members. 2541 if (!OldDC->isRecord()) 2542 return; 2543 2544 // TODO: should we warn about static data members shadowing 2545 // static data members from base classes? 2546 2547 // TODO: don't diagnose for inaccessible shadowed members. 2548 // This is hard to do perfectly because we might friend the 2549 // shadowing context, but that's just a false negative. 2550 } 2551 2552 // Determine what kind of declaration we're shadowing. 2553 unsigned Kind; 2554 if (isa<RecordDecl>(OldDC)) { 2555 if (isa<FieldDecl>(ShadowedDecl)) 2556 Kind = 3; // field 2557 else 2558 Kind = 2; // static data member 2559 } else if (OldDC->isFileContext()) 2560 Kind = 1; // global 2561 else 2562 Kind = 0; // local 2563 2564 DeclarationName Name = R.getLookupName(); 2565 2566 // Emit warning and note. 2567 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 2568 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 2569} 2570 2571/// \brief Check -Wshadow without the advantage of a previous lookup. 2572void Sema::CheckShadow(Scope *S, VarDecl *D) { 2573 LookupResult R(*this, D->getDeclName(), D->getLocation(), 2574 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 2575 LookupName(R, S); 2576 CheckShadow(S, D, R); 2577} 2578 2579/// \brief Perform semantic checking on a newly-created variable 2580/// declaration. 2581/// 2582/// This routine performs all of the type-checking required for a 2583/// variable declaration once it has been built. It is used both to 2584/// check variables after they have been parsed and their declarators 2585/// have been translated into a declaration, and to check variables 2586/// that have been instantiated from a template. 2587/// 2588/// Sets NewVD->isInvalidDecl() if an error was encountered. 2589void Sema::CheckVariableDeclaration(VarDecl *NewVD, 2590 LookupResult &Previous, 2591 bool &Redeclaration) { 2592 // If the decl is already known invalid, don't check it. 2593 if (NewVD->isInvalidDecl()) 2594 return; 2595 2596 QualType T = NewVD->getType(); 2597 2598 if (T->isObjCInterfaceType()) { 2599 Diag(NewVD->getLocation(), diag::err_statically_allocated_object); 2600 return NewVD->setInvalidDecl(); 2601 } 2602 2603 // Emit an error if an address space was applied to decl with local storage. 2604 // This includes arrays of objects with address space qualifiers, but not 2605 // automatic variables that point to other address spaces. 2606 // ISO/IEC TR 18037 S5.1.2 2607 if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) { 2608 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 2609 return NewVD->setInvalidDecl(); 2610 } 2611 2612 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 2613 && !NewVD->hasAttr<BlocksAttr>()) 2614 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 2615 2616 bool isVM = T->isVariablyModifiedType(); 2617 if (isVM || NewVD->hasAttr<CleanupAttr>() || 2618 NewVD->hasAttr<BlocksAttr>() || 2619 // FIXME: We need to diagnose jumps passed initialized variables in C++. 2620 // However, this turns on the scope checker for everything with a variable 2621 // which may impact compile time. See if we can find a better solution 2622 // to this, perhaps only checking functions that contain gotos in C++? 2623 (LangOpts.CPlusPlus && NewVD->hasLocalStorage())) 2624 FunctionNeedsScopeChecking() = true; 2625 2626 if ((isVM && NewVD->hasLinkage()) || 2627 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 2628 bool SizeIsNegative; 2629 QualType FixedTy = 2630 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative); 2631 2632 if (FixedTy.isNull() && T->isVariableArrayType()) { 2633 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 2634 // FIXME: This won't give the correct result for 2635 // int a[10][n]; 2636 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 2637 2638 if (NewVD->isFileVarDecl()) 2639 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 2640 << SizeRange; 2641 else if (NewVD->getStorageClass() == VarDecl::Static) 2642 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 2643 << SizeRange; 2644 else 2645 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 2646 << SizeRange; 2647 return NewVD->setInvalidDecl(); 2648 } 2649 2650 if (FixedTy.isNull()) { 2651 if (NewVD->isFileVarDecl()) 2652 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 2653 else 2654 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 2655 return NewVD->setInvalidDecl(); 2656 } 2657 2658 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 2659 NewVD->setType(FixedTy); 2660 } 2661 2662 if (Previous.empty() && NewVD->isExternC()) { 2663 // Since we did not find anything by this name and we're declaring 2664 // an extern "C" variable, look for a non-visible extern "C" 2665 // declaration with the same name. 2666 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 2667 = LocallyScopedExternalDecls.find(NewVD->getDeclName()); 2668 if (Pos != LocallyScopedExternalDecls.end()) 2669 Previous.addDecl(Pos->second); 2670 } 2671 2672 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 2673 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 2674 << T; 2675 return NewVD->setInvalidDecl(); 2676 } 2677 2678 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 2679 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 2680 return NewVD->setInvalidDecl(); 2681 } 2682 2683 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 2684 Diag(NewVD->getLocation(), diag::err_block_on_vm); 2685 return NewVD->setInvalidDecl(); 2686 } 2687 2688 if (!Previous.empty()) { 2689 Redeclaration = true; 2690 MergeVarDecl(NewVD, Previous); 2691 } 2692} 2693 2694/// \brief Data used with FindOverriddenMethod 2695struct FindOverriddenMethodData { 2696 Sema *S; 2697 CXXMethodDecl *Method; 2698}; 2699 2700/// \brief Member lookup function that determines whether a given C++ 2701/// method overrides a method in a base class, to be used with 2702/// CXXRecordDecl::lookupInBases(). 2703static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 2704 CXXBasePath &Path, 2705 void *UserData) { 2706 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 2707 2708 FindOverriddenMethodData *Data 2709 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 2710 2711 DeclarationName Name = Data->Method->getDeclName(); 2712 2713 // FIXME: Do we care about other names here too? 2714 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 2715 // We really want to find the base class constructor here. 2716 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 2717 CanQualType CT = Data->S->Context.getCanonicalType(T); 2718 2719 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 2720 } 2721 2722 for (Path.Decls = BaseRecord->lookup(Name); 2723 Path.Decls.first != Path.Decls.second; 2724 ++Path.Decls.first) { 2725 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) { 2726 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD)) 2727 return true; 2728 } 2729 } 2730 2731 return false; 2732} 2733 2734/// AddOverriddenMethods - See if a method overrides any in the base classes, 2735/// and if so, check that it's a valid override and remember it. 2736void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 2737 // Look for virtual methods in base classes that this method might override. 2738 CXXBasePaths Paths; 2739 FindOverriddenMethodData Data; 2740 Data.Method = MD; 2741 Data.S = this; 2742 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 2743 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 2744 E = Paths.found_decls_end(); I != E; ++I) { 2745 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 2746 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 2747 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 2748 !CheckOverridingFunctionAttributes(MD, OldMD)) 2749 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 2750 } 2751 } 2752 } 2753} 2754 2755NamedDecl* 2756Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2757 QualType R, TypeSourceInfo *TInfo, 2758 LookupResult &Previous, 2759 MultiTemplateParamsArg TemplateParamLists, 2760 bool IsFunctionDefinition, bool &Redeclaration) { 2761 assert(R.getTypePtr()->isFunctionType()); 2762 2763 DeclarationName Name = GetNameForDeclarator(D); 2764 FunctionDecl::StorageClass SC = FunctionDecl::None; 2765 switch (D.getDeclSpec().getStorageClassSpec()) { 2766 default: assert(0 && "Unknown storage class!"); 2767 case DeclSpec::SCS_auto: 2768 case DeclSpec::SCS_register: 2769 case DeclSpec::SCS_mutable: 2770 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2771 diag::err_typecheck_sclass_func); 2772 D.setInvalidType(); 2773 break; 2774 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 2775 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 2776 case DeclSpec::SCS_static: { 2777 if (CurContext->getLookupContext()->isFunctionOrMethod()) { 2778 // C99 6.7.1p5: 2779 // The declaration of an identifier for a function that has 2780 // block scope shall have no explicit storage-class specifier 2781 // other than extern 2782 // See also (C++ [dcl.stc]p4). 2783 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 2784 diag::err_static_block_func); 2785 SC = FunctionDecl::None; 2786 } else 2787 SC = FunctionDecl::Static; 2788 break; 2789 } 2790 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 2791 } 2792 2793 if (D.getDeclSpec().isThreadSpecified()) 2794 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2795 2796 bool isFriend = D.getDeclSpec().isFriendSpecified(); 2797 bool isInline = D.getDeclSpec().isInlineSpecified(); 2798 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2799 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 2800 2801 // Check that the return type is not an abstract class type. 2802 // For record types, this is done by the AbstractClassUsageDiagnoser once 2803 // the class has been completely parsed. 2804 if (!DC->isRecord() && 2805 RequireNonAbstractType(D.getIdentifierLoc(), 2806 R->getAs<FunctionType>()->getResultType(), 2807 diag::err_abstract_type_in_decl, 2808 AbstractReturnType)) 2809 D.setInvalidType(); 2810 2811 // Do not allow returning a objc interface by-value. 2812 if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) { 2813 Diag(D.getIdentifierLoc(), 2814 diag::err_object_cannot_be_passed_returned_by_value) << 0 2815 << R->getAs<FunctionType>()->getResultType(); 2816 D.setInvalidType(); 2817 } 2818 2819 bool isVirtualOkay = false; 2820 FunctionDecl *NewFD; 2821 2822 if (isFriend) { 2823 // C++ [class.friend]p5 2824 // A function can be defined in a friend declaration of a 2825 // class . . . . Such a function is implicitly inline. 2826 isInline |= IsFunctionDefinition; 2827 } 2828 2829 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 2830 // This is a C++ constructor declaration. 2831 assert(DC->isRecord() && 2832 "Constructors can only be declared in a member context"); 2833 2834 R = CheckConstructorDeclarator(D, R, SC); 2835 2836 // Create the new declaration 2837 NewFD = CXXConstructorDecl::Create(Context, 2838 cast<CXXRecordDecl>(DC), 2839 D.getIdentifierLoc(), Name, R, TInfo, 2840 isExplicit, isInline, 2841 /*isImplicitlyDeclared=*/false); 2842 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 2843 // This is a C++ destructor declaration. 2844 if (DC->isRecord()) { 2845 R = CheckDestructorDeclarator(D, SC); 2846 2847 NewFD = CXXDestructorDecl::Create(Context, 2848 cast<CXXRecordDecl>(DC), 2849 D.getIdentifierLoc(), Name, R, 2850 isInline, 2851 /*isImplicitlyDeclared=*/false); 2852 NewFD->setTypeSourceInfo(TInfo); 2853 2854 isVirtualOkay = true; 2855 } else { 2856 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 2857 2858 // Create a FunctionDecl to satisfy the function definition parsing 2859 // code path. 2860 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 2861 Name, R, TInfo, SC, isInline, 2862 /*hasPrototype=*/true); 2863 D.setInvalidType(); 2864 } 2865 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2866 if (!DC->isRecord()) { 2867 Diag(D.getIdentifierLoc(), 2868 diag::err_conv_function_not_member); 2869 return 0; 2870 } 2871 2872 CheckConversionDeclarator(D, R, SC); 2873 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 2874 D.getIdentifierLoc(), Name, R, TInfo, 2875 isInline, isExplicit); 2876 2877 isVirtualOkay = true; 2878 } else if (DC->isRecord()) { 2879 // If the of the function is the same as the name of the record, then this 2880 // must be an invalid constructor that has a return type. 2881 // (The parser checks for a return type and makes the declarator a 2882 // constructor if it has no return type). 2883 // must have an invalid constructor that has a return type 2884 if (Name.getAsIdentifierInfo() && 2885 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 2886 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 2887 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2888 << SourceRange(D.getIdentifierLoc()); 2889 return 0; 2890 } 2891 2892 bool isStatic = SC == FunctionDecl::Static; 2893 2894 // [class.free]p1: 2895 // Any allocation function for a class T is a static member 2896 // (even if not explicitly declared static). 2897 if (Name.getCXXOverloadedOperator() == OO_New || 2898 Name.getCXXOverloadedOperator() == OO_Array_New) 2899 isStatic = true; 2900 2901 // [class.free]p6 Any deallocation function for a class X is a static member 2902 // (even if not explicitly declared static). 2903 if (Name.getCXXOverloadedOperator() == OO_Delete || 2904 Name.getCXXOverloadedOperator() == OO_Array_Delete) 2905 isStatic = true; 2906 2907 // This is a C++ method declaration. 2908 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 2909 D.getIdentifierLoc(), Name, R, TInfo, 2910 isStatic, isInline); 2911 2912 isVirtualOkay = !isStatic; 2913 } else { 2914 // Determine whether the function was written with a 2915 // prototype. This true when: 2916 // - we're in C++ (where every function has a prototype), 2917 // - there is a prototype in the declarator, or 2918 // - the type R of the function is some kind of typedef or other reference 2919 // to a type name (which eventually refers to a function type). 2920 bool HasPrototype = 2921 getLangOptions().CPlusPlus || 2922 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) || 2923 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 2924 2925 NewFD = FunctionDecl::Create(Context, DC, 2926 D.getIdentifierLoc(), 2927 Name, R, TInfo, SC, isInline, HasPrototype); 2928 } 2929 2930 if (D.isInvalidType()) 2931 NewFD->setInvalidDecl(); 2932 2933 SetNestedNameSpecifier(NewFD, D); 2934 2935 // Set the lexical context. If the declarator has a C++ 2936 // scope specifier, or is the object of a friend declaration, the 2937 // lexical context will be different from the semantic context. 2938 NewFD->setLexicalDeclContext(CurContext); 2939 2940 // Match up the template parameter lists with the scope specifier, then 2941 // determine whether we have a template or a template specialization. 2942 FunctionTemplateDecl *FunctionTemplate = 0; 2943 bool isExplicitSpecialization = false; 2944 bool isFunctionTemplateSpecialization = false; 2945 if (TemplateParameterList *TemplateParams 2946 = MatchTemplateParametersToScopeSpecifier( 2947 D.getDeclSpec().getSourceRange().getBegin(), 2948 D.getCXXScopeSpec(), 2949 (TemplateParameterList**)TemplateParamLists.get(), 2950 TemplateParamLists.size(), 2951 isFriend, 2952 isExplicitSpecialization)) { 2953 if (TemplateParams->size() > 0) { 2954 // This is a function template 2955 2956 // Check that we can declare a template here. 2957 if (CheckTemplateDeclScope(S, TemplateParams)) 2958 return 0; 2959 2960 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 2961 NewFD->getLocation(), 2962 Name, TemplateParams, 2963 NewFD); 2964 FunctionTemplate->setLexicalDeclContext(CurContext); 2965 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 2966 } else { 2967 // This is a function template specialization. 2968 isFunctionTemplateSpecialization = true; 2969 2970 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 2971 if (isFriend && isFunctionTemplateSpecialization) { 2972 // We want to remove the "template<>", found here. 2973 SourceRange RemoveRange = TemplateParams->getSourceRange(); 2974 2975 // If we remove the template<> and the name is not a 2976 // template-id, we're actually silently creating a problem: 2977 // the friend declaration will refer to an untemplated decl, 2978 // and clearly the user wants a template specialization. So 2979 // we need to insert '<>' after the name. 2980 SourceLocation InsertLoc; 2981 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 2982 InsertLoc = D.getName().getSourceRange().getEnd(); 2983 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 2984 } 2985 2986 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 2987 << Name << RemoveRange 2988 << FixItHint::CreateRemoval(RemoveRange) 2989 << FixItHint::CreateInsertion(InsertLoc, "<>"); 2990 } 2991 } 2992 2993 // FIXME: Free this memory properly. 2994 TemplateParamLists.release(); 2995 } 2996 2997 // C++ [dcl.fct.spec]p5: 2998 // The virtual specifier shall only be used in declarations of 2999 // nonstatic class member functions that appear within a 3000 // member-specification of a class declaration; see 10.3. 3001 // 3002 if (isVirtual && !NewFD->isInvalidDecl()) { 3003 if (!isVirtualOkay) { 3004 Diag(D.getDeclSpec().getVirtualSpecLoc(), 3005 diag::err_virtual_non_function); 3006 } else if (!CurContext->isRecord()) { 3007 // 'virtual' was specified outside of the class. 3008 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class) 3009 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 3010 } else { 3011 // Okay: Add virtual to the method. 3012 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC); 3013 CurClass->setMethodAsVirtual(NewFD); 3014 } 3015 } 3016 3017 // C++ [dcl.fct.spec]p6: 3018 // The explicit specifier shall be used only in the declaration of a 3019 // constructor or conversion function within its class definition; see 12.3.1 3020 // and 12.3.2. 3021 if (isExplicit && !NewFD->isInvalidDecl()) { 3022 if (!CurContext->isRecord()) { 3023 // 'explicit' was specified outside of the class. 3024 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3025 diag::err_explicit_out_of_class) 3026 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 3027 } else if (!isa<CXXConstructorDecl>(NewFD) && 3028 !isa<CXXConversionDecl>(NewFD)) { 3029 // 'explicit' was specified on a function that wasn't a constructor 3030 // or conversion function. 3031 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3032 diag::err_explicit_non_ctor_or_conv_function) 3033 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 3034 } 3035 } 3036 3037 // Filter out previous declarations that don't match the scope. 3038 FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage()); 3039 3040 if (isFriend) { 3041 // DC is the namespace in which the function is being declared. 3042 assert((DC->isFileContext() || !Previous.empty()) && 3043 "previously-undeclared friend function being created " 3044 "in a non-namespace context"); 3045 3046 // For now, claim that the objects have no previous declaration. 3047 if (FunctionTemplate) { 3048 FunctionTemplate->setObjectOfFriendDecl(false); 3049 FunctionTemplate->setAccess(AS_public); 3050 } 3051 NewFD->setObjectOfFriendDecl(false); 3052 NewFD->setAccess(AS_public); 3053 } 3054 3055 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) && 3056 !CurContext->isRecord()) { 3057 // C++ [class.static]p1: 3058 // A data or function member of a class may be declared static 3059 // in a class definition, in which case it is a static member of 3060 // the class. 3061 3062 // Complain about the 'static' specifier if it's on an out-of-line 3063 // member function definition. 3064 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 3065 diag::err_static_out_of_line) 3066 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3067 } 3068 3069 // Handle GNU asm-label extension (encoded as an attribute). 3070 if (Expr *E = (Expr*) D.getAsmLabel()) { 3071 // The parser guarantees this is a string. 3072 StringLiteral *SE = cast<StringLiteral>(E); 3073 NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString())); 3074 } 3075 3076 // Copy the parameter declarations from the declarator D to the function 3077 // declaration NewFD, if they are available. First scavenge them into Params. 3078 llvm::SmallVector<ParmVarDecl*, 16> Params; 3079 if (D.getNumTypeObjects() > 0) { 3080 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3081 3082 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 3083 // function that takes no arguments, not a function that takes a 3084 // single void argument. 3085 // We let through "const void" here because Sema::GetTypeForDeclarator 3086 // already checks for that case. 3087 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3088 FTI.ArgInfo[0].Param && 3089 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) { 3090 // Empty arg list, don't push any params. 3091 ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>(); 3092 3093 // In C++, the empty parameter-type-list must be spelled "void"; a 3094 // typedef of void is not permitted. 3095 if (getLangOptions().CPlusPlus && 3096 Param->getType().getUnqualifiedType() != Context.VoidTy) 3097 Diag(Param->getLocation(), diag::err_param_typedef_of_void); 3098 // FIXME: Leaks decl? 3099 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 3100 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 3101 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 3102 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 3103 Param->setDeclContext(NewFD); 3104 Params.push_back(Param); 3105 3106 if (Param->isInvalidDecl()) 3107 NewFD->setInvalidDecl(); 3108 } 3109 } 3110 3111 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 3112 // When we're declaring a function with a typedef, typeof, etc as in the 3113 // following example, we'll need to synthesize (unnamed) 3114 // parameters for use in the declaration. 3115 // 3116 // @code 3117 // typedef void fn(int); 3118 // fn f; 3119 // @endcode 3120 3121 // Synthesize a parameter for each argument type. 3122 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 3123 AE = FT->arg_type_end(); AI != AE; ++AI) { 3124 ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD, 3125 SourceLocation(), 0, 3126 *AI, /*TInfo=*/0, 3127 VarDecl::None, 0); 3128 Param->setImplicit(); 3129 Params.push_back(Param); 3130 } 3131 } else { 3132 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 3133 "Should not need args for typedef of non-prototype fn"); 3134 } 3135 // Finally, we know we have the right number of parameters, install them. 3136 NewFD->setParams(Params.data(), Params.size()); 3137 3138 // If the declarator is a template-id, translate the parser's template 3139 // argument list into our AST format. 3140 bool HasExplicitTemplateArgs = false; 3141 TemplateArgumentListInfo TemplateArgs; 3142 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 3143 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 3144 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 3145 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 3146 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3147 TemplateId->getTemplateArgs(), 3148 TemplateId->NumArgs); 3149 translateTemplateArguments(TemplateArgsPtr, 3150 TemplateArgs); 3151 TemplateArgsPtr.release(); 3152 3153 HasExplicitTemplateArgs = true; 3154 3155 if (FunctionTemplate) { 3156 // FIXME: Diagnose function template with explicit template 3157 // arguments. 3158 HasExplicitTemplateArgs = false; 3159 } else if (!isFunctionTemplateSpecialization && 3160 !D.getDeclSpec().isFriendSpecified()) { 3161 // We have encountered something that the user meant to be a 3162 // specialization (because it has explicitly-specified template 3163 // arguments) but that was not introduced with a "template<>" (or had 3164 // too few of them). 3165 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 3166 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 3167 << FixItHint::CreateInsertion( 3168 D.getDeclSpec().getSourceRange().getBegin(), 3169 "template<> "); 3170 isFunctionTemplateSpecialization = true; 3171 } else { 3172 // "friend void foo<>(int);" is an implicit specialization decl. 3173 isFunctionTemplateSpecialization = true; 3174 } 3175 } else if (isFriend && isFunctionTemplateSpecialization) { 3176 // This combination is only possible in a recovery case; the user 3177 // wrote something like: 3178 // template <> friend void foo(int); 3179 // which we're recovering from as if the user had written: 3180 // friend void foo<>(int); 3181 // Go ahead and fake up a template id. 3182 HasExplicitTemplateArgs = true; 3183 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 3184 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 3185 } 3186 3187 // If it's a friend (and only if it's a friend), it's possible 3188 // that either the specialized function type or the specialized 3189 // template is dependent, and therefore matching will fail. In 3190 // this case, don't check the specialization yet. 3191 if (isFunctionTemplateSpecialization && isFriend && 3192 (NewFD->getType()->isDependentType() || DC->isDependentContext())) { 3193 assert(HasExplicitTemplateArgs && 3194 "friend function specialization without template args"); 3195 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 3196 Previous)) 3197 NewFD->setInvalidDecl(); 3198 } else if (isFunctionTemplateSpecialization) { 3199 if (CheckFunctionTemplateSpecialization(NewFD, 3200 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 3201 Previous)) 3202 NewFD->setInvalidDecl(); 3203 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 3204 if (CheckMemberSpecialization(NewFD, Previous)) 3205 NewFD->setInvalidDecl(); 3206 } 3207 3208 // Perform semantic checking on the function declaration. 3209 bool OverloadableAttrRequired = false; // FIXME: HACK! 3210 CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization, 3211 Redeclaration, /*FIXME:*/OverloadableAttrRequired); 3212 3213 assert((NewFD->isInvalidDecl() || !Redeclaration || 3214 Previous.getResultKind() != LookupResult::FoundOverloaded) && 3215 "previous declaration set still overloaded"); 3216 3217 if (isFriend && Redeclaration) { 3218 AccessSpecifier Access = AS_public; 3219 if (!NewFD->isInvalidDecl()) 3220 Access = NewFD->getPreviousDeclaration()->getAccess(); 3221 3222 if (FunctionTemplate) { 3223 FunctionTemplate->setObjectOfFriendDecl(true); 3224 FunctionTemplate->setAccess(Access); 3225 } else { 3226 NewFD->setObjectOfFriendDecl(true); 3227 } 3228 NewFD->setAccess(Access); 3229 } 3230 3231 // If we have a function template, check the template parameter 3232 // list. This will check and merge default template arguments. 3233 if (FunctionTemplate) { 3234 FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration(); 3235 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 3236 PrevTemplate? PrevTemplate->getTemplateParameters() : 0, 3237 D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate 3238 : TPC_FunctionTemplate); 3239 } 3240 3241 if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) { 3242 // Fake up an access specifier if it's supposed to be a class member. 3243 if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext())) 3244 NewFD->setAccess(AS_public); 3245 3246 // An out-of-line member function declaration must also be a 3247 // definition (C++ [dcl.meaning]p1). 3248 // Note that this is not the case for explicit specializations of 3249 // function templates or member functions of class templates, per 3250 // C++ [temp.expl.spec]p2. 3251 if (!IsFunctionDefinition && !isFriend && 3252 !isFunctionTemplateSpecialization && !isExplicitSpecialization) { 3253 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration) 3254 << D.getCXXScopeSpec().getRange(); 3255 NewFD->setInvalidDecl(); 3256 } else if (!Redeclaration && 3257 !(isFriend && CurContext->isDependentContext())) { 3258 // The user tried to provide an out-of-line definition for a 3259 // function that is a member of a class or namespace, but there 3260 // was no such member function declared (C++ [class.mfct]p2, 3261 // C++ [namespace.memdef]p2). For example: 3262 // 3263 // class X { 3264 // void f() const; 3265 // }; 3266 // 3267 // void X::f() { } // ill-formed 3268 // 3269 // Complain about this problem, and attempt to suggest close 3270 // matches (e.g., those that differ only in cv-qualifiers and 3271 // whether the parameter types are references). 3272 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 3273 << Name << DC << D.getCXXScopeSpec().getRange(); 3274 NewFD->setInvalidDecl(); 3275 3276 LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 3277 ForRedeclaration); 3278 LookupQualifiedName(Prev, DC); 3279 assert(!Prev.isAmbiguous() && 3280 "Cannot have an ambiguity in previous-declaration lookup"); 3281 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 3282 Func != FuncEnd; ++Func) { 3283 if (isa<FunctionDecl>(*Func) && 3284 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD)) 3285 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 3286 } 3287 } 3288 } 3289 3290 // Handle attributes. We need to have merged decls when handling attributes 3291 // (for example to check for conflicts, etc). 3292 // FIXME: This needs to happen before we merge declarations. Then, 3293 // let attribute merging cope with attribute conflicts. 3294 ProcessDeclAttributes(S, NewFD, D); 3295 3296 // attributes declared post-definition are currently ignored 3297 if (Redeclaration && Previous.isSingleResult()) { 3298 const FunctionDecl *Def; 3299 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl()); 3300 if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) { 3301 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition); 3302 Diag(Def->getLocation(), diag::note_previous_definition); 3303 } 3304 } 3305 3306 AddKnownFunctionAttributes(NewFD); 3307 3308 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) { 3309 // If a function name is overloadable in C, then every function 3310 // with that name must be marked "overloadable". 3311 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 3312 << Redeclaration << NewFD; 3313 if (!Previous.empty()) 3314 Diag(Previous.getRepresentativeDecl()->getLocation(), 3315 diag::note_attribute_overloadable_prev_overload); 3316 NewFD->addAttr(::new (Context) OverloadableAttr()); 3317 } 3318 3319 // If this is a locally-scoped extern C function, update the 3320 // map of such names. 3321 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 3322 && !NewFD->isInvalidDecl()) 3323 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 3324 3325 // Set this FunctionDecl's range up to the right paren. 3326 NewFD->setLocEnd(D.getSourceRange().getEnd()); 3327 3328 if (FunctionTemplate && NewFD->isInvalidDecl()) 3329 FunctionTemplate->setInvalidDecl(); 3330 3331 if (FunctionTemplate) 3332 return FunctionTemplate; 3333 3334 3335 // Keep track of static, non-inlined function definitions that 3336 // have not been used. We will warn later. 3337 // FIXME: Also include static functions declared but not defined. 3338 if (!NewFD->isInvalidDecl() && IsFunctionDefinition 3339 && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage 3340 && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>() 3341 && !NewFD->hasAttr<ConstructorAttr>() 3342 && !NewFD->hasAttr<DestructorAttr>()) 3343 UnusedStaticFuncs.push_back(NewFD); 3344 3345 return NewFD; 3346} 3347 3348/// \brief Perform semantic checking of a new function declaration. 3349/// 3350/// Performs semantic analysis of the new function declaration 3351/// NewFD. This routine performs all semantic checking that does not 3352/// require the actual declarator involved in the declaration, and is 3353/// used both for the declaration of functions as they are parsed 3354/// (called via ActOnDeclarator) and for the declaration of functions 3355/// that have been instantiated via C++ template instantiation (called 3356/// via InstantiateDecl). 3357/// 3358/// \param IsExplicitSpecialiation whether this new function declaration is 3359/// an explicit specialization of the previous declaration. 3360/// 3361/// This sets NewFD->isInvalidDecl() to true if there was an error. 3362void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 3363 LookupResult &Previous, 3364 bool IsExplicitSpecialization, 3365 bool &Redeclaration, 3366 bool &OverloadableAttrRequired) { 3367 // If NewFD is already known erroneous, don't do any of this checking. 3368 if (NewFD->isInvalidDecl()) 3369 return; 3370 3371 if (NewFD->getResultType()->isVariablyModifiedType()) { 3372 // Functions returning a variably modified type violate C99 6.7.5.2p2 3373 // because all functions have linkage. 3374 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 3375 return NewFD->setInvalidDecl(); 3376 } 3377 3378 if (NewFD->isMain()) 3379 CheckMain(NewFD); 3380 3381 // Check for a previous declaration of this name. 3382 if (Previous.empty() && NewFD->isExternC()) { 3383 // Since we did not find anything by this name and we're declaring 3384 // an extern "C" function, look for a non-visible extern "C" 3385 // declaration with the same name. 3386 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 3387 = LocallyScopedExternalDecls.find(NewFD->getDeclName()); 3388 if (Pos != LocallyScopedExternalDecls.end()) 3389 Previous.addDecl(Pos->second); 3390 } 3391 3392 // Merge or overload the declaration with an existing declaration of 3393 // the same name, if appropriate. 3394 if (!Previous.empty()) { 3395 // Determine whether NewFD is an overload of PrevDecl or 3396 // a declaration that requires merging. If it's an overload, 3397 // there's no more work to do here; we'll just add the new 3398 // function to the scope. 3399 3400 NamedDecl *OldDecl = 0; 3401 if (!AllowOverloadingOfFunction(Previous, Context)) { 3402 Redeclaration = true; 3403 OldDecl = Previous.getFoundDecl(); 3404 } else { 3405 if (!getLangOptions().CPlusPlus) { 3406 OverloadableAttrRequired = true; 3407 3408 // Functions marked "overloadable" must have a prototype (that 3409 // we can't get through declaration merging). 3410 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 3411 Diag(NewFD->getLocation(), 3412 diag::err_attribute_overloadable_no_prototype) 3413 << NewFD; 3414 Redeclaration = true; 3415 3416 // Turn this into a variadic function with no parameters. 3417 QualType R = Context.getFunctionType( 3418 NewFD->getType()->getAs<FunctionType>()->getResultType(), 3419 0, 0, true, 0, false, false, 0, 0, 3420 FunctionType::ExtInfo()); 3421 NewFD->setType(R); 3422 return NewFD->setInvalidDecl(); 3423 } 3424 } 3425 3426 switch (CheckOverload(NewFD, Previous, OldDecl)) { 3427 case Ovl_Match: 3428 Redeclaration = true; 3429 if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) { 3430 HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl)); 3431 Redeclaration = false; 3432 } 3433 break; 3434 3435 case Ovl_NonFunction: 3436 Redeclaration = true; 3437 break; 3438 3439 case Ovl_Overload: 3440 Redeclaration = false; 3441 break; 3442 } 3443 } 3444 3445 if (Redeclaration) { 3446 // NewFD and OldDecl represent declarations that need to be 3447 // merged. 3448 if (MergeFunctionDecl(NewFD, OldDecl)) 3449 return NewFD->setInvalidDecl(); 3450 3451 Previous.clear(); 3452 Previous.addDecl(OldDecl); 3453 3454 if (FunctionTemplateDecl *OldTemplateDecl 3455 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 3456 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 3457 FunctionTemplateDecl *NewTemplateDecl 3458 = NewFD->getDescribedFunctionTemplate(); 3459 assert(NewTemplateDecl && "Template/non-template mismatch"); 3460 if (CXXMethodDecl *Method 3461 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 3462 Method->setAccess(OldTemplateDecl->getAccess()); 3463 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 3464 } 3465 3466 // If this is an explicit specialization of a member that is a function 3467 // template, mark it as a member specialization. 3468 if (IsExplicitSpecialization && 3469 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 3470 NewTemplateDecl->setMemberSpecialization(); 3471 assert(OldTemplateDecl->isMemberSpecialization()); 3472 } 3473 } else { 3474 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 3475 NewFD->setAccess(OldDecl->getAccess()); 3476 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 3477 } 3478 } 3479 } 3480 3481 // Semantic checking for this function declaration (in isolation). 3482 if (getLangOptions().CPlusPlus) { 3483 // C++-specific checks. 3484 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 3485 CheckConstructor(Constructor); 3486 } else if (CXXDestructorDecl *Destructor = 3487 dyn_cast<CXXDestructorDecl>(NewFD)) { 3488 CXXRecordDecl *Record = Destructor->getParent(); 3489 QualType ClassType = Context.getTypeDeclType(Record); 3490 3491 // FIXME: Shouldn't we be able to perform thisc heck even when the class 3492 // type is dependent? Both gcc and edg can handle that. 3493 if (!ClassType->isDependentType()) { 3494 DeclarationName Name 3495 = Context.DeclarationNames.getCXXDestructorName( 3496 Context.getCanonicalType(ClassType)); 3497 if (NewFD->getDeclName() != Name) { 3498 Diag(NewFD->getLocation(), diag::err_destructor_name); 3499 return NewFD->setInvalidDecl(); 3500 } 3501 } 3502 3503 Record->setUserDeclaredDestructor(true); 3504 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 3505 // user-defined destructor. 3506 Record->setPOD(false); 3507 3508 // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly- 3509 // declared destructor. 3510 // FIXME: C++0x: don't do this for "= default" destructors 3511 Record->setHasTrivialDestructor(false); 3512 } else if (CXXConversionDecl *Conversion 3513 = dyn_cast<CXXConversionDecl>(NewFD)) { 3514 ActOnConversionDeclarator(Conversion); 3515 } 3516 3517 // Find any virtual functions that this function overrides. 3518 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 3519 if (!Method->isFunctionTemplateSpecialization() && 3520 !Method->getDescribedFunctionTemplate()) 3521 AddOverriddenMethods(Method->getParent(), Method); 3522 } 3523 3524 // Additional checks for the destructor; make sure we do this after we 3525 // figure out whether the destructor is virtual. 3526 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD)) 3527 if (!Destructor->getParent()->isDependentType()) 3528 CheckDestructor(Destructor); 3529 3530 // Extra checking for C++ overloaded operators (C++ [over.oper]). 3531 if (NewFD->isOverloadedOperator() && 3532 CheckOverloadedOperatorDeclaration(NewFD)) 3533 return NewFD->setInvalidDecl(); 3534 3535 // Extra checking for C++0x literal operators (C++0x [over.literal]). 3536 if (NewFD->getLiteralIdentifier() && 3537 CheckLiteralOperatorDeclaration(NewFD)) 3538 return NewFD->setInvalidDecl(); 3539 3540 // In C++, check default arguments now that we have merged decls. Unless 3541 // the lexical context is the class, because in this case this is done 3542 // during delayed parsing anyway. 3543 if (!CurContext->isRecord()) 3544 CheckCXXDefaultArguments(NewFD); 3545 } 3546} 3547 3548void Sema::CheckMain(FunctionDecl* FD) { 3549 // C++ [basic.start.main]p3: A program that declares main to be inline 3550 // or static is ill-formed. 3551 // C99 6.7.4p4: In a hosted environment, the inline function specifier 3552 // shall not appear in a declaration of main. 3553 // static main is not an error under C99, but we should warn about it. 3554 bool isInline = FD->isInlineSpecified(); 3555 bool isStatic = FD->getStorageClass() == FunctionDecl::Static; 3556 if (isInline || isStatic) { 3557 unsigned diagID = diag::warn_unusual_main_decl; 3558 if (isInline || getLangOptions().CPlusPlus) 3559 diagID = diag::err_unusual_main_decl; 3560 3561 int which = isStatic + (isInline << 1) - 1; 3562 Diag(FD->getLocation(), diagID) << which; 3563 } 3564 3565 QualType T = FD->getType(); 3566 assert(T->isFunctionType() && "function decl is not of function type"); 3567 const FunctionType* FT = T->getAs<FunctionType>(); 3568 3569 if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 3570 // TODO: add a replacement fixit to turn the return type into 'int'. 3571 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 3572 FD->setInvalidDecl(true); 3573 } 3574 3575 // Treat protoless main() as nullary. 3576 if (isa<FunctionNoProtoType>(FT)) return; 3577 3578 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 3579 unsigned nparams = FTP->getNumArgs(); 3580 assert(FD->getNumParams() == nparams); 3581 3582 bool HasExtraParameters = (nparams > 3); 3583 3584 // Darwin passes an undocumented fourth argument of type char**. If 3585 // other platforms start sprouting these, the logic below will start 3586 // getting shifty. 3587 if (nparams == 4 && 3588 Context.Target.getTriple().getOS() == llvm::Triple::Darwin) 3589 HasExtraParameters = false; 3590 3591 if (HasExtraParameters) { 3592 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 3593 FD->setInvalidDecl(true); 3594 nparams = 3; 3595 } 3596 3597 // FIXME: a lot of the following diagnostics would be improved 3598 // if we had some location information about types. 3599 3600 QualType CharPP = 3601 Context.getPointerType(Context.getPointerType(Context.CharTy)); 3602 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 3603 3604 for (unsigned i = 0; i < nparams; ++i) { 3605 QualType AT = FTP->getArgType(i); 3606 3607 bool mismatch = true; 3608 3609 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 3610 mismatch = false; 3611 else if (Expected[i] == CharPP) { 3612 // As an extension, the following forms are okay: 3613 // char const ** 3614 // char const * const * 3615 // char * const * 3616 3617 QualifierCollector qs; 3618 const PointerType* PT; 3619 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 3620 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 3621 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 3622 qs.removeConst(); 3623 mismatch = !qs.empty(); 3624 } 3625 } 3626 3627 if (mismatch) { 3628 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 3629 // TODO: suggest replacing given type with expected type 3630 FD->setInvalidDecl(true); 3631 } 3632 } 3633 3634 if (nparams == 1 && !FD->isInvalidDecl()) { 3635 Diag(FD->getLocation(), diag::warn_main_one_arg); 3636 } 3637} 3638 3639bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 3640 // FIXME: Need strict checking. In C89, we need to check for 3641 // any assignment, increment, decrement, function-calls, or 3642 // commas outside of a sizeof. In C99, it's the same list, 3643 // except that the aforementioned are allowed in unevaluated 3644 // expressions. Everything else falls under the 3645 // "may accept other forms of constant expressions" exception. 3646 // (We never end up here for C++, so the constant expression 3647 // rules there don't matter.) 3648 if (Init->isConstantInitializer(Context)) 3649 return false; 3650 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 3651 << Init->getSourceRange(); 3652 return true; 3653} 3654 3655void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) { 3656 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false); 3657} 3658 3659/// AddInitializerToDecl - Adds the initializer Init to the 3660/// declaration dcl. If DirectInit is true, this is C++ direct 3661/// initialization rather than copy initialization. 3662void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) { 3663 Decl *RealDecl = dcl.getAs<Decl>(); 3664 // If there is no declaration, there was an error parsing it. Just ignore 3665 // the initializer. 3666 if (RealDecl == 0) 3667 return; 3668 3669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 3670 // With declarators parsed the way they are, the parser cannot 3671 // distinguish between a normal initializer and a pure-specifier. 3672 // Thus this grotesque test. 3673 IntegerLiteral *IL; 3674 Expr *Init = static_cast<Expr *>(init.get()); 3675 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 3676 Context.getCanonicalType(IL->getType()) == Context.IntTy) 3677 CheckPureMethod(Method, Init->getSourceRange()); 3678 else { 3679 Diag(Method->getLocation(), diag::err_member_function_initialization) 3680 << Method->getDeclName() << Init->getSourceRange(); 3681 Method->setInvalidDecl(); 3682 } 3683 return; 3684 } 3685 3686 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 3687 if (!VDecl) { 3688 if (getLangOptions().CPlusPlus && 3689 RealDecl->getLexicalDeclContext()->isRecord() && 3690 isa<NamedDecl>(RealDecl)) 3691 Diag(RealDecl->getLocation(), diag::err_member_initialization) 3692 << cast<NamedDecl>(RealDecl)->getDeclName(); 3693 else 3694 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 3695 RealDecl->setInvalidDecl(); 3696 return; 3697 } 3698 3699 // A definition must end up with a complete type, which means it must be 3700 // complete with the restriction that an array type might be completed by the 3701 // initializer; note that later code assumes this restriction. 3702 QualType BaseDeclType = VDecl->getType(); 3703 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 3704 BaseDeclType = Array->getElementType(); 3705 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 3706 diag::err_typecheck_decl_incomplete_type)) { 3707 RealDecl->setInvalidDecl(); 3708 return; 3709 } 3710 3711 // The variable can not have an abstract class type. 3712 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 3713 diag::err_abstract_type_in_decl, 3714 AbstractVariableType)) 3715 VDecl->setInvalidDecl(); 3716 3717 const VarDecl *Def; 3718 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 3719 Diag(VDecl->getLocation(), diag::err_redefinition) 3720 << VDecl->getDeclName(); 3721 Diag(Def->getLocation(), diag::note_previous_definition); 3722 VDecl->setInvalidDecl(); 3723 return; 3724 } 3725 3726 // Take ownership of the expression, now that we're sure we have somewhere 3727 // to put it. 3728 Expr *Init = init.takeAs<Expr>(); 3729 assert(Init && "missing initializer"); 3730 3731 // Capture the variable that is being initialized and the style of 3732 // initialization. 3733 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 3734 3735 // FIXME: Poor source location information. 3736 InitializationKind Kind 3737 = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(), 3738 Init->getLocStart(), 3739 Init->getLocEnd()) 3740 : InitializationKind::CreateCopy(VDecl->getLocation(), 3741 Init->getLocStart()); 3742 3743 // Get the decls type and save a reference for later, since 3744 // CheckInitializerTypes may change it. 3745 QualType DclT = VDecl->getType(), SavT = DclT; 3746 if (VDecl->isBlockVarDecl()) { 3747 if (VDecl->hasExternalStorage()) { // C99 6.7.8p5 3748 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 3749 VDecl->setInvalidDecl(); 3750 } else if (!VDecl->isInvalidDecl()) { 3751 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 3752 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3753 MultiExprArg(*this, (void**)&Init, 1), 3754 &DclT); 3755 if (Result.isInvalid()) { 3756 VDecl->setInvalidDecl(); 3757 return; 3758 } 3759 3760 Init = Result.takeAs<Expr>(); 3761 3762 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 3763 // Don't check invalid declarations to avoid emitting useless diagnostics. 3764 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 3765 if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4. 3766 CheckForConstantInitializer(Init, DclT); 3767 } 3768 } 3769 } else if (VDecl->isStaticDataMember() && 3770 VDecl->getLexicalDeclContext()->isRecord()) { 3771 // This is an in-class initialization for a static data member, e.g., 3772 // 3773 // struct S { 3774 // static const int value = 17; 3775 // }; 3776 3777 // Attach the initializer 3778 VDecl->setInit(Init); 3779 3780 // C++ [class.mem]p4: 3781 // A member-declarator can contain a constant-initializer only 3782 // if it declares a static member (9.4) of const integral or 3783 // const enumeration type, see 9.4.2. 3784 QualType T = VDecl->getType(); 3785 if (!T->isDependentType() && 3786 (!Context.getCanonicalType(T).isConstQualified() || 3787 !T->isIntegralType())) { 3788 Diag(VDecl->getLocation(), diag::err_member_initialization) 3789 << VDecl->getDeclName() << Init->getSourceRange(); 3790 VDecl->setInvalidDecl(); 3791 } else { 3792 // C++ [class.static.data]p4: 3793 // If a static data member is of const integral or const 3794 // enumeration type, its declaration in the class definition 3795 // can specify a constant-initializer which shall be an 3796 // integral constant expression (5.19). 3797 if (!Init->isTypeDependent() && 3798 !Init->getType()->isIntegralType()) { 3799 // We have a non-dependent, non-integral or enumeration type. 3800 Diag(Init->getSourceRange().getBegin(), 3801 diag::err_in_class_initializer_non_integral_type) 3802 << Init->getType() << Init->getSourceRange(); 3803 VDecl->setInvalidDecl(); 3804 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) { 3805 // Check whether the expression is a constant expression. 3806 llvm::APSInt Value; 3807 SourceLocation Loc; 3808 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) { 3809 Diag(Loc, diag::err_in_class_initializer_non_constant) 3810 << Init->getSourceRange(); 3811 VDecl->setInvalidDecl(); 3812 } else if (!VDecl->getType()->isDependentType()) 3813 ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast); 3814 } 3815 } 3816 } else if (VDecl->isFileVarDecl()) { 3817 if (VDecl->getStorageClass() == VarDecl::Extern) 3818 Diag(VDecl->getLocation(), diag::warn_extern_init); 3819 if (!VDecl->isInvalidDecl()) { 3820 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1); 3821 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3822 MultiExprArg(*this, (void**)&Init, 1), 3823 &DclT); 3824 if (Result.isInvalid()) { 3825 VDecl->setInvalidDecl(); 3826 return; 3827 } 3828 3829 Init = Result.takeAs<Expr>(); 3830 } 3831 3832 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 3833 // Don't check invalid declarations to avoid emitting useless diagnostics. 3834 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) { 3835 // C99 6.7.8p4. All file scoped initializers need to be constant. 3836 CheckForConstantInitializer(Init, DclT); 3837 } 3838 } 3839 // If the type changed, it means we had an incomplete type that was 3840 // completed by the initializer. For example: 3841 // int ary[] = { 1, 3, 5 }; 3842 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 3843 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 3844 VDecl->setType(DclT); 3845 Init->setType(DclT); 3846 } 3847 3848 Init = MaybeCreateCXXExprWithTemporaries(Init); 3849 // Attach the initializer to the decl. 3850 VDecl->setInit(Init); 3851 3852 if (getLangOptions().CPlusPlus) { 3853 // Make sure we mark the destructor as used if necessary. 3854 QualType InitType = VDecl->getType(); 3855 while (const ArrayType *Array = Context.getAsArrayType(InitType)) 3856 InitType = Context.getBaseElementType(Array); 3857 if (const RecordType *Record = InitType->getAs<RecordType>()) 3858 FinalizeVarWithDestructor(VDecl, Record); 3859 } 3860 3861 return; 3862} 3863 3864/// ActOnInitializerError - Given that there was an error parsing an 3865/// initializer for the given declaration, try to return to some form 3866/// of sanity. 3867void Sema::ActOnInitializerError(DeclPtrTy dcl) { 3868 // Our main concern here is re-establishing invariants like "a 3869 // variable's type is either dependent or complete". 3870 Decl *D = dcl.getAs<Decl>(); 3871 if (!D || D->isInvalidDecl()) return; 3872 3873 VarDecl *VD = dyn_cast<VarDecl>(D); 3874 if (!VD) return; 3875 3876 QualType Ty = VD->getType(); 3877 if (Ty->isDependentType()) return; 3878 3879 // Require a complete type. 3880 if (RequireCompleteType(VD->getLocation(), 3881 Context.getBaseElementType(Ty), 3882 diag::err_typecheck_decl_incomplete_type)) { 3883 VD->setInvalidDecl(); 3884 return; 3885 } 3886 3887 // Require an abstract type. 3888 if (RequireNonAbstractType(VD->getLocation(), Ty, 3889 diag::err_abstract_type_in_decl, 3890 AbstractVariableType)) { 3891 VD->setInvalidDecl(); 3892 return; 3893 } 3894 3895 // Don't bother complaining about constructors or destructors, 3896 // though. 3897} 3898 3899void Sema::ActOnUninitializedDecl(DeclPtrTy dcl, 3900 bool TypeContainsUndeducedAuto) { 3901 Decl *RealDecl = dcl.getAs<Decl>(); 3902 3903 // If there is no declaration, there was an error parsing it. Just ignore it. 3904 if (RealDecl == 0) 3905 return; 3906 3907 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 3908 QualType Type = Var->getType(); 3909 3910 // C++0x [dcl.spec.auto]p3 3911 if (TypeContainsUndeducedAuto) { 3912 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 3913 << Var->getDeclName() << Type; 3914 Var->setInvalidDecl(); 3915 return; 3916 } 3917 3918 switch (Var->isThisDeclarationADefinition()) { 3919 case VarDecl::Definition: 3920 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 3921 break; 3922 3923 // We have an out-of-line definition of a static data member 3924 // that has an in-class initializer, so we type-check this like 3925 // a declaration. 3926 // 3927 // Fall through 3928 3929 case VarDecl::DeclarationOnly: 3930 // It's only a declaration. 3931 3932 // Block scope. C99 6.7p7: If an identifier for an object is 3933 // declared with no linkage (C99 6.2.2p6), the type for the 3934 // object shall be complete. 3935 if (!Type->isDependentType() && Var->isBlockVarDecl() && 3936 !Var->getLinkage() && !Var->isInvalidDecl() && 3937 RequireCompleteType(Var->getLocation(), Type, 3938 diag::err_typecheck_decl_incomplete_type)) 3939 Var->setInvalidDecl(); 3940 3941 // Make sure that the type is not abstract. 3942 if (!Type->isDependentType() && !Var->isInvalidDecl() && 3943 RequireNonAbstractType(Var->getLocation(), Type, 3944 diag::err_abstract_type_in_decl, 3945 AbstractVariableType)) 3946 Var->setInvalidDecl(); 3947 return; 3948 3949 case VarDecl::TentativeDefinition: 3950 // File scope. C99 6.9.2p2: A declaration of an identifier for an 3951 // object that has file scope without an initializer, and without a 3952 // storage-class specifier or with the storage-class specifier "static", 3953 // constitutes a tentative definition. Note: A tentative definition with 3954 // external linkage is valid (C99 6.2.2p5). 3955 if (!Var->isInvalidDecl()) { 3956 if (const IncompleteArrayType *ArrayT 3957 = Context.getAsIncompleteArrayType(Type)) { 3958 if (RequireCompleteType(Var->getLocation(), 3959 ArrayT->getElementType(), 3960 diag::err_illegal_decl_array_incomplete_type)) 3961 Var->setInvalidDecl(); 3962 } else if (Var->getStorageClass() == VarDecl::Static) { 3963 // C99 6.9.2p3: If the declaration of an identifier for an object is 3964 // a tentative definition and has internal linkage (C99 6.2.2p3), the 3965 // declared type shall not be an incomplete type. 3966 // NOTE: code such as the following 3967 // static struct s; 3968 // struct s { int a; }; 3969 // is accepted by gcc. Hence here we issue a warning instead of 3970 // an error and we do not invalidate the static declaration. 3971 // NOTE: to avoid multiple warnings, only check the first declaration. 3972 if (Var->getPreviousDeclaration() == 0) 3973 RequireCompleteType(Var->getLocation(), Type, 3974 diag::ext_typecheck_decl_incomplete_type); 3975 } 3976 } 3977 3978 // Record the tentative definition; we're done. 3979 if (!Var->isInvalidDecl()) 3980 TentativeDefinitions.push_back(Var); 3981 return; 3982 } 3983 3984 // Provide a specific diagnostic for uninitialized variable 3985 // definitions with incomplete array type. 3986 if (Type->isIncompleteArrayType()) { 3987 Diag(Var->getLocation(), 3988 diag::err_typecheck_incomplete_array_needs_initializer); 3989 Var->setInvalidDecl(); 3990 return; 3991 } 3992 3993 // Provide a specific diagnostic for uninitialized variable 3994 // definitions with reference type. 3995 if (Type->isReferenceType()) { 3996 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 3997 << Var->getDeclName() 3998 << SourceRange(Var->getLocation(), Var->getLocation()); 3999 Var->setInvalidDecl(); 4000 return; 4001 } 4002 4003 // Do not attempt to type-check the default initializer for a 4004 // variable with dependent type. 4005 if (Type->isDependentType()) 4006 return; 4007 4008 if (Var->isInvalidDecl()) 4009 return; 4010 4011 if (RequireCompleteType(Var->getLocation(), 4012 Context.getBaseElementType(Type), 4013 diag::err_typecheck_decl_incomplete_type)) { 4014 Var->setInvalidDecl(); 4015 return; 4016 } 4017 4018 // The variable can not have an abstract class type. 4019 if (RequireNonAbstractType(Var->getLocation(), Type, 4020 diag::err_abstract_type_in_decl, 4021 AbstractVariableType)) { 4022 Var->setInvalidDecl(); 4023 return; 4024 } 4025 4026 const RecordType *Record 4027 = Context.getBaseElementType(Type)->getAs<RecordType>(); 4028 if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x && 4029 cast<CXXRecordDecl>(Record->getDecl())->isPOD()) { 4030 // C++03 [dcl.init]p9: 4031 // If no initializer is specified for an object, and the 4032 // object is of (possibly cv-qualified) non-POD class type (or 4033 // array thereof), the object shall be default-initialized; if 4034 // the object is of const-qualified type, the underlying class 4035 // type shall have a user-declared default 4036 // constructor. Otherwise, if no initializer is specified for 4037 // a non- static object, the object and its subobjects, if 4038 // any, have an indeterminate initial value); if the object 4039 // or any of its subobjects are of const-qualified type, the 4040 // program is ill-formed. 4041 // FIXME: DPG thinks it is very fishy that C++0x disables this. 4042 } else { 4043 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 4044 InitializationKind Kind 4045 = InitializationKind::CreateDefault(Var->getLocation()); 4046 4047 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 4048 OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind, 4049 MultiExprArg(*this, 0, 0)); 4050 if (Init.isInvalid()) 4051 Var->setInvalidDecl(); 4052 else if (Init.get()) 4053 Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>())); 4054 } 4055 4056 if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record) 4057 FinalizeVarWithDestructor(Var, Record); 4058 } 4059} 4060 4061Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 4062 DeclPtrTy *Group, 4063 unsigned NumDecls) { 4064 llvm::SmallVector<Decl*, 8> Decls; 4065 4066 if (DS.isTypeSpecOwned()) 4067 Decls.push_back((Decl*)DS.getTypeRep()); 4068 4069 for (unsigned i = 0; i != NumDecls; ++i) 4070 if (Decl *D = Group[i].getAs<Decl>()) 4071 Decls.push_back(D); 4072 4073 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, 4074 Decls.data(), Decls.size())); 4075} 4076 4077 4078/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 4079/// to introduce parameters into function prototype scope. 4080Sema::DeclPtrTy 4081Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 4082 const DeclSpec &DS = D.getDeclSpec(); 4083 4084 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 4085 VarDecl::StorageClass StorageClass = VarDecl::None; 4086 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4087 StorageClass = VarDecl::Register; 4088 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 4089 Diag(DS.getStorageClassSpecLoc(), 4090 diag::err_invalid_storage_class_in_func_decl); 4091 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4092 } 4093 4094 if (D.getDeclSpec().isThreadSpecified()) 4095 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 4096 4097 DiagnoseFunctionSpecifiers(D); 4098 4099 // Check that there are no default arguments inside the type of this 4100 // parameter (C++ only). 4101 if (getLangOptions().CPlusPlus) 4102 CheckExtraCXXDefaultArguments(D); 4103 4104 TypeSourceInfo *TInfo = 0; 4105 TagDecl *OwnedDecl = 0; 4106 QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl); 4107 4108 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) { 4109 // C++ [dcl.fct]p6: 4110 // Types shall not be defined in return or parameter types. 4111 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type) 4112 << Context.getTypeDeclType(OwnedDecl); 4113 } 4114 4115 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 4116 IdentifierInfo *II = D.getIdentifier(); 4117 if (II) { 4118 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 4119 ForRedeclaration); 4120 LookupName(R, S); 4121 if (R.isSingleResult()) { 4122 NamedDecl *PrevDecl = R.getFoundDecl(); 4123 if (PrevDecl->isTemplateParameter()) { 4124 // Maybe we will complain about the shadowed template parameter. 4125 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 4126 // Just pretend that we didn't see the previous declaration. 4127 PrevDecl = 0; 4128 } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) { 4129 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 4130 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4131 4132 // Recover by removing the name 4133 II = 0; 4134 D.SetIdentifier(0, D.getIdentifierLoc()); 4135 D.setInvalidType(true); 4136 } 4137 } 4138 } 4139 4140 // Temporarily put parameter variables in the translation unit, not 4141 // the enclosing context. This prevents them from accidentally 4142 // looking like class members in C++. 4143 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 4144 TInfo, parmDeclType, II, 4145 D.getIdentifierLoc(), StorageClass); 4146 4147 if (D.isInvalidType()) 4148 New->setInvalidDecl(); 4149 4150 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4151 if (D.getCXXScopeSpec().isSet()) { 4152 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 4153 << D.getCXXScopeSpec().getRange(); 4154 New->setInvalidDecl(); 4155 } 4156 4157 // Add the parameter declaration into this scope. 4158 S->AddDecl(DeclPtrTy::make(New)); 4159 if (II) 4160 IdResolver.AddDecl(New); 4161 4162 ProcessDeclAttributes(S, New, D); 4163 4164 if (New->hasAttr<BlocksAttr>()) { 4165 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4166 } 4167 return DeclPtrTy::make(New); 4168} 4169 4170ParmVarDecl *Sema::CheckParameter(DeclContext *DC, 4171 TypeSourceInfo *TSInfo, QualType T, 4172 IdentifierInfo *Name, 4173 SourceLocation NameLoc, 4174 VarDecl::StorageClass StorageClass) { 4175 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name, 4176 adjustParameterType(T), TSInfo, 4177 StorageClass, 0); 4178 4179 // Parameters can not be abstract class types. 4180 // For record types, this is done by the AbstractClassUsageDiagnoser once 4181 // the class has been completely parsed. 4182 if (!CurContext->isRecord() && 4183 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 4184 AbstractParamType)) 4185 New->setInvalidDecl(); 4186 4187 // Parameter declarators cannot be interface types. All ObjC objects are 4188 // passed by reference. 4189 if (T->isObjCInterfaceType()) { 4190 Diag(NameLoc, 4191 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T; 4192 New->setInvalidDecl(); 4193 } 4194 4195 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4196 // duration shall not be qualified by an address-space qualifier." 4197 // Since all parameters have automatic store duration, they can not have 4198 // an address space. 4199 if (T.getAddressSpace() != 0) { 4200 Diag(NameLoc, diag::err_arg_with_address_space); 4201 New->setInvalidDecl(); 4202 } 4203 4204 return New; 4205} 4206 4207void Sema::ActOnObjCCatchParam(DeclPtrTy D) { 4208 ParmVarDecl *Param = cast<ParmVarDecl>(D.getAs<Decl>()); 4209 Param->setDeclContext(CurContext); 4210} 4211 4212void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 4213 SourceLocation LocAfterDecls) { 4214 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 4215 "Not a function declarator!"); 4216 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 4217 4218 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 4219 // for a K&R function. 4220 if (!FTI.hasPrototype) { 4221 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 4222 --i; 4223 if (FTI.ArgInfo[i].Param == 0) { 4224 llvm::SmallString<256> Code; 4225 llvm::raw_svector_ostream(Code) << " int " 4226 << FTI.ArgInfo[i].Ident->getName() 4227 << ";\n"; 4228 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 4229 << FTI.ArgInfo[i].Ident 4230 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 4231 4232 // Implicitly declare the argument as type 'int' for lack of a better 4233 // type. 4234 DeclSpec DS; 4235 const char* PrevSpec; // unused 4236 unsigned DiagID; // unused 4237 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 4238 PrevSpec, DiagID); 4239 Declarator ParamD(DS, Declarator::KNRTypeListContext); 4240 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 4241 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 4242 } 4243 } 4244 } 4245} 4246 4247Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, 4248 Declarator &D) { 4249 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 4250 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 4251 "Not a function declarator!"); 4252 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 4253 4254 if (FTI.hasPrototype) { 4255 // FIXME: Diagnose arguments without names in C. 4256 } 4257 4258 Scope *ParentScope = FnBodyScope->getParent(); 4259 4260 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 4261 MultiTemplateParamsArg(*this), 4262 /*IsFunctionDefinition=*/true); 4263 return ActOnStartOfFunctionDef(FnBodyScope, DP); 4264} 4265 4266static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 4267 // Don't warn about invalid declarations. 4268 if (FD->isInvalidDecl()) 4269 return false; 4270 4271 // Or declarations that aren't global. 4272 if (!FD->isGlobal()) 4273 return false; 4274 4275 // Don't warn about C++ member functions. 4276 if (isa<CXXMethodDecl>(FD)) 4277 return false; 4278 4279 // Don't warn about 'main'. 4280 if (FD->isMain()) 4281 return false; 4282 4283 // Don't warn about inline functions. 4284 if (FD->isInlineSpecified()) 4285 return false; 4286 4287 // Don't warn about function templates. 4288 if (FD->getDescribedFunctionTemplate()) 4289 return false; 4290 4291 // Don't warn about function template specializations. 4292 if (FD->isFunctionTemplateSpecialization()) 4293 return false; 4294 4295 bool MissingPrototype = true; 4296 for (const FunctionDecl *Prev = FD->getPreviousDeclaration(); 4297 Prev; Prev = Prev->getPreviousDeclaration()) { 4298 // Ignore any declarations that occur in function or method 4299 // scope, because they aren't visible from the header. 4300 if (Prev->getDeclContext()->isFunctionOrMethod()) 4301 continue; 4302 4303 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 4304 break; 4305 } 4306 4307 return MissingPrototype; 4308} 4309 4310Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) { 4311 // Clear the last template instantiation error context. 4312 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 4313 4314 if (!D) 4315 return D; 4316 FunctionDecl *FD = 0; 4317 4318 if (FunctionTemplateDecl *FunTmpl 4319 = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>())) 4320 FD = FunTmpl->getTemplatedDecl(); 4321 else 4322 FD = cast<FunctionDecl>(D.getAs<Decl>()); 4323 4324 // Enter a new function scope 4325 PushFunctionScope(); 4326 4327 // See if this is a redefinition. 4328 // But don't complain if we're in GNU89 mode and the previous definition 4329 // was an extern inline function. 4330 const FunctionDecl *Definition; 4331 if (FD->getBody(Definition) && 4332 !canRedefineFunction(Definition, getLangOptions())) { 4333 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 4334 Diag(Definition->getLocation(), diag::note_previous_definition); 4335 } 4336 4337 // Builtin functions cannot be defined. 4338 if (unsigned BuiltinID = FD->getBuiltinID()) { 4339 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4340 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 4341 FD->setInvalidDecl(); 4342 } 4343 } 4344 4345 // The return type of a function definition must be complete 4346 // (C99 6.9.1p3, C++ [dcl.fct]p6). 4347 QualType ResultType = FD->getResultType(); 4348 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 4349 !FD->isInvalidDecl() && 4350 RequireCompleteType(FD->getLocation(), ResultType, 4351 diag::err_func_def_incomplete_result)) 4352 FD->setInvalidDecl(); 4353 4354 // GNU warning -Wmissing-prototypes: 4355 // Warn if a global function is defined without a previous 4356 // prototype declaration. This warning is issued even if the 4357 // definition itself provides a prototype. The aim is to detect 4358 // global functions that fail to be declared in header files. 4359 if (ShouldWarnAboutMissingPrototype(FD)) 4360 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 4361 4362 if (FnBodyScope) 4363 PushDeclContext(FnBodyScope, FD); 4364 4365 // Check the validity of our function parameters 4366 CheckParmsForFunctionDef(FD); 4367 4368 bool ShouldCheckShadow = 4369 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored; 4370 4371 // Introduce our parameters into the function scope 4372 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 4373 ParmVarDecl *Param = FD->getParamDecl(p); 4374 Param->setOwningFunction(FD); 4375 4376 // If this has an identifier, add it to the scope stack. 4377 if (Param->getIdentifier() && FnBodyScope) { 4378 if (ShouldCheckShadow) 4379 CheckShadow(FnBodyScope, Param); 4380 4381 PushOnScopeChains(Param, FnBodyScope); 4382 } 4383 } 4384 4385 // Checking attributes of current function definition 4386 // dllimport attribute. 4387 if (FD->getAttr<DLLImportAttr>() && 4388 (!FD->getAttr<DLLExportAttr>())) { 4389 // dllimport attribute cannot be applied to definition. 4390 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 4391 Diag(FD->getLocation(), 4392 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 4393 << "dllimport"; 4394 FD->setInvalidDecl(); 4395 return DeclPtrTy::make(FD); 4396 } 4397 4398 // Visual C++ appears to not think this is an issue, so only issue 4399 // a warning when Microsoft extensions are disabled. 4400 if (!LangOpts.Microsoft) { 4401 // If a symbol previously declared dllimport is later defined, the 4402 // attribute is ignored in subsequent references, and a warning is 4403 // emitted. 4404 Diag(FD->getLocation(), 4405 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 4406 << FD->getNameAsCString() << "dllimport"; 4407 } 4408 } 4409 return DeclPtrTy::make(FD); 4410} 4411 4412Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) { 4413 return ActOnFinishFunctionBody(D, move(BodyArg), false); 4414} 4415 4416Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg, 4417 bool IsInstantiation) { 4418 Decl *dcl = D.getAs<Decl>(); 4419 Stmt *Body = BodyArg.takeAs<Stmt>(); 4420 4421 FunctionDecl *FD = 0; 4422 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 4423 if (FunTmpl) 4424 FD = FunTmpl->getTemplatedDecl(); 4425 else 4426 FD = dyn_cast_or_null<FunctionDecl>(dcl); 4427 4428 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 4429 4430 if (FD) { 4431 FD->setBody(Body); 4432 if (FD->isMain()) { 4433 // C and C++ allow for main to automagically return 0. 4434 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3. 4435 FD->setHasImplicitReturnZero(true); 4436 WP.disableCheckFallThrough(); 4437 } 4438 4439 if (!FD->isInvalidDecl()) 4440 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 4441 4442 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 4443 MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method); 4444 4445 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 4446 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 4447 assert(MD == getCurMethodDecl() && "Method parsing confused"); 4448 MD->setBody(Body); 4449 MD->setEndLoc(Body->getLocEnd()); 4450 if (!MD->isInvalidDecl()) 4451 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 4452 } else { 4453 Body->Destroy(Context); 4454 return DeclPtrTy(); 4455 } 4456 4457 // Verify and clean out per-function state. 4458 4459 // Check goto/label use. 4460 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 4461 I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) { 4462 LabelStmt *L = I->second; 4463 4464 // Verify that we have no forward references left. If so, there was a goto 4465 // or address of a label taken, but no definition of it. Label fwd 4466 // definitions are indicated with a null substmt. 4467 if (L->getSubStmt() != 0) 4468 continue; 4469 4470 // Emit error. 4471 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 4472 4473 // At this point, we have gotos that use the bogus label. Stitch it into 4474 // the function body so that they aren't leaked and that the AST is well 4475 // formed. 4476 if (Body == 0) { 4477 // The whole function wasn't parsed correctly, just delete this. 4478 L->Destroy(Context); 4479 continue; 4480 } 4481 4482 // Otherwise, the body is valid: we want to stitch the label decl into the 4483 // function somewhere so that it is properly owned and so that the goto 4484 // has a valid target. Do this by creating a new compound stmt with the 4485 // label in it. 4486 4487 // Give the label a sub-statement. 4488 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc())); 4489 4490 CompoundStmt *Compound = isa<CXXTryStmt>(Body) ? 4491 cast<CXXTryStmt>(Body)->getTryBlock() : 4492 cast<CompoundStmt>(Body); 4493 llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(), 4494 Compound->body_end()); 4495 Elements.push_back(L); 4496 Compound->setStmts(Context, Elements.data(), Elements.size()); 4497 } 4498 4499 if (Body) { 4500 // C++ constructors that have function-try-blocks can't have return 4501 // statements in the handlers of that block. (C++ [except.handle]p14) 4502 // Verify this. 4503 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 4504 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 4505 4506 // Verify that that gotos and switch cases don't jump into scopes illegally. 4507 // Verify that that gotos and switch cases don't jump into scopes illegally. 4508 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction()) 4509 DiagnoseInvalidJumps(Body); 4510 4511 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) 4512 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 4513 Destructor->getParent()); 4514 4515 // If any errors have occurred, clear out any temporaries that may have 4516 // been leftover. This ensures that these temporaries won't be picked up for 4517 // deletion in some later function. 4518 if (PP.getDiagnostics().hasErrorOccurred()) 4519 ExprTemporaries.clear(); 4520 else if (!isa<FunctionTemplateDecl>(dcl)) { 4521 // Since the body is valid, issue any analysis-based warnings that are 4522 // enabled. 4523 QualType ResultType; 4524 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) { 4525 ResultType = FD->getResultType(); 4526 } 4527 else { 4528 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl); 4529 ResultType = MD->getResultType(); 4530 } 4531 AnalysisWarnings.IssueWarnings(WP, dcl); 4532 } 4533 4534 assert(ExprTemporaries.empty() && "Leftover temporaries in function"); 4535 } 4536 4537 if (!IsInstantiation) 4538 PopDeclContext(); 4539 4540 PopFunctionOrBlockScope(); 4541 4542 // If any errors have occurred, clear out any temporaries that may have 4543 // been leftover. This ensures that these temporaries won't be picked up for 4544 // deletion in some later function. 4545 if (getDiagnostics().hasErrorOccurred()) 4546 ExprTemporaries.clear(); 4547 4548 return D; 4549} 4550 4551/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 4552/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 4553NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 4554 IdentifierInfo &II, Scope *S) { 4555 // Before we produce a declaration for an implicitly defined 4556 // function, see whether there was a locally-scoped declaration of 4557 // this name as a function or variable. If so, use that 4558 // (non-visible) declaration, and complain about it. 4559 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4560 = LocallyScopedExternalDecls.find(&II); 4561 if (Pos != LocallyScopedExternalDecls.end()) { 4562 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 4563 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 4564 return Pos->second; 4565 } 4566 4567 // Extension in C99. Legal in C90, but warn about it. 4568 if (II.getName().startswith("__builtin_")) 4569 Diag(Loc, diag::warn_builtin_unknown) << &II; 4570 else if (getLangOptions().C99) 4571 Diag(Loc, diag::ext_implicit_function_decl) << &II; 4572 else 4573 Diag(Loc, diag::warn_implicit_function_decl) << &II; 4574 4575 // Set a Declarator for the implicit definition: int foo(); 4576 const char *Dummy; 4577 DeclSpec DS; 4578 unsigned DiagID; 4579 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 4580 Error = Error; // Silence warning. 4581 assert(!Error && "Error setting up implicit decl!"); 4582 Declarator D(DS, Declarator::BlockContext); 4583 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 4584 0, 0, false, SourceLocation(), 4585 false, 0,0,0, Loc, Loc, D), 4586 SourceLocation()); 4587 D.SetIdentifier(&II, Loc); 4588 4589 // Insert this function into translation-unit scope. 4590 4591 DeclContext *PrevDC = CurContext; 4592 CurContext = Context.getTranslationUnitDecl(); 4593 4594 FunctionDecl *FD = 4595 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>()); 4596 FD->setImplicit(); 4597 4598 CurContext = PrevDC; 4599 4600 AddKnownFunctionAttributes(FD); 4601 4602 return FD; 4603} 4604 4605/// \brief Adds any function attributes that we know a priori based on 4606/// the declaration of this function. 4607/// 4608/// These attributes can apply both to implicitly-declared builtins 4609/// (like __builtin___printf_chk) or to library-declared functions 4610/// like NSLog or printf. 4611void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 4612 if (FD->isInvalidDecl()) 4613 return; 4614 4615 // If this is a built-in function, map its builtin attributes to 4616 // actual attributes. 4617 if (unsigned BuiltinID = FD->getBuiltinID()) { 4618 // Handle printf-formatting attributes. 4619 unsigned FormatIdx; 4620 bool HasVAListArg; 4621 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 4622 if (!FD->getAttr<FormatAttr>()) 4623 FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1, 4624 HasVAListArg ? 0 : FormatIdx+2)); 4625 } 4626 4627 // Mark const if we don't care about errno and that is the only 4628 // thing preventing the function from being const. This allows 4629 // IRgen to use LLVM intrinsics for such functions. 4630 if (!getLangOptions().MathErrno && 4631 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 4632 if (!FD->getAttr<ConstAttr>()) 4633 FD->addAttr(::new (Context) ConstAttr()); 4634 } 4635 4636 if (Context.BuiltinInfo.isNoReturn(BuiltinID)) 4637 FD->setType(Context.getNoReturnType(FD->getType())); 4638 if (Context.BuiltinInfo.isNoThrow(BuiltinID)) 4639 FD->addAttr(::new (Context) NoThrowAttr()); 4640 if (Context.BuiltinInfo.isConst(BuiltinID)) 4641 FD->addAttr(::new (Context) ConstAttr()); 4642 } 4643 4644 IdentifierInfo *Name = FD->getIdentifier(); 4645 if (!Name) 4646 return; 4647 if ((!getLangOptions().CPlusPlus && 4648 FD->getDeclContext()->isTranslationUnit()) || 4649 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 4650 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 4651 LinkageSpecDecl::lang_c)) { 4652 // Okay: this could be a libc/libm/Objective-C function we know 4653 // about. 4654 } else 4655 return; 4656 4657 if (Name->isStr("NSLog") || Name->isStr("NSLogv")) { 4658 // FIXME: NSLog and NSLogv should be target specific 4659 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) { 4660 // FIXME: We known better than our headers. 4661 const_cast<FormatAttr *>(Format)->setType(Context, "printf"); 4662 } else 4663 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1, 4664 Name->isStr("NSLogv") ? 0 : 2)); 4665 } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 4666 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 4667 // target-specific builtins, perhaps? 4668 if (!FD->getAttr<FormatAttr>()) 4669 FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2, 4670 Name->isStr("vasprintf") ? 0 : 3)); 4671 } 4672} 4673 4674TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 4675 TypeSourceInfo *TInfo) { 4676 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 4677 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 4678 4679 if (!TInfo) { 4680 assert(D.isInvalidType() && "no declarator info for valid type"); 4681 TInfo = Context.getTrivialTypeSourceInfo(T); 4682 } 4683 4684 // Scope manipulation handled by caller. 4685 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 4686 D.getIdentifierLoc(), 4687 D.getIdentifier(), 4688 TInfo); 4689 4690 if (const TagType *TT = T->getAs<TagType>()) { 4691 TagDecl *TD = TT->getDecl(); 4692 4693 // If the TagDecl that the TypedefDecl points to is an anonymous decl 4694 // keep track of the TypedefDecl. 4695 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 4696 TD->setTypedefForAnonDecl(NewTD); 4697 } 4698 4699 if (D.isInvalidType()) 4700 NewTD->setInvalidDecl(); 4701 return NewTD; 4702} 4703 4704 4705/// \brief Determine whether a tag with a given kind is acceptable 4706/// as a redeclaration of the given tag declaration. 4707/// 4708/// \returns true if the new tag kind is acceptable, false otherwise. 4709bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 4710 TagDecl::TagKind NewTag, 4711 SourceLocation NewTagLoc, 4712 const IdentifierInfo &Name) { 4713 // C++ [dcl.type.elab]p3: 4714 // The class-key or enum keyword present in the 4715 // elaborated-type-specifier shall agree in kind with the 4716 // declaration to which the name in theelaborated-type-specifier 4717 // refers. This rule also applies to the form of 4718 // elaborated-type-specifier that declares a class-name or 4719 // friend class since it can be construed as referring to the 4720 // definition of the class. Thus, in any 4721 // elaborated-type-specifier, the enum keyword shall be used to 4722 // refer to an enumeration (7.2), the union class-keyshall be 4723 // used to refer to a union (clause 9), and either the class or 4724 // struct class-key shall be used to refer to a class (clause 9) 4725 // declared using the class or struct class-key. 4726 TagDecl::TagKind OldTag = Previous->getTagKind(); 4727 if (OldTag == NewTag) 4728 return true; 4729 4730 if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) && 4731 (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) { 4732 // Warn about the struct/class tag mismatch. 4733 bool isTemplate = false; 4734 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 4735 isTemplate = Record->getDescribedClassTemplate(); 4736 4737 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 4738 << (NewTag == TagDecl::TK_class) 4739 << isTemplate << &Name 4740 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 4741 OldTag == TagDecl::TK_class? "class" : "struct"); 4742 Diag(Previous->getLocation(), diag::note_previous_use); 4743 return true; 4744 } 4745 return false; 4746} 4747 4748/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 4749/// former case, Name will be non-null. In the later case, Name will be null. 4750/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 4751/// reference/declaration/definition of a tag. 4752Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 4753 SourceLocation KWLoc, CXXScopeSpec &SS, 4754 IdentifierInfo *Name, SourceLocation NameLoc, 4755 AttributeList *Attr, AccessSpecifier AS, 4756 MultiTemplateParamsArg TemplateParameterLists, 4757 bool &OwnedDecl, bool &IsDependent) { 4758 // If this is not a definition, it must have a name. 4759 assert((Name != 0 || TUK == TUK_Definition) && 4760 "Nameless record must be a definition!"); 4761 4762 OwnedDecl = false; 4763 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec); 4764 4765 // FIXME: Check explicit specializations more carefully. 4766 bool isExplicitSpecialization = false; 4767 if (TUK != TUK_Reference) { 4768 if (TemplateParameterList *TemplateParams 4769 = MatchTemplateParametersToScopeSpecifier(KWLoc, SS, 4770 (TemplateParameterList**)TemplateParameterLists.get(), 4771 TemplateParameterLists.size(), 4772 TUK == TUK_Friend, 4773 isExplicitSpecialization)) { 4774 if (TemplateParams->size() > 0) { 4775 // This is a declaration or definition of a class template (which may 4776 // be a member of another template). 4777 OwnedDecl = false; 4778 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 4779 SS, Name, NameLoc, Attr, 4780 TemplateParams, 4781 AS); 4782 TemplateParameterLists.release(); 4783 return Result.get(); 4784 } else { 4785 // The "template<>" header is extraneous. 4786 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 4787 << ElaboratedType::getNameForTagKind(Kind) << Name; 4788 isExplicitSpecialization = true; 4789 } 4790 } 4791 4792 TemplateParameterLists.release(); 4793 } 4794 4795 DeclContext *SearchDC = CurContext; 4796 DeclContext *DC = CurContext; 4797 bool isStdBadAlloc = false; 4798 bool Invalid = false; 4799 4800 RedeclarationKind Redecl = ForRedeclaration; 4801 if (TUK == TUK_Friend || TUK == TUK_Reference) 4802 Redecl = NotForRedeclaration; 4803 4804 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 4805 4806 if (Name && SS.isNotEmpty()) { 4807 // We have a nested-name tag ('struct foo::bar'). 4808 4809 // Check for invalid 'foo::'. 4810 if (SS.isInvalid()) { 4811 Name = 0; 4812 goto CreateNewDecl; 4813 } 4814 4815 // If this is a friend or a reference to a class in a dependent 4816 // context, don't try to make a decl for it. 4817 if (TUK == TUK_Friend || TUK == TUK_Reference) { 4818 DC = computeDeclContext(SS, false); 4819 if (!DC) { 4820 IsDependent = true; 4821 return DeclPtrTy(); 4822 } 4823 } 4824 4825 if (RequireCompleteDeclContext(SS)) 4826 return DeclPtrTy::make((Decl *)0); 4827 4828 DC = computeDeclContext(SS, true); 4829 SearchDC = DC; 4830 // Look-up name inside 'foo::'. 4831 LookupQualifiedName(Previous, DC); 4832 4833 if (Previous.isAmbiguous()) 4834 return DeclPtrTy(); 4835 4836 if (Previous.empty()) { 4837 // Name lookup did not find anything. However, if the 4838 // nested-name-specifier refers to the current instantiation, 4839 // and that current instantiation has any dependent base 4840 // classes, we might find something at instantiation time: treat 4841 // this as a dependent elaborated-type-specifier. 4842 if (Previous.wasNotFoundInCurrentInstantiation()) { 4843 IsDependent = true; 4844 return DeclPtrTy(); 4845 } 4846 4847 // A tag 'foo::bar' must already exist. 4848 Diag(NameLoc, diag::err_not_tag_in_scope) 4849 << Kind << Name << DC << SS.getRange(); 4850 Name = 0; 4851 Invalid = true; 4852 goto CreateNewDecl; 4853 } 4854 } else if (Name) { 4855 // If this is a named struct, check to see if there was a previous forward 4856 // declaration or definition. 4857 // FIXME: We're looking into outer scopes here, even when we 4858 // shouldn't be. Doing so can result in ambiguities that we 4859 // shouldn't be diagnosing. 4860 LookupName(Previous, S); 4861 4862 // Note: there used to be some attempt at recovery here. 4863 if (Previous.isAmbiguous()) 4864 return DeclPtrTy(); 4865 4866 if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) { 4867 // FIXME: This makes sure that we ignore the contexts associated 4868 // with C structs, unions, and enums when looking for a matching 4869 // tag declaration or definition. See the similar lookup tweak 4870 // in Sema::LookupName; is there a better way to deal with this? 4871 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 4872 SearchDC = SearchDC->getParent(); 4873 } 4874 } 4875 4876 if (Previous.isSingleResult() && 4877 Previous.getFoundDecl()->isTemplateParameter()) { 4878 // Maybe we will complain about the shadowed template parameter. 4879 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 4880 // Just pretend that we didn't see the previous declaration. 4881 Previous.clear(); 4882 } 4883 4884 if (getLangOptions().CPlusPlus && Name && DC && StdNamespace && 4885 DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) { 4886 // This is a declaration of or a reference to "std::bad_alloc". 4887 isStdBadAlloc = true; 4888 4889 if (Previous.empty() && StdBadAlloc) { 4890 // std::bad_alloc has been implicitly declared (but made invisible to 4891 // name lookup). Fill in this implicit declaration as the previous 4892 // declaration, so that the declarations get chained appropriately. 4893 Previous.addDecl(StdBadAlloc); 4894 } 4895 } 4896 4897 // If we didn't find a previous declaration, and this is a reference 4898 // (or friend reference), move to the correct scope. In C++, we 4899 // also need to do a redeclaration lookup there, just in case 4900 // there's a shadow friend decl. 4901 if (Name && Previous.empty() && 4902 (TUK == TUK_Reference || TUK == TUK_Friend)) { 4903 if (Invalid) goto CreateNewDecl; 4904 assert(SS.isEmpty()); 4905 4906 if (TUK == TUK_Reference) { 4907 // C++ [basic.scope.pdecl]p5: 4908 // -- for an elaborated-type-specifier of the form 4909 // 4910 // class-key identifier 4911 // 4912 // if the elaborated-type-specifier is used in the 4913 // decl-specifier-seq or parameter-declaration-clause of a 4914 // function defined in namespace scope, the identifier is 4915 // declared as a class-name in the namespace that contains 4916 // the declaration; otherwise, except as a friend 4917 // declaration, the identifier is declared in the smallest 4918 // non-class, non-function-prototype scope that contains the 4919 // declaration. 4920 // 4921 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 4922 // C structs and unions. 4923 // 4924 // It is an error in C++ to declare (rather than define) an enum 4925 // type, including via an elaborated type specifier. We'll 4926 // diagnose that later; for now, declare the enum in the same 4927 // scope as we would have picked for any other tag type. 4928 // 4929 // GNU C also supports this behavior as part of its incomplete 4930 // enum types extension, while GNU C++ does not. 4931 // 4932 // Find the context where we'll be declaring the tag. 4933 // FIXME: We would like to maintain the current DeclContext as the 4934 // lexical context, 4935 while (SearchDC->isRecord()) 4936 SearchDC = SearchDC->getParent(); 4937 4938 // Find the scope where we'll be declaring the tag. 4939 while (S->isClassScope() || 4940 (getLangOptions().CPlusPlus && 4941 S->isFunctionPrototypeScope()) || 4942 ((S->getFlags() & Scope::DeclScope) == 0) || 4943 (S->getEntity() && 4944 ((DeclContext *)S->getEntity())->isTransparentContext())) 4945 S = S->getParent(); 4946 } else { 4947 assert(TUK == TUK_Friend); 4948 // C++ [namespace.memdef]p3: 4949 // If a friend declaration in a non-local class first declares a 4950 // class or function, the friend class or function is a member of 4951 // the innermost enclosing namespace. 4952 SearchDC = SearchDC->getEnclosingNamespaceContext(); 4953 } 4954 4955 // In C++, look for a shadow friend decl. 4956 if (getLangOptions().CPlusPlus) { 4957 Previous.setRedeclarationKind(ForRedeclaration); 4958 LookupQualifiedName(Previous, SearchDC); 4959 } 4960 } 4961 4962 if (!Previous.empty()) { 4963 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 4964 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 4965 // If this is a use of a previous tag, or if the tag is already declared 4966 // in the same scope (so that the definition/declaration completes or 4967 // rementions the tag), reuse the decl. 4968 if (TUK == TUK_Reference || TUK == TUK_Friend || 4969 isDeclInScope(PrevDecl, SearchDC, S)) { 4970 // Make sure that this wasn't declared as an enum and now used as a 4971 // struct or something similar. 4972 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) { 4973 bool SafeToContinue 4974 = (PrevTagDecl->getTagKind() != TagDecl::TK_enum && 4975 Kind != TagDecl::TK_enum); 4976 if (SafeToContinue) 4977 Diag(KWLoc, diag::err_use_with_wrong_tag) 4978 << Name 4979 << FixItHint::CreateReplacement(SourceRange(KWLoc), 4980 PrevTagDecl->getKindName()); 4981 else 4982 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 4983 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 4984 4985 if (SafeToContinue) 4986 Kind = PrevTagDecl->getTagKind(); 4987 else { 4988 // Recover by making this an anonymous redefinition. 4989 Name = 0; 4990 Previous.clear(); 4991 Invalid = true; 4992 } 4993 } 4994 4995 if (!Invalid) { 4996 // If this is a use, just return the declaration we found. 4997 4998 // FIXME: In the future, return a variant or some other clue 4999 // for the consumer of this Decl to know it doesn't own it. 5000 // For our current ASTs this shouldn't be a problem, but will 5001 // need to be changed with DeclGroups. 5002 if (TUK == TUK_Reference || TUK == TUK_Friend) 5003 return DeclPtrTy::make(PrevTagDecl); 5004 5005 // Diagnose attempts to redefine a tag. 5006 if (TUK == TUK_Definition) { 5007 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 5008 // If we're defining a specialization and the previous definition 5009 // is from an implicit instantiation, don't emit an error 5010 // here; we'll catch this in the general case below. 5011 if (!isExplicitSpecialization || 5012 !isa<CXXRecordDecl>(Def) || 5013 cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind() 5014 == TSK_ExplicitSpecialization) { 5015 Diag(NameLoc, diag::err_redefinition) << Name; 5016 Diag(Def->getLocation(), diag::note_previous_definition); 5017 // If this is a redefinition, recover by making this 5018 // struct be anonymous, which will make any later 5019 // references get the previous definition. 5020 Name = 0; 5021 Previous.clear(); 5022 Invalid = true; 5023 } 5024 } else { 5025 // If the type is currently being defined, complain 5026 // about a nested redefinition. 5027 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 5028 if (Tag->isBeingDefined()) { 5029 Diag(NameLoc, diag::err_nested_redefinition) << Name; 5030 Diag(PrevTagDecl->getLocation(), 5031 diag::note_previous_definition); 5032 Name = 0; 5033 Previous.clear(); 5034 Invalid = true; 5035 } 5036 } 5037 5038 // Okay, this is definition of a previously declared or referenced 5039 // tag PrevDecl. We're going to create a new Decl for it. 5040 } 5041 } 5042 // If we get here we have (another) forward declaration or we 5043 // have a definition. Just create a new decl. 5044 5045 } else { 5046 // If we get here, this is a definition of a new tag type in a nested 5047 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 5048 // new decl/type. We set PrevDecl to NULL so that the entities 5049 // have distinct types. 5050 Previous.clear(); 5051 } 5052 // If we get here, we're going to create a new Decl. If PrevDecl 5053 // is non-NULL, it's a definition of the tag declared by 5054 // PrevDecl. If it's NULL, we have a new definition. 5055 } else { 5056 // PrevDecl is a namespace, template, or anything else 5057 // that lives in the IDNS_Tag identifier namespace. 5058 if (TUK == TUK_Reference || TUK == TUK_Friend || 5059 isDeclInScope(PrevDecl, SearchDC, S)) { 5060 // The tag name clashes with a namespace name, issue an error and 5061 // recover by making this tag be anonymous. 5062 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 5063 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5064 Name = 0; 5065 Previous.clear(); 5066 Invalid = true; 5067 } else { 5068 // The existing declaration isn't relevant to us; we're in a 5069 // new scope, so clear out the previous declaration. 5070 Previous.clear(); 5071 } 5072 } 5073 } 5074 5075CreateNewDecl: 5076 5077 TagDecl *PrevDecl = 0; 5078 if (Previous.isSingleResult()) 5079 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 5080 5081 // If there is an identifier, use the location of the identifier as the 5082 // location of the decl, otherwise use the location of the struct/union 5083 // keyword. 5084 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 5085 5086 // Otherwise, create a new declaration. If there is a previous 5087 // declaration of the same entity, the two will be linked via 5088 // PrevDecl. 5089 TagDecl *New; 5090 5091 if (Kind == TagDecl::TK_enum) { 5092 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 5093 // enum X { A, B, C } D; D should chain to X. 5094 New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc, 5095 cast_or_null<EnumDecl>(PrevDecl)); 5096 // If this is an undefined enum, warn. 5097 if (TUK != TUK_Definition && !Invalid) { 5098 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum 5099 : diag::ext_forward_ref_enum; 5100 Diag(Loc, DK); 5101 } 5102 } else { 5103 // struct/union/class 5104 5105 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 5106 // struct X { int A; } D; D should chain to X. 5107 if (getLangOptions().CPlusPlus) { 5108 // FIXME: Look for a way to use RecordDecl for simple structs. 5109 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 5110 cast_or_null<CXXRecordDecl>(PrevDecl)); 5111 5112 if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit())) 5113 StdBadAlloc = cast<CXXRecordDecl>(New); 5114 } else 5115 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc, 5116 cast_or_null<RecordDecl>(PrevDecl)); 5117 } 5118 5119 // Maybe add qualifier info. 5120 if (SS.isNotEmpty()) { 5121 NestedNameSpecifier *NNS 5122 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 5123 New->setQualifierInfo(NNS, SS.getRange()); 5124 } 5125 5126 if (Kind != TagDecl::TK_enum) { 5127 // Handle #pragma pack: if the #pragma pack stack has non-default 5128 // alignment, make up a packed attribute for this decl. These 5129 // attributes are checked when the ASTContext lays out the 5130 // structure. 5131 // 5132 // It is important for implementing the correct semantics that this 5133 // happen here (in act on tag decl). The #pragma pack stack is 5134 // maintained as a result of parser callbacks which can occur at 5135 // many points during the parsing of a struct declaration (because 5136 // the #pragma tokens are effectively skipped over during the 5137 // parsing of the struct). 5138 if (unsigned Alignment = getPragmaPackAlignment()) 5139 New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8)); 5140 } 5141 5142 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) { 5143 // C++ [dcl.typedef]p3: 5144 // [...] Similarly, in a given scope, a class or enumeration 5145 // shall not be declared with the same name as a typedef-name 5146 // that is declared in that scope and refers to a type other 5147 // than the class or enumeration itself. 5148 LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName, 5149 ForRedeclaration); 5150 LookupName(Lookup, S); 5151 TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>(); 5152 NamedDecl *PrevTypedefNamed = PrevTypedef; 5153 if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) && 5154 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) != 5155 Context.getCanonicalType(Context.getTypeDeclType(New))) { 5156 Diag(Loc, diag::err_tag_definition_of_typedef) 5157 << Context.getTypeDeclType(New) 5158 << PrevTypedef->getUnderlyingType(); 5159 Diag(PrevTypedef->getLocation(), diag::note_previous_definition); 5160 Invalid = true; 5161 } 5162 } 5163 5164 // If this is a specialization of a member class (of a class template), 5165 // check the specialization. 5166 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 5167 Invalid = true; 5168 5169 if (Invalid) 5170 New->setInvalidDecl(); 5171 5172 if (Attr) 5173 ProcessDeclAttributeList(S, New, Attr); 5174 5175 // If we're declaring or defining a tag in function prototype scope 5176 // in C, note that this type can only be used within the function. 5177 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 5178 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 5179 5180 // Set the lexical context. If the tag has a C++ scope specifier, the 5181 // lexical context will be different from the semantic context. 5182 New->setLexicalDeclContext(CurContext); 5183 5184 // Mark this as a friend decl if applicable. 5185 if (TUK == TUK_Friend) 5186 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty()); 5187 5188 // Set the access specifier. 5189 if (!Invalid && SearchDC->isRecord()) 5190 SetMemberAccessSpecifier(New, PrevDecl, AS); 5191 5192 if (TUK == TUK_Definition) 5193 New->startDefinition(); 5194 5195 // If this has an identifier, add it to the scope stack. 5196 if (TUK == TUK_Friend) { 5197 // We might be replacing an existing declaration in the lookup tables; 5198 // if so, borrow its access specifier. 5199 if (PrevDecl) 5200 New->setAccess(PrevDecl->getAccess()); 5201 5202 DeclContext *DC = New->getDeclContext()->getLookupContext(); 5203 DC->makeDeclVisibleInContext(New, /* Recoverable = */ false); 5204 if (Name) // can be null along some error paths 5205 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5206 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 5207 } else if (Name) { 5208 S = getNonFieldDeclScope(S); 5209 PushOnScopeChains(New, S); 5210 } else { 5211 CurContext->addDecl(New); 5212 } 5213 5214 // If this is the C FILE type, notify the AST context. 5215 if (IdentifierInfo *II = New->getIdentifier()) 5216 if (!New->isInvalidDecl() && 5217 New->getDeclContext()->getLookupContext()->isTranslationUnit() && 5218 II->isStr("FILE")) 5219 Context.setFILEDecl(New); 5220 5221 OwnedDecl = true; 5222 return DeclPtrTy::make(New); 5223} 5224 5225void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) { 5226 AdjustDeclIfTemplate(TagD); 5227 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 5228 5229 // Enter the tag context. 5230 PushDeclContext(S, Tag); 5231} 5232 5233void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD, 5234 SourceLocation LBraceLoc) { 5235 AdjustDeclIfTemplate(TagD); 5236 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>()); 5237 5238 FieldCollector->StartClass(); 5239 5240 if (!Record->getIdentifier()) 5241 return; 5242 5243 // C++ [class]p2: 5244 // [...] The class-name is also inserted into the scope of the 5245 // class itself; this is known as the injected-class-name. For 5246 // purposes of access checking, the injected-class-name is treated 5247 // as if it were a public member name. 5248 CXXRecordDecl *InjectedClassName 5249 = CXXRecordDecl::Create(Context, Record->getTagKind(), 5250 CurContext, Record->getLocation(), 5251 Record->getIdentifier(), 5252 Record->getTagKeywordLoc(), 5253 Record); 5254 InjectedClassName->setImplicit(); 5255 InjectedClassName->setAccess(AS_public); 5256 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 5257 InjectedClassName->setDescribedClassTemplate(Template); 5258 PushOnScopeChains(InjectedClassName, S); 5259 assert(InjectedClassName->isInjectedClassName() && 5260 "Broken injected-class-name"); 5261} 5262 5263// Traverses the class and any nested classes, making a note of any 5264// dynamic classes that have no key function so that we can mark all of 5265// their virtual member functions as "used" at the end of the translation 5266// unit. This ensures that all functions needed by the vtable will get 5267// instantiated/synthesized. 5268static void 5269RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record, 5270 SourceLocation Loc) { 5271 // We don't look at dependent or undefined classes. 5272 if (Record->isDependentContext() || !Record->isDefinition()) 5273 return; 5274 5275 if (Record->isDynamicClass()) { 5276 const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record); 5277 5278 if (!KeyFunction) 5279 S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record, 5280 Loc)); 5281 5282 if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined())) 5283 && Record->getLinkage() == ExternalLinkage) 5284 S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record; 5285 } 5286 for (DeclContext::decl_iterator D = Record->decls_begin(), 5287 DEnd = Record->decls_end(); 5288 D != DEnd; ++D) { 5289 if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D)) 5290 RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc); 5291 } 5292} 5293 5294void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD, 5295 SourceLocation RBraceLoc) { 5296 AdjustDeclIfTemplate(TagD); 5297 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 5298 Tag->setRBraceLoc(RBraceLoc); 5299 5300 if (isa<CXXRecordDecl>(Tag)) 5301 FieldCollector->FinishClass(); 5302 5303 // Exit this scope of this tag's definition. 5304 PopDeclContext(); 5305 5306 if (isa<CXXRecordDecl>(Tag) && !Tag->getLexicalDeclContext()->isRecord()) 5307 RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag), 5308 RBraceLoc); 5309 5310 // Notify the consumer that we've defined a tag. 5311 Consumer.HandleTagDeclDefinition(Tag); 5312} 5313 5314void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) { 5315 AdjustDeclIfTemplate(TagD); 5316 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 5317 Tag->setInvalidDecl(); 5318 5319 // We're undoing ActOnTagStartDefinition here, not 5320 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 5321 // the FieldCollector. 5322 5323 PopDeclContext(); 5324} 5325 5326// Note that FieldName may be null for anonymous bitfields. 5327bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 5328 QualType FieldTy, const Expr *BitWidth, 5329 bool *ZeroWidth) { 5330 // Default to true; that shouldn't confuse checks for emptiness 5331 if (ZeroWidth) 5332 *ZeroWidth = true; 5333 5334 // C99 6.7.2.1p4 - verify the field type. 5335 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 5336 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) { 5337 // Handle incomplete types with specific error. 5338 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 5339 return true; 5340 if (FieldName) 5341 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 5342 << FieldName << FieldTy << BitWidth->getSourceRange(); 5343 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 5344 << FieldTy << BitWidth->getSourceRange(); 5345 } 5346 5347 // If the bit-width is type- or value-dependent, don't try to check 5348 // it now. 5349 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 5350 return false; 5351 5352 llvm::APSInt Value; 5353 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 5354 return true; 5355 5356 if (Value != 0 && ZeroWidth) 5357 *ZeroWidth = false; 5358 5359 // Zero-width bitfield is ok for anonymous field. 5360 if (Value == 0 && FieldName) 5361 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 5362 5363 if (Value.isSigned() && Value.isNegative()) { 5364 if (FieldName) 5365 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 5366 << FieldName << Value.toString(10); 5367 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 5368 << Value.toString(10); 5369 } 5370 5371 if (!FieldTy->isDependentType()) { 5372 uint64_t TypeSize = Context.getTypeSize(FieldTy); 5373 if (Value.getZExtValue() > TypeSize) { 5374 if (FieldName) 5375 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 5376 << FieldName << (unsigned)TypeSize; 5377 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 5378 << (unsigned)TypeSize; 5379 } 5380 } 5381 5382 return false; 5383} 5384 5385/// ActOnField - Each field of a struct/union/class is passed into this in order 5386/// to create a FieldDecl object for it. 5387Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD, 5388 SourceLocation DeclStart, 5389 Declarator &D, ExprTy *BitfieldWidth) { 5390 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()), 5391 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 5392 AS_public); 5393 return DeclPtrTy::make(Res); 5394} 5395 5396/// HandleField - Analyze a field of a C struct or a C++ data member. 5397/// 5398FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 5399 SourceLocation DeclStart, 5400 Declarator &D, Expr *BitWidth, 5401 AccessSpecifier AS) { 5402 IdentifierInfo *II = D.getIdentifier(); 5403 SourceLocation Loc = DeclStart; 5404 if (II) Loc = D.getIdentifierLoc(); 5405 5406 TypeSourceInfo *TInfo = 0; 5407 QualType T = GetTypeForDeclarator(D, S, &TInfo); 5408 if (getLangOptions().CPlusPlus) 5409 CheckExtraCXXDefaultArguments(D); 5410 5411 DiagnoseFunctionSpecifiers(D); 5412 5413 if (D.getDeclSpec().isThreadSpecified()) 5414 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 5415 5416 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName, 5417 ForRedeclaration); 5418 5419 if (PrevDecl && PrevDecl->isTemplateParameter()) { 5420 // Maybe we will complain about the shadowed template parameter. 5421 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5422 // Just pretend that we didn't see the previous declaration. 5423 PrevDecl = 0; 5424 } 5425 5426 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 5427 PrevDecl = 0; 5428 5429 bool Mutable 5430 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 5431 SourceLocation TSSL = D.getSourceRange().getBegin(); 5432 FieldDecl *NewFD 5433 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL, 5434 AS, PrevDecl, &D); 5435 5436 if (NewFD->isInvalidDecl()) 5437 Record->setInvalidDecl(); 5438 5439 if (NewFD->isInvalidDecl() && PrevDecl) { 5440 // Don't introduce NewFD into scope; there's already something 5441 // with the same name in the same scope. 5442 } else if (II) { 5443 PushOnScopeChains(NewFD, S); 5444 } else 5445 Record->addDecl(NewFD); 5446 5447 return NewFD; 5448} 5449 5450/// \brief Build a new FieldDecl and check its well-formedness. 5451/// 5452/// This routine builds a new FieldDecl given the fields name, type, 5453/// record, etc. \p PrevDecl should refer to any previous declaration 5454/// with the same name and in the same scope as the field to be 5455/// created. 5456/// 5457/// \returns a new FieldDecl. 5458/// 5459/// \todo The Declarator argument is a hack. It will be removed once 5460FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 5461 TypeSourceInfo *TInfo, 5462 RecordDecl *Record, SourceLocation Loc, 5463 bool Mutable, Expr *BitWidth, 5464 SourceLocation TSSL, 5465 AccessSpecifier AS, NamedDecl *PrevDecl, 5466 Declarator *D) { 5467 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5468 bool InvalidDecl = false; 5469 if (D) InvalidDecl = D->isInvalidType(); 5470 5471 // If we receive a broken type, recover by assuming 'int' and 5472 // marking this declaration as invalid. 5473 if (T.isNull()) { 5474 InvalidDecl = true; 5475 T = Context.IntTy; 5476 } 5477 5478 QualType EltTy = Context.getBaseElementType(T); 5479 if (!EltTy->isDependentType() && 5480 RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) 5481 InvalidDecl = true; 5482 5483 // C99 6.7.2.1p8: A member of a structure or union may have any type other 5484 // than a variably modified type. 5485 if (!InvalidDecl && T->isVariablyModifiedType()) { 5486 bool SizeIsNegative; 5487 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 5488 SizeIsNegative); 5489 if (!FixedTy.isNull()) { 5490 Diag(Loc, diag::warn_illegal_constant_array_size); 5491 T = FixedTy; 5492 } else { 5493 if (SizeIsNegative) 5494 Diag(Loc, diag::err_typecheck_negative_array_size); 5495 else 5496 Diag(Loc, diag::err_typecheck_field_variable_size); 5497 InvalidDecl = true; 5498 } 5499 } 5500 5501 // Fields can not have abstract class types 5502 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 5503 diag::err_abstract_type_in_decl, 5504 AbstractFieldType)) 5505 InvalidDecl = true; 5506 5507 bool ZeroWidth = false; 5508 // If this is declared as a bit-field, check the bit-field. 5509 if (!InvalidDecl && BitWidth && 5510 VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) { 5511 InvalidDecl = true; 5512 DeleteExpr(BitWidth); 5513 BitWidth = 0; 5514 ZeroWidth = false; 5515 } 5516 5517 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo, 5518 BitWidth, Mutable); 5519 if (InvalidDecl) 5520 NewFD->setInvalidDecl(); 5521 5522 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 5523 Diag(Loc, diag::err_duplicate_member) << II; 5524 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5525 NewFD->setInvalidDecl(); 5526 } 5527 5528 if (!InvalidDecl && getLangOptions().CPlusPlus) { 5529 CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record); 5530 5531 if (!T->isPODType()) 5532 CXXRecord->setPOD(false); 5533 if (!ZeroWidth) 5534 CXXRecord->setEmpty(false); 5535 5536 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 5537 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 5538 5539 if (!RDecl->hasTrivialConstructor()) 5540 CXXRecord->setHasTrivialConstructor(false); 5541 if (!RDecl->hasTrivialCopyConstructor()) 5542 CXXRecord->setHasTrivialCopyConstructor(false); 5543 if (!RDecl->hasTrivialCopyAssignment()) 5544 CXXRecord->setHasTrivialCopyAssignment(false); 5545 if (!RDecl->hasTrivialDestructor()) 5546 CXXRecord->setHasTrivialDestructor(false); 5547 5548 // C++ 9.5p1: An object of a class with a non-trivial 5549 // constructor, a non-trivial copy constructor, a non-trivial 5550 // destructor, or a non-trivial copy assignment operator 5551 // cannot be a member of a union, nor can an array of such 5552 // objects. 5553 // TODO: C++0x alters this restriction significantly. 5554 if (Record->isUnion()) { 5555 // We check for copy constructors before constructors 5556 // because otherwise we'll never get complaints about 5557 // copy constructors. 5558 5559 const CXXSpecialMember invalid = (CXXSpecialMember) -1; 5560 5561 CXXSpecialMember member; 5562 if (!RDecl->hasTrivialCopyConstructor()) 5563 member = CXXCopyConstructor; 5564 else if (!RDecl->hasTrivialConstructor()) 5565 member = CXXDefaultConstructor; 5566 else if (!RDecl->hasTrivialCopyAssignment()) 5567 member = CXXCopyAssignment; 5568 else if (!RDecl->hasTrivialDestructor()) 5569 member = CXXDestructor; 5570 else 5571 member = invalid; 5572 5573 if (member != invalid) { 5574 Diag(Loc, diag::err_illegal_union_member) << Name << member; 5575 DiagnoseNontrivial(RT, member); 5576 NewFD->setInvalidDecl(); 5577 } 5578 } 5579 } 5580 } 5581 5582 // FIXME: We need to pass in the attributes given an AST 5583 // representation, not a parser representation. 5584 if (D) 5585 // FIXME: What to pass instead of TUScope? 5586 ProcessDeclAttributes(TUScope, NewFD, *D); 5587 5588 if (T.isObjCGCWeak()) 5589 Diag(Loc, diag::warn_attribute_weak_on_field); 5590 5591 NewFD->setAccess(AS); 5592 5593 // C++ [dcl.init.aggr]p1: 5594 // An aggregate is an array or a class (clause 9) with [...] no 5595 // private or protected non-static data members (clause 11). 5596 // A POD must be an aggregate. 5597 if (getLangOptions().CPlusPlus && 5598 (AS == AS_private || AS == AS_protected)) { 5599 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 5600 CXXRecord->setAggregate(false); 5601 CXXRecord->setPOD(false); 5602 } 5603 5604 return NewFD; 5605} 5606 5607/// DiagnoseNontrivial - Given that a class has a non-trivial 5608/// special member, figure out why. 5609void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 5610 QualType QT(T, 0U); 5611 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 5612 5613 // Check whether the member was user-declared. 5614 switch (member) { 5615 case CXXDefaultConstructor: 5616 if (RD->hasUserDeclaredConstructor()) { 5617 typedef CXXRecordDecl::ctor_iterator ctor_iter; 5618 for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){ 5619 const FunctionDecl *body = 0; 5620 ci->getBody(body); 5621 if (!body || 5622 !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) { 5623 SourceLocation CtorLoc = ci->getLocation(); 5624 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 5625 return; 5626 } 5627 } 5628 5629 assert(0 && "found no user-declared constructors"); 5630 return; 5631 } 5632 break; 5633 5634 case CXXCopyConstructor: 5635 if (RD->hasUserDeclaredCopyConstructor()) { 5636 SourceLocation CtorLoc = 5637 RD->getCopyConstructor(Context, 0)->getLocation(); 5638 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 5639 return; 5640 } 5641 break; 5642 5643 case CXXCopyAssignment: 5644 if (RD->hasUserDeclaredCopyAssignment()) { 5645 // FIXME: this should use the location of the copy 5646 // assignment, not the type. 5647 SourceLocation TyLoc = RD->getSourceRange().getBegin(); 5648 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 5649 return; 5650 } 5651 break; 5652 5653 case CXXDestructor: 5654 if (RD->hasUserDeclaredDestructor()) { 5655 SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation(); 5656 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 5657 return; 5658 } 5659 break; 5660 } 5661 5662 typedef CXXRecordDecl::base_class_iterator base_iter; 5663 5664 // Virtual bases and members inhibit trivial copying/construction, 5665 // but not trivial destruction. 5666 if (member != CXXDestructor) { 5667 // Check for virtual bases. vbases includes indirect virtual bases, 5668 // so we just iterate through the direct bases. 5669 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 5670 if (bi->isVirtual()) { 5671 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 5672 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 5673 return; 5674 } 5675 5676 // Check for virtual methods. 5677 typedef CXXRecordDecl::method_iterator meth_iter; 5678 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 5679 ++mi) { 5680 if (mi->isVirtual()) { 5681 SourceLocation MLoc = mi->getSourceRange().getBegin(); 5682 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 5683 return; 5684 } 5685 } 5686 } 5687 5688 bool (CXXRecordDecl::*hasTrivial)() const; 5689 switch (member) { 5690 case CXXDefaultConstructor: 5691 hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break; 5692 case CXXCopyConstructor: 5693 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 5694 case CXXCopyAssignment: 5695 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 5696 case CXXDestructor: 5697 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 5698 default: 5699 assert(0 && "unexpected special member"); return; 5700 } 5701 5702 // Check for nontrivial bases (and recurse). 5703 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 5704 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 5705 assert(BaseRT && "Don't know how to handle dependent bases"); 5706 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 5707 if (!(BaseRecTy->*hasTrivial)()) { 5708 SourceLocation BaseLoc = bi->getSourceRange().getBegin(); 5709 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 5710 DiagnoseNontrivial(BaseRT, member); 5711 return; 5712 } 5713 } 5714 5715 // Check for nontrivial members (and recurse). 5716 typedef RecordDecl::field_iterator field_iter; 5717 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 5718 ++fi) { 5719 QualType EltTy = Context.getBaseElementType((*fi)->getType()); 5720 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 5721 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 5722 5723 if (!(EltRD->*hasTrivial)()) { 5724 SourceLocation FLoc = (*fi)->getLocation(); 5725 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 5726 DiagnoseNontrivial(EltRT, member); 5727 return; 5728 } 5729 } 5730 } 5731 5732 assert(0 && "found no explanation for non-trivial member"); 5733} 5734 5735/// TranslateIvarVisibility - Translate visibility from a token ID to an 5736/// AST enum value. 5737static ObjCIvarDecl::AccessControl 5738TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 5739 switch (ivarVisibility) { 5740 default: assert(0 && "Unknown visitibility kind"); 5741 case tok::objc_private: return ObjCIvarDecl::Private; 5742 case tok::objc_public: return ObjCIvarDecl::Public; 5743 case tok::objc_protected: return ObjCIvarDecl::Protected; 5744 case tok::objc_package: return ObjCIvarDecl::Package; 5745 } 5746} 5747 5748/// ActOnIvar - Each ivar field of an objective-c class is passed into this 5749/// in order to create an IvarDecl object for it. 5750Sema::DeclPtrTy Sema::ActOnIvar(Scope *S, 5751 SourceLocation DeclStart, 5752 DeclPtrTy IntfDecl, 5753 Declarator &D, ExprTy *BitfieldWidth, 5754 tok::ObjCKeywordKind Visibility) { 5755 5756 IdentifierInfo *II = D.getIdentifier(); 5757 Expr *BitWidth = (Expr*)BitfieldWidth; 5758 SourceLocation Loc = DeclStart; 5759 if (II) Loc = D.getIdentifierLoc(); 5760 5761 // FIXME: Unnamed fields can be handled in various different ways, for 5762 // example, unnamed unions inject all members into the struct namespace! 5763 5764 TypeSourceInfo *TInfo = 0; 5765 QualType T = GetTypeForDeclarator(D, S, &TInfo); 5766 5767 if (BitWidth) { 5768 // 6.7.2.1p3, 6.7.2.1p4 5769 if (VerifyBitField(Loc, II, T, BitWidth)) { 5770 D.setInvalidType(); 5771 DeleteExpr(BitWidth); 5772 BitWidth = 0; 5773 } 5774 } else { 5775 // Not a bitfield. 5776 5777 // validate II. 5778 5779 } 5780 5781 // C99 6.7.2.1p8: A member of a structure or union may have any type other 5782 // than a variably modified type. 5783 if (T->isVariablyModifiedType()) { 5784 Diag(Loc, diag::err_typecheck_ivar_variable_size); 5785 D.setInvalidType(); 5786 } 5787 5788 // Get the visibility (access control) for this ivar. 5789 ObjCIvarDecl::AccessControl ac = 5790 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 5791 : ObjCIvarDecl::None; 5792 // Must set ivar's DeclContext to its enclosing interface. 5793 ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>(); 5794 ObjCContainerDecl *EnclosingContext; 5795 if (ObjCImplementationDecl *IMPDecl = 5796 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 5797 // Case of ivar declared in an implementation. Context is that of its class. 5798 EnclosingContext = IMPDecl->getClassInterface(); 5799 assert(EnclosingContext && "Implementation has no class interface!"); 5800 } else { 5801 if (ObjCCategoryDecl *CDecl = 5802 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 5803 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 5804 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 5805 return DeclPtrTy(); 5806 } 5807 } 5808 EnclosingContext = EnclosingDecl; 5809 } 5810 5811 // Construct the decl. 5812 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, 5813 EnclosingContext, Loc, II, T, 5814 TInfo, ac, (Expr *)BitfieldWidth); 5815 5816 if (II) { 5817 NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName, 5818 ForRedeclaration); 5819 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 5820 && !isa<TagDecl>(PrevDecl)) { 5821 Diag(Loc, diag::err_duplicate_member) << II; 5822 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5823 NewID->setInvalidDecl(); 5824 } 5825 } 5826 5827 // Process attributes attached to the ivar. 5828 ProcessDeclAttributes(S, NewID, D); 5829 5830 if (D.isInvalidType()) 5831 NewID->setInvalidDecl(); 5832 5833 if (II) { 5834 // FIXME: When interfaces are DeclContexts, we'll need to add 5835 // these to the interface. 5836 S->AddDecl(DeclPtrTy::make(NewID)); 5837 IdResolver.AddDecl(NewID); 5838 } 5839 5840 return DeclPtrTy::make(NewID); 5841} 5842 5843void Sema::ActOnFields(Scope* S, 5844 SourceLocation RecLoc, DeclPtrTy RecDecl, 5845 DeclPtrTy *Fields, unsigned NumFields, 5846 SourceLocation LBrac, SourceLocation RBrac, 5847 AttributeList *Attr) { 5848 Decl *EnclosingDecl = RecDecl.getAs<Decl>(); 5849 assert(EnclosingDecl && "missing record or interface decl"); 5850 5851 // If the decl this is being inserted into is invalid, then it may be a 5852 // redeclaration or some other bogus case. Don't try to add fields to it. 5853 if (EnclosingDecl->isInvalidDecl()) { 5854 // FIXME: Deallocate fields? 5855 return; 5856 } 5857 5858 5859 // Verify that all the fields are okay. 5860 unsigned NumNamedMembers = 0; 5861 llvm::SmallVector<FieldDecl*, 32> RecFields; 5862 5863 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 5864 for (unsigned i = 0; i != NumFields; ++i) { 5865 FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>()); 5866 5867 // Get the type for the field. 5868 Type *FDTy = FD->getType().getTypePtr(); 5869 5870 if (!FD->isAnonymousStructOrUnion()) { 5871 // Remember all fields written by the user. 5872 RecFields.push_back(FD); 5873 } 5874 5875 // If the field is already invalid for some reason, don't emit more 5876 // diagnostics about it. 5877 if (FD->isInvalidDecl()) { 5878 EnclosingDecl->setInvalidDecl(); 5879 continue; 5880 } 5881 5882 // C99 6.7.2.1p2: 5883 // A structure or union shall not contain a member with 5884 // incomplete or function type (hence, a structure shall not 5885 // contain an instance of itself, but may contain a pointer to 5886 // an instance of itself), except that the last member of a 5887 // structure with more than one named member may have incomplete 5888 // array type; such a structure (and any union containing, 5889 // possibly recursively, a member that is such a structure) 5890 // shall not be a member of a structure or an element of an 5891 // array. 5892 if (FDTy->isFunctionType()) { 5893 // Field declared as a function. 5894 Diag(FD->getLocation(), diag::err_field_declared_as_function) 5895 << FD->getDeclName(); 5896 FD->setInvalidDecl(); 5897 EnclosingDecl->setInvalidDecl(); 5898 continue; 5899 } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 && 5900 Record && Record->isStruct()) { 5901 // Flexible array member. 5902 if (NumNamedMembers < 1) { 5903 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 5904 << FD->getDeclName(); 5905 FD->setInvalidDecl(); 5906 EnclosingDecl->setInvalidDecl(); 5907 continue; 5908 } 5909 // Okay, we have a legal flexible array member at the end of the struct. 5910 if (Record) 5911 Record->setHasFlexibleArrayMember(true); 5912 } else if (!FDTy->isDependentType() && 5913 RequireCompleteType(FD->getLocation(), FD->getType(), 5914 diag::err_field_incomplete)) { 5915 // Incomplete type 5916 FD->setInvalidDecl(); 5917 EnclosingDecl->setInvalidDecl(); 5918 continue; 5919 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 5920 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 5921 // If this is a member of a union, then entire union becomes "flexible". 5922 if (Record && Record->isUnion()) { 5923 Record->setHasFlexibleArrayMember(true); 5924 } else { 5925 // If this is a struct/class and this is not the last element, reject 5926 // it. Note that GCC supports variable sized arrays in the middle of 5927 // structures. 5928 if (i != NumFields-1) 5929 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 5930 << FD->getDeclName() << FD->getType(); 5931 else { 5932 // We support flexible arrays at the end of structs in 5933 // other structs as an extension. 5934 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 5935 << FD->getDeclName(); 5936 if (Record) 5937 Record->setHasFlexibleArrayMember(true); 5938 } 5939 } 5940 } 5941 if (Record && FDTTy->getDecl()->hasObjectMember()) 5942 Record->setHasObjectMember(true); 5943 } else if (FDTy->isObjCInterfaceType()) { 5944 /// A field cannot be an Objective-c object 5945 Diag(FD->getLocation(), diag::err_statically_allocated_object); 5946 FD->setInvalidDecl(); 5947 EnclosingDecl->setInvalidDecl(); 5948 continue; 5949 } else if (getLangOptions().ObjC1 && 5950 getLangOptions().getGCMode() != LangOptions::NonGC && 5951 Record && 5952 (FD->getType()->isObjCObjectPointerType() || 5953 FD->getType().isObjCGCStrong())) 5954 Record->setHasObjectMember(true); 5955 // Keep track of the number of named members. 5956 if (FD->getIdentifier()) 5957 ++NumNamedMembers; 5958 } 5959 5960 // Okay, we successfully defined 'Record'. 5961 if (Record) { 5962 Record->completeDefinition(); 5963 } else { 5964 ObjCIvarDecl **ClsFields = 5965 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 5966 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 5967 ID->setLocEnd(RBrac); 5968 // Add ivar's to class's DeclContext. 5969 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 5970 ClsFields[i]->setLexicalDeclContext(ID); 5971 ID->addDecl(ClsFields[i]); 5972 } 5973 // Must enforce the rule that ivars in the base classes may not be 5974 // duplicates. 5975 if (ID->getSuperClass()) 5976 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 5977 } else if (ObjCImplementationDecl *IMPDecl = 5978 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 5979 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 5980 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 5981 // Ivar declared in @implementation never belongs to the implementation. 5982 // Only it is in implementation's lexical context. 5983 ClsFields[I]->setLexicalDeclContext(IMPDecl); 5984 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 5985 } else if (ObjCCategoryDecl *CDecl = 5986 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 5987 // case of ivars in class extension; all other cases have been 5988 // reported as errors elsewhere. 5989 // FIXME. Class extension does not have a LocEnd field. 5990 // CDecl->setLocEnd(RBrac); 5991 // Add ivar's to class extension's DeclContext. 5992 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 5993 ClsFields[i]->setLexicalDeclContext(CDecl); 5994 CDecl->addDecl(ClsFields[i]); 5995 } 5996 } 5997 } 5998 5999 if (Attr) 6000 ProcessDeclAttributeList(S, Record, Attr); 6001} 6002 6003/// \brief Determine whether the given integral value is representable within 6004/// the given type T. 6005static bool isRepresentableIntegerValue(ASTContext &Context, 6006 llvm::APSInt &Value, 6007 QualType T) { 6008 assert(T->isIntegralType() && "Integral type required!"); 6009 unsigned BitWidth = Context.getTypeSize(T); 6010 6011 if (Value.isUnsigned() || Value.isNonNegative()) 6012 return Value.getActiveBits() < BitWidth; 6013 6014 return Value.getMinSignedBits() <= BitWidth; 6015} 6016 6017// \brief Given an integral type, return the next larger integral type 6018// (or a NULL type of no such type exists). 6019static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 6020 // FIXME: Int128/UInt128 support, which also needs to be introduced into 6021 // enum checking below. 6022 assert(T->isIntegralType() && "Integral type required!"); 6023 const unsigned NumTypes = 4; 6024 QualType SignedIntegralTypes[NumTypes] = { 6025 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 6026 }; 6027 QualType UnsignedIntegralTypes[NumTypes] = { 6028 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 6029 Context.UnsignedLongLongTy 6030 }; 6031 6032 unsigned BitWidth = Context.getTypeSize(T); 6033 QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes 6034 : UnsignedIntegralTypes; 6035 for (unsigned I = 0; I != NumTypes; ++I) 6036 if (Context.getTypeSize(Types[I]) > BitWidth) 6037 return Types[I]; 6038 6039 return QualType(); 6040} 6041 6042EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 6043 EnumConstantDecl *LastEnumConst, 6044 SourceLocation IdLoc, 6045 IdentifierInfo *Id, 6046 ExprArg val) { 6047 Expr *Val = (Expr *)val.get(); 6048 6049 unsigned IntWidth = Context.Target.getIntWidth(); 6050 llvm::APSInt EnumVal(IntWidth); 6051 QualType EltTy; 6052 if (Val) { 6053 if (Enum->isDependentType() || Val->isTypeDependent()) 6054 EltTy = Context.DependentTy; 6055 else { 6056 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 6057 SourceLocation ExpLoc; 6058 if (!Val->isValueDependent() && 6059 VerifyIntegerConstantExpression(Val, &EnumVal)) { 6060 Val = 0; 6061 } else { 6062 if (!getLangOptions().CPlusPlus) { 6063 // C99 6.7.2.2p2: 6064 // The expression that defines the value of an enumeration constant 6065 // shall be an integer constant expression that has a value 6066 // representable as an int. 6067 6068 // Complain if the value is not representable in an int. 6069 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 6070 Diag(IdLoc, diag::ext_enum_value_not_int) 6071 << EnumVal.toString(10) << Val->getSourceRange() 6072 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 6073 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 6074 // Force the type of the expression to 'int'. 6075 ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast); 6076 6077 if (Val != val.get()) { 6078 val.release(); 6079 val = Val; 6080 } 6081 } 6082 } 6083 6084 // C++0x [dcl.enum]p5: 6085 // If the underlying type is not fixed, the type of each enumerator 6086 // is the type of its initializing value: 6087 // - If an initializer is specified for an enumerator, the 6088 // initializing value has the same type as the expression. 6089 EltTy = Val->getType(); 6090 } 6091 } 6092 } 6093 6094 if (!Val) { 6095 if (Enum->isDependentType()) 6096 EltTy = Context.DependentTy; 6097 else if (!LastEnumConst) { 6098 // C++0x [dcl.enum]p5: 6099 // If the underlying type is not fixed, the type of each enumerator 6100 // is the type of its initializing value: 6101 // - If no initializer is specified for the first enumerator, the 6102 // initializing value has an unspecified integral type. 6103 // 6104 // GCC uses 'int' for its unspecified integral type, as does 6105 // C99 6.7.2.2p3. 6106 EltTy = Context.IntTy; 6107 } else { 6108 // Assign the last value + 1. 6109 EnumVal = LastEnumConst->getInitVal(); 6110 ++EnumVal; 6111 EltTy = LastEnumConst->getType(); 6112 6113 // Check for overflow on increment. 6114 if (EnumVal < LastEnumConst->getInitVal()) { 6115 // C++0x [dcl.enum]p5: 6116 // If the underlying type is not fixed, the type of each enumerator 6117 // is the type of its initializing value: 6118 // 6119 // - Otherwise the type of the initializing value is the same as 6120 // the type of the initializing value of the preceding enumerator 6121 // unless the incremented value is not representable in that type, 6122 // in which case the type is an unspecified integral type 6123 // sufficient to contain the incremented value. If no such type 6124 // exists, the program is ill-formed. 6125 QualType T = getNextLargerIntegralType(Context, EltTy); 6126 if (T.isNull()) { 6127 // There is no integral type larger enough to represent this 6128 // value. Complain, then allow the value to wrap around. 6129 EnumVal = LastEnumConst->getInitVal(); 6130 EnumVal.zext(EnumVal.getBitWidth() * 2); 6131 Diag(IdLoc, diag::warn_enumerator_too_large) 6132 << EnumVal.toString(10); 6133 } else { 6134 EltTy = T; 6135 } 6136 6137 // Retrieve the last enumerator's value, extent that type to the 6138 // type that is supposed to be large enough to represent the incremented 6139 // value, then increment. 6140 EnumVal = LastEnumConst->getInitVal(); 6141 EnumVal.setIsSigned(EltTy->isSignedIntegerType()); 6142 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy)); 6143 ++EnumVal; 6144 6145 // If we're not in C++, diagnose the overflow of enumerator values, 6146 // which in C99 means that the enumerator value is not representable in 6147 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 6148 // permits enumerator values that are representable in some larger 6149 // integral type. 6150 if (!getLangOptions().CPlusPlus && !T.isNull()) 6151 Diag(IdLoc, diag::warn_enum_value_overflow); 6152 } else if (!getLangOptions().CPlusPlus && 6153 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 6154 // Enforce C99 6.7.2.2p2 even when we compute the next value. 6155 Diag(IdLoc, diag::ext_enum_value_not_int) 6156 << EnumVal.toString(10) << 1; 6157 } 6158 } 6159 } 6160 6161 if (!EltTy->isDependentType()) { 6162 // Make the enumerator value match the signedness and size of the 6163 // enumerator's type. 6164 EnumVal.zextOrTrunc(Context.getTypeSize(EltTy)); 6165 EnumVal.setIsSigned(EltTy->isSignedIntegerType()); 6166 } 6167 6168 val.release(); 6169 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 6170 Val, EnumVal); 6171} 6172 6173 6174Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl, 6175 DeclPtrTy lastEnumConst, 6176 SourceLocation IdLoc, 6177 IdentifierInfo *Id, 6178 SourceLocation EqualLoc, ExprTy *val) { 6179 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>()); 6180 EnumConstantDecl *LastEnumConst = 6181 cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>()); 6182 Expr *Val = static_cast<Expr*>(val); 6183 6184 // The scope passed in may not be a decl scope. Zip up the scope tree until 6185 // we find one that is. 6186 S = getNonFieldDeclScope(S); 6187 6188 // Verify that there isn't already something declared with this name in this 6189 // scope. 6190 NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName, 6191 ForRedeclaration); 6192 if (PrevDecl && PrevDecl->isTemplateParameter()) { 6193 // Maybe we will complain about the shadowed template parameter. 6194 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 6195 // Just pretend that we didn't see the previous declaration. 6196 PrevDecl = 0; 6197 } 6198 6199 if (PrevDecl) { 6200 // When in C++, we may get a TagDecl with the same name; in this case the 6201 // enum constant will 'hide' the tag. 6202 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 6203 "Received TagDecl when not in C++!"); 6204 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 6205 if (isa<EnumConstantDecl>(PrevDecl)) 6206 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 6207 else 6208 Diag(IdLoc, diag::err_redefinition) << Id; 6209 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6210 if (Val) Val->Destroy(Context); 6211 return DeclPtrTy(); 6212 } 6213 } 6214 6215 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst, 6216 IdLoc, Id, Owned(Val)); 6217 6218 // Register this decl in the current scope stack. 6219 if (New) { 6220 New->setAccess(TheEnumDecl->getAccess()); 6221 PushOnScopeChains(New, S); 6222 } 6223 6224 return DeclPtrTy::make(New); 6225} 6226 6227void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 6228 SourceLocation RBraceLoc, DeclPtrTy EnumDeclX, 6229 DeclPtrTy *Elements, unsigned NumElements, 6230 Scope *S, AttributeList *Attr) { 6231 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>()); 6232 QualType EnumType = Context.getTypeDeclType(Enum); 6233 6234 if (Attr) 6235 ProcessDeclAttributeList(S, Enum, Attr); 6236 6237 if (Enum->isDependentType()) { 6238 for (unsigned i = 0; i != NumElements; ++i) { 6239 EnumConstantDecl *ECD = 6240 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 6241 if (!ECD) continue; 6242 6243 ECD->setType(EnumType); 6244 } 6245 6246 Enum->completeDefinition(Context.DependentTy, Context.DependentTy); 6247 return; 6248 } 6249 6250 // TODO: If the result value doesn't fit in an int, it must be a long or long 6251 // long value. ISO C does not support this, but GCC does as an extension, 6252 // emit a warning. 6253 unsigned IntWidth = Context.Target.getIntWidth(); 6254 unsigned CharWidth = Context.Target.getCharWidth(); 6255 unsigned ShortWidth = Context.Target.getShortWidth(); 6256 6257 // Verify that all the values are okay, compute the size of the values, and 6258 // reverse the list. 6259 unsigned NumNegativeBits = 0; 6260 unsigned NumPositiveBits = 0; 6261 6262 // Keep track of whether all elements have type int. 6263 bool AllElementsInt = true; 6264 6265 for (unsigned i = 0; i != NumElements; ++i) { 6266 EnumConstantDecl *ECD = 6267 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 6268 if (!ECD) continue; // Already issued a diagnostic. 6269 6270 const llvm::APSInt &InitVal = ECD->getInitVal(); 6271 6272 // Keep track of the size of positive and negative values. 6273 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 6274 NumPositiveBits = std::max(NumPositiveBits, 6275 (unsigned)InitVal.getActiveBits()); 6276 else 6277 NumNegativeBits = std::max(NumNegativeBits, 6278 (unsigned)InitVal.getMinSignedBits()); 6279 6280 // Keep track of whether every enum element has type int (very commmon). 6281 if (AllElementsInt) 6282 AllElementsInt = ECD->getType() == Context.IntTy; 6283 } 6284 6285 // Figure out the type that should be used for this enum. 6286 // FIXME: Support -fshort-enums. 6287 QualType BestType; 6288 unsigned BestWidth; 6289 6290 // C++0x N3000 [conv.prom]p3: 6291 // An rvalue of an unscoped enumeration type whose underlying 6292 // type is not fixed can be converted to an rvalue of the first 6293 // of the following types that can represent all the values of 6294 // the enumeration: int, unsigned int, long int, unsigned long 6295 // int, long long int, or unsigned long long int. 6296 // C99 6.4.4.3p2: 6297 // An identifier declared as an enumeration constant has type int. 6298 // The C99 rule is modified by a gcc extension 6299 QualType BestPromotionType; 6300 6301 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 6302 6303 if (NumNegativeBits) { 6304 // If there is a negative value, figure out the smallest integer type (of 6305 // int/long/longlong) that fits. 6306 // If it's packed, check also if it fits a char or a short. 6307 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 6308 BestType = Context.SignedCharTy; 6309 BestWidth = CharWidth; 6310 } else if (Packed && NumNegativeBits <= ShortWidth && 6311 NumPositiveBits < ShortWidth) { 6312 BestType = Context.ShortTy; 6313 BestWidth = ShortWidth; 6314 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 6315 BestType = Context.IntTy; 6316 BestWidth = IntWidth; 6317 } else { 6318 BestWidth = Context.Target.getLongWidth(); 6319 6320 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 6321 BestType = Context.LongTy; 6322 } else { 6323 BestWidth = Context.Target.getLongLongWidth(); 6324 6325 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 6326 Diag(Enum->getLocation(), diag::warn_enum_too_large); 6327 BestType = Context.LongLongTy; 6328 } 6329 } 6330 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 6331 } else { 6332 // If there is no negative value, figure out the smallest type that fits 6333 // all of the enumerator values. 6334 // If it's packed, check also if it fits a char or a short. 6335 if (Packed && NumPositiveBits <= CharWidth) { 6336 BestType = Context.UnsignedCharTy; 6337 BestPromotionType = Context.IntTy; 6338 BestWidth = CharWidth; 6339 } else if (Packed && NumPositiveBits <= ShortWidth) { 6340 BestType = Context.UnsignedShortTy; 6341 BestPromotionType = Context.IntTy; 6342 BestWidth = ShortWidth; 6343 } else if (NumPositiveBits <= IntWidth) { 6344 BestType = Context.UnsignedIntTy; 6345 BestWidth = IntWidth; 6346 BestPromotionType 6347 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 6348 ? Context.UnsignedIntTy : Context.IntTy; 6349 } else if (NumPositiveBits <= 6350 (BestWidth = Context.Target.getLongWidth())) { 6351 BestType = Context.UnsignedLongTy; 6352 BestPromotionType 6353 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 6354 ? Context.UnsignedLongTy : Context.LongTy; 6355 } else { 6356 BestWidth = Context.Target.getLongLongWidth(); 6357 assert(NumPositiveBits <= BestWidth && 6358 "How could an initializer get larger than ULL?"); 6359 BestType = Context.UnsignedLongLongTy; 6360 BestPromotionType 6361 = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus) 6362 ? Context.UnsignedLongLongTy : Context.LongLongTy; 6363 } 6364 } 6365 6366 // Loop over all of the enumerator constants, changing their types to match 6367 // the type of the enum if needed. 6368 for (unsigned i = 0; i != NumElements; ++i) { 6369 EnumConstantDecl *ECD = 6370 cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>()); 6371 if (!ECD) continue; // Already issued a diagnostic. 6372 6373 // Standard C says the enumerators have int type, but we allow, as an 6374 // extension, the enumerators to be larger than int size. If each 6375 // enumerator value fits in an int, type it as an int, otherwise type it the 6376 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 6377 // that X has type 'int', not 'unsigned'. 6378 6379 // Determine whether the value fits into an int. 6380 llvm::APSInt InitVal = ECD->getInitVal(); 6381 6382 // If it fits into an integer type, force it. Otherwise force it to match 6383 // the enum decl type. 6384 QualType NewTy; 6385 unsigned NewWidth; 6386 bool NewSign; 6387 if (!getLangOptions().CPlusPlus && 6388 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 6389 NewTy = Context.IntTy; 6390 NewWidth = IntWidth; 6391 NewSign = true; 6392 } else if (ECD->getType() == BestType) { 6393 // Already the right type! 6394 if (getLangOptions().CPlusPlus) 6395 // C++ [dcl.enum]p4: Following the closing brace of an 6396 // enum-specifier, each enumerator has the type of its 6397 // enumeration. 6398 ECD->setType(EnumType); 6399 continue; 6400 } else { 6401 NewTy = BestType; 6402 NewWidth = BestWidth; 6403 NewSign = BestType->isSignedIntegerType(); 6404 } 6405 6406 // Adjust the APSInt value. 6407 InitVal.extOrTrunc(NewWidth); 6408 InitVal.setIsSigned(NewSign); 6409 ECD->setInitVal(InitVal); 6410 6411 // Adjust the Expr initializer and type. 6412 if (ECD->getInitExpr()) 6413 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, 6414 CastExpr::CK_IntegralCast, 6415 ECD->getInitExpr(), 6416 /*isLvalue=*/false)); 6417 if (getLangOptions().CPlusPlus) 6418 // C++ [dcl.enum]p4: Following the closing brace of an 6419 // enum-specifier, each enumerator has the type of its 6420 // enumeration. 6421 ECD->setType(EnumType); 6422 else 6423 ECD->setType(NewTy); 6424 } 6425 6426 Enum->completeDefinition(BestType, BestPromotionType); 6427} 6428 6429Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 6430 ExprArg expr) { 6431 StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>()); 6432 6433 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 6434 Loc, AsmString); 6435 CurContext->addDecl(New); 6436 return DeclPtrTy::make(New); 6437} 6438 6439void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 6440 SourceLocation PragmaLoc, 6441 SourceLocation NameLoc) { 6442 Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName); 6443 6444 if (PrevDecl) { 6445 PrevDecl->addAttr(::new (Context) WeakAttr()); 6446 } else { 6447 (void)WeakUndeclaredIdentifiers.insert( 6448 std::pair<IdentifierInfo*,WeakInfo> 6449 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 6450 } 6451} 6452 6453void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 6454 IdentifierInfo* AliasName, 6455 SourceLocation PragmaLoc, 6456 SourceLocation NameLoc, 6457 SourceLocation AliasNameLoc) { 6458 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName); 6459 WeakInfo W = WeakInfo(Name, NameLoc); 6460 6461 if (PrevDecl) { 6462 if (!PrevDecl->hasAttr<AliasAttr>()) 6463 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 6464 DeclApplyPragmaWeak(TUScope, ND, W); 6465 } else { 6466 (void)WeakUndeclaredIdentifiers.insert( 6467 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 6468 } 6469} 6470