blob: 2db8208d7245103ec127d2487355b19a9249303a [file] [log] [blame]
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//
#include "Sema.h"
#include "SemaInherit.h"
#include "clang/AST/APValue.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/Analysis/CFG.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Parse/DeclSpec.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/SourceManager.h"
// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include <algorithm>
#include <functional>
#include <queue>
using namespace clang;
/// getDeclName - Return a pretty name for the specified decl if possible, or
/// an empty string if not. This is used for pretty crash reporting.
std::string Sema::getDeclName(DeclPtrTy d) {
Decl *D = d.getAs<Decl>();
if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
return DN->getQualifiedNameAsString();
return "";
}
Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
}
/// \brief If the identifier refers to a type name within this scope,
/// return the declaration of that type.
///
/// This routine performs ordinary name lookup of the identifier II
/// within the given scope, with optional C++ scope specifier SS, to
/// determine whether the name refers to a type. If so, returns an
/// opaque pointer (actually a QualType) corresponding to that
/// type. Otherwise, returns NULL.
///
/// If name lookup results in an ambiguity, this routine will complain
/// and then return NULL.
Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, const CXXScopeSpec *SS) {
// C++ [temp.res]p3:
// A qualified-id that refers to a type and in which the
// nested-name-specifier depends on a template-parameter (14.6.2)
// shall be prefixed by the keyword typename to indicate that the
// qualified-id denotes a type, forming an
// elaborated-type-specifier (7.1.5.3).
//
// We therefore do not perform any name lookup if the result would
// refer to a member of an unknown specialization.
if (SS && isUnknownSpecialization(*SS))
return 0;
LookupResult Result
= LookupParsedName(S, SS, &II, LookupOrdinaryName, false, false);
NamedDecl *IIDecl = 0;
switch (Result.getKind()) {
case LookupResult::NotFound:
case LookupResult::FoundOverloaded:
return 0;
case LookupResult::AmbiguousBaseSubobjectTypes:
case LookupResult::AmbiguousBaseSubobjects:
case LookupResult::AmbiguousReference: {
// Look to see if we have a type anywhere in the list of results.
for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
Res != ResEnd; ++Res) {
if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
if (!IIDecl ||
(*Res)->getLocation().getRawEncoding() <
IIDecl->getLocation().getRawEncoding())
IIDecl = *Res;
}
}
if (!IIDecl) {
// None of the entities we found is a type, so there is no way
// to even assume that the result is a type. In this case, don't
// complain about the ambiguity. The parser will either try to
// perform this lookup again (e.g., as an object name), which
// will produce the ambiguity, or will complain that it expected
// a type name.
Result.Destroy();
return 0;
}
// We found a type within the ambiguous lookup; diagnose the
// ambiguity and then return that type. This might be the right
// answer, or it might not be, but it suppresses any attempt to
// perform the name lookup again.
DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
break;
}
case LookupResult::Found:
IIDecl = Result.getAsDecl();
break;
}
if (IIDecl) {
QualType T;
if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
// Check whether we can use this type
(void)DiagnoseUseOfDecl(IIDecl, NameLoc);
if (getLangOptions().CPlusPlus) {
// C++ [temp.local]p2:
// Within the scope of a class template specialization or
// partial specialization, when the injected-class-name is
// not followed by a <, it is equivalent to the
// injected-class-name followed by the template-argument s
// of the class template specialization or partial
// specialization enclosed in <>.
if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD))
if (RD->isInjectedClassName())
if (ClassTemplateDecl *Template = RD->getDescribedClassTemplate())
T = Template->getInjectedClassNameType(Context);
}
if (T.isNull())
T = Context.getTypeDeclType(TD);
} else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
// Check whether we can use this interface.
(void)DiagnoseUseOfDecl(IIDecl, NameLoc);
T = Context.getObjCInterfaceType(IDecl);
} else
return 0;
if (SS)
T = getQualifiedNameType(*SS, T);
return T.getAsOpaquePtr();
}
return 0;
}
/// isTagName() - This method is called *for error recovery purposes only*
/// to determine if the specified name is a valid tag name ("struct foo"). If
/// so, this returns the TST for the tag corresponding to it (TST_enum,
/// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
/// where the user forgot to specify the tag.
DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
// Do a tag name lookup in this scope.
LookupResult R = LookupName(S, &II, LookupTagName, false, false);
if (R.getKind() == LookupResult::Found)
if (const TagDecl *TD = dyn_cast<TagDecl>(R.getAsDecl())) {
switch (TD->getTagKind()) {
case TagDecl::TK_struct: return DeclSpec::TST_struct;
case TagDecl::TK_union: return DeclSpec::TST_union;
case TagDecl::TK_class: return DeclSpec::TST_class;
case TagDecl::TK_enum: return DeclSpec::TST_enum;
}
}
return DeclSpec::TST_unspecified;
}
// Determines the context to return to after temporarily entering a
// context. This depends in an unnecessarily complicated way on the
// exact ordering of callbacks from the parser.
DeclContext *Sema::getContainingDC(DeclContext *DC) {
// Functions defined inline within classes aren't parsed until we've
// finished parsing the top-level class, so the top-level class is
// the context we'll need to return to.
if (isa<FunctionDecl>(DC)) {
DC = DC->getLexicalParent();
// A function not defined within a class will always return to its
// lexical context.
if (!isa<CXXRecordDecl>(DC))
return DC;
// A C++ inline method/friend is parsed *after* the topmost class
// it was declared in is fully parsed ("complete"); the topmost
// class is the context we need to return to.
while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
DC = RD;
// Return the declaration context of the topmost class the inline method is
// declared in.
return DC;
}
if (isa<ObjCMethodDecl>(DC))
return Context.getTranslationUnitDecl();
return DC->getLexicalParent();
}
void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
assert(getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one.");
CurContext = DC;
S->setEntity(DC);
}
void Sema::PopDeclContext() {
assert(CurContext && "DeclContext imbalance!");
CurContext = getContainingDC(CurContext);
}
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
assert(PreDeclaratorDC == 0 && "Previous declarator context not popped?");
PreDeclaratorDC = static_cast<DeclContext*>(S->getEntity());
CurContext = DC;
assert(CurContext && "No context?");
S->setEntity(CurContext);
}
void Sema::ExitDeclaratorContext(Scope *S) {
S->setEntity(PreDeclaratorDC);
PreDeclaratorDC = 0;
// Reset CurContext to the nearest enclosing context.
while (!S->getEntity() && S->getParent())
S = S->getParent();
CurContext = static_cast<DeclContext*>(S->getEntity());
assert(CurContext && "No context?");
}
/// \brief Determine whether we allow overloading of the function
/// PrevDecl with another declaration.
///
/// This routine determines whether overloading is possible, not
/// whether some new function is actually an overload. It will return
/// true in C++ (where we can always provide overloads) or, as an
/// extension, in C when the previous function is already an
/// overloaded function declaration or has the "overloadable"
/// attribute.
static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
if (Context.getLangOptions().CPlusPlus)
return true;
if (isa<OverloadedFunctionDecl>(PrevDecl))
return true;
return PrevDecl->getAttr<OverloadableAttr>() != 0;
}
/// Add this decl to the scope shadowed decl chains.
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
// Move up the scope chain until we find the nearest enclosing
// non-transparent context. The declaration will be introduced into this
// scope.
while (S->getEntity() &&
((DeclContext *)S->getEntity())->isTransparentContext())
S = S->getParent();
S->AddDecl(DeclPtrTy::make(D));
// Add scoped declarations into their context, so that they can be
// found later. Declarations without a context won't be inserted
// into any context.
CurContext->addDecl(D);
// C++ [basic.scope]p4:
// -- exactly one declaration shall declare a class name or
// enumeration name that is not a typedef name and the other
// declarations shall all refer to the same object or
// enumerator, or all refer to functions and function templates;
// in this case the class name or enumeration name is hidden.
if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
// We are pushing the name of a tag (enum or class).
if (CurContext->getLookupContext()
== TD->getDeclContext()->getLookupContext()) {
// We're pushing the tag into the current context, which might
// require some reshuffling in the identifier resolver.
IdentifierResolver::iterator
I = IdResolver.begin(TD->getDeclName()),
IEnd = IdResolver.end();
if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
NamedDecl *PrevDecl = *I;
for (; I != IEnd && isDeclInScope(*I, CurContext, S);
PrevDecl = *I, ++I) {
if (TD->declarationReplaces(*I)) {
// This is a redeclaration. Remove it from the chain and
// break out, so that we'll add in the shadowed
// declaration.
S->RemoveDecl(DeclPtrTy::make(*I));
if (PrevDecl == *I) {
IdResolver.RemoveDecl(*I);
IdResolver.AddDecl(TD);
return;
} else {
IdResolver.RemoveDecl(*I);
break;
}
}
}
// There is already a declaration with the same name in the same
// scope, which is not a tag declaration. It must be found
// before we find the new declaration, so insert the new
// declaration at the end of the chain.
IdResolver.AddShadowedDecl(TD, PrevDecl);
return;
}
}
} else if ((isa<FunctionDecl>(D) &&
AllowOverloadingOfFunction(D, Context)) ||
isa<FunctionTemplateDecl>(D)) {
// We are pushing the name of a function or function template,
// which might be an overloaded name.
IdentifierResolver::iterator Redecl
= std::find_if(IdResolver.begin(D->getDeclName()),
IdResolver.end(),
std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
D));
if (Redecl != IdResolver.end() &&
S->isDeclScope(DeclPtrTy::make(*Redecl))) {
// There is already a declaration of a function on our
// IdResolver chain. Replace it with this declaration.
S->RemoveDecl(DeclPtrTy::make(*Redecl));
IdResolver.RemoveDecl(*Redecl);
}
} else if (isa<ObjCInterfaceDecl>(D)) {
// We're pushing an Objective-C interface into the current
// context. If there is already an alias declaration, remove it first.
for (IdentifierResolver::iterator
I = IdResolver.begin(D->getDeclName()), IEnd = IdResolver.end();
I != IEnd; ++I) {
if (isa<ObjCCompatibleAliasDecl>(*I)) {
S->RemoveDecl(DeclPtrTy::make(*I));
IdResolver.RemoveDecl(*I);
break;
}
}
}
IdResolver.AddDecl(D);
}
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
if (S->decl_empty()) return;
assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
"Scope shouldn't contain decls!");
for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
I != E; ++I) {
Decl *TmpD = (*I).getAs<Decl>();
assert(TmpD && "This decl didn't get pushed??");
assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
NamedDecl *D = cast<NamedDecl>(TmpD);
if (!D->getDeclName()) continue;
// Remove this name from our lexical scope.
IdResolver.RemoveDecl(D);
}
}
/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
/// return 0 if one not found.
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
// The third "scope" argument is 0 since we aren't enabling lazy built-in
// creation from this context.
NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
}
/// getNonFieldDeclScope - Retrieves the innermost scope, starting
/// from S, where a non-field would be declared. This routine copes
/// with the difference between C and C++ scoping rules in structs and
/// unions. For example, the following code is well-formed in C but
/// ill-formed in C++:
/// @code
/// struct S6 {
/// enum { BAR } e;
/// };
///
/// void test_S6() {
/// struct S6 a;
/// a.e = BAR;
/// }
/// @endcode
/// For the declaration of BAR, this routine will return a different
/// scope. The scope S will be the scope of the unnamed enumeration
/// within S6. In C++, this routine will return the scope associated
/// with S6, because the enumeration's scope is a transparent
/// context but structures can contain non-field names. In C, this
/// routine will return the translation unit scope, since the
/// enumeration's scope is a transparent context and structures cannot
/// contain non-field names.
Scope *Sema::getNonFieldDeclScope(Scope *S) {
while (((S->getFlags() & Scope::DeclScope) == 0) ||
(S->getEntity() &&
((DeclContext *)S->getEntity())->isTransparentContext()) ||
(S->isClassScope() && !getLangOptions().CPlusPlus))
S = S->getParent();
return S;
}
void Sema::InitBuiltinVaListType() {
if (!Context.getBuiltinVaListType().isNull())
return;
IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
}
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
/// file scope. lazily create a decl for it. ForRedeclaration is true
/// if we're creating this built-in in anticipation of redeclaring the
/// built-in.
NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Scope *S, bool ForRedeclaration,
SourceLocation Loc) {
Builtin::ID BID = (Builtin::ID)bid;
if (Context.BuiltinInfo.hasVAListUse(BID))
InitBuiltinVaListType();
ASTContext::GetBuiltinTypeError Error;
QualType R = Context.GetBuiltinType(BID, Error);
switch (Error) {
case ASTContext::GE_None:
// Okay
break;
case ASTContext::GE_Missing_stdio:
if (ForRedeclaration)
Diag(Loc, diag::err_implicit_decl_requires_stdio)
<< Context.BuiltinInfo.GetName(BID);
return 0;
case ASTContext::GE_Missing_setjmp:
if (ForRedeclaration)
Diag(Loc, diag::err_implicit_decl_requires_setjmp)
<< Context.BuiltinInfo.GetName(BID);
return 0;
}
if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
Diag(Loc, diag::ext_implicit_lib_function_decl)
<< Context.BuiltinInfo.GetName(BID)
<< R;
if (Context.BuiltinInfo.getHeaderName(BID) &&
Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
!= Diagnostic::Ignored)
Diag(Loc, diag::note_please_include_header)
<< Context.BuiltinInfo.getHeaderName(BID)
<< Context.BuiltinInfo.GetName(BID);
}
FunctionDecl *New = FunctionDecl::Create(Context,
Context.getTranslationUnitDecl(),
Loc, II, R, /*DInfo=*/0,
FunctionDecl::Extern, false,
/*hasPrototype=*/true);
New->setImplicit();
// Create Decl objects for each parameter, adding them to the
// FunctionDecl.
if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
llvm::SmallVector<ParmVarDecl*, 16> Params;
for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
FT->getArgType(i), /*DInfo=*/0,
VarDecl::None, 0));
New->setParams(Context, Params.data(), Params.size());
}
AddKnownFunctionAttributes(New);
// TUScope is the translation-unit scope to insert this function into.
// FIXME: This is hideous. We need to teach PushOnScopeChains to
// relate Scopes to DeclContexts, and probably eliminate CurContext
// entirely, but we're not there yet.
DeclContext *SavedContext = CurContext;
CurContext = Context.getTranslationUnitDecl();
PushOnScopeChains(New, TUScope);
CurContext = SavedContext;
return New;
}
/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
/// everything from the standard library is defined.
NamespaceDecl *Sema::GetStdNamespace() {
if (!StdNamespace) {
IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
DeclContext *Global = Context.getTranslationUnitDecl();
Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
}
return StdNamespace;
}
/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
/// same name and scope as a previous declaration 'Old'. Figure out
/// how to resolve this situation, merging decls or emitting
/// diagnostics as appropriate. If there was an error, set New to be invalid.
///
void Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
// If either decl is known invalid already, set the new one to be invalid and
// don't bother doing any merging checks.
if (New->isInvalidDecl() || OldD->isInvalidDecl())
return New->setInvalidDecl();
// Allow multiple definitions for ObjC built-in typedefs.
// FIXME: Verify the underlying types are equivalent!
if (getLangOptions().ObjC1) {
const IdentifierInfo *TypeID = New->getIdentifier();
switch (TypeID->getLength()) {
default: break;
case 2:
if (!TypeID->isStr("id"))
break;
Context.ObjCIdRedefinitionType = New->getUnderlyingType();
// Install the built-in type for 'id', ignoring the current definition.
New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
return;
case 5:
if (!TypeID->isStr("Class"))
break;
Context.ObjCClassRedefinitionType = New->getUnderlyingType();
// Install the built-in type for 'Class', ignoring the current definition.
New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
return;
case 3:
if (!TypeID->isStr("SEL"))
break;
Context.setObjCSelType(Context.getTypeDeclType(New));
return;
case 8:
if (!TypeID->isStr("Protocol"))
break;
Context.setObjCProtoType(New->getUnderlyingType());
return;
}
// Fall through - the typedef name was not a builtin type.
}
// Verify the old decl was also a type.
TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
if (OldD->getLocation().isValid())
Diag(OldD->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
// Determine the "old" type we'll use for checking and diagnostics.
QualType OldType;
if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
OldType = OldTypedef->getUnderlyingType();
else
OldType = Context.getTypeDeclType(Old);
// If the typedef types are not identical, reject them in all languages and
// with any extensions enabled.
if (OldType != New->getUnderlyingType() &&
Context.getCanonicalType(OldType) !=
Context.getCanonicalType(New->getUnderlyingType())) {
Diag(New->getLocation(), diag::err_redefinition_different_typedef)
<< New->getUnderlyingType() << OldType;
if (Old->getLocation().isValid())
Diag(Old->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
if (getLangOptions().Microsoft)
return;
// C++ [dcl.typedef]p2:
// In a given non-class scope, a typedef specifier can be used to
// redefine the name of any type declared in that scope to refer
// to the type to which it already refers.
if (getLangOptions().CPlusPlus) {
if (!isa<CXXRecordDecl>(CurContext))
return;
Diag(New->getLocation(), diag::err_redefinition)
<< New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
// If we have a redefinition of a typedef in C, emit a warning. This warning
// is normally mapped to an error, but can be controlled with
// -Wtypedef-redefinition. If either the original or the redefinition is
// in a system header, don't emit this for compatibility with GCC.
if (PP.getDiagnostics().getSuppressSystemWarnings() &&
(Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
Context.getSourceManager().isInSystemHeader(New->getLocation())))
return;
Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
<< New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
return;
}
/// DeclhasAttr - returns true if decl Declaration already has the target
/// attribute.
static bool
DeclHasAttr(const Decl *decl, const Attr *target) {
for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
if (attr->getKind() == target->getKind())
return true;
return false;
}
/// MergeAttributes - append attributes from the Old decl to the New one.
static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
if (!DeclHasAttr(New, attr) && attr->isMerged()) {
Attr *NewAttr = attr->clone(C);
NewAttr->setInherited(true);
New->addAttr(NewAttr);
}
}
}
/// Used in MergeFunctionDecl to keep track of function parameters in
/// C.
struct GNUCompatibleParamWarning {
ParmVarDecl *OldParm;
ParmVarDecl *NewParm;
QualType PromotedType;
};
/// MergeFunctionDecl - We just parsed a function 'New' from
/// declarator D which has the same name and scope as a previous
/// declaration 'Old'. Figure out how to resolve this situation,
/// merging decls or emitting diagnostics as appropriate.
///
/// In C++, New and Old must be declarations that are not
/// overloaded. Use IsOverload to determine whether New and Old are
/// overloaded, and to select the Old declaration that New should be
/// merged with.
///
/// Returns true if there was an error, false otherwise.
bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
assert(!isa<OverloadedFunctionDecl>(OldD) &&
"Cannot merge with an overloaded function declaration");
// Verify the old decl was also a function.
FunctionDecl *Old = 0;
if (FunctionTemplateDecl *OldFunctionTemplate
= dyn_cast<FunctionTemplateDecl>(OldD))
Old = OldFunctionTemplate->getTemplatedDecl();
else
Old = dyn_cast<FunctionDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
Diag(OldD->getLocation(), diag::note_previous_definition);
return true;
}
// Determine whether the previous declaration was a definition,
// implicit declaration, or a declaration.
diag::kind PrevDiag;
if (Old->isThisDeclarationADefinition())
PrevDiag = diag::note_previous_definition;
else if (Old->isImplicit())
PrevDiag = diag::note_previous_implicit_declaration;
else
PrevDiag = diag::note_previous_declaration;
QualType OldQType = Context.getCanonicalType(Old->getType());
QualType NewQType = Context.getCanonicalType(New->getType());
if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
New->getStorageClass() == FunctionDecl::Static &&
Old->getStorageClass() != FunctionDecl::Static) {
Diag(New->getLocation(), diag::err_static_non_static)
<< New;
Diag(Old->getLocation(), PrevDiag);
return true;
}
if (getLangOptions().CPlusPlus) {
// (C++98 13.1p2):
// Certain function declarations cannot be overloaded:
// -- Function declarations that differ only in the return type
// cannot be overloaded.
QualType OldReturnType
= cast<FunctionType>(OldQType.getTypePtr())->getResultType();
QualType NewReturnType
= cast<FunctionType>(NewQType.getTypePtr())->getResultType();
if (OldReturnType != NewReturnType) {
Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
return true;
}
const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
if (OldMethod && NewMethod &&
NewMethod->getLexicalDeclContext()->isRecord()) {
// -- Member function declarations with the same name and the
// same parameter types cannot be overloaded if any of them
// is a static member function declaration.
if (OldMethod->isStatic() || NewMethod->isStatic()) {
Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
return true;
}
// C++ [class.mem]p1:
// [...] A member shall not be declared twice in the
// member-specification, except that a nested class or member
// class template can be declared and then later defined.
unsigned NewDiag;
if (isa<CXXConstructorDecl>(OldMethod))
NewDiag = diag::err_constructor_redeclared;
else if (isa<CXXDestructorDecl>(NewMethod))
NewDiag = diag::err_destructor_redeclared;
else if (isa<CXXConversionDecl>(NewMethod))
NewDiag = diag::err_conv_function_redeclared;
else
NewDiag = diag::err_member_redeclared;
Diag(New->getLocation(), NewDiag);
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
}
// (C++98 8.3.5p3):
// All declarations for a function shall agree exactly in both the
// return type and the parameter-type-list.
if (OldQType == NewQType)
return MergeCompatibleFunctionDecls(New, Old);
// Fall through for conflicting redeclarations and redefinitions.
}
// C: Function types need to be compatible, not identical. This handles
// duplicate function decls like "void f(int); void f(enum X);" properly.
if (!getLangOptions().CPlusPlus &&
Context.typesAreCompatible(OldQType, NewQType)) {
const FunctionType *OldFuncType = OldQType->getAsFunctionType();
const FunctionType *NewFuncType = NewQType->getAsFunctionType();
const FunctionProtoType *OldProto = 0;
if (isa<FunctionNoProtoType>(NewFuncType) &&
(OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
// The old declaration provided a function prototype, but the
// new declaration does not. Merge in the prototype.
assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
OldProto->arg_type_end());
NewQType = Context.getFunctionType(NewFuncType->getResultType(),
ParamTypes.data(), ParamTypes.size(),
OldProto->isVariadic(),
OldProto->getTypeQuals());
New->setType(NewQType);
New->setHasInheritedPrototype();
// Synthesize a parameter for each argument type.
llvm::SmallVector<ParmVarDecl*, 16> Params;
for (FunctionProtoType::arg_type_iterator
ParamType = OldProto->arg_type_begin(),
ParamEnd = OldProto->arg_type_end();
ParamType != ParamEnd; ++ParamType) {
ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
SourceLocation(), 0,
*ParamType, /*DInfo=*/0,
VarDecl::None, 0);
Param->setImplicit();
Params.push_back(Param);
}
New->setParams(Context, Params.data(), Params.size());
}
return MergeCompatibleFunctionDecls(New, Old);
}
// GNU C permits a K&R definition to follow a prototype declaration
// if the declared types of the parameters in the K&R definition
// match the types in the prototype declaration, even when the
// promoted types of the parameters from the K&R definition differ
// from the types in the prototype. GCC then keeps the types from
// the prototype.
//
// If a variadic prototype is followed by a non-variadic K&R definition,
// the K&R definition becomes variadic. This is sort of an edge case, but
// it's legal per the standard depending on how you read C99 6.7.5.3p15 and
// C99 6.9.1p8.
if (!getLangOptions().CPlusPlus &&
Old->hasPrototype() && !New->hasPrototype() &&
New->getType()->getAsFunctionProtoType() &&
Old->getNumParams() == New->getNumParams()) {
llvm::SmallVector<QualType, 16> ArgTypes;
llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
const FunctionProtoType *OldProto
= Old->getType()->getAsFunctionProtoType();
const FunctionProtoType *NewProto
= New->getType()->getAsFunctionProtoType();
// Determine whether this is the GNU C extension.
QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
NewProto->getResultType());
bool LooseCompatible = !MergedReturn.isNull();
for (unsigned Idx = 0, End = Old->getNumParams();
LooseCompatible && Idx != End; ++Idx) {
ParmVarDecl *OldParm = Old->getParamDecl(Idx);
ParmVarDecl *NewParm = New->getParamDecl(Idx);
if (Context.typesAreCompatible(OldParm->getType(),
NewProto->getArgType(Idx))) {
ArgTypes.push_back(NewParm->getType());
} else if (Context.typesAreCompatible(OldParm->getType(),
NewParm->getType())) {
GNUCompatibleParamWarning Warn
= { OldParm, NewParm, NewProto->getArgType(Idx) };
Warnings.push_back(Warn);
ArgTypes.push_back(NewParm->getType());
} else
LooseCompatible = false;
}
if (LooseCompatible) {
for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
Diag(Warnings[Warn].NewParm->getLocation(),
diag::ext_param_promoted_not_compatible_with_prototype)
<< Warnings[Warn].PromotedType
<< Warnings[Warn].OldParm->getType();
Diag(Warnings[Warn].OldParm->getLocation(),
diag::note_previous_declaration);
}
New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
ArgTypes.size(),
OldProto->isVariadic(), 0));
return MergeCompatibleFunctionDecls(New, Old);
}
// Fall through to diagnose conflicting types.
}
// A function that has already been declared has been redeclared or defined
// with a different type- show appropriate diagnostic
if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
// The user has declared a builtin function with an incompatible
// signature.
if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
// The function the user is redeclaring is a library-defined
// function like 'malloc' or 'printf'. Warn about the
// redeclaration, then pretend that we don't know about this
// library built-in.
Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
<< Old << Old->getType();
New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
Old->setInvalidDecl();
return false;
}
PrevDiag = diag::note_previous_builtin_declaration;
}
Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
return true;
}
/// \brief Completes the merge of two function declarations that are
/// known to be compatible.
///
/// This routine handles the merging of attributes and other
/// properties of function declarations form the old declaration to
/// the new declaration, once we know that New is in fact a
/// redeclaration of Old.
///
/// \returns false
bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
// Merge the attributes
MergeAttributes(New, Old, Context);
// Merge the storage class.
if (Old->getStorageClass() != FunctionDecl::Extern)
New->setStorageClass(Old->getStorageClass());
// Merge "inline"
if (Old->isInline())
New->setInline(true);
// If this function declaration by itself qualifies as a C99 inline
// definition (C99 6.7.4p6), but the previous definition did not,
// then the function is not a C99 inline definition.
if (New->isC99InlineDefinition() && !Old->isC99InlineDefinition())
New->setC99InlineDefinition(false);
else if (Old->isC99InlineDefinition() && !New->isC99InlineDefinition()) {
// Mark all preceding definitions as not being C99 inline definitions.
for (const FunctionDecl *Prev = Old; Prev;
Prev = Prev->getPreviousDeclaration())
const_cast<FunctionDecl *>(Prev)->setC99InlineDefinition(false);
}
// Merge "pure" flag.
if (Old->isPure())
New->setPure();
// Merge the "deleted" flag.
if (Old->isDeleted())
New->setDeleted();
if (getLangOptions().CPlusPlus)
return MergeCXXFunctionDecl(New, Old);
return false;
}
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
/// and scope as a previous declaration 'Old'. Figure out how to resolve this
/// situation, merging decls or emitting diagnostics as appropriate.
///
/// Tentative definition rules (C99 6.9.2p2) are checked by
/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
/// definitions here, since the initializer hasn't been attached.
///
void Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
// If either decl is invalid, make sure the new one is marked invalid and
// don't do any other checking.
if (New->isInvalidDecl() || OldD->isInvalidDecl())
return New->setInvalidDecl();
// Verify the old decl was also a variable.
VarDecl *Old = dyn_cast<VarDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind)
<< New->getDeclName();
Diag(OldD->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
MergeAttributes(New, Old, Context);
// Merge the types
QualType MergedT;
if (getLangOptions().CPlusPlus) {
if (Context.hasSameType(New->getType(), Old->getType()))
MergedT = New->getType();
} else {
MergedT = Context.mergeTypes(New->getType(), Old->getType());
}
if (MergedT.isNull()) {
Diag(New->getLocation(), diag::err_redefinition_different_type)
<< New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
New->setType(MergedT);
// C99 6.2.2p4: Check if we have a static decl followed by a non-static.
if (New->getStorageClass() == VarDecl::Static &&
(Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
// C99 6.2.2p4:
// For an identifier declared with the storage-class specifier
// extern in a scope in which a prior declaration of that
// identifier is visible,23) if the prior declaration specifies
// internal or external linkage, the linkage of the identifier at
// the later declaration is the same as the linkage specified at
// the prior declaration. If no prior declaration is visible, or
// if the prior declaration specifies no linkage, then the
// identifier has external linkage.
if (New->hasExternalStorage() && Old->hasLinkage())
/* Okay */;
else if (New->getStorageClass() != VarDecl::Static &&
Old->getStorageClass() == VarDecl::Static) {
Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
// Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
// FIXME: The test for external storage here seems wrong? We still
// need to check for mismatches.
if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
// Don't complain about out-of-line definitions of static members.
!(Old->getLexicalDeclContext()->isRecord() &&
!New->getLexicalDeclContext()->isRecord())) {
Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
return New->setInvalidDecl();
}
if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
} else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
Diag(Old->getLocation(), diag::note_previous_definition);
}
// Keep a chain of previous declarations.
New->setPreviousDeclaration(Old);
}
/// CheckFallThrough - Check that we don't fall off the end of a
/// Statement that should return a value.
///
/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
/// MaybeFallThrough iff we might or might not fall off the end and
/// NeverFallThrough iff we never fall off the end of the statement. We assume
/// that functions not marked noreturn will return.
Sema::ControlFlowKind Sema::CheckFallThrough(Stmt *Root) {
llvm::OwningPtr<CFG> cfg (CFG::buildCFG(Root, &Context));
// FIXME: They should never return 0, fix that, delete this code.
if (cfg == 0)
return NeverFallThrough;
// The CFG leaves in dead things, and we don't want to dead code paths to
// confuse us, so we mark all live things first.
std::queue<CFGBlock*> workq;
llvm::BitVector live(cfg->getNumBlockIDs());
// Prep work queue
workq.push(&cfg->getEntry());
// Solve
while (!workq.empty()) {
CFGBlock *item = workq.front();
workq.pop();
live.set(item->getBlockID());
for (CFGBlock::succ_iterator I=item->succ_begin(),
E=item->succ_end();
I != E;
++I) {
if ((*I) && !live[(*I)->getBlockID()]) {
live.set((*I)->getBlockID());
workq.push(*I);
}
}
}
// Now we know what is live, we check the live precessors of the exit block
// and look for fall through paths, being careful to ignore normal returns,
// and exceptional paths.
bool HasLiveReturn = false;
bool HasFakeEdge = false;
bool HasPlainEdge = false;
for (CFGBlock::succ_iterator I=cfg->getExit().pred_begin(),
E = cfg->getExit().pred_end();
I != E;
++I) {
CFGBlock& B = **I;
if (!live[B.getBlockID()])
continue;
if (B.size() == 0) {
// A labeled empty statement, or the entry block...
HasPlainEdge = true;
continue;
}
Stmt *S = B[B.size()-1];
if (isa<ReturnStmt>(S)) {
HasLiveReturn = true;
continue;
}
if (isa<ObjCAtThrowStmt>(S)) {
HasFakeEdge = true;
continue;
}
if (isa<CXXThrowExpr>(S)) {
HasFakeEdge = true;
continue;
}
bool NoReturnEdge = false;
if (CallExpr *C = dyn_cast<CallExpr>(S)) {
Expr *CEE = C->getCallee()->IgnoreParenCasts();
if (CEE->getType().getNoReturnAttr()) {
NoReturnEdge = true;
HasFakeEdge = true;
} else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
if (FD->hasAttr<NoReturnAttr>()) {
NoReturnEdge = true;
HasFakeEdge = true;
}
}
}
}
// FIXME: Add noreturn message sends.
if (NoReturnEdge == false)
HasPlainEdge = true;
}
if (!HasPlainEdge)
return NeverFallThrough;
if (HasFakeEdge || HasLiveReturn)
return MaybeFallThrough;
// This says AlwaysFallThrough for calls to functions that are not marked
// noreturn, that don't return. If people would like this warning to be more
// accurate, such functions should be marked as noreturn.
return AlwaysFallThrough;
}
/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
/// function that should return a value. Check that we don't fall off the end
/// of a noreturn function. We assume that functions and blocks not marked
/// noreturn will return.
void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body) {
// FIXME: Would be nice if we had a better way to control cascading errors,
// but for now, avoid them. The problem is that when Parse sees:
// int foo() { return a; }
// The return is eaten and the Sema code sees just:
// int foo() { }
// which this code would then warn about.
if (getDiagnostics().hasErrorOccurred())
return;
bool ReturnsVoid = false;
bool HasNoReturn = false;
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->getResultType()->isVoidType())
ReturnsVoid = true;
if (FD->hasAttr<NoReturnAttr>())
HasNoReturn = true;
} else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
if (MD->getResultType()->isVoidType())
ReturnsVoid = true;
if (MD->hasAttr<NoReturnAttr>())
HasNoReturn = true;
}
// Short circuit for compilation speed.
if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
== Diagnostic::Ignored || ReturnsVoid)
&& (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
== Diagnostic::Ignored || !HasNoReturn)
&& (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
== Diagnostic::Ignored || !ReturnsVoid))
return;
// FIXME: Funtion try block
if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
switch (CheckFallThrough(Body)) {
case MaybeFallThrough:
if (HasNoReturn)
Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
else if (!ReturnsVoid)
Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
break;
case AlwaysFallThrough:
if (HasNoReturn)
Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
else if (!ReturnsVoid)
Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
break;
case NeverFallThrough:
if (ReturnsVoid)
Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
break;
}
}
}
/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
/// that should return a value. Check that we don't fall off the end of a
/// noreturn block. We assume that functions and blocks not marked noreturn
/// will return.
void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body) {
// FIXME: Would be nice if we had a better way to control cascading errors,
// but for now, avoid them. The problem is that when Parse sees:
// int foo() { return a; }
// The return is eaten and the Sema code sees just:
// int foo() { }
// which this code would then warn about.
if (getDiagnostics().hasErrorOccurred())
return;
bool ReturnsVoid = false;
bool HasNoReturn = false;
if (const FunctionType *FT = BlockTy->getPointeeType()->getAsFunctionType()) {
if (FT->getResultType()->isVoidType())
ReturnsVoid = true;
if (FT->getNoReturnAttr())
HasNoReturn = true;
}
// Short circuit for compilation speed.
if (ReturnsVoid
&& !HasNoReturn
&& (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
== Diagnostic::Ignored || !ReturnsVoid))
return;
// FIXME: Funtion try block
if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
switch (CheckFallThrough(Body)) {
case MaybeFallThrough:
if (HasNoReturn)
Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
else if (!ReturnsVoid)
Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
break;
case AlwaysFallThrough:
if (HasNoReturn)
Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
else if (!ReturnsVoid)
Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
break;
case NeverFallThrough:
if (ReturnsVoid)
Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
break;
}
}
}
/// CheckParmsForFunctionDef - Check that the parameters of the given
/// function are appropriate for the definition of a function. This
/// takes care of any checks that cannot be performed on the
/// declaration itself, e.g., that the types of each of the function
/// parameters are complete.
bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
bool HasInvalidParm = false;
for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
ParmVarDecl *Param = FD->getParamDecl(p);
// C99 6.7.5.3p4: the parameters in a parameter type list in a
// function declarator that is part of a function definition of
// that function shall not have incomplete type.
//
// This is also C++ [dcl.fct]p6.
if (!Param->isInvalidDecl() &&
RequireCompleteType(Param->getLocation(), Param->getType(),
diag::err_typecheck_decl_incomplete_type)) {
Param->setInvalidDecl();
HasInvalidParm = true;
}
// C99 6.9.1p5: If the declarator includes a parameter type list, the
// declaration of each parameter shall include an identifier.
if (Param->getIdentifier() == 0 &&
!Param->isImplicit() &&
!getLangOptions().CPlusPlus)
Diag(Param->getLocation(), diag::err_parameter_name_omitted);
}
return HasInvalidParm;
}
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
/// no declarator (e.g. "struct foo;") is parsed.
Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
// FIXME: Error on auto/register at file scope
// FIXME: Error on inline/virtual/explicit
// FIXME: Error on invalid restrict
// FIXME: Warn on useless __thread
// FIXME: Warn on useless const/volatile
// FIXME: Warn on useless static/extern/typedef/private_extern/mutable
// FIXME: Warn on useless attributes
TagDecl *Tag = 0;
if (DS.getTypeSpecType() == DeclSpec::TST_class ||
DS.getTypeSpecType() == DeclSpec::TST_struct ||
DS.getTypeSpecType() == DeclSpec::TST_union ||
DS.getTypeSpecType() == DeclSpec::TST_enum) {
if (!DS.getTypeRep()) // We probably had an error
return DeclPtrTy();
// Note that the above type specs guarantee that the
// type rep is a Decl, whereas in many of the others
// it's a Type.
Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
}
if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
if (!Record->getDeclName() && Record->isDefinition() &&
DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
if (getLangOptions().CPlusPlus ||
Record->getDeclContext()->isRecord())
return BuildAnonymousStructOrUnion(S, DS, Record);
Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
<< DS.getSourceRange();
}
// Microsoft allows unnamed struct/union fields. Don't complain
// about them.
// FIXME: Should we support Microsoft's extensions in this area?
if (Record->getDeclName() && getLangOptions().Microsoft)
return DeclPtrTy::make(Tag);
}
if (!DS.isMissingDeclaratorOk() &&
DS.getTypeSpecType() != DeclSpec::TST_error) {
// Warn about typedefs of enums without names, since this is an
// extension in both Microsoft an GNU.
if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
Tag && isa<EnumDecl>(Tag)) {
Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
<< DS.getSourceRange();
return DeclPtrTy::make(Tag);
}
Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
<< DS.getSourceRange();
return DeclPtrTy();
}
return DeclPtrTy::make(Tag);
}
/// InjectAnonymousStructOrUnionMembers - Inject the members of the
/// anonymous struct or union AnonRecord into the owning context Owner
/// and scope S. This routine will be invoked just after we realize
/// that an unnamed union or struct is actually an anonymous union or
/// struct, e.g.,
///
/// @code
/// union {
/// int i;
/// float f;
/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
/// // f into the surrounding scope.x
/// @endcode
///
/// This routine is recursive, injecting the names of nested anonymous
/// structs/unions into the owning context and scope as well.
bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
RecordDecl *AnonRecord) {
bool Invalid = false;
for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
FEnd = AnonRecord->field_end();
F != FEnd; ++F) {
if ((*F)->getDeclName()) {
NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
LookupOrdinaryName, true);
if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
// C++ [class.union]p2:
// The names of the members of an anonymous union shall be
// distinct from the names of any other entity in the
// scope in which the anonymous union is declared.
unsigned diagKind
= AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
: diag::err_anonymous_struct_member_redecl;
Diag((*F)->getLocation(), diagKind)
<< (*F)->getDeclName();
Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
Invalid = true;
} else {
// C++ [class.union]p2:
// For the purpose of name lookup, after the anonymous union
// definition, the members of the anonymous union are
// considered to have been defined in the scope in which the
// anonymous union is declared.
Owner->makeDeclVisibleInContext(*F);
S->AddDecl(DeclPtrTy::make(*F));
IdResolver.AddDecl(*F);
}
} else if (const RecordType *InnerRecordType
= (*F)->getType()->getAs<RecordType>()) {
RecordDecl *InnerRecord = InnerRecordType->getDecl();
if (InnerRecord->isAnonymousStructOrUnion())
Invalid = Invalid ||
InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
}
}
return Invalid;
}
/// ActOnAnonymousStructOrUnion - Handle the declaration of an
/// anonymous structure or union. Anonymous unions are a C++ feature
/// (C++ [class.union]) and a GNU C extension; anonymous structures
/// are a GNU C and GNU C++ extension.
Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
RecordDecl *Record) {
DeclContext *Owner = Record->getDeclContext();
// Diagnose whether this anonymous struct/union is an extension.
if (Record->isUnion() && !getLangOptions().CPlusPlus)
Diag(Record->getLocation(), diag::ext_anonymous_union);
else if (!Record->isUnion())
Diag(Record->getLocation(), diag::ext_anonymous_struct);
// C and C++ require different kinds of checks for anonymous
// structs/unions.
bool Invalid = false;
if (getLangOptions().CPlusPlus) {
const char* PrevSpec = 0;
unsigned DiagID;
// C++ [class.union]p3:
// Anonymous unions declared in a named namespace or in the
// global namespace shall be declared static.
if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
(isa<TranslationUnitDecl>(Owner) ||
(isa<NamespaceDecl>(Owner) &&
cast<NamespaceDecl>(Owner)->getDeclName()))) {
Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
Invalid = true;
// Recover by adding 'static'.
DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
PrevSpec, DiagID);
}
// C++ [class.union]p3:
// A storage class is not allowed in a declaration of an
// anonymous union in a class scope.
else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
isa<RecordDecl>(Owner)) {
Diag(DS.getStorageClassSpecLoc(),
diag::err_anonymous_union_with_storage_spec);
Invalid = true;
// Recover by removing the storage specifier.
DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
PrevSpec, DiagID);
}
// C++ [class.union]p2:
// The member-specification of an anonymous union shall only
// define non-static data members. [Note: nested types and
// functions cannot be declared within an anonymous union. ]
for (DeclContext::decl_iterator Mem = Record->decls_begin(),
MemEnd = Record->decls_end();
Mem != MemEnd; ++Mem) {
if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
// C++ [class.union]p3:
// An anonymous union shall not have private or protected
// members (clause 11).
if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
<< (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
Invalid = true;
}
} else if ((*Mem)->isImplicit()) {
// Any implicit members are fine.
} else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
// This is a type that showed up in an
// elaborated-type-specifier inside the anonymous struct or
// union, but which actually declares a type outside of the
// anonymous struct or union. It's okay.
} else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
if (!MemRecord->isAnonymousStructOrUnion() &&
MemRecord->getDeclName()) {
// This is a nested type declaration.
Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
<< (int)Record->isUnion();
Invalid = true;
}
} else {
// We have something that isn't a non-static data
// member. Complain about it.
unsigned DK = diag::err_anonymous_record_bad_member;
if (isa<TypeDecl>(*Mem))
DK = diag::err_anonymous_record_with_type;
else if (isa<FunctionDecl>(*Mem))
DK = diag::err_anonymous_record_with_function;
else if (isa<VarDecl>(*Mem))
DK = diag::err_anonymous_record_with_static;
Diag((*Mem)->getLocation(), DK)
<< (int)Record->isUnion();
Invalid = true;
}
}
}
if (!Record->isUnion() && !Owner->isRecord()) {
Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
<< (int)getLangOptions().CPlusPlus;
Invalid = true;
}
// Create a declaration for this anonymous struct/union.
NamedDecl *Anon = 0;
if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
/*IdentifierInfo=*/0,
Context.getTypeDeclType(Record),
// FIXME: Type source info.
/*DInfo=*/0,
/*BitWidth=*/0, /*Mutable=*/false);
Anon->setAccess(AS_public);
if (getLangOptions().CPlusPlus)
FieldCollector->Add(cast<FieldDecl>(Anon));
} else {
VarDecl::StorageClass SC;
switch (DS.getStorageClassSpec()) {
default: assert(0 && "Unknown storage class!");
case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
case DeclSpec::SCS_static: SC = VarDecl::Static; break;
case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
case DeclSpec::SCS_register: SC = VarDecl::Register; break;
case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
case DeclSpec::SCS_mutable:
// mutable can only appear on non-static class members, so it's always
// an error here
Diag(Record->getLocation(), diag::err_mutable_nonmember);
Invalid = true;
SC = VarDecl::None;
break;
}
Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
/*IdentifierInfo=*/0,
Context.getTypeDeclType(Record),
// FIXME: Type source info.
/*DInfo=*/0,
SC);
}
Anon->setImplicit();
// Add the anonymous struct/union object to the current
// context. We'll be referencing this object when we refer to one of
// its members.
Owner->addDecl(Anon);
// Inject the members of the anonymous struct/union into the owning
// context and into the identifier resolver chain for name lookup
// purposes.
if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
Invalid = true;
// Mark this as an anonymous struct/union type. Note that we do not
// do this until after we have already checked and injected the
// members of this anonymous struct/union type, because otherwise
// the members could be injected twice: once by DeclContext when it
// builds its lookup table, and once by
// InjectAnonymousStructOrUnionMembers.
Record->setAnonymousStructOrUnion(true);
if (Invalid)
Anon->setInvalidDecl();
return DeclPtrTy::make(Anon);
}
/// GetNameForDeclarator - Determine the full declaration name for the
/// given Declarator.
DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
switch (D.getKind()) {
case Declarator::DK_Abstract:
assert(D.getIdentifier() == 0 && "abstract declarators have no name");
return DeclarationName();
case Declarator::DK_Normal:
assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
return DeclarationName(D.getIdentifier());
case Declarator::DK_Constructor: {
QualType Ty = GetTypeFromParser(D.getDeclaratorIdType());
return Context.DeclarationNames.getCXXConstructorName(
Context.getCanonicalType(Ty));
}
case Declarator::DK_Destructor: {
QualType Ty = GetTypeFromParser(D.getDeclaratorIdType());
return Context.DeclarationNames.getCXXDestructorName(
Context.getCanonicalType(Ty));
}
case Declarator::DK_Conversion: {
// FIXME: We'd like to keep the non-canonical type for diagnostics!
QualType Ty = GetTypeFromParser(D.getDeclaratorIdType());
return Context.DeclarationNames.getCXXConversionFunctionName(
Context.getCanonicalType(Ty));
}
case Declarator::DK_Operator:
assert(D.getIdentifier() == 0 && "operator names have no identifier");
return Context.DeclarationNames.getCXXOperatorName(
D.getOverloadedOperator());
}
assert(false && "Unknown name kind");
return DeclarationName();
}
/// isNearlyMatchingFunction - Determine whether the C++ functions
/// Declaration and Definition are "nearly" matching. This heuristic
/// is used to improve diagnostics in the case where an out-of-line
/// function definition doesn't match any declaration within
/// the class or namespace.
static bool isNearlyMatchingFunction(ASTContext &Context,
FunctionDecl *Declaration,
FunctionDecl *Definition) {
if (Declaration->param_size() != Definition->param_size())
return false;
for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
return false;
}
return true;
}
Sema::DeclPtrTy
Sema::HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists,
bool IsFunctionDefinition) {
DeclarationName Name = GetNameForDeclarator(D);
// All of these full declarators require an identifier. If it doesn't have
// one, the ParsedFreeStandingDeclSpec action should be used.
if (!Name) {
if (!D.isInvalidType()) // Reject this if we think it is valid.
Diag(D.getDeclSpec().getSourceRange().getBegin(),
diag::err_declarator_need_ident)
<< D.getDeclSpec().getSourceRange() << D.getSourceRange();
return DeclPtrTy();
}
// The scope passed in may not be a decl scope. Zip up the scope tree until
// we find one that is.
while ((S->getFlags() & Scope::DeclScope) == 0 ||
(S->getFlags() & Scope::TemplateParamScope) != 0)
S = S->getParent();
// If this is an out-of-line definition of a member of a class template
// or class template partial specialization, we may need to rebuild the
// type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
// for more information.
// FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
// handle expressions properly.
DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
(DS.getTypeSpecType() == DeclSpec::TST_typename ||
DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
// FIXME: Preserve type source info.
QualType T = GetTypeFromParser(DS.getTypeRep());
EnterDeclaratorContext(S, DC);
T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
ExitDeclaratorContext(S);
if (T.isNull())
return DeclPtrTy();
DS.UpdateTypeRep(T.getAsOpaquePtr());
}
}
DeclContext *DC;
NamedDecl *PrevDecl;
NamedDecl *New;
DeclaratorInfo *DInfo = 0;
QualType R = GetTypeForDeclarator(D, S, &DInfo);
// See if this is a redefinition of a variable in the same scope.
if (D.getCXXScopeSpec().isInvalid()) {
DC = CurContext;
PrevDecl = 0;
D.setInvalidType();
} else if (!D.getCXXScopeSpec().isSet()) {
LookupNameKind NameKind = LookupOrdinaryName;
// If the declaration we're planning to build will be a function
// or object with linkage, then look for another declaration with
// linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
/* Do nothing*/;
else if (R->isFunctionType()) {
if (CurContext->isFunctionOrMethod() ||
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
NameKind = LookupRedeclarationWithLinkage;
} else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
NameKind = LookupRedeclarationWithLinkage;
else if (CurContext->getLookupContext()->isTranslationUnit() &&
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
NameKind = LookupRedeclarationWithLinkage;
DC = CurContext;
PrevDecl = LookupName(S, Name, NameKind, true,
NameKind == LookupRedeclarationWithLinkage,
D.getIdentifierLoc());
} else { // Something like "int foo::x;"
DC = computeDeclContext(D.getCXXScopeSpec(), true);
// FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ?
PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
// C++ 7.3.1.2p2:
// Members (including explicit specializations of templates) of a named
// namespace can also be defined outside that namespace by explicit
// qualification of the name being defined, provided that the entity being
// defined was already declared in the namespace and the definition appears
// after the point of declaration in a namespace that encloses the
// declarations namespace.
//
// Note that we only check the context at this point. We don't yet
// have enough information to make sure that PrevDecl is actually
// the declaration we want to match. For example, given:
//
// class X {
// void f();
// void f(float);
// };
//
// void X::f(int) { } // ill-formed
//
// In this case, PrevDecl will point to the overload set
// containing the two f's declared in X, but neither of them
// matches.
// First check whether we named the global scope.
if (isa<TranslationUnitDecl>(DC)) {
Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
<< Name << D.getCXXScopeSpec().getRange();
} else if (!CurContext->Encloses(DC)) {
// The qualifying scope doesn't enclose the original declaration.
// Emit diagnostic based on current scope.
SourceLocation L = D.getIdentifierLoc();
SourceRange R = D.getCXXScopeSpec().getRange();
if (isa<FunctionDecl>(CurContext))
Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
else
Diag(L, diag::err_invalid_declarator_scope)
<< Name << cast<NamedDecl>(DC) << R;
D.setInvalidType();
}
}
if (PrevDecl && PrevDecl->isTemplateParameter()) {
// Maybe we will complain about the shadowed template parameter.
if (!D.isInvalidType())
if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl))
D.setInvalidType();
// Just pretend that we didn't see the previous declaration.
PrevDecl = 0;
}
// In C++, the previous declaration we find might be a tag type
// (class or enum). In this case, the new declaration will hide the
// tag type. Note that this does does not apply if we're declaring a
// typedef (C++ [dcl.typedef]p4).
if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
PrevDecl = 0;
bool Redeclaration = false;
if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
if (TemplateParamLists.size()) {
Diag(D.getIdentifierLoc(), diag::err_template_typedef);
return DeclPtrTy();
}
New = ActOnTypedefDeclarator(S, D, DC, R, DInfo, PrevDecl, Redeclaration);
} else if (R->isFunctionType()) {
New = ActOnFunctionDeclarator(S, D, DC, R, DInfo, PrevDecl,
move(TemplateParamLists),
IsFunctionDefinition, Redeclaration);
} else {
New = ActOnVariableDeclarator(S, D, DC, R, DInfo, PrevDecl,
move(TemplateParamLists),
Redeclaration);
}
if (New == 0)
return DeclPtrTy();
// If this has an identifier and is not an invalid redeclaration,
// add it to the scope stack.
if (Name && !(Redeclaration && New->isInvalidDecl()))
PushOnScopeChains(New, S);
return DeclPtrTy::make(New);
}
/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
/// types into constant array types in certain situations which would otherwise
/// be errors (for GCC compatibility).
static QualType TryToFixInvalidVariablyModifiedType(QualType T,
ASTContext &Context,
bool &SizeIsNegative) {
// This method tries to turn a variable array into a constant
// array even when the size isn't an ICE. This is necessary
// for compatibility with code that depends on gcc's buggy
// constant expression folding, like struct {char x[(int)(char*)2];}
SizeIsNegative = false;
if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
QualType Pointee = PTy->getPointeeType();
QualType FixedType =
TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
if (FixedType.isNull()) return FixedType;
FixedType = Context.getPointerType(FixedType);
FixedType.setCVRQualifiers(T.getCVRQualifiers());
return FixedType;
}
const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
if (!VLATy)
return QualType();
// FIXME: We should probably handle this case
if (VLATy->getElementType()->isVariablyModifiedType())
return QualType();
Expr::EvalResult EvalResult;
if (!VLATy->getSizeExpr() ||
!VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
!EvalResult.Val.isInt())
return QualType();
llvm::APSInt &Res = EvalResult.Val.getInt();
if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
Expr* ArySizeExpr = VLATy->getSizeExpr();
// FIXME: here we could "steal" (how?) ArySizeExpr from the VLA,
// so as to transfer ownership to the ConstantArrayWithExpr.
// Alternatively, we could "clone" it (how?).
// Since we don't know how to do things above, we just use the
// very same Expr*.
return Context.getConstantArrayWithExprType(VLATy->getElementType(),
Res, ArySizeExpr,
ArrayType::Normal, 0,
VLATy->getBracketsRange());
}
SizeIsNegative = true;
return QualType();
}
/// \brief Register the given locally-scoped external C declaration so
/// that it can be found later for redeclarations
void
Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
Scope *S) {
assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
"Decl is not a locally-scoped decl!");
// Note that we have a locally-scoped external with this name.
LocallyScopedExternalDecls[ND->getDeclName()] = ND;
if (!PrevDecl)
return;
// If there was a previous declaration of this variable, it may be
// in our identifier chain. Update the identifier chain with the new
// declaration.
if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
// The previous declaration was found on the identifer resolver
// chain, so remove it from its scope.
while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
S = S->getParent();
if (S)
S->RemoveDecl(DeclPtrTy::make(PrevDecl));
}
}
/// \brief Diagnose function specifiers on a declaration of an identifier that
/// does not identify a function.
void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
// FIXME: We should probably indicate the identifier in question to avoid
// confusion for constructs like "inline int a(), b;"
if (D.getDeclSpec().isInlineSpecified())
Diag(D.getDeclSpec().getInlineSpecLoc(),
diag::err_inline_non_function);
if (D.getDeclSpec().isVirtualSpecified())
Diag(D.getDeclSpec().getVirtualSpecLoc(),
diag::err_virtual_non_function);
if (D.getDeclSpec().isExplicitSpecified())
Diag(D.getDeclSpec().getExplicitSpecLoc(),
diag::err_explicit_non_function);
}
NamedDecl*
Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
QualType R, DeclaratorInfo *DInfo,
Decl* PrevDecl, bool &Redeclaration) {
// Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
if (D.getCXXScopeSpec().isSet()) {
Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
<< D.getCXXScopeSpec().getRange();
D.setInvalidType();
// Pretend we didn't see the scope specifier.
DC = 0;
}
if (getLangOptions().CPlusPlus) {
// Check that there are no default arguments (C++ only).
CheckExtraCXXDefaultArguments(D);
}
DiagnoseFunctionSpecifiers(D);
if (D.getDeclSpec().isThreadSpecified())
Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
TypedefDecl *NewTD = ParseTypedefDecl(S, D, R);
if (!NewTD) return 0;
if (D.isInvalidType())
NewTD->setInvalidDecl();
// Handle attributes prior to checking for duplicates in MergeVarDecl
ProcessDeclAttributes(S, NewTD, D);
// Merge the decl with the existing one if appropriate. If the decl is
// in an outer scope, it isn't the same thing.
if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Redeclaration = true;
MergeTypeDefDecl(NewTD, PrevDecl);
}
// C99 6.7.7p2: If a typedef name specifies a variably modified type
// then it shall have block scope.
QualType T = NewTD->getUnderlyingType();
if (T->isVariablyModifiedType()) {
CurFunctionNeedsScopeChecking = true;
if (S->getFnParent() == 0) {
bool SizeIsNegative;
QualType FixedTy =
TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
if (!FixedTy.isNull()) {
Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
NewTD->setUnderlyingType(FixedTy);
} else {
if (SizeIsNegative)
Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
else if (T->isVariableArrayType())
Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
else
Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
NewTD->setInvalidDecl();
}
}
}
// If this is the C FILE type, notify the AST context.
if (IdentifierInfo *II = NewTD->getIdentifier())
if (!NewTD->isInvalidDecl() &&
NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
if (II->isStr("FILE"))
Context.setFILEDecl(NewTD);
else if (II->isStr("jmp_buf"))
Context.setjmp_bufDecl(NewTD);
else if (II->isStr("sigjmp_buf"))
Context.setsigjmp_bufDecl(NewTD);
}
return NewTD;
}
/// \brief Determines whether the given declaration is an out-of-scope
/// previous declaration.
///
/// This routine should be invoked when name lookup has found a
/// previous declaration (PrevDecl) that is not in the scope where a
/// new declaration by the same name is being introduced. If the new
/// declaration occurs in a local scope, previous declarations with
/// linkage may still be considered previous declarations (C99
/// 6.2.2p4-5, C++ [basic.link]p6).
///
/// \param PrevDecl the previous declaration found by name
/// lookup
///
/// \param DC the context in which the new declaration is being
/// declared.
///
/// \returns true if PrevDecl is an out-of-scope previous declaration
/// for a new delcaration with the same name.
static bool
isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
ASTContext &Context) {
if (!PrevDecl)
return 0;
// FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
// case we need to check each of the overloaded functions.
if (!PrevDecl->hasLinkage())
return false;
if (Context.getLangOptions().CPlusPlus) {
// C++ [basic.link]p6:
// If there is a visible declaration of an entity with linkage
// having the same name and type, ignoring entities declared
// outside the innermost enclosing namespace scope, the block
// scope declaration declares that same entity and receives the
// linkage of the previous declaration.
DeclContext *OuterContext = DC->getLookupContext();
if (!OuterContext->isFunctionOrMethod())
// This rule only applies to block-scope declarations.
return false;
else {
DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
if (PrevOuterContext->isRecord())
// We found a member function: ignore it.
return false;
else {
// Find the innermost enclosing namespace for the new and
// previous declarations.
while (!OuterContext->isFileContext())
OuterContext = OuterContext->getParent();
while (!PrevOuterContext->isFileContext())
PrevOuterContext = PrevOuterContext->getParent();
// The previous declaration is in a different namespace, so it
// isn't the same function.
if (OuterContext->getPrimaryContext() !=
PrevOuterContext->getPrimaryContext())
return false;
}
}
}
return true;
}
NamedDecl*
Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
QualType R, DeclaratorInfo *DInfo,
NamedDecl* PrevDecl,
MultiTemplateParamsArg TemplateParamLists,
bool &Redeclaration) {
DeclarationName Name = GetNameForDeclarator(D);
// Check that there are no default arguments (C++ only).
if (getLangOptions().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
VarDecl *NewVD;
VarDecl::StorageClass SC;
switch (D.getDeclSpec().getStorageClassSpec()) {
default: assert(0 && "Unknown storage class!");
case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
case DeclSpec::SCS_static: SC = VarDecl::Static; break;
case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
case DeclSpec::SCS_register: SC = VarDecl::Register; break;
case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
case DeclSpec::SCS_mutable:
// mutable can only appear on non-static class members, so it's always
// an error here
Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
D.setInvalidType();
SC = VarDecl::None;
break;
}
IdentifierInfo *II = Name.getAsIdentifierInfo();
if (!II) {
Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
<< Name.getAsString();
return 0;
}
DiagnoseFunctionSpecifiers(D);
if (!DC->isRecord() && S->getFnParent() == 0) {
// C99 6.9p2: The storage-class specifiers auto and register shall not
// appear in the declaration specifiers in an external declaration.
if (SC == VarDecl::Auto || SC == VarDecl::Register) {
// If this is a register variable with an asm label specified, then this
// is a GNU extension.
if (SC == VarDecl::Register && D.getAsmLabel())
Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
else
Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
D.setInvalidType();
}
}
if (DC->isRecord() && !CurContext->isRecord()) {
// This is an out-of-line definition of a static data member.
if (SC == VarDecl::Static) {
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_static_out_of_line)
<< CodeModificationHint::CreateRemoval(
SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
} else if (SC == VarDecl::None)
SC = VarDecl::Static;
}
if (SC == VarDecl::Static) {
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
if (RD->isLocalClass())
Diag(D.getIdentifierLoc(),
diag::err_static_data_member_not_allowed_in_local_class)
<< Name << RD->getDeclName();
}
}
// Check that we can declare a template here.
if (TemplateParamLists.size() &&
CheckTemplateDeclScope(S, TemplateParamLists))
return 0;
// Match up the template parameter lists with the scope specifier, then
// determine whether we have a template or a template specialization.
if (TemplateParameterList *TemplateParams
= MatchTemplateParametersToScopeSpecifier(
D.getDeclSpec().getSourceRange().getBegin(),
D.getCXXScopeSpec(),
(TemplateParameterList**)TemplateParamLists.get(),
TemplateParamLists.size())) {
if (TemplateParams->size() > 0) {
// There is no such thing as a variable template.
Diag(D.getIdentifierLoc(), diag::err_template_variable)
<< II
<< SourceRange(TemplateParams->getTemplateLoc(),
TemplateParams->getRAngleLoc());
return 0;
} else {
// There is an extraneous 'template<>' for this variable. Complain
// about it, but allow the declaration of the variable.
Diag(TemplateParams->getTemplateLoc(),
diag::err_template_variable_noparams)
<< II
<< SourceRange(TemplateParams->getTemplateLoc(),
TemplateParams->getRAngleLoc());
}
}
NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
II, R, DInfo, SC);
if (D.isInvalidType())
NewVD->setInvalidDecl();
if (D.getDeclSpec().isThreadSpecified()) {
if (NewVD->hasLocalStorage())
Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
else if (!Context.Target.isTLSSupported())
Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
else
NewVD->setThreadSpecified(true);
}
// Set the lexical context. If the declarator has a C++ scope specifier, the
// lexical context will be different from the semantic context.
NewVD->setLexicalDeclContext(CurContext);
// Handle attributes prior to checking for duplicates in MergeVarDecl
ProcessDeclAttributes(S, NewVD, D);
// Handle GNU asm-label extension (encoded as an attribute).
if (Expr *E = (Expr*) D.getAsmLabel()) {
// The parser guarantees this is a string.
StringLiteral *SE = cast<StringLiteral>(E);
NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
SE->getByteLength())));
}
// If name lookup finds a previous declaration that is not in the
// same scope as the new declaration, this may still be an
// acceptable redeclaration.
if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
!(NewVD->hasLinkage() &&
isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
PrevDecl = 0;
// Merge the decl with the existing one if appropriate.
if (PrevDecl) {
if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
// The user tried to define a non-static data member
// out-of-line (C++ [dcl.meaning]p1).
Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
<< D.getCXXScopeSpec().getRange();
PrevDecl = 0;
NewVD->setInvalidDecl();
}
} else if (D.getCXXScopeSpec().isSet()) {
// No previous declaration in the qualifying scope.
Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
<< Name << D.getCXXScopeSpec().getRange();
NewVD->setInvalidDecl();
}
CheckVariableDeclaration(NewVD, PrevDecl, Redeclaration);
// attributes declared post-definition are currently ignored
if (PrevDecl) {
const VarDecl *Def = 0, *PrevVD = dyn_cast<VarDecl>(PrevDecl);
if (PrevVD->getDefinition(Def) && D.hasAttributes()) {
Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
Diag(Def->getLocation(), diag::note_previous_definition);
}
}
// If this is a locally-scoped extern C variable, update the map of
// such variables.
if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) &&
!NewVD->isInvalidDecl())
RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
return NewVD;
}
/// \brief Perform semantic checking on a newly-created variable
/// declaration.
///
/// This routine performs all of the type-checking required for a
/// variable declaration once it has been built. It is used both to
/// check variables after they have been parsed and their declarators
/// have been translated into a declaration, and to check variables
/// that have been instantiated from a template.
///
/// Sets NewVD->isInvalidDecl() if an error was encountered.
void Sema::CheckVariableDeclaration(VarDecl *NewVD, NamedDecl *PrevDecl,
bool &Redeclaration) {
// If the decl is already known invalid, don't check it.
if (NewVD->isInvalidDecl())
return;
QualType T = NewVD->getType();
if (T->isObjCInterfaceType()) {
Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
return NewVD->setInvalidDecl();
}
// The variable can not have an abstract class type.
if (RequireNonAbstractType(NewVD->getLocation(), T,
diag::err_abstract_type_in_decl,
AbstractVariableType))
return NewVD->setInvalidDecl();
// Emit an error if an address space was applied to decl with local storage.
// This includes arrays of objects with address space qualifiers, but not
// automatic variables that point to other address spaces.
// ISO/IEC TR 18037 S5.1.2
if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
return NewVD->setInvalidDecl();
}
if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
&& !NewVD->hasAttr<BlocksAttr>())
Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
bool isVM = T->isVariablyModifiedType();
if (isVM || NewVD->hasAttr<CleanupAttr>() ||
NewVD->hasAttr<BlocksAttr>())
CurFunctionNeedsScopeChecking = true;
if ((isVM && NewVD->hasLinkage()) ||
(T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
bool SizeIsNegative;
QualType FixedTy =
TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
if (FixedTy.isNull() && T->isVariableArrayType()) {
const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
// FIXME: This won't give the correct result for
// int a[10][n];
SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
if (NewVD->isFileVarDecl())
Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
<< SizeRange;
else if (NewVD->getStorageClass() == VarDecl::Static)
Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
<< SizeRange;
else
Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
<< SizeRange;
return NewVD->setInvalidDecl();
}
if (FixedTy.isNull()) {
if (NewVD->isFileVarDecl())
Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
else
Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
return NewVD->setInvalidDecl();
}
Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
NewVD->setType(FixedTy);
}
if (!PrevDecl && NewVD->isExternC(Context)) {
// Since we did not find anything by this name and we're declaring
// an extern "C" variable, look for a non-visible extern "C"
// declaration with the same name.
llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
= LocallyScopedExternalDecls.find(NewVD->getDeclName());
if (Pos != LocallyScopedExternalDecls.end())
PrevDecl = Pos->second;
}
if (T->isVoidType() && !NewVD->hasExternalStorage()) {
Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
<< T;
return NewVD->setInvalidDecl();
}
if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
return NewVD->setInvalidDecl();
}
if (isVM && NewVD->hasAttr<BlocksAttr>()) {
Diag(NewVD->getLocation(), diag::err_block_on_vm);
return NewVD->setInvalidDecl();
}
if (PrevDecl) {
Redeclaration = true;
MergeVarDecl(NewVD, PrevDecl);
}
}
NamedDecl*
Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
QualType R, DeclaratorInfo *DInfo,
NamedDecl* PrevDecl,
MultiTemplateParamsArg TemplateParamLists,
bool IsFunctionDefinition, bool &Redeclaration) {
assert(R.getTypePtr()->isFunctionType());
DeclarationName Name = GetNameForDeclarator(D);
FunctionDecl::StorageClass SC = FunctionDecl::None;
switch (D.getDeclSpec().getStorageClassSpec()) {
default: assert(0 && "Unknown storage class!");
case DeclSpec::SCS_auto:
case DeclSpec::SCS_register:
case DeclSpec::SCS_mutable:
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_typecheck_sclass_func);
D.setInvalidType();
break;
case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
case DeclSpec::SCS_static: {
if (CurContext->getLookupContext()->isFunctionOrMethod()) {
// C99 6.7.1p5:
// The declaration of an identifier for a function that has
// block scope shall have no explicit storage-class specifier
// other than extern
// See also (C++ [dcl.stc]p4).
Diag(D.getDeclSpec().getStorageClassSpecLoc(),
diag::err_static_block_func);
SC = FunctionDecl::None;
} else
SC = FunctionDecl::Static;
break;
}
case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
}
if (D.getDeclSpec().isThreadSpecified())
Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
bool isFriend = D.getDeclSpec().isFriendSpecified();
bool isInline = D.getDeclSpec().isInlineSpecified();
bool isVirtual = D.getDeclSpec().isVirtualSpecified();
bool isExplicit = D.getDeclSpec().isExplicitSpecified();
// Check that the return type is not an abstract class type.
// For record types, this is done by the AbstractClassUsageDiagnoser once
// the class has been completely parsed.
if (!DC->isRecord() &&
RequireNonAbstractType(D.getIdentifierLoc(),
R->getAsFunctionType()->getResultType(),
diag::err_abstract_type_in_decl,
AbstractReturnType))
D.setInvalidType();
// Do not allow returning a objc interface by-value.
if (R->getAsFunctionType()->getResultType()->isObjCInterfaceType()) {
Diag(D.getIdentifierLoc(),
diag::err_object_cannot_be_passed_returned_by_value) << 0
<< R->getAsFunctionType()->getResultType();
D.setInvalidType();
}
// Check that we can declare a template here.
if (TemplateParamLists.size() &&
CheckTemplateDeclScope(S, TemplateParamLists))
return 0;
bool isVirtualOkay = false;
FunctionDecl *NewFD;
if (isFriend) {
// DC is the namespace in which the function is being declared.
assert(DC->isFileContext() || D.getCXXScopeSpec().isSet());
// C++ [class.friend]p5
// A function can be defined in a friend declaration of a
// class . . . . Such a function is implicitly inline.
isInline |= IsFunctionDefinition;
NewFD = FriendFunctionDecl::Create(Context, DC,
D.getIdentifierLoc(), Name, R, DInfo,
isInline,
D.getDeclSpec().getFriendSpecLoc());
} else if (D.getKind() == Declarator::DK_Constructor) {
// This is a C++ constructor declaration.
assert(DC->isRecord() &&
"Constructors can only be declared in a member context");
R = CheckConstructorDeclarator(D, R, SC);
// Create the new declaration
NewFD = CXXConstructorDecl::Create(Context,
cast<CXXRecordDecl>(DC),
D.getIdentifierLoc(), Name, R, DInfo,
isExplicit, isInline,
/*isImplicitlyDeclared=*/false);
} else if (D.getKind() == Declarator::DK_Destructor) {
// This is a C++ destructor declaration.
if (DC->isRecord()) {
R = CheckDestructorDeclarator(D, SC);
NewFD = CXXDestructorDecl::Create(Context,
cast<CXXRecordDecl>(DC),
D.getIdentifierLoc(), Name, R,
isInline,
/*isImplicitlyDeclared=*/false);
isVirtualOkay = true;
} else {
Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
// Create a FunctionDecl to satisfy the function definition parsing
// code path.
NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Name, R, DInfo, SC, isInline,
/*hasPrototype=*/true);
D.setInvalidType();
}
} else if (D.getKind() == Declarator::DK_Conversion) {
if (!DC->isRecord()) {
Diag(D.getIdentifierLoc(),
diag::err_conv_function_not_member);
return 0;
}
CheckConversionDeclarator(D, R, SC);
NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
D.getIdentifierLoc(), Name, R, DInfo,
isInline, isExplicit);
isVirtualOkay = true;
} else if (DC->isRecord()) {
// If the of the function is the same as the name of the record, then this
// must be an invalid constructor that has a return type.
// (The parser checks for a return type and makes the declarator a
// constructor if it has no return type).
// must have an invalid constructor that has a return type
if (Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
<< SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
<< SourceRange(D.getIdentifierLoc());
return 0;
}
// This is a C++ method declaration.
NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
D.getIdentifierLoc(), Name, R, DInfo,
(SC == FunctionDecl::Static), isInline);
isVirtualOkay = (SC != FunctionDecl::Static);
} else {
// Determine whether the function was written with a
// prototype. This true when:
// - we're in C++ (where every function has a prototype),
// - there is a prototype in the declarator, or
// - the type R of the function is some kind of typedef or other reference
// to a type name (which eventually refers to a function type).
bool HasPrototype =
getLangOptions().CPlusPlus ||
(D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
(!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
NewFD = FunctionDecl::Create(Context, DC,
D.getIdentifierLoc(),