1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/CXXFieldCollector.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/AST/APValue.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/CharUnits.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Parse/ParseDiagnostic.h"
33 #include "clang/Basic/PartialDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Lex/HeaderSearch.h"
39 #include "llvm/ADT/Triple.h"
43 using namespace clang
;
46 Sema::DeclGroupPtrTy
Sema::ConvertDeclToDeclGroup(Decl
*Ptr
) {
47 return DeclGroupPtrTy::make(DeclGroupRef(Ptr
));
50 /// \brief If the identifier refers to a type name within this scope,
51 /// return the declaration of that type.
53 /// This routine performs ordinary name lookup of the identifier II
54 /// within the given scope, with optional C++ scope specifier SS, to
55 /// determine whether the name refers to a type. If so, returns an
56 /// opaque pointer (actually a QualType) corresponding to that
57 /// type. Otherwise, returns NULL.
59 /// If name lookup results in an ambiguity, this routine will complain
60 /// and then return NULL.
61 ParsedType
Sema::getTypeName(IdentifierInfo
&II
, SourceLocation NameLoc
,
62 Scope
*S
, CXXScopeSpec
*SS
,
64 ParsedType ObjectTypePtr
) {
65 // Determine where we will perform name lookup.
66 DeclContext
*LookupCtx
= 0;
68 QualType ObjectType
= ObjectTypePtr
.get();
69 if (ObjectType
->isRecordType())
70 LookupCtx
= computeDeclContext(ObjectType
);
71 } else if (SS
&& SS
->isNotEmpty()) {
72 LookupCtx
= computeDeclContext(*SS
, false);
75 if (isDependentScopeSpecifier(*SS
)) {
77 // A qualified-id that refers to a type and in which the
78 // nested-name-specifier depends on a template-parameter (14.6.2)
79 // shall be prefixed by the keyword typename to indicate that the
80 // qualified-id denotes a type, forming an
81 // elaborated-type-specifier (7.1.5.3).
83 // We therefore do not perform any name lookup if the result would
84 // refer to a member of an unknown specialization.
88 // We know from the grammar that this name refers to a type,
89 // so build a dependent node to describe the type.
91 CheckTypenameType(ETK_None
, SS
->getScopeRep(), II
,
92 SourceLocation(), SS
->getRange(), NameLoc
);
93 return ParsedType::make(T
);
99 if (!LookupCtx
->isDependentContext() &&
100 RequireCompleteDeclContext(*SS
, LookupCtx
))
104 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
105 // lookup for class-names.
106 LookupNameKind Kind
= isClassName
? LookupNestedNameSpecifierName
:
108 LookupResult
Result(*this, &II
, NameLoc
, Kind
);
110 // Perform "qualified" name lookup into the declaration context we
111 // computed, which is either the type of the base of a member access
112 // expression or the declaration context associated with a prior
113 // nested-name-specifier.
114 LookupQualifiedName(Result
, LookupCtx
);
116 if (ObjectTypePtr
&& Result
.empty()) {
117 // C++ [basic.lookup.classref]p3:
118 // If the unqualified-id is ~type-name, the type-name is looked up
119 // in the context of the entire postfix-expression. If the type T of
120 // the object expression is of a class type C, the type-name is also
121 // looked up in the scope of class C. At least one of the lookups shall
122 // find a name that refers to (possibly cv-qualified) T.
123 LookupName(Result
, S
);
126 // Perform unqualified name lookup.
127 LookupName(Result
, S
);
130 NamedDecl
*IIDecl
= 0;
131 switch (Result
.getResultKind()) {
132 case LookupResult::NotFound
:
133 case LookupResult::NotFoundInCurrentInstantiation
:
134 case LookupResult::FoundOverloaded
:
135 case LookupResult::FoundUnresolvedValue
:
136 Result
.suppressDiagnostics();
139 case LookupResult::Ambiguous
:
140 // Recover from type-hiding ambiguities by hiding the type. We'll
141 // do the lookup again when looking for an object, and we can
142 // diagnose the error then. If we don't do this, then the error
143 // about hiding the type will be immediately followed by an error
144 // that only makes sense if the identifier was treated like a type.
145 if (Result
.getAmbiguityKind() == LookupResult::AmbiguousTagHiding
) {
146 Result
.suppressDiagnostics();
150 // Look to see if we have a type anywhere in the list of results.
151 for (LookupResult::iterator Res
= Result
.begin(), ResEnd
= Result
.end();
152 Res
!= ResEnd
; ++Res
) {
153 if (isa
<TypeDecl
>(*Res
) || isa
<ObjCInterfaceDecl
>(*Res
)) {
155 (*Res
)->getLocation().getRawEncoding() <
156 IIDecl
->getLocation().getRawEncoding())
162 // None of the entities we found is a type, so there is no way
163 // to even assume that the result is a type. In this case, don't
164 // complain about the ambiguity. The parser will either try to
165 // perform this lookup again (e.g., as an object name), which
166 // will produce the ambiguity, or will complain that it expected
168 Result
.suppressDiagnostics();
172 // We found a type within the ambiguous lookup; diagnose the
173 // ambiguity and then return that type. This might be the right
174 // answer, or it might not be, but it suppresses any attempt to
175 // perform the name lookup again.
178 case LookupResult::Found
:
179 IIDecl
= Result
.getFoundDecl();
183 assert(IIDecl
&& "Didn't find decl");
186 if (TypeDecl
*TD
= dyn_cast
<TypeDecl
>(IIDecl
)) {
187 DiagnoseUseOfDecl(IIDecl
, NameLoc
);
190 T
= Context
.getTypeDeclType(TD
);
193 T
= getElaboratedType(ETK_None
, *SS
, T
);
195 } else if (ObjCInterfaceDecl
*IDecl
= dyn_cast
<ObjCInterfaceDecl
>(IIDecl
)) {
196 T
= Context
.getObjCInterfaceType(IDecl
);
198 // If it's not plausibly a type, suppress diagnostics.
199 Result
.suppressDiagnostics();
203 return ParsedType::make(T
);
206 /// isTagName() - This method is called *for error recovery purposes only*
207 /// to determine if the specified name is a valid tag name ("struct foo"). If
208 /// so, this returns the TST for the tag corresponding to it (TST_enum,
209 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
210 /// where the user forgot to specify the tag.
211 DeclSpec::TST
Sema::isTagName(IdentifierInfo
&II
, Scope
*S
) {
212 // Do a tag name lookup in this scope.
213 LookupResult
R(*this, &II
, SourceLocation(), LookupTagName
);
214 LookupName(R
, S
, false);
215 R
.suppressDiagnostics();
216 if (R
.getResultKind() == LookupResult::Found
)
217 if (const TagDecl
*TD
= R
.getAsSingle
<TagDecl
>()) {
218 switch (TD
->getTagKind()) {
219 default: return DeclSpec::TST_unspecified
;
220 case TTK_Struct
: return DeclSpec::TST_struct
;
221 case TTK_Union
: return DeclSpec::TST_union
;
222 case TTK_Class
: return DeclSpec::TST_class
;
223 case TTK_Enum
: return DeclSpec::TST_enum
;
227 return DeclSpec::TST_unspecified
;
230 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo
&II
,
231 SourceLocation IILoc
,
234 ParsedType
&SuggestedType
) {
235 // We don't have anything to suggest (yet).
236 SuggestedType
= ParsedType();
238 // There may have been a typo in the name of the type. Look up typo
239 // results, in case we have something that we can suggest.
240 LookupResult
Lookup(*this, &II
, IILoc
, LookupOrdinaryName
,
241 NotForRedeclaration
);
243 if (DeclarationName Corrected
= CorrectTypo(Lookup
, S
, SS
, 0, 0, CTC_Type
)) {
244 if (NamedDecl
*Result
= Lookup
.getAsSingle
<NamedDecl
>()) {
245 if ((isa
<TypeDecl
>(Result
) || isa
<ObjCInterfaceDecl
>(Result
)) &&
246 !Result
->isInvalidDecl()) {
247 // We found a similarly-named type or interface; suggest that.
248 if (!SS
|| !SS
->isSet())
249 Diag(IILoc
, diag::err_unknown_typename_suggest
)
250 << &II
<< Lookup
.getLookupName()
251 << FixItHint::CreateReplacement(SourceRange(IILoc
),
252 Result
->getNameAsString());
253 else if (DeclContext
*DC
= computeDeclContext(*SS
, false))
254 Diag(IILoc
, diag::err_unknown_nested_typename_suggest
)
255 << &II
<< DC
<< Lookup
.getLookupName() << SS
->getRange()
256 << FixItHint::CreateReplacement(SourceRange(IILoc
),
257 Result
->getNameAsString());
259 llvm_unreachable("could not have corrected a typo here");
261 Diag(Result
->getLocation(), diag::note_previous_decl
)
262 << Result
->getDeclName();
264 SuggestedType
= getTypeName(*Result
->getIdentifier(), IILoc
, S
, SS
);
267 } else if (Lookup
.empty()) {
268 // We corrected to a keyword.
269 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
270 Diag(IILoc
, diag::err_unknown_typename_suggest
)
276 if (getLangOptions().CPlusPlus
) {
277 // See if II is a class template that the user forgot to pass arguments to.
279 Name
.setIdentifier(&II
, IILoc
);
280 CXXScopeSpec EmptySS
;
281 TemplateTy TemplateResult
;
282 bool MemberOfUnknownSpecialization
;
283 if (isTemplateName(S
, SS
? *SS
: EmptySS
, /*hasTemplateKeyword=*/false,
284 Name
, ParsedType(), true, TemplateResult
,
285 MemberOfUnknownSpecialization
) == TNK_Type_template
) {
286 TemplateName TplName
= TemplateResult
.getAsVal
<TemplateName
>();
287 Diag(IILoc
, diag::err_template_missing_args
) << TplName
;
288 if (TemplateDecl
*TplDecl
= TplName
.getAsTemplateDecl()) {
289 Diag(TplDecl
->getLocation(), diag::note_template_decl_here
)
290 << TplDecl
->getTemplateParameters()->getSourceRange();
296 // FIXME: Should we move the logic that tries to recover from a missing tag
297 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
299 if (!SS
|| (!SS
->isSet() && !SS
->isInvalid()))
300 Diag(IILoc
, diag::err_unknown_typename
) << &II
;
301 else if (DeclContext
*DC
= computeDeclContext(*SS
, false))
302 Diag(IILoc
, diag::err_typename_nested_not_found
)
303 << &II
<< DC
<< SS
->getRange();
304 else if (isDependentScopeSpecifier(*SS
)) {
305 Diag(SS
->getRange().getBegin(), diag::err_typename_missing
)
306 << (NestedNameSpecifier
*)SS
->getScopeRep() << II
.getName()
307 << SourceRange(SS
->getRange().getBegin(), IILoc
)
308 << FixItHint::CreateInsertion(SS
->getRange().getBegin(), "typename ");
309 SuggestedType
= ActOnTypenameType(S
, SourceLocation(), *SS
, II
, IILoc
).get();
311 assert(SS
&& SS
->isInvalid() &&
312 "Invalid scope specifier has already been diagnosed");
318 // Determines the context to return to after temporarily entering a
319 // context. This depends in an unnecessarily complicated way on the
320 // exact ordering of callbacks from the parser.
321 DeclContext
*Sema::getContainingDC(DeclContext
*DC
) {
323 // Functions defined inline within classes aren't parsed until we've
324 // finished parsing the top-level class, so the top-level class is
325 // the context we'll need to return to.
326 if (isa
<FunctionDecl
>(DC
)) {
327 DC
= DC
->getLexicalParent();
329 // A function not defined within a class will always return to its
331 if (!isa
<CXXRecordDecl
>(DC
))
334 // A C++ inline method/friend is parsed *after* the topmost class
335 // it was declared in is fully parsed ("complete"); the topmost
336 // class is the context we need to return to.
337 while (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(DC
->getLexicalParent()))
340 // Return the declaration context of the topmost class the inline method is
345 // ObjCMethodDecls are parsed (for some reason) outside the context
347 if (isa
<ObjCMethodDecl
>(DC
))
348 return DC
->getLexicalParent()->getLexicalParent();
350 return DC
->getLexicalParent();
353 void Sema::PushDeclContext(Scope
*S
, DeclContext
*DC
) {
354 assert(getContainingDC(DC
) == CurContext
&&
355 "The next DeclContext should be lexically contained in the current one.");
360 void Sema::PopDeclContext() {
361 assert(CurContext
&& "DeclContext imbalance!");
363 CurContext
= getContainingDC(CurContext
);
364 assert(CurContext
&& "Popped translation unit!");
367 /// EnterDeclaratorContext - Used when we must lookup names in the context
368 /// of a declarator's nested name specifier.
370 void Sema::EnterDeclaratorContext(Scope
*S
, DeclContext
*DC
) {
371 // C++0x [basic.lookup.unqual]p13:
372 // A name used in the definition of a static data member of class
373 // X (after the qualified-id of the static member) is looked up as
374 // if the name was used in a member function of X.
375 // C++0x [basic.lookup.unqual]p14:
376 // If a variable member of a namespace is defined outside of the
377 // scope of its namespace then any name used in the definition of
378 // the variable member (after the declarator-id) is looked up as
379 // if the definition of the variable member occurred in its
381 // Both of these imply that we should push a scope whose context
382 // is the semantic context of the declaration. We can't use
383 // PushDeclContext here because that context is not necessarily
384 // lexically contained in the current context. Fortunately,
385 // the containing scope should have the appropriate information.
387 assert(!S
->getEntity() && "scope already has entity");
390 Scope
*Ancestor
= S
->getParent();
391 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
392 assert(Ancestor
->getEntity() == CurContext
&& "ancestor context mismatch");
399 void Sema::ExitDeclaratorContext(Scope
*S
) {
400 assert(S
->getEntity() == CurContext
&& "Context imbalance!");
402 // Switch back to the lexical context. The safety of this is
403 // enforced by an assert in EnterDeclaratorContext.
404 Scope
*Ancestor
= S
->getParent();
405 while (!Ancestor
->getEntity()) Ancestor
= Ancestor
->getParent();
406 CurContext
= (DeclContext
*) Ancestor
->getEntity();
408 // We don't need to do anything with the scope, which is going to
412 /// \brief Determine whether we allow overloading of the function
413 /// PrevDecl with another declaration.
415 /// This routine determines whether overloading is possible, not
416 /// whether some new function is actually an overload. It will return
417 /// true in C++ (where we can always provide overloads) or, as an
418 /// extension, in C when the previous function is already an
419 /// overloaded function declaration or has the "overloadable"
421 static bool AllowOverloadingOfFunction(LookupResult
&Previous
,
422 ASTContext
&Context
) {
423 if (Context
.getLangOptions().CPlusPlus
)
426 if (Previous
.getResultKind() == LookupResult::FoundOverloaded
)
429 return (Previous
.getResultKind() == LookupResult::Found
430 && Previous
.getFoundDecl()->hasAttr
<OverloadableAttr
>());
433 /// Add this decl to the scope shadowed decl chains.
434 void Sema::PushOnScopeChains(NamedDecl
*D
, Scope
*S
, bool AddToContext
) {
435 // Move up the scope chain until we find the nearest enclosing
436 // non-transparent context. The declaration will be introduced into this
438 while (S
->getEntity() &&
439 ((DeclContext
*)S
->getEntity())->isTransparentContext())
442 // Add scoped declarations into their context, so that they can be
443 // found later. Declarations without a context won't be inserted
446 CurContext
->addDecl(D
);
448 // Out-of-line definitions shouldn't be pushed into scope in C++.
449 // Out-of-line variable and function definitions shouldn't even in C.
450 if ((getLangOptions().CPlusPlus
|| isa
<VarDecl
>(D
) || isa
<FunctionDecl
>(D
)) &&
454 // Template instantiations should also not be pushed into scope.
455 if (isa
<FunctionDecl
>(D
) &&
456 cast
<FunctionDecl
>(D
)->isFunctionTemplateSpecialization())
459 // If this replaces anything in the current scope,
460 IdentifierResolver::iterator I
= IdResolver
.begin(D
->getDeclName()),
461 IEnd
= IdResolver
.end();
462 for (; I
!= IEnd
; ++I
) {
463 if (S
->isDeclScope(*I
) && D
->declarationReplaces(*I
)) {
465 IdResolver
.RemoveDecl(*I
);
467 // Should only need to replace one decl.
473 IdResolver
.AddDecl(D
);
476 bool Sema::isDeclInScope(NamedDecl
*&D
, DeclContext
*Ctx
, Scope
*S
) {
477 return IdResolver
.isDeclInScope(D
, Ctx
, Context
, S
);
480 Scope
*Sema::getScopeForDeclContext(Scope
*S
, DeclContext
*DC
) {
481 DeclContext
*TargetDC
= DC
->getPrimaryContext();
483 if (DeclContext
*ScopeDC
= (DeclContext
*) S
->getEntity())
484 if (ScopeDC
->getPrimaryContext() == TargetDC
)
486 } while ((S
= S
->getParent()));
491 static bool isOutOfScopePreviousDeclaration(NamedDecl
*,
495 /// Filters out lookup results that don't fall within the given scope
496 /// as determined by isDeclInScope.
497 static void FilterLookupForScope(Sema
&SemaRef
, LookupResult
&R
,
498 DeclContext
*Ctx
, Scope
*S
,
499 bool ConsiderLinkage
) {
500 LookupResult::Filter F
= R
.makeFilter();
501 while (F
.hasNext()) {
502 NamedDecl
*D
= F
.next();
504 if (SemaRef
.isDeclInScope(D
, Ctx
, S
))
507 if (ConsiderLinkage
&&
508 isOutOfScopePreviousDeclaration(D
, Ctx
, SemaRef
.Context
))
517 static bool isUsingDecl(NamedDecl
*D
) {
518 return isa
<UsingShadowDecl
>(D
) ||
519 isa
<UnresolvedUsingTypenameDecl
>(D
) ||
520 isa
<UnresolvedUsingValueDecl
>(D
);
523 /// Removes using shadow declarations from the lookup results.
524 static void RemoveUsingDecls(LookupResult
&R
) {
525 LookupResult::Filter F
= R
.makeFilter();
527 if (isUsingDecl(F
.next()))
533 /// \brief Check for this common pattern:
536 /// S(const S&); // DO NOT IMPLEMENT
537 /// void operator=(const S&); // DO NOT IMPLEMENT
540 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl
*D
) {
541 // FIXME: Should check for private access too but access is set after we get
543 if (D
->isThisDeclarationADefinition())
546 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(D
))
547 return CD
->isCopyConstructor();
548 if (const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
))
549 return Method
->isCopyAssignmentOperator();
553 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl
*D
) const {
556 if (D
->isInvalidDecl() || D
->isUsed() || D
->hasAttr
<UnusedAttr
>())
559 // Ignore class templates.
560 if (D
->getDeclContext()->isDependentContext() ||
561 D
->getLexicalDeclContext()->isDependentContext())
564 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
565 if (FD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
568 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
)) {
569 if (MD
->isVirtual() || IsDisallowedCopyOrAssign(MD
))
572 // 'static inline' functions are used in headers; don't warn.
573 if (FD
->getStorageClass() == SC_Static
&&
574 FD
->isInlineSpecified())
578 if (FD
->isThisDeclarationADefinition() &&
579 Context
.DeclMustBeEmitted(FD
))
582 } else if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
583 if (!VD
->isFileVarDecl() ||
584 VD
->getType().isConstant(Context
) ||
585 Context
.DeclMustBeEmitted(VD
))
588 if (VD
->isStaticDataMember() &&
589 VD
->getTemplateSpecializationKind() == TSK_ImplicitInstantiation
)
596 // Only warn for unused decls internal to the translation unit.
597 if (D
->getLinkage() == ExternalLinkage
)
603 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl
*D
) {
607 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
608 const FunctionDecl
*First
= FD
->getFirstDeclaration();
609 if (FD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
610 return; // First should already be in the vector.
613 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
614 const VarDecl
*First
= VD
->getFirstDeclaration();
615 if (VD
!= First
&& ShouldWarnIfUnusedFileScopedDecl(First
))
616 return; // First should already be in the vector.
619 if (ShouldWarnIfUnusedFileScopedDecl(D
))
620 UnusedFileScopedDecls
.push_back(D
);
623 static bool ShouldDiagnoseUnusedDecl(const NamedDecl
*D
) {
624 if (D
->isInvalidDecl())
627 if (D
->isUsed() || D
->hasAttr
<UnusedAttr
>())
630 // White-list anything that isn't a local variable.
631 if (!isa
<VarDecl
>(D
) || isa
<ParmVarDecl
>(D
) || isa
<ImplicitParamDecl
>(D
) ||
632 !D
->getDeclContext()->isFunctionOrMethod())
635 // Types of valid local variables should be complete, so this should succeed.
636 if (const ValueDecl
*VD
= dyn_cast
<ValueDecl
>(D
)) {
638 // White-list anything with an __attribute__((unused)) type.
639 QualType Ty
= VD
->getType();
641 // Only look at the outermost level of typedef.
642 if (const TypedefType
*TT
= dyn_cast
<TypedefType
>(Ty
)) {
643 if (TT
->getDecl()->hasAttr
<UnusedAttr
>())
647 // If we failed to complete the type for some reason, or if the type is
648 // dependent, don't diagnose the variable.
649 if (Ty
->isIncompleteType() || Ty
->isDependentType())
652 if (const TagType
*TT
= Ty
->getAs
<TagType
>()) {
653 const TagDecl
*Tag
= TT
->getDecl();
654 if (Tag
->hasAttr
<UnusedAttr
>())
657 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Tag
)) {
658 // FIXME: Checking for the presence of a user-declared constructor
659 // isn't completely accurate; we'd prefer to check that the initializer
660 // has no side effects.
661 if (RD
->hasUserDeclaredConstructor() || !RD
->hasTrivialDestructor())
666 // TODO: __attribute__((unused)) templates?
672 void Sema::DiagnoseUnusedDecl(const NamedDecl
*D
) {
673 if (!ShouldDiagnoseUnusedDecl(D
))
676 if (isa
<VarDecl
>(D
) && cast
<VarDecl
>(D
)->isExceptionVariable())
677 Diag(D
->getLocation(), diag::warn_unused_exception_param
)
680 Diag(D
->getLocation(), diag::warn_unused_variable
)
684 void Sema::ActOnPopScope(SourceLocation Loc
, Scope
*S
) {
685 if (S
->decl_empty()) return;
686 assert((S
->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope
)) &&
687 "Scope shouldn't contain decls!");
689 for (Scope::decl_iterator I
= S
->decl_begin(), E
= S
->decl_end();
692 assert(TmpD
&& "This decl didn't get pushed??");
694 assert(isa
<NamedDecl
>(TmpD
) && "Decl isn't NamedDecl?");
695 NamedDecl
*D
= cast
<NamedDecl
>(TmpD
);
697 if (!D
->getDeclName()) continue;
699 // Diagnose unused variables in this scope.
700 if (!S
->hasErrorOccurred())
701 DiagnoseUnusedDecl(D
);
703 // Remove this name from our lexical scope.
704 IdResolver
.RemoveDecl(D
);
708 /// \brief Look for an Objective-C class in the translation unit.
710 /// \param Id The name of the Objective-C class we're looking for. If
711 /// typo-correction fixes this name, the Id will be updated
712 /// to the fixed name.
714 /// \param IdLoc The location of the name in the translation unit.
716 /// \param TypoCorrection If true, this routine will attempt typo correction
717 /// if there is no class with the given name.
719 /// \returns The declaration of the named Objective-C class, or NULL if the
720 /// class could not be found.
721 ObjCInterfaceDecl
*Sema::getObjCInterfaceDecl(IdentifierInfo
*&Id
,
722 SourceLocation IdLoc
,
723 bool TypoCorrection
) {
724 // The third "scope" argument is 0 since we aren't enabling lazy built-in
725 // creation from this context.
726 NamedDecl
*IDecl
= LookupSingleName(TUScope
, Id
, IdLoc
, LookupOrdinaryName
);
728 if (!IDecl
&& TypoCorrection
) {
729 // Perform typo correction at the given location, but only if we
730 // find an Objective-C class name.
731 LookupResult
R(*this, Id
, IdLoc
, LookupOrdinaryName
);
732 if (CorrectTypo(R
, TUScope
, 0, 0, false, CTC_NoKeywords
) &&
733 (IDecl
= R
.getAsSingle
<ObjCInterfaceDecl
>())) {
734 Diag(IdLoc
, diag::err_undef_interface_suggest
)
735 << Id
<< IDecl
->getDeclName()
736 << FixItHint::CreateReplacement(IdLoc
, IDecl
->getNameAsString());
737 Diag(IDecl
->getLocation(), diag::note_previous_decl
)
738 << IDecl
->getDeclName();
740 Id
= IDecl
->getIdentifier();
744 return dyn_cast_or_null
<ObjCInterfaceDecl
>(IDecl
);
747 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
748 /// from S, where a non-field would be declared. This routine copes
749 /// with the difference between C and C++ scoping rules in structs and
750 /// unions. For example, the following code is well-formed in C but
751 /// ill-formed in C++:
762 /// For the declaration of BAR, this routine will return a different
763 /// scope. The scope S will be the scope of the unnamed enumeration
764 /// within S6. In C++, this routine will return the scope associated
765 /// with S6, because the enumeration's scope is a transparent
766 /// context but structures can contain non-field names. In C, this
767 /// routine will return the translation unit scope, since the
768 /// enumeration's scope is a transparent context and structures cannot
769 /// contain non-field names.
770 Scope
*Sema::getNonFieldDeclScope(Scope
*S
) {
771 while (((S
->getFlags() & Scope::DeclScope
) == 0) ||
773 ((DeclContext
*)S
->getEntity())->isTransparentContext()) ||
774 (S
->isClassScope() && !getLangOptions().CPlusPlus
))
779 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
780 /// file scope. lazily create a decl for it. ForRedeclaration is true
781 /// if we're creating this built-in in anticipation of redeclaring the
783 NamedDecl
*Sema::LazilyCreateBuiltin(IdentifierInfo
*II
, unsigned bid
,
784 Scope
*S
, bool ForRedeclaration
,
785 SourceLocation Loc
) {
786 Builtin::ID BID
= (Builtin::ID
)bid
;
788 ASTContext::GetBuiltinTypeError Error
;
789 QualType R
= Context
.GetBuiltinType(BID
, Error
);
791 case ASTContext::GE_None
:
795 case ASTContext::GE_Missing_stdio
:
796 if (ForRedeclaration
)
797 Diag(Loc
, diag::warn_implicit_decl_requires_stdio
)
798 << Context
.BuiltinInfo
.GetName(BID
);
801 case ASTContext::GE_Missing_setjmp
:
802 if (ForRedeclaration
)
803 Diag(Loc
, diag::warn_implicit_decl_requires_setjmp
)
804 << Context
.BuiltinInfo
.GetName(BID
);
808 if (!ForRedeclaration
&& Context
.BuiltinInfo
.isPredefinedLibFunction(BID
)) {
809 Diag(Loc
, diag::ext_implicit_lib_function_decl
)
810 << Context
.BuiltinInfo
.GetName(BID
)
812 if (Context
.BuiltinInfo
.getHeaderName(BID
) &&
813 Diags
.getDiagnosticLevel(diag::ext_implicit_lib_function_decl
, Loc
)
814 != Diagnostic::Ignored
)
815 Diag(Loc
, diag::note_please_include_header
)
816 << Context
.BuiltinInfo
.getHeaderName(BID
)
817 << Context
.BuiltinInfo
.GetName(BID
);
820 FunctionDecl
*New
= FunctionDecl::Create(Context
,
821 Context
.getTranslationUnitDecl(),
822 Loc
, II
, R
, /*TInfo=*/0,
825 /*hasPrototype=*/true);
828 // Create Decl objects for each parameter, adding them to the
830 if (const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(R
)) {
831 llvm::SmallVector
<ParmVarDecl
*, 16> Params
;
832 for (unsigned i
= 0, e
= FT
->getNumArgs(); i
!= e
; ++i
)
833 Params
.push_back(ParmVarDecl::Create(Context
, New
, SourceLocation(), 0,
834 FT
->getArgType(i
), /*TInfo=*/0,
835 SC_None
, SC_None
, 0));
836 New
->setParams(Params
.data(), Params
.size());
839 AddKnownFunctionAttributes(New
);
841 // TUScope is the translation-unit scope to insert this function into.
842 // FIXME: This is hideous. We need to teach PushOnScopeChains to
843 // relate Scopes to DeclContexts, and probably eliminate CurContext
844 // entirely, but we're not there yet.
845 DeclContext
*SavedContext
= CurContext
;
846 CurContext
= Context
.getTranslationUnitDecl();
847 PushOnScopeChains(New
, TUScope
);
848 CurContext
= SavedContext
;
852 /// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
853 /// same name and scope as a previous declaration 'Old'. Figure out
854 /// how to resolve this situation, merging decls or emitting
855 /// diagnostics as appropriate. If there was an error, set New to be invalid.
857 void Sema::MergeTypeDefDecl(TypedefDecl
*New
, LookupResult
&OldDecls
) {
858 // If the new decl is known invalid already, don't bother doing any
860 if (New
->isInvalidDecl()) return;
862 // Allow multiple definitions for ObjC built-in typedefs.
863 // FIXME: Verify the underlying types are equivalent!
864 if (getLangOptions().ObjC1
) {
865 const IdentifierInfo
*TypeID
= New
->getIdentifier();
866 switch (TypeID
->getLength()) {
869 if (!TypeID
->isStr("id"))
871 Context
.ObjCIdRedefinitionType
= New
->getUnderlyingType();
872 // Install the built-in type for 'id', ignoring the current definition.
873 New
->setTypeForDecl(Context
.getObjCIdType().getTypePtr());
876 if (!TypeID
->isStr("Class"))
878 Context
.ObjCClassRedefinitionType
= New
->getUnderlyingType();
879 // Install the built-in type for 'Class', ignoring the current definition.
880 New
->setTypeForDecl(Context
.getObjCClassType().getTypePtr());
883 if (!TypeID
->isStr("SEL"))
885 Context
.ObjCSelRedefinitionType
= New
->getUnderlyingType();
886 // Install the built-in type for 'SEL', ignoring the current definition.
887 New
->setTypeForDecl(Context
.getObjCSelType().getTypePtr());
890 if (!TypeID
->isStr("Protocol"))
892 Context
.setObjCProtoType(New
->getUnderlyingType());
895 // Fall through - the typedef name was not a builtin type.
898 // Verify the old decl was also a type.
899 TypeDecl
*Old
= OldDecls
.getAsSingle
<TypeDecl
>();
901 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
902 << New
->getDeclName();
904 NamedDecl
*OldD
= OldDecls
.getRepresentativeDecl();
905 if (OldD
->getLocation().isValid())
906 Diag(OldD
->getLocation(), diag::note_previous_definition
);
908 return New
->setInvalidDecl();
911 // If the old declaration is invalid, just give up here.
912 if (Old
->isInvalidDecl())
913 return New
->setInvalidDecl();
915 // Determine the "old" type we'll use for checking and diagnostics.
917 if (TypedefDecl
*OldTypedef
= dyn_cast
<TypedefDecl
>(Old
))
918 OldType
= OldTypedef
->getUnderlyingType();
920 OldType
= Context
.getTypeDeclType(Old
);
922 // If the typedef types are not identical, reject them in all languages and
923 // with any extensions enabled.
925 if (OldType
!= New
->getUnderlyingType() &&
926 Context
.getCanonicalType(OldType
) !=
927 Context
.getCanonicalType(New
->getUnderlyingType())) {
928 Diag(New
->getLocation(), diag::err_redefinition_different_typedef
)
929 << New
->getUnderlyingType() << OldType
;
930 if (Old
->getLocation().isValid())
931 Diag(Old
->getLocation(), diag::note_previous_definition
);
932 return New
->setInvalidDecl();
935 // The types match. Link up the redeclaration chain if the old
936 // declaration was a typedef.
937 // FIXME: this is a potential source of wierdness if the type
938 // spellings don't match exactly.
939 if (isa
<TypedefDecl
>(Old
))
940 New
->setPreviousDeclaration(cast
<TypedefDecl
>(Old
));
942 if (getLangOptions().Microsoft
)
945 if (getLangOptions().CPlusPlus
) {
946 // C++ [dcl.typedef]p2:
947 // In a given non-class scope, a typedef specifier can be used to
948 // redefine the name of any type declared in that scope to refer
949 // to the type to which it already refers.
950 if (!isa
<CXXRecordDecl
>(CurContext
))
953 // C++0x [dcl.typedef]p4:
954 // In a given class scope, a typedef specifier can be used to redefine
955 // any class-name declared in that scope that is not also a typedef-name
956 // to refer to the type to which it already refers.
958 // This wording came in via DR424, which was a correction to the
959 // wording in DR56, which accidentally banned code like:
962 // typedef struct A { } A;
965 // in the C++03 standard. We implement the C++0x semantics, which
966 // allow the above but disallow
973 // since that was the intent of DR56.
974 if (!isa
<TypedefDecl
>(Old
))
977 Diag(New
->getLocation(), diag::err_redefinition
)
978 << New
->getDeclName();
979 Diag(Old
->getLocation(), diag::note_previous_definition
);
980 return New
->setInvalidDecl();
983 // If we have a redefinition of a typedef in C, emit a warning. This warning
984 // is normally mapped to an error, but can be controlled with
985 // -Wtypedef-redefinition. If either the original or the redefinition is
986 // in a system header, don't emit this for compatibility with GCC.
987 if (getDiagnostics().getSuppressSystemWarnings() &&
988 (Context
.getSourceManager().isInSystemHeader(Old
->getLocation()) ||
989 Context
.getSourceManager().isInSystemHeader(New
->getLocation())))
992 Diag(New
->getLocation(), diag::warn_redefinition_of_typedef
)
993 << New
->getDeclName();
994 Diag(Old
->getLocation(), diag::note_previous_definition
);
998 /// DeclhasAttr - returns true if decl Declaration already has the target
1001 DeclHasAttr(const Decl
*D
, const Attr
*A
) {
1002 const OwnershipAttr
*OA
= dyn_cast
<OwnershipAttr
>(A
);
1003 for (Decl::attr_iterator i
= D
->attr_begin(), e
= D
->attr_end(); i
!= e
; ++i
)
1004 if ((*i
)->getKind() == A
->getKind()) {
1005 // FIXME: Don't hardcode this check
1006 if (OA
&& isa
<OwnershipAttr
>(*i
))
1007 return OA
->getOwnKind() == cast
<OwnershipAttr
>(*i
)->getOwnKind();
1014 /// MergeDeclAttributes - append attributes from the Old decl to the New one.
1015 static void MergeDeclAttributes(Decl
*New
, Decl
*Old
, ASTContext
&C
) {
1016 if (!Old
->hasAttrs())
1018 // Ensure that any moving of objects within the allocated map is done before
1020 if (!New
->hasAttrs())
1021 New
->setAttrs(AttrVec());
1022 for (specific_attr_iterator
<InheritableAttr
>
1023 i
= Old
->specific_attr_begin
<InheritableAttr
>(),
1024 e
= Old
->specific_attr_end
<InheritableAttr
>(); i
!= e
; ++i
) {
1025 if (!DeclHasAttr(New
, *i
)) {
1026 InheritableAttr
*NewAttr
= cast
<InheritableAttr
>((*i
)->clone(C
));
1027 NewAttr
->setInherited(true);
1028 New
->addAttr(NewAttr
);
1035 /// Used in MergeFunctionDecl to keep track of function parameters in
1037 struct GNUCompatibleParamWarning
{
1038 ParmVarDecl
*OldParm
;
1039 ParmVarDecl
*NewParm
;
1040 QualType PromotedType
;
1045 /// getSpecialMember - get the special member enum for a method.
1046 Sema::CXXSpecialMember
Sema::getSpecialMember(const CXXMethodDecl
*MD
) {
1047 if (const CXXConstructorDecl
*Ctor
= dyn_cast
<CXXConstructorDecl
>(MD
)) {
1048 if (Ctor
->isCopyConstructor())
1049 return Sema::CXXCopyConstructor
;
1051 return Sema::CXXConstructor
;
1054 if (isa
<CXXDestructorDecl
>(MD
))
1055 return Sema::CXXDestructor
;
1057 assert(MD
->isCopyAssignmentOperator() &&
1058 "Must have copy assignment operator");
1059 return Sema::CXXCopyAssignment
;
1062 /// canRedefineFunction - checks if a function can be redefined. Currently,
1063 /// only extern inline functions can be redefined, and even then only in
1065 static bool canRedefineFunction(const FunctionDecl
*FD
,
1066 const LangOptions
& LangOpts
) {
1067 return (LangOpts
.GNUMode
&& !LangOpts
.C99
&& !LangOpts
.CPlusPlus
&&
1068 FD
->isInlineSpecified() &&
1069 FD
->getStorageClass() == SC_Extern
);
1072 /// MergeFunctionDecl - We just parsed a function 'New' from
1073 /// declarator D which has the same name and scope as a previous
1074 /// declaration 'Old'. Figure out how to resolve this situation,
1075 /// merging decls or emitting diagnostics as appropriate.
1077 /// In C++, New and Old must be declarations that are not
1078 /// overloaded. Use IsOverload to determine whether New and Old are
1079 /// overloaded, and to select the Old declaration that New should be
1082 /// Returns true if there was an error, false otherwise.
1083 bool Sema::MergeFunctionDecl(FunctionDecl
*New
, Decl
*OldD
) {
1084 // Verify the old decl was also a function.
1085 FunctionDecl
*Old
= 0;
1086 if (FunctionTemplateDecl
*OldFunctionTemplate
1087 = dyn_cast
<FunctionTemplateDecl
>(OldD
))
1088 Old
= OldFunctionTemplate
->getTemplatedDecl();
1090 Old
= dyn_cast
<FunctionDecl
>(OldD
);
1092 if (UsingShadowDecl
*Shadow
= dyn_cast
<UsingShadowDecl
>(OldD
)) {
1093 Diag(New
->getLocation(), diag::err_using_decl_conflict_reverse
);
1094 Diag(Shadow
->getTargetDecl()->getLocation(),
1095 diag::note_using_decl_target
);
1096 Diag(Shadow
->getUsingDecl()->getLocation(),
1097 diag::note_using_decl
) << 0;
1101 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
1102 << New
->getDeclName();
1103 Diag(OldD
->getLocation(), diag::note_previous_definition
);
1107 // Determine whether the previous declaration was a definition,
1108 // implicit declaration, or a declaration.
1109 diag::kind PrevDiag
;
1110 if (Old
->isThisDeclarationADefinition())
1111 PrevDiag
= diag::note_previous_definition
;
1112 else if (Old
->isImplicit())
1113 PrevDiag
= diag::note_previous_implicit_declaration
;
1115 PrevDiag
= diag::note_previous_declaration
;
1117 QualType OldQType
= Context
.getCanonicalType(Old
->getType());
1118 QualType NewQType
= Context
.getCanonicalType(New
->getType());
1120 // Don't complain about this if we're in GNU89 mode and the old function
1121 // is an extern inline function.
1122 if (!isa
<CXXMethodDecl
>(New
) && !isa
<CXXMethodDecl
>(Old
) &&
1123 New
->getStorageClass() == SC_Static
&&
1124 Old
->getStorageClass() != SC_Static
&&
1125 !canRedefineFunction(Old
, getLangOptions())) {
1126 Diag(New
->getLocation(), diag::err_static_non_static
)
1128 Diag(Old
->getLocation(), PrevDiag
);
1132 // If a function is first declared with a calling convention, but is
1133 // later declared or defined without one, the second decl assumes the
1134 // calling convention of the first.
1136 // For the new decl, we have to look at the NON-canonical type to tell the
1137 // difference between a function that really doesn't have a calling
1138 // convention and one that is declared cdecl. That's because in
1139 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1140 // because it is the default calling convention.
1142 // Note also that we DO NOT return at this point, because we still have
1143 // other tests to run.
1144 const FunctionType
*OldType
= cast
<FunctionType
>(OldQType
);
1145 const FunctionType
*NewType
= New
->getType()->getAs
<FunctionType
>();
1146 FunctionType::ExtInfo OldTypeInfo
= OldType
->getExtInfo();
1147 FunctionType::ExtInfo NewTypeInfo
= NewType
->getExtInfo();
1148 bool RequiresAdjustment
= false;
1149 if (OldTypeInfo
.getCC() != CC_Default
&&
1150 NewTypeInfo
.getCC() == CC_Default
) {
1151 NewTypeInfo
= NewTypeInfo
.withCallingConv(OldTypeInfo
.getCC());
1152 RequiresAdjustment
= true;
1153 } else if (!Context
.isSameCallConv(OldTypeInfo
.getCC(),
1154 NewTypeInfo
.getCC())) {
1155 // Calling conventions really aren't compatible, so complain.
1156 Diag(New
->getLocation(), diag::err_cconv_change
)
1157 << FunctionType::getNameForCallConv(NewTypeInfo
.getCC())
1158 << (OldTypeInfo
.getCC() == CC_Default
)
1159 << (OldTypeInfo
.getCC() == CC_Default
? "" :
1160 FunctionType::getNameForCallConv(OldTypeInfo
.getCC()));
1161 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1165 // FIXME: diagnose the other way around?
1166 if (OldTypeInfo
.getNoReturn() && !NewTypeInfo
.getNoReturn()) {
1167 NewTypeInfo
= NewTypeInfo
.withNoReturn(true);
1168 RequiresAdjustment
= true;
1171 // Merge regparm attribute.
1172 if (OldTypeInfo
.getRegParm() != NewTypeInfo
.getRegParm()) {
1173 if (NewTypeInfo
.getRegParm()) {
1174 Diag(New
->getLocation(), diag::err_regparm_mismatch
)
1175 << NewType
->getRegParmType()
1176 << OldType
->getRegParmType();
1177 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1181 NewTypeInfo
= NewTypeInfo
.withRegParm(OldTypeInfo
.getRegParm());
1182 RequiresAdjustment
= true;
1185 if (RequiresAdjustment
) {
1186 NewType
= Context
.adjustFunctionType(NewType
, NewTypeInfo
);
1187 New
->setType(QualType(NewType
, 0));
1188 NewQType
= Context
.getCanonicalType(New
->getType());
1191 if (getLangOptions().CPlusPlus
) {
1193 // Certain function declarations cannot be overloaded:
1194 // -- Function declarations that differ only in the return type
1195 // cannot be overloaded.
1196 QualType OldReturnType
= OldType
->getResultType();
1197 QualType NewReturnType
= cast
<FunctionType
>(NewQType
)->getResultType();
1199 if (OldReturnType
!= NewReturnType
) {
1200 if (NewReturnType
->isObjCObjectPointerType()
1201 && OldReturnType
->isObjCObjectPointerType())
1202 ResQT
= Context
.mergeObjCGCQualifiers(NewQType
, OldQType
);
1203 if (ResQT
.isNull()) {
1204 Diag(New
->getLocation(), diag::err_ovl_diff_return_type
);
1205 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
1212 const CXXMethodDecl
* OldMethod
= dyn_cast
<CXXMethodDecl
>(Old
);
1213 CXXMethodDecl
* NewMethod
= dyn_cast
<CXXMethodDecl
>(New
);
1214 if (OldMethod
&& NewMethod
) {
1215 // Preserve triviality.
1216 NewMethod
->setTrivial(OldMethod
->isTrivial());
1218 bool isFriend
= NewMethod
->getFriendObjectKind();
1220 if (!isFriend
&& NewMethod
->getLexicalDeclContext()->isRecord()) {
1221 // -- Member function declarations with the same name and the
1222 // same parameter types cannot be overloaded if any of them
1223 // is a static member function declaration.
1224 if (OldMethod
->isStatic() || NewMethod
->isStatic()) {
1225 Diag(New
->getLocation(), diag::err_ovl_static_nonstatic_member
);
1226 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
1230 // C++ [class.mem]p1:
1231 // [...] A member shall not be declared twice in the
1232 // member-specification, except that a nested class or member
1233 // class template can be declared and then later defined.
1235 if (isa
<CXXConstructorDecl
>(OldMethod
))
1236 NewDiag
= diag::err_constructor_redeclared
;
1237 else if (isa
<CXXDestructorDecl
>(NewMethod
))
1238 NewDiag
= diag::err_destructor_redeclared
;
1239 else if (isa
<CXXConversionDecl
>(NewMethod
))
1240 NewDiag
= diag::err_conv_function_redeclared
;
1242 NewDiag
= diag::err_member_redeclared
;
1244 Diag(New
->getLocation(), NewDiag
);
1245 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
1247 // Complain if this is an explicit declaration of a special
1248 // member that was initially declared implicitly.
1250 // As an exception, it's okay to befriend such methods in order
1251 // to permit the implicit constructor/destructor/operator calls.
1252 } else if (OldMethod
->isImplicit()) {
1254 NewMethod
->setImplicit();
1256 Diag(NewMethod
->getLocation(),
1257 diag::err_definition_of_implicitly_declared_member
)
1258 << New
<< getSpecialMember(OldMethod
);
1265 // All declarations for a function shall agree exactly in both the
1266 // return type and the parameter-type-list.
1267 // We also want to respect all the extended bits except noreturn.
1269 // noreturn should now match unless the old type info didn't have it.
1270 QualType OldQTypeForComparison
= OldQType
;
1271 if (!OldTypeInfo
.getNoReturn() && NewTypeInfo
.getNoReturn()) {
1272 assert(OldQType
== QualType(OldType
, 0));
1273 const FunctionType
*OldTypeForComparison
1274 = Context
.adjustFunctionType(OldType
, OldTypeInfo
.withNoReturn(true));
1275 OldQTypeForComparison
= QualType(OldTypeForComparison
, 0);
1276 assert(OldQTypeForComparison
.isCanonical());
1279 if (OldQTypeForComparison
== NewQType
)
1280 return MergeCompatibleFunctionDecls(New
, Old
);
1282 // Fall through for conflicting redeclarations and redefinitions.
1285 // C: Function types need to be compatible, not identical. This handles
1286 // duplicate function decls like "void f(int); void f(enum X);" properly.
1287 if (!getLangOptions().CPlusPlus
&&
1288 Context
.typesAreCompatible(OldQType
, NewQType
)) {
1289 const FunctionType
*OldFuncType
= OldQType
->getAs
<FunctionType
>();
1290 const FunctionType
*NewFuncType
= NewQType
->getAs
<FunctionType
>();
1291 const FunctionProtoType
*OldProto
= 0;
1292 if (isa
<FunctionNoProtoType
>(NewFuncType
) &&
1293 (OldProto
= dyn_cast
<FunctionProtoType
>(OldFuncType
))) {
1294 // The old declaration provided a function prototype, but the
1295 // new declaration does not. Merge in the prototype.
1296 assert(!OldProto
->hasExceptionSpec() && "Exception spec in C");
1297 llvm::SmallVector
<QualType
, 16> ParamTypes(OldProto
->arg_type_begin(),
1298 OldProto
->arg_type_end());
1299 NewQType
= Context
.getFunctionType(NewFuncType
->getResultType(),
1300 ParamTypes
.data(), ParamTypes
.size(),
1301 OldProto
->getExtProtoInfo());
1302 New
->setType(NewQType
);
1303 New
->setHasInheritedPrototype();
1305 // Synthesize a parameter for each argument type.
1306 llvm::SmallVector
<ParmVarDecl
*, 16> Params
;
1307 for (FunctionProtoType::arg_type_iterator
1308 ParamType
= OldProto
->arg_type_begin(),
1309 ParamEnd
= OldProto
->arg_type_end();
1310 ParamType
!= ParamEnd
; ++ParamType
) {
1311 ParmVarDecl
*Param
= ParmVarDecl::Create(Context
, New
,
1312 SourceLocation(), 0,
1313 *ParamType
, /*TInfo=*/0,
1316 Param
->setImplicit();
1317 Params
.push_back(Param
);
1320 New
->setParams(Params
.data(), Params
.size());
1323 return MergeCompatibleFunctionDecls(New
, Old
);
1326 // GNU C permits a K&R definition to follow a prototype declaration
1327 // if the declared types of the parameters in the K&R definition
1328 // match the types in the prototype declaration, even when the
1329 // promoted types of the parameters from the K&R definition differ
1330 // from the types in the prototype. GCC then keeps the types from
1333 // If a variadic prototype is followed by a non-variadic K&R definition,
1334 // the K&R definition becomes variadic. This is sort of an edge case, but
1335 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1337 if (!getLangOptions().CPlusPlus
&&
1338 Old
->hasPrototype() && !New
->hasPrototype() &&
1339 New
->getType()->getAs
<FunctionProtoType
>() &&
1340 Old
->getNumParams() == New
->getNumParams()) {
1341 llvm::SmallVector
<QualType
, 16> ArgTypes
;
1342 llvm::SmallVector
<GNUCompatibleParamWarning
, 16> Warnings
;
1343 const FunctionProtoType
*OldProto
1344 = Old
->getType()->getAs
<FunctionProtoType
>();
1345 const FunctionProtoType
*NewProto
1346 = New
->getType()->getAs
<FunctionProtoType
>();
1348 // Determine whether this is the GNU C extension.
1349 QualType MergedReturn
= Context
.mergeTypes(OldProto
->getResultType(),
1350 NewProto
->getResultType());
1351 bool LooseCompatible
= !MergedReturn
.isNull();
1352 for (unsigned Idx
= 0, End
= Old
->getNumParams();
1353 LooseCompatible
&& Idx
!= End
; ++Idx
) {
1354 ParmVarDecl
*OldParm
= Old
->getParamDecl(Idx
);
1355 ParmVarDecl
*NewParm
= New
->getParamDecl(Idx
);
1356 if (Context
.typesAreCompatible(OldParm
->getType(),
1357 NewProto
->getArgType(Idx
))) {
1358 ArgTypes
.push_back(NewParm
->getType());
1359 } else if (Context
.typesAreCompatible(OldParm
->getType(),
1361 /*CompareUnqualified=*/true)) {
1362 GNUCompatibleParamWarning Warn
1363 = { OldParm
, NewParm
, NewProto
->getArgType(Idx
) };
1364 Warnings
.push_back(Warn
);
1365 ArgTypes
.push_back(NewParm
->getType());
1367 LooseCompatible
= false;
1370 if (LooseCompatible
) {
1371 for (unsigned Warn
= 0; Warn
< Warnings
.size(); ++Warn
) {
1372 Diag(Warnings
[Warn
].NewParm
->getLocation(),
1373 diag::ext_param_promoted_not_compatible_with_prototype
)
1374 << Warnings
[Warn
].PromotedType
1375 << Warnings
[Warn
].OldParm
->getType();
1376 if (Warnings
[Warn
].OldParm
->getLocation().isValid())
1377 Diag(Warnings
[Warn
].OldParm
->getLocation(),
1378 diag::note_previous_declaration
);
1381 New
->setType(Context
.getFunctionType(MergedReturn
, &ArgTypes
[0],
1383 OldProto
->getExtProtoInfo()));
1384 return MergeCompatibleFunctionDecls(New
, Old
);
1387 // Fall through to diagnose conflicting types.
1390 // A function that has already been declared has been redeclared or defined
1391 // with a different type- show appropriate diagnostic
1392 if (unsigned BuiltinID
= Old
->getBuiltinID()) {
1393 // The user has declared a builtin function with an incompatible
1395 if (Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
)) {
1396 // The function the user is redeclaring is a library-defined
1397 // function like 'malloc' or 'printf'. Warn about the
1398 // redeclaration, then pretend that we don't know about this
1399 // library built-in.
1400 Diag(New
->getLocation(), diag::warn_redecl_library_builtin
) << New
;
1401 Diag(Old
->getLocation(), diag::note_previous_builtin_declaration
)
1402 << Old
<< Old
->getType();
1403 New
->getIdentifier()->setBuiltinID(Builtin::NotBuiltin
);
1404 Old
->setInvalidDecl();
1408 PrevDiag
= diag::note_previous_builtin_declaration
;
1411 Diag(New
->getLocation(), diag::err_conflicting_types
) << New
->getDeclName();
1412 Diag(Old
->getLocation(), PrevDiag
) << Old
<< Old
->getType();
1416 /// \brief Completes the merge of two function declarations that are
1417 /// known to be compatible.
1419 /// This routine handles the merging of attributes and other
1420 /// properties of function declarations form the old declaration to
1421 /// the new declaration, once we know that New is in fact a
1422 /// redeclaration of Old.
1425 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl
*New
, FunctionDecl
*Old
) {
1426 // Merge the attributes
1427 MergeDeclAttributes(New
, Old
, Context
);
1429 // Merge the storage class.
1430 if (Old
->getStorageClass() != SC_Extern
&&
1431 Old
->getStorageClass() != SC_None
)
1432 New
->setStorageClass(Old
->getStorageClass());
1434 // Merge "pure" flag.
1438 // Merge the "deleted" flag.
1439 if (Old
->isDeleted())
1442 if (getLangOptions().CPlusPlus
)
1443 return MergeCXXFunctionDecl(New
, Old
);
1448 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
1449 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
1450 /// situation, merging decls or emitting diagnostics as appropriate.
1452 /// Tentative definition rules (C99 6.9.2p2) are checked by
1453 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1454 /// definitions here, since the initializer hasn't been attached.
1456 void Sema::MergeVarDecl(VarDecl
*New
, LookupResult
&Previous
) {
1457 // If the new decl is already invalid, don't do any other checking.
1458 if (New
->isInvalidDecl())
1461 // Verify the old decl was also a variable.
1463 if (!Previous
.isSingleResult() ||
1464 !(Old
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl()))) {
1465 Diag(New
->getLocation(), diag::err_redefinition_different_kind
)
1466 << New
->getDeclName();
1467 Diag(Previous
.getRepresentativeDecl()->getLocation(),
1468 diag::note_previous_definition
);
1469 return New
->setInvalidDecl();
1472 // C++ [class.mem]p1:
1473 // A member shall not be declared twice in the member-specification [...]
1475 // Here, we need only consider static data members.
1476 if (Old
->isStaticDataMember() && !New
->isOutOfLine()) {
1477 Diag(New
->getLocation(), diag::err_duplicate_member
)
1478 << New
->getIdentifier();
1479 Diag(Old
->getLocation(), diag::note_previous_declaration
);
1480 New
->setInvalidDecl();
1483 MergeDeclAttributes(New
, Old
, Context
);
1487 if (getLangOptions().CPlusPlus
) {
1488 if (Context
.hasSameType(New
->getType(), Old
->getType()))
1489 MergedT
= New
->getType();
1490 // C++ [basic.link]p10:
1491 // [...] the types specified by all declarations referring to a given
1492 // object or function shall be identical, except that declarations for an
1493 // array object can specify array types that differ by the presence or
1494 // absence of a major array bound (8.3.4).
1495 else if (Old
->getType()->isIncompleteArrayType() &&
1496 New
->getType()->isArrayType()) {
1497 CanQual
<ArrayType
> OldArray
1498 = Context
.getCanonicalType(Old
->getType())->getAs
<ArrayType
>();
1499 CanQual
<ArrayType
> NewArray
1500 = Context
.getCanonicalType(New
->getType())->getAs
<ArrayType
>();
1501 if (OldArray
->getElementType() == NewArray
->getElementType())
1502 MergedT
= New
->getType();
1503 } else if (Old
->getType()->isArrayType() &&
1504 New
->getType()->isIncompleteArrayType()) {
1505 CanQual
<ArrayType
> OldArray
1506 = Context
.getCanonicalType(Old
->getType())->getAs
<ArrayType
>();
1507 CanQual
<ArrayType
> NewArray
1508 = Context
.getCanonicalType(New
->getType())->getAs
<ArrayType
>();
1509 if (OldArray
->getElementType() == NewArray
->getElementType())
1510 MergedT
= Old
->getType();
1511 } else if (New
->getType()->isObjCObjectPointerType()
1512 && Old
->getType()->isObjCObjectPointerType()) {
1513 MergedT
= Context
.mergeObjCGCQualifiers(New
->getType(), Old
->getType());
1516 MergedT
= Context
.mergeTypes(New
->getType(), Old
->getType());
1518 if (MergedT
.isNull()) {
1519 Diag(New
->getLocation(), diag::err_redefinition_different_type
)
1520 << New
->getDeclName();
1521 Diag(Old
->getLocation(), diag::note_previous_definition
);
1522 return New
->setInvalidDecl();
1524 New
->setType(MergedT
);
1526 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1527 if (New
->getStorageClass() == SC_Static
&&
1528 (Old
->getStorageClass() == SC_None
|| Old
->hasExternalStorage())) {
1529 Diag(New
->getLocation(), diag::err_static_non_static
) << New
->getDeclName();
1530 Diag(Old
->getLocation(), diag::note_previous_definition
);
1531 return New
->setInvalidDecl();
1534 // For an identifier declared with the storage-class specifier
1535 // extern in a scope in which a prior declaration of that
1536 // identifier is visible,23) if the prior declaration specifies
1537 // internal or external linkage, the linkage of the identifier at
1538 // the later declaration is the same as the linkage specified at
1539 // the prior declaration. If no prior declaration is visible, or
1540 // if the prior declaration specifies no linkage, then the
1541 // identifier has external linkage.
1542 if (New
->hasExternalStorage() && Old
->hasLinkage())
1544 else if (New
->getStorageClass() != SC_Static
&&
1545 Old
->getStorageClass() == SC_Static
) {
1546 Diag(New
->getLocation(), diag::err_non_static_static
) << New
->getDeclName();
1547 Diag(Old
->getLocation(), diag::note_previous_definition
);
1548 return New
->setInvalidDecl();
1551 // Check if extern is followed by non-extern and vice-versa.
1552 if (New
->hasExternalStorage() &&
1553 !Old
->hasLinkage() && Old
->isLocalVarDecl()) {
1554 Diag(New
->getLocation(), diag::err_extern_non_extern
) << New
->getDeclName();
1555 Diag(Old
->getLocation(), diag::note_previous_definition
);
1556 return New
->setInvalidDecl();
1558 if (Old
->hasExternalStorage() &&
1559 !New
->hasLinkage() && New
->isLocalVarDecl()) {
1560 Diag(New
->getLocation(), diag::err_non_extern_extern
) << New
->getDeclName();
1561 Diag(Old
->getLocation(), diag::note_previous_definition
);
1562 return New
->setInvalidDecl();
1565 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1567 // FIXME: The test for external storage here seems wrong? We still
1568 // need to check for mismatches.
1569 if (!New
->hasExternalStorage() && !New
->isFileVarDecl() &&
1570 // Don't complain about out-of-line definitions of static members.
1571 !(Old
->getLexicalDeclContext()->isRecord() &&
1572 !New
->getLexicalDeclContext()->isRecord())) {
1573 Diag(New
->getLocation(), diag::err_redefinition
) << New
->getDeclName();
1574 Diag(Old
->getLocation(), diag::note_previous_definition
);
1575 return New
->setInvalidDecl();
1578 if (New
->isThreadSpecified() && !Old
->isThreadSpecified()) {
1579 Diag(New
->getLocation(), diag::err_thread_non_thread
) << New
->getDeclName();
1580 Diag(Old
->getLocation(), diag::note_previous_definition
);
1581 } else if (!New
->isThreadSpecified() && Old
->isThreadSpecified()) {
1582 Diag(New
->getLocation(), diag::err_non_thread_thread
) << New
->getDeclName();
1583 Diag(Old
->getLocation(), diag::note_previous_definition
);
1586 // C++ doesn't have tentative definitions, so go right ahead and check here.
1588 if (getLangOptions().CPlusPlus
&&
1589 New
->isThisDeclarationADefinition() == VarDecl::Definition
&&
1590 (Def
= Old
->getDefinition())) {
1591 Diag(New
->getLocation(), diag::err_redefinition
)
1592 << New
->getDeclName();
1593 Diag(Def
->getLocation(), diag::note_previous_definition
);
1594 New
->setInvalidDecl();
1598 // For an identifier declared with the storage-class specifier extern in a
1599 // scope in which a prior declaration of that identifier is visible, if
1600 // the prior declaration specifies internal or external linkage, the linkage
1601 // of the identifier at the later declaration is the same as the linkage
1602 // specified at the prior declaration.
1603 // FIXME. revisit this code.
1604 if (New
->hasExternalStorage() &&
1605 Old
->getLinkage() == InternalLinkage
&&
1606 New
->getDeclContext() == Old
->getDeclContext())
1607 New
->setStorageClass(Old
->getStorageClass());
1609 // Keep a chain of previous declarations.
1610 New
->setPreviousDeclaration(Old
);
1612 // Inherit access appropriately.
1613 New
->setAccess(Old
->getAccess());
1616 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1617 /// no declarator (e.g. "struct foo;") is parsed.
1618 Decl
*Sema::ParsedFreeStandingDeclSpec(Scope
*S
, AccessSpecifier AS
,
1620 // FIXME: Error on inline/virtual/explicit
1621 // FIXME: Warn on useless __thread
1622 // FIXME: Warn on useless const/volatile
1623 // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1624 // FIXME: Warn on useless attributes
1627 if (DS
.getTypeSpecType() == DeclSpec::TST_class
||
1628 DS
.getTypeSpecType() == DeclSpec::TST_struct
||
1629 DS
.getTypeSpecType() == DeclSpec::TST_union
||
1630 DS
.getTypeSpecType() == DeclSpec::TST_enum
) {
1631 TagD
= DS
.getRepAsDecl();
1633 if (!TagD
) // We probably had an error
1636 // Note that the above type specs guarantee that the
1637 // type rep is a Decl, whereas in many of the others
1639 Tag
= dyn_cast
<TagDecl
>(TagD
);
1642 if (unsigned TypeQuals
= DS
.getTypeQualifiers()) {
1643 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1644 // or incomplete types shall not be restrict-qualified."
1645 if (TypeQuals
& DeclSpec::TQ_restrict
)
1646 Diag(DS
.getRestrictSpecLoc(),
1647 diag::err_typecheck_invalid_restrict_not_pointer_noarg
)
1648 << DS
.getSourceRange();
1651 if (DS
.isFriendSpecified()) {
1652 // If we're dealing with a decl but not a TagDecl, assume that
1653 // whatever routines created it handled the friendship aspect.
1656 return ActOnFriendTypeDecl(S
, DS
, MultiTemplateParamsArg(*this, 0, 0));
1659 if (RecordDecl
*Record
= dyn_cast_or_null
<RecordDecl
>(Tag
)) {
1660 ProcessDeclAttributeList(S
, Record
, DS
.getAttributes().getList());
1662 if (!Record
->getDeclName() && Record
->isDefinition() &&
1663 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
) {
1664 if (getLangOptions().CPlusPlus
||
1665 Record
->getDeclContext()->isRecord())
1666 return BuildAnonymousStructOrUnion(S
, DS
, AS
, Record
);
1668 Diag(DS
.getSourceRange().getBegin(), diag::ext_no_declarators
)
1669 << DS
.getSourceRange();
1673 // Check for Microsoft C extension: anonymous struct.
1674 if (getLangOptions().Microsoft
&& !getLangOptions().CPlusPlus
&&
1675 CurContext
->isRecord() &&
1676 DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
) {
1677 // Handle 2 kinds of anonymous struct:
1680 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
1681 RecordDecl
*Record
= dyn_cast_or_null
<RecordDecl
>(Tag
);
1682 if ((Record
&& Record
->getDeclName() && !Record
->isDefinition()) ||
1683 (DS
.getTypeSpecType() == DeclSpec::TST_typename
&&
1684 DS
.getRepAsType().get()->isStructureType())) {
1685 Diag(DS
.getSourceRange().getBegin(), diag::ext_ms_anonymous_struct
)
1686 << DS
.getSourceRange();
1687 return BuildMicrosoftCAnonymousStruct(S
, DS
, Record
);
1691 if (getLangOptions().CPlusPlus
&&
1692 DS
.getStorageClassSpec() != DeclSpec::SCS_typedef
)
1693 if (EnumDecl
*Enum
= dyn_cast_or_null
<EnumDecl
>(Tag
))
1694 if (Enum
->enumerator_begin() == Enum
->enumerator_end() &&
1695 !Enum
->getIdentifier() && !Enum
->isInvalidDecl())
1696 Diag(Enum
->getLocation(), diag::ext_no_declarators
)
1697 << DS
.getSourceRange();
1699 if (!DS
.isMissingDeclaratorOk() &&
1700 DS
.getTypeSpecType() != DeclSpec::TST_error
) {
1701 // Warn about typedefs of enums without names, since this is an
1702 // extension in both Microsoft and GNU.
1703 if (DS
.getStorageClassSpec() == DeclSpec::SCS_typedef
&&
1704 Tag
&& isa
<EnumDecl
>(Tag
)) {
1705 Diag(DS
.getSourceRange().getBegin(), diag::ext_typedef_without_a_name
)
1706 << DS
.getSourceRange();
1710 Diag(DS
.getSourceRange().getBegin(), diag::ext_no_declarators
)
1711 << DS
.getSourceRange();
1717 /// ActOnVlaStmt - This rouine if finds a vla expression in a decl spec.
1718 /// builds a statement for it and returns it so it is evaluated.
1719 StmtResult
Sema::ActOnVlaStmt(const DeclSpec
&DS
) {
1721 if (DS
.getTypeSpecType() == DeclSpec::TST_typeofExpr
) {
1722 Expr
*Exp
= DS
.getRepAsExpr();
1723 QualType Ty
= Exp
->getType();
1724 if (Ty
->isPointerType()) {
1726 Ty
= Ty
->getAs
<PointerType
>()->getPointeeType();
1727 while (Ty
->isPointerType());
1729 if (Ty
->isVariableArrayType()) {
1730 R
= ActOnExprStmt(MakeFullExpr(Exp
));
1736 /// We are trying to inject an anonymous member into the given scope;
1737 /// check if there's an existing declaration that can't be overloaded.
1739 /// \return true if this is a forbidden redeclaration
1740 static bool CheckAnonMemberRedeclaration(Sema
&SemaRef
,
1743 DeclarationName Name
,
1744 SourceLocation NameLoc
,
1745 unsigned diagnostic
) {
1746 LookupResult
R(SemaRef
, Name
, NameLoc
, Sema::LookupMemberName
,
1747 Sema::ForRedeclaration
);
1748 if (!SemaRef
.LookupName(R
, S
)) return false;
1750 if (R
.getAsSingle
<TagDecl
>())
1753 // Pick a representative declaration.
1754 NamedDecl
*PrevDecl
= R
.getRepresentativeDecl()->getUnderlyingDecl();
1755 assert(PrevDecl
&& "Expected a non-null Decl");
1757 if (!SemaRef
.isDeclInScope(PrevDecl
, Owner
, S
))
1760 SemaRef
.Diag(NameLoc
, diagnostic
) << Name
;
1761 SemaRef
.Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
1766 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
1767 /// anonymous struct or union AnonRecord into the owning context Owner
1768 /// and scope S. This routine will be invoked just after we realize
1769 /// that an unnamed union or struct is actually an anonymous union or
1776 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1777 /// // f into the surrounding scope.x
1780 /// This routine is recursive, injecting the names of nested anonymous
1781 /// structs/unions into the owning context and scope as well.
1782 static bool InjectAnonymousStructOrUnionMembers(Sema
&SemaRef
, Scope
*S
,
1784 RecordDecl
*AnonRecord
,
1786 llvm::SmallVector
<NamedDecl
*, 2> &Chaining
,
1787 bool MSAnonStruct
) {
1789 = AnonRecord
->isUnion() ? diag::err_anonymous_union_member_redecl
1790 : diag::err_anonymous_struct_member_redecl
;
1792 bool Invalid
= false;
1794 // Look every FieldDecl and IndirectFieldDecl with a name.
1795 for (RecordDecl::decl_iterator D
= AnonRecord
->decls_begin(),
1796 DEnd
= AnonRecord
->decls_end();
1798 if ((isa
<FieldDecl
>(*D
) || isa
<IndirectFieldDecl
>(*D
)) &&
1799 cast
<NamedDecl
>(*D
)->getDeclName()) {
1800 ValueDecl
*VD
= cast
<ValueDecl
>(*D
);
1801 if (CheckAnonMemberRedeclaration(SemaRef
, S
, Owner
, VD
->getDeclName(),
1802 VD
->getLocation(), diagKind
)) {
1803 // C++ [class.union]p2:
1804 // The names of the members of an anonymous union shall be
1805 // distinct from the names of any other entity in the
1806 // scope in which the anonymous union is declared.
1809 // C++ [class.union]p2:
1810 // For the purpose of name lookup, after the anonymous union
1811 // definition, the members of the anonymous union are
1812 // considered to have been defined in the scope in which the
1813 // anonymous union is declared.
1814 unsigned OldChainingSize
= Chaining
.size();
1815 if (IndirectFieldDecl
*IF
= dyn_cast
<IndirectFieldDecl
>(VD
))
1816 for (IndirectFieldDecl::chain_iterator PI
= IF
->chain_begin(),
1817 PE
= IF
->chain_end(); PI
!= PE
; ++PI
)
1818 Chaining
.push_back(*PI
);
1820 Chaining
.push_back(VD
);
1822 assert(Chaining
.size() >= 2);
1823 NamedDecl
**NamedChain
=
1824 new (SemaRef
.Context
)NamedDecl
*[Chaining
.size()];
1825 for (unsigned i
= 0; i
< Chaining
.size(); i
++)
1826 NamedChain
[i
] = Chaining
[i
];
1828 IndirectFieldDecl
* IndirectField
=
1829 IndirectFieldDecl::Create(SemaRef
.Context
, Owner
, VD
->getLocation(),
1830 VD
->getIdentifier(), VD
->getType(),
1831 NamedChain
, Chaining
.size());
1833 IndirectField
->setAccess(AS
);
1834 IndirectField
->setImplicit();
1835 SemaRef
.PushOnScopeChains(IndirectField
, S
);
1837 // That includes picking up the appropriate access specifier.
1838 if (AS
!= AS_none
) IndirectField
->setAccess(AS
);
1840 Chaining
.resize(OldChainingSize
);
1848 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1849 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
1850 /// illegal input values are mapped to SC_None.
1852 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec
) {
1853 switch (StorageClassSpec
) {
1854 case DeclSpec::SCS_unspecified
: return SC_None
;
1855 case DeclSpec::SCS_extern
: return SC_Extern
;
1856 case DeclSpec::SCS_static
: return SC_Static
;
1857 case DeclSpec::SCS_auto
: return SC_Auto
;
1858 case DeclSpec::SCS_register
: return SC_Register
;
1859 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
1860 // Illegal SCSs map to None: error reporting is up to the caller.
1861 case DeclSpec::SCS_mutable
: // Fall through.
1862 case DeclSpec::SCS_typedef
: return SC_None
;
1864 llvm_unreachable("unknown storage class specifier");
1867 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1868 /// a StorageClass. Any error reporting is up to the caller:
1869 /// illegal input values are mapped to SC_None.
1871 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec
) {
1872 switch (StorageClassSpec
) {
1873 case DeclSpec::SCS_unspecified
: return SC_None
;
1874 case DeclSpec::SCS_extern
: return SC_Extern
;
1875 case DeclSpec::SCS_static
: return SC_Static
;
1876 case DeclSpec::SCS_private_extern
: return SC_PrivateExtern
;
1877 // Illegal SCSs map to None: error reporting is up to the caller.
1878 case DeclSpec::SCS_auto
: // Fall through.
1879 case DeclSpec::SCS_mutable
: // Fall through.
1880 case DeclSpec::SCS_register
: // Fall through.
1881 case DeclSpec::SCS_typedef
: return SC_None
;
1883 llvm_unreachable("unknown storage class specifier");
1886 /// BuildAnonymousStructOrUnion - Handle the declaration of an
1887 /// anonymous structure or union. Anonymous unions are a C++ feature
1888 /// (C++ [class.union]) and a GNU C extension; anonymous structures
1889 /// are a GNU C and GNU C++ extension.
1890 Decl
*Sema::BuildAnonymousStructOrUnion(Scope
*S
, DeclSpec
&DS
,
1892 RecordDecl
*Record
) {
1893 DeclContext
*Owner
= Record
->getDeclContext();
1895 // Diagnose whether this anonymous struct/union is an extension.
1896 if (Record
->isUnion() && !getLangOptions().CPlusPlus
)
1897 Diag(Record
->getLocation(), diag::ext_anonymous_union
);
1898 else if (!Record
->isUnion())
1899 Diag(Record
->getLocation(), diag::ext_anonymous_struct
);
1901 // C and C++ require different kinds of checks for anonymous
1903 bool Invalid
= false;
1904 if (getLangOptions().CPlusPlus
) {
1905 const char* PrevSpec
= 0;
1907 // C++ [class.union]p3:
1908 // Anonymous unions declared in a named namespace or in the
1909 // global namespace shall be declared static.
1910 if (DS
.getStorageClassSpec() != DeclSpec::SCS_static
&&
1911 (isa
<TranslationUnitDecl
>(Owner
) ||
1912 (isa
<NamespaceDecl
>(Owner
) &&
1913 cast
<NamespaceDecl
>(Owner
)->getDeclName()))) {
1914 Diag(Record
->getLocation(), diag::err_anonymous_union_not_static
);
1917 // Recover by adding 'static'.
1918 DS
.SetStorageClassSpec(DeclSpec::SCS_static
, SourceLocation(),
1921 // C++ [class.union]p3:
1922 // A storage class is not allowed in a declaration of an
1923 // anonymous union in a class scope.
1924 else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
&&
1925 isa
<RecordDecl
>(Owner
)) {
1926 Diag(DS
.getStorageClassSpecLoc(),
1927 diag::err_anonymous_union_with_storage_spec
);
1930 // Recover by removing the storage specifier.
1931 DS
.SetStorageClassSpec(DeclSpec::SCS_unspecified
, SourceLocation(),
1935 // C++ [class.union]p2:
1936 // The member-specification of an anonymous union shall only
1937 // define non-static data members. [Note: nested types and
1938 // functions cannot be declared within an anonymous union. ]
1939 for (DeclContext::decl_iterator Mem
= Record
->decls_begin(),
1940 MemEnd
= Record
->decls_end();
1941 Mem
!= MemEnd
; ++Mem
) {
1942 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(*Mem
)) {
1943 // C++ [class.union]p3:
1944 // An anonymous union shall not have private or protected
1945 // members (clause 11).
1946 assert(FD
->getAccess() != AS_none
);
1947 if (FD
->getAccess() != AS_public
) {
1948 Diag(FD
->getLocation(), diag::err_anonymous_record_nonpublic_member
)
1949 << (int)Record
->isUnion() << (int)(FD
->getAccess() == AS_protected
);
1953 if (CheckNontrivialField(FD
))
1955 } else if ((*Mem
)->isImplicit()) {
1956 // Any implicit members are fine.
1957 } else if (isa
<TagDecl
>(*Mem
) && (*Mem
)->getDeclContext() != Record
) {
1958 // This is a type that showed up in an
1959 // elaborated-type-specifier inside the anonymous struct or
1960 // union, but which actually declares a type outside of the
1961 // anonymous struct or union. It's okay.
1962 } else if (RecordDecl
*MemRecord
= dyn_cast
<RecordDecl
>(*Mem
)) {
1963 if (!MemRecord
->isAnonymousStructOrUnion() &&
1964 MemRecord
->getDeclName()) {
1965 // Visual C++ allows type definition in anonymous struct or union.
1966 if (getLangOptions().Microsoft
)
1967 Diag(MemRecord
->getLocation(), diag::ext_anonymous_record_with_type
)
1968 << (int)Record
->isUnion();
1970 // This is a nested type declaration.
1971 Diag(MemRecord
->getLocation(), diag::err_anonymous_record_with_type
)
1972 << (int)Record
->isUnion();
1976 } else if (isa
<AccessSpecDecl
>(*Mem
)) {
1977 // Any access specifier is fine.
1979 // We have something that isn't a non-static data
1980 // member. Complain about it.
1981 unsigned DK
= diag::err_anonymous_record_bad_member
;
1982 if (isa
<TypeDecl
>(*Mem
))
1983 DK
= diag::err_anonymous_record_with_type
;
1984 else if (isa
<FunctionDecl
>(*Mem
))
1985 DK
= diag::err_anonymous_record_with_function
;
1986 else if (isa
<VarDecl
>(*Mem
))
1987 DK
= diag::err_anonymous_record_with_static
;
1989 // Visual C++ allows type definition in anonymous struct or union.
1990 if (getLangOptions().Microsoft
&&
1991 DK
== diag::err_anonymous_record_with_type
)
1992 Diag((*Mem
)->getLocation(), diag::ext_anonymous_record_with_type
)
1993 << (int)Record
->isUnion();
1995 Diag((*Mem
)->getLocation(), DK
)
1996 << (int)Record
->isUnion();
2003 if (!Record
->isUnion() && !Owner
->isRecord()) {
2004 Diag(Record
->getLocation(), diag::err_anonymous_struct_not_member
)
2005 << (int)getLangOptions().CPlusPlus
;
2009 // Mock up a declarator.
2010 Declarator
Dc(DS
, Declarator::TypeNameContext
);
2011 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
2012 assert(TInfo
&& "couldn't build declarator info for anonymous struct/union");
2014 // Create a declaration for this anonymous struct/union.
2015 NamedDecl
*Anon
= 0;
2016 if (RecordDecl
*OwningClass
= dyn_cast
<RecordDecl
>(Owner
)) {
2017 Anon
= FieldDecl::Create(Context
, OwningClass
, Record
->getLocation(),
2018 /*IdentifierInfo=*/0,
2019 Context
.getTypeDeclType(Record
),
2021 /*BitWidth=*/0, /*Mutable=*/false);
2022 Anon
->setAccess(AS
);
2023 if (getLangOptions().CPlusPlus
)
2024 FieldCollector
->Add(cast
<FieldDecl
>(Anon
));
2026 DeclSpec::SCS SCSpec
= DS
.getStorageClassSpec();
2027 assert(SCSpec
!= DeclSpec::SCS_typedef
&&
2028 "Parser allowed 'typedef' as storage class VarDecl.");
2029 VarDecl::StorageClass SC
= StorageClassSpecToVarDeclStorageClass(SCSpec
);
2030 if (SCSpec
== DeclSpec::SCS_mutable
) {
2031 // mutable can only appear on non-static class members, so it's always
2033 Diag(Record
->getLocation(), diag::err_mutable_nonmember
);
2037 SCSpec
= DS
.getStorageClassSpecAsWritten();
2038 VarDecl::StorageClass SCAsWritten
2039 = StorageClassSpecToVarDeclStorageClass(SCSpec
);
2041 Anon
= VarDecl::Create(Context
, Owner
, Record
->getLocation(),
2042 /*IdentifierInfo=*/0,
2043 Context
.getTypeDeclType(Record
),
2044 TInfo
, SC
, SCAsWritten
);
2046 Anon
->setImplicit();
2048 // Add the anonymous struct/union object to the current
2049 // context. We'll be referencing this object when we refer to one of
2051 Owner
->addDecl(Anon
);
2053 // Inject the members of the anonymous struct/union into the owning
2054 // context and into the identifier resolver chain for name lookup
2056 llvm::SmallVector
<NamedDecl
*, 2> Chain
;
2057 Chain
.push_back(Anon
);
2059 if (InjectAnonymousStructOrUnionMembers(*this, S
, Owner
, Record
, AS
,
2063 // Mark this as an anonymous struct/union type. Note that we do not
2064 // do this until after we have already checked and injected the
2065 // members of this anonymous struct/union type, because otherwise
2066 // the members could be injected twice: once by DeclContext when it
2067 // builds its lookup table, and once by
2068 // InjectAnonymousStructOrUnionMembers.
2069 Record
->setAnonymousStructOrUnion(true);
2072 Anon
->setInvalidDecl();
2077 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2078 /// Microsoft C anonymous structure.
2079 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2082 /// struct A { int a; };
2083 /// struct B { struct A; int b; };
2090 Decl
*Sema::BuildMicrosoftCAnonymousStruct(Scope
*S
, DeclSpec
&DS
,
2091 RecordDecl
*Record
) {
2093 // If there is no Record, get the record via the typedef.
2095 Record
= DS
.getRepAsType().get()->getAsStructureType()->getDecl();
2097 // Mock up a declarator.
2098 Declarator
Dc(DS
, Declarator::TypeNameContext
);
2099 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(Dc
, S
);
2100 assert(TInfo
&& "couldn't build declarator info for anonymous struct");
2102 // Create a declaration for this anonymous struct.
2103 NamedDecl
* Anon
= FieldDecl::Create(Context
,
2104 cast
<RecordDecl
>(CurContext
),
2105 DS
.getSourceRange().getBegin(),
2106 /*IdentifierInfo=*/0,
2107 Context
.getTypeDeclType(Record
),
2109 /*BitWidth=*/0, /*Mutable=*/false);
2110 Anon
->setImplicit();
2112 // Add the anonymous struct object to the current context.
2113 CurContext
->addDecl(Anon
);
2115 // Inject the members of the anonymous struct into the current
2116 // context and into the identifier resolver chain for name lookup
2118 llvm::SmallVector
<NamedDecl
*, 2> Chain
;
2119 Chain
.push_back(Anon
);
2121 if (InjectAnonymousStructOrUnionMembers(*this, S
, CurContext
,
2122 Record
->getDefinition(),
2123 AS_none
, Chain
, true))
2124 Anon
->setInvalidDecl();
2129 /// GetNameForDeclarator - Determine the full declaration name for the
2130 /// given Declarator.
2131 DeclarationNameInfo
Sema::GetNameForDeclarator(Declarator
&D
) {
2132 return GetNameFromUnqualifiedId(D
.getName());
2135 /// \brief Retrieves the declaration name from a parsed unqualified-id.
2137 Sema::GetNameFromUnqualifiedId(const UnqualifiedId
&Name
) {
2138 DeclarationNameInfo NameInfo
;
2139 NameInfo
.setLoc(Name
.StartLocation
);
2141 switch (Name
.getKind()) {
2143 case UnqualifiedId::IK_Identifier
:
2144 NameInfo
.setName(Name
.Identifier
);
2145 NameInfo
.setLoc(Name
.StartLocation
);
2148 case UnqualifiedId::IK_OperatorFunctionId
:
2149 NameInfo
.setName(Context
.DeclarationNames
.getCXXOperatorName(
2150 Name
.OperatorFunctionId
.Operator
));
2151 NameInfo
.setLoc(Name
.StartLocation
);
2152 NameInfo
.getInfo().CXXOperatorName
.BeginOpNameLoc
2153 = Name
.OperatorFunctionId
.SymbolLocations
[0];
2154 NameInfo
.getInfo().CXXOperatorName
.EndOpNameLoc
2155 = Name
.EndLocation
.getRawEncoding();
2158 case UnqualifiedId::IK_LiteralOperatorId
:
2159 NameInfo
.setName(Context
.DeclarationNames
.getCXXLiteralOperatorName(
2161 NameInfo
.setLoc(Name
.StartLocation
);
2162 NameInfo
.setCXXLiteralOperatorNameLoc(Name
.EndLocation
);
2165 case UnqualifiedId::IK_ConversionFunctionId
: {
2166 TypeSourceInfo
*TInfo
;
2167 QualType Ty
= GetTypeFromParser(Name
.ConversionFunctionId
, &TInfo
);
2169 return DeclarationNameInfo();
2170 NameInfo
.setName(Context
.DeclarationNames
.getCXXConversionFunctionName(
2171 Context
.getCanonicalType(Ty
)));
2172 NameInfo
.setLoc(Name
.StartLocation
);
2173 NameInfo
.setNamedTypeInfo(TInfo
);
2177 case UnqualifiedId::IK_ConstructorName
: {
2178 TypeSourceInfo
*TInfo
;
2179 QualType Ty
= GetTypeFromParser(Name
.ConstructorName
, &TInfo
);
2181 return DeclarationNameInfo();
2182 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
2183 Context
.getCanonicalType(Ty
)));
2184 NameInfo
.setLoc(Name
.StartLocation
);
2185 NameInfo
.setNamedTypeInfo(TInfo
);
2189 case UnqualifiedId::IK_ConstructorTemplateId
: {
2190 // In well-formed code, we can only have a constructor
2191 // template-id that refers to the current context, so go there
2192 // to find the actual type being constructed.
2193 CXXRecordDecl
*CurClass
= dyn_cast
<CXXRecordDecl
>(CurContext
);
2194 if (!CurClass
|| CurClass
->getIdentifier() != Name
.TemplateId
->Name
)
2195 return DeclarationNameInfo();
2197 // Determine the type of the class being constructed.
2198 QualType CurClassType
= Context
.getTypeDeclType(CurClass
);
2200 // FIXME: Check two things: that the template-id names the same type as
2201 // CurClassType, and that the template-id does not occur when the name
2204 NameInfo
.setName(Context
.DeclarationNames
.getCXXConstructorName(
2205 Context
.getCanonicalType(CurClassType
)));
2206 NameInfo
.setLoc(Name
.StartLocation
);
2207 // FIXME: should we retrieve TypeSourceInfo?
2208 NameInfo
.setNamedTypeInfo(0);
2212 case UnqualifiedId::IK_DestructorName
: {
2213 TypeSourceInfo
*TInfo
;
2214 QualType Ty
= GetTypeFromParser(Name
.DestructorName
, &TInfo
);
2216 return DeclarationNameInfo();
2217 NameInfo
.setName(Context
.DeclarationNames
.getCXXDestructorName(
2218 Context
.getCanonicalType(Ty
)));
2219 NameInfo
.setLoc(Name
.StartLocation
);
2220 NameInfo
.setNamedTypeInfo(TInfo
);
2224 case UnqualifiedId::IK_TemplateId
: {
2225 TemplateName TName
= Name
.TemplateId
->Template
.get();
2226 SourceLocation TNameLoc
= Name
.TemplateId
->TemplateNameLoc
;
2227 return Context
.getNameForTemplate(TName
, TNameLoc
);
2230 } // switch (Name.getKind())
2232 assert(false && "Unknown name kind");
2233 return DeclarationNameInfo();
2236 /// isNearlyMatchingFunction - Determine whether the C++ functions
2237 /// Declaration and Definition are "nearly" matching. This heuristic
2238 /// is used to improve diagnostics in the case where an out-of-line
2239 /// function definition doesn't match any declaration within
2240 /// the class or namespace.
2241 static bool isNearlyMatchingFunction(ASTContext
&Context
,
2242 FunctionDecl
*Declaration
,
2243 FunctionDecl
*Definition
) {
2244 if (Declaration
->param_size() != Definition
->param_size())
2246 for (unsigned Idx
= 0; Idx
< Declaration
->param_size(); ++Idx
) {
2247 QualType DeclParamTy
= Declaration
->getParamDecl(Idx
)->getType();
2248 QualType DefParamTy
= Definition
->getParamDecl(Idx
)->getType();
2250 if (!Context
.hasSameUnqualifiedType(DeclParamTy
.getNonReferenceType(),
2251 DefParamTy
.getNonReferenceType()))
2258 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
2259 /// declarator needs to be rebuilt in the current instantiation.
2260 /// Any bits of declarator which appear before the name are valid for
2261 /// consideration here. That's specifically the type in the decl spec
2262 /// and the base type in any member-pointer chunks.
2263 static bool RebuildDeclaratorInCurrentInstantiation(Sema
&S
, Declarator
&D
,
2264 DeclarationName Name
) {
2265 // The types we specifically need to rebuild are:
2266 // - typenames, typeofs, and decltypes
2267 // - types which will become injected class names
2268 // Of course, we also need to rebuild any type referencing such a
2269 // type. It's safest to just say "dependent", but we call out a
2272 DeclSpec
&DS
= D
.getMutableDeclSpec();
2273 switch (DS
.getTypeSpecType()) {
2274 case DeclSpec::TST_typename
:
2275 case DeclSpec::TST_typeofType
:
2276 case DeclSpec::TST_decltype
: {
2277 // Grab the type from the parser.
2278 TypeSourceInfo
*TSI
= 0;
2279 QualType T
= S
.GetTypeFromParser(DS
.getRepAsType(), &TSI
);
2280 if (T
.isNull() || !T
->isDependentType()) break;
2282 // Make sure there's a type source info. This isn't really much
2283 // of a waste; most dependent types should have type source info
2284 // attached already.
2286 TSI
= S
.Context
.getTrivialTypeSourceInfo(T
, DS
.getTypeSpecTypeLoc());
2288 // Rebuild the type in the current instantiation.
2289 TSI
= S
.RebuildTypeInCurrentInstantiation(TSI
, D
.getIdentifierLoc(), Name
);
2290 if (!TSI
) return true;
2292 // Store the new type back in the decl spec.
2293 ParsedType LocType
= S
.CreateParsedType(TSI
->getType(), TSI
);
2294 DS
.UpdateTypeRep(LocType
);
2298 case DeclSpec::TST_typeofExpr
: {
2299 Expr
*E
= DS
.getRepAsExpr();
2300 ExprResult Result
= S
.RebuildExprInCurrentInstantiation(E
);
2301 if (Result
.isInvalid()) return true;
2302 DS
.UpdateExprRep(Result
.get());
2307 // Nothing to do for these decl specs.
2311 // It doesn't matter what order we do this in.
2312 for (unsigned I
= 0, E
= D
.getNumTypeObjects(); I
!= E
; ++I
) {
2313 DeclaratorChunk
&Chunk
= D
.getTypeObject(I
);
2315 // The only type information in the declarator which can come
2316 // before the declaration name is the base type of a member
2318 if (Chunk
.Kind
!= DeclaratorChunk::MemberPointer
)
2321 // Rebuild the scope specifier in-place.
2322 CXXScopeSpec
&SS
= Chunk
.Mem
.Scope();
2323 if (S
.RebuildNestedNameSpecifierInCurrentInstantiation(SS
))
2330 Decl
*Sema::ActOnDeclarator(Scope
*S
, Declarator
&D
) {
2331 return HandleDeclarator(S
, D
, MultiTemplateParamsArg(*this), false);
2334 Decl
*Sema::HandleDeclarator(Scope
*S
, Declarator
&D
,
2335 MultiTemplateParamsArg TemplateParamLists
,
2336 bool IsFunctionDefinition
) {
2337 // TODO: consider using NameInfo for diagnostic.
2338 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
2339 DeclarationName Name
= NameInfo
.getName();
2341 // All of these full declarators require an identifier. If it doesn't have
2342 // one, the ParsedFreeStandingDeclSpec action should be used.
2344 if (!D
.isInvalidType()) // Reject this if we think it is valid.
2345 Diag(D
.getDeclSpec().getSourceRange().getBegin(),
2346 diag::err_declarator_need_ident
)
2347 << D
.getDeclSpec().getSourceRange() << D
.getSourceRange();
2349 } else if (DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_DeclarationType
))
2352 // The scope passed in may not be a decl scope. Zip up the scope tree until
2353 // we find one that is.
2354 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
2355 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
2358 DeclContext
*DC
= CurContext
;
2359 if (D
.getCXXScopeSpec().isInvalid())
2361 else if (D
.getCXXScopeSpec().isSet()) {
2362 if (DiagnoseUnexpandedParameterPack(D
.getCXXScopeSpec(),
2363 UPPC_DeclarationQualifier
))
2366 bool EnteringContext
= !D
.getDeclSpec().isFriendSpecified();
2367 DC
= computeDeclContext(D
.getCXXScopeSpec(), EnteringContext
);
2369 // If we could not compute the declaration context, it's because the
2370 // declaration context is dependent but does not refer to a class,
2371 // class template, or class template partial specialization. Complain
2372 // and return early, to avoid the coming semantic disaster.
2373 Diag(D
.getIdentifierLoc(),
2374 diag::err_template_qualified_declarator_no_match
)
2375 << (NestedNameSpecifier
*)D
.getCXXScopeSpec().getScopeRep()
2376 << D
.getCXXScopeSpec().getRange();
2380 bool IsDependentContext
= DC
->isDependentContext();
2382 if (!IsDependentContext
&&
2383 RequireCompleteDeclContext(D
.getCXXScopeSpec(), DC
))
2386 if (isa
<CXXRecordDecl
>(DC
)) {
2387 if (!cast
<CXXRecordDecl
>(DC
)->hasDefinition()) {
2388 Diag(D
.getIdentifierLoc(),
2389 diag::err_member_def_undefined_record
)
2390 << Name
<< DC
<< D
.getCXXScopeSpec().getRange();
2392 } else if (isa
<CXXRecordDecl
>(CurContext
) &&
2393 !D
.getDeclSpec().isFriendSpecified()) {
2394 // The user provided a superfluous scope specifier inside a class
2400 if (CurContext
->Equals(DC
))
2401 Diag(D
.getIdentifierLoc(), diag::warn_member_extra_qualification
)
2402 << Name
<< FixItHint::CreateRemoval(D
.getCXXScopeSpec().getRange());
2404 Diag(D
.getIdentifierLoc(), diag::err_member_qualification
)
2405 << Name
<< D
.getCXXScopeSpec().getRange();
2407 // Pretend that this qualifier was not here.
2408 D
.getCXXScopeSpec().clear();
2412 // Check whether we need to rebuild the type of the given
2413 // declaration in the current instantiation.
2414 if (EnteringContext
&& IsDependentContext
&&
2415 TemplateParamLists
.size() != 0) {
2416 ContextRAII
SavedContext(*this, DC
);
2417 if (RebuildDeclaratorInCurrentInstantiation(*this, D
, Name
))
2422 // C++ [class.mem]p13:
2423 // If T is the name of a class, then each of the following shall have a
2424 // name different from T:
2425 // - every static data member of class T;
2426 // - every member function of class T
2427 // - every member of class T that is itself a type;
2428 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
))
2429 if (Record
->getIdentifier() && Record
->getDeclName() == Name
) {
2430 Diag(D
.getIdentifierLoc(), diag::err_member_name_of_class
)
2433 // If this is a typedef, we'll end up spewing multiple diagnostics.
2434 // Just return early; it's safer.
2435 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
)
2441 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
2442 QualType R
= TInfo
->getType();
2444 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
2445 UPPC_DeclarationType
))
2448 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
2451 // See if this is a redefinition of a variable in the same scope.
2452 if (!D
.getCXXScopeSpec().isSet()) {
2453 bool IsLinkageLookup
= false;
2455 // If the declaration we're planning to build will be a function
2456 // or object with linkage, then look for another declaration with
2457 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
2458 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
)
2460 else if (R
->isFunctionType()) {
2461 if (CurContext
->isFunctionOrMethod() ||
2462 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static
)
2463 IsLinkageLookup
= true;
2464 } else if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern
)
2465 IsLinkageLookup
= true;
2466 else if (CurContext
->getRedeclContext()->isTranslationUnit() &&
2467 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static
)
2468 IsLinkageLookup
= true;
2470 if (IsLinkageLookup
)
2471 Previous
.clear(LookupRedeclarationWithLinkage
);
2473 LookupName(Previous
, S
, /* CreateBuiltins = */ IsLinkageLookup
);
2474 } else { // Something like "int foo::x;"
2475 LookupQualifiedName(Previous
, DC
);
2477 // Don't consider using declarations as previous declarations for
2478 // out-of-line members.
2479 RemoveUsingDecls(Previous
);
2482 // Members (including explicit specializations of templates) of a named
2483 // namespace can also be defined outside that namespace by explicit
2484 // qualification of the name being defined, provided that the entity being
2485 // defined was already declared in the namespace and the definition appears
2486 // after the point of declaration in a namespace that encloses the
2487 // declarations namespace.
2489 // Note that we only check the context at this point. We don't yet
2490 // have enough information to make sure that PrevDecl is actually
2491 // the declaration we want to match. For example, given:
2498 // void X::f(int) { } // ill-formed
2500 // In this case, PrevDecl will point to the overload set
2501 // containing the two f's declared in X, but neither of them
2504 // First check whether we named the global scope.
2505 if (isa
<TranslationUnitDecl
>(DC
)) {
2506 Diag(D
.getIdentifierLoc(), diag::err_invalid_declarator_global_scope
)
2507 << Name
<< D
.getCXXScopeSpec().getRange();
2509 DeclContext
*Cur
= CurContext
;
2510 while (isa
<LinkageSpecDecl
>(Cur
))
2511 Cur
= Cur
->getParent();
2512 if (!Cur
->Encloses(DC
)) {
2513 // The qualifying scope doesn't enclose the original declaration.
2514 // Emit diagnostic based on current scope.
2515 SourceLocation L
= D
.getIdentifierLoc();
2516 SourceRange R
= D
.getCXXScopeSpec().getRange();
2517 if (isa
<FunctionDecl
>(Cur
))
2518 Diag(L
, diag::err_invalid_declarator_in_function
) << Name
<< R
;
2520 Diag(L
, diag::err_invalid_declarator_scope
)
2521 << Name
<< cast
<NamedDecl
>(DC
) << R
;
2527 if (Previous
.isSingleResult() &&
2528 Previous
.getFoundDecl()->isTemplateParameter()) {
2529 // Maybe we will complain about the shadowed template parameter.
2530 if (!D
.isInvalidType())
2531 if (DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(),
2532 Previous
.getFoundDecl()))
2535 // Just pretend that we didn't see the previous declaration.
2539 // In C++, the previous declaration we find might be a tag type
2540 // (class or enum). In this case, the new declaration will hide the
2541 // tag type. Note that this does does not apply if we're declaring a
2542 // typedef (C++ [dcl.typedef]p4).
2543 if (Previous
.isSingleTagDecl() &&
2544 D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
)
2547 bool Redeclaration
= false;
2548 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
) {
2549 if (TemplateParamLists
.size()) {
2550 Diag(D
.getIdentifierLoc(), diag::err_template_typedef
);
2554 New
= ActOnTypedefDeclarator(S
, D
, DC
, R
, TInfo
, Previous
, Redeclaration
);
2555 } else if (R
->isFunctionType()) {
2556 New
= ActOnFunctionDeclarator(S
, D
, DC
, R
, TInfo
, Previous
,
2557 move(TemplateParamLists
),
2558 IsFunctionDefinition
, Redeclaration
);
2560 New
= ActOnVariableDeclarator(S
, D
, DC
, R
, TInfo
, Previous
,
2561 move(TemplateParamLists
),
2568 // If this has an identifier and is not an invalid redeclaration or
2569 // function template specialization, add it to the scope stack.
2570 if (New
->getDeclName() && !(Redeclaration
&& New
->isInvalidDecl()))
2571 PushOnScopeChains(New
, S
);
2576 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2577 /// types into constant array types in certain situations which would otherwise
2578 /// be errors (for GCC compatibility).
2579 static QualType
TryToFixInvalidVariablyModifiedType(QualType T
,
2580 ASTContext
&Context
,
2581 bool &SizeIsNegative
,
2582 llvm::APSInt
&Oversized
) {
2583 // This method tries to turn a variable array into a constant
2584 // array even when the size isn't an ICE. This is necessary
2585 // for compatibility with code that depends on gcc's buggy
2586 // constant expression folding, like struct {char x[(int)(char*)2];}
2587 SizeIsNegative
= false;
2590 if (T
->isDependentType())
2593 QualifierCollector Qs
;
2594 const Type
*Ty
= Qs
.strip(T
);
2596 if (const PointerType
* PTy
= dyn_cast
<PointerType
>(Ty
)) {
2597 QualType Pointee
= PTy
->getPointeeType();
2598 QualType FixedType
=
2599 TryToFixInvalidVariablyModifiedType(Pointee
, Context
, SizeIsNegative
,
2601 if (FixedType
.isNull()) return FixedType
;
2602 FixedType
= Context
.getPointerType(FixedType
);
2603 return Qs
.apply(Context
, FixedType
);
2605 if (const ParenType
* PTy
= dyn_cast
<ParenType
>(Ty
)) {
2606 QualType Inner
= PTy
->getInnerType();
2607 QualType FixedType
=
2608 TryToFixInvalidVariablyModifiedType(Inner
, Context
, SizeIsNegative
,
2610 if (FixedType
.isNull()) return FixedType
;
2611 FixedType
= Context
.getParenType(FixedType
);
2612 return Qs
.apply(Context
, FixedType
);
2615 const VariableArrayType
* VLATy
= dyn_cast
<VariableArrayType
>(T
);
2618 // FIXME: We should probably handle this case
2619 if (VLATy
->getElementType()->isVariablyModifiedType())
2622 Expr::EvalResult EvalResult
;
2623 if (!VLATy
->getSizeExpr() ||
2624 !VLATy
->getSizeExpr()->Evaluate(EvalResult
, Context
) ||
2625 !EvalResult
.Val
.isInt())
2628 // Check whether the array size is negative.
2629 llvm::APSInt
&Res
= EvalResult
.Val
.getInt();
2630 if (Res
.isSigned() && Res
.isNegative()) {
2631 SizeIsNegative
= true;
2635 // Check whether the array is too large to be addressed.
2636 unsigned ActiveSizeBits
2637 = ConstantArrayType::getNumAddressingBits(Context
, VLATy
->getElementType(),
2639 if (ActiveSizeBits
> ConstantArrayType::getMaxSizeBits(Context
)) {
2644 return Context
.getConstantArrayType(VLATy
->getElementType(),
2645 Res
, ArrayType::Normal
, 0);
2648 /// \brief Register the given locally-scoped external C declaration so
2649 /// that it can be found later for redeclarations
2651 Sema::RegisterLocallyScopedExternCDecl(NamedDecl
*ND
,
2652 const LookupResult
&Previous
,
2654 assert(ND
->getLexicalDeclContext()->isFunctionOrMethod() &&
2655 "Decl is not a locally-scoped decl!");
2656 // Note that we have a locally-scoped external with this name.
2657 LocallyScopedExternalDecls
[ND
->getDeclName()] = ND
;
2659 if (!Previous
.isSingleResult())
2662 NamedDecl
*PrevDecl
= Previous
.getFoundDecl();
2664 // If there was a previous declaration of this variable, it may be
2665 // in our identifier chain. Update the identifier chain with the new
2667 if (S
&& IdResolver
.ReplaceDecl(PrevDecl
, ND
)) {
2668 // The previous declaration was found on the identifer resolver
2669 // chain, so remove it from its scope.
2670 while (S
&& !S
->isDeclScope(PrevDecl
))
2674 S
->RemoveDecl(PrevDecl
);
2678 /// \brief Diagnose function specifiers on a declaration of an identifier that
2679 /// does not identify a function.
2680 void Sema::DiagnoseFunctionSpecifiers(Declarator
& D
) {
2681 // FIXME: We should probably indicate the identifier in question to avoid
2682 // confusion for constructs like "inline int a(), b;"
2683 if (D
.getDeclSpec().isInlineSpecified())
2684 Diag(D
.getDeclSpec().getInlineSpecLoc(),
2685 diag::err_inline_non_function
);
2687 if (D
.getDeclSpec().isVirtualSpecified())
2688 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
2689 diag::err_virtual_non_function
);
2691 if (D
.getDeclSpec().isExplicitSpecified())
2692 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
2693 diag::err_explicit_non_function
);
2697 Sema::ActOnTypedefDeclarator(Scope
* S
, Declarator
& D
, DeclContext
* DC
,
2698 QualType R
, TypeSourceInfo
*TInfo
,
2699 LookupResult
&Previous
, bool &Redeclaration
) {
2700 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2701 if (D
.getCXXScopeSpec().isSet()) {
2702 Diag(D
.getIdentifierLoc(), diag::err_qualified_typedef_declarator
)
2703 << D
.getCXXScopeSpec().getRange();
2705 // Pretend we didn't see the scope specifier.
2710 if (getLangOptions().CPlusPlus
) {
2711 // Check that there are no default arguments (C++ only).
2712 CheckExtraCXXDefaultArguments(D
);
2715 DiagnoseFunctionSpecifiers(D
);
2717 if (D
.getDeclSpec().isThreadSpecified())
2718 Diag(D
.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread
);
2720 if (D
.getName().Kind
!= UnqualifiedId::IK_Identifier
) {
2721 Diag(D
.getName().StartLocation
, diag::err_typedef_not_identifier
)
2722 << D
.getName().getSourceRange();
2726 TypedefDecl
*NewTD
= ParseTypedefDecl(S
, D
, R
, TInfo
);
2727 if (!NewTD
) return 0;
2729 // Handle attributes prior to checking for duplicates in MergeVarDecl
2730 ProcessDeclAttributes(S
, NewTD
, D
);
2732 // C99 6.7.7p2: If a typedef name specifies a variably modified type
2733 // then it shall have block scope.
2734 // Note that variably modified types must be fixed before merging the decl so
2735 // that redeclarations will match.
2736 QualType T
= NewTD
->getUnderlyingType();
2737 if (T
->isVariablyModifiedType()) {
2738 getCurFunction()->setHasBranchProtectedScope();
2740 if (S
->getFnParent() == 0) {
2741 bool SizeIsNegative
;
2742 llvm::APSInt Oversized
;
2744 TryToFixInvalidVariablyModifiedType(T
, Context
, SizeIsNegative
,
2746 if (!FixedTy
.isNull()) {
2747 Diag(D
.getIdentifierLoc(), diag::warn_illegal_constant_array_size
);
2748 NewTD
->setTypeSourceInfo(Context
.getTrivialTypeSourceInfo(FixedTy
));
2751 Diag(D
.getIdentifierLoc(), diag::err_typecheck_negative_array_size
);
2752 else if (T
->isVariableArrayType())
2753 Diag(D
.getIdentifierLoc(), diag::err_vla_decl_in_file_scope
);
2754 else if (Oversized
.getBoolValue())
2755 Diag(D
.getIdentifierLoc(), diag::err_array_too_large
)
2756 << Oversized
.toString(10);
2758 Diag(D
.getIdentifierLoc(), diag::err_vm_decl_in_file_scope
);
2759 NewTD
->setInvalidDecl();
2764 // Merge the decl with the existing one if appropriate. If the decl is
2765 // in an outer scope, it isn't the same thing.
2766 FilterLookupForScope(*this, Previous
, DC
, S
, /*ConsiderLinkage*/ false);
2767 if (!Previous
.empty()) {
2768 Redeclaration
= true;
2769 MergeTypeDefDecl(NewTD
, Previous
);
2772 // If this is the C FILE type, notify the AST context.
2773 if (IdentifierInfo
*II
= NewTD
->getIdentifier())
2774 if (!NewTD
->isInvalidDecl() &&
2775 NewTD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
2776 if (II
->isStr("FILE"))
2777 Context
.setFILEDecl(NewTD
);
2778 else if (II
->isStr("jmp_buf"))
2779 Context
.setjmp_bufDecl(NewTD
);
2780 else if (II
->isStr("sigjmp_buf"))
2781 Context
.setsigjmp_bufDecl(NewTD
);
2782 else if (II
->isStr("__builtin_va_list"))
2783 Context
.setBuiltinVaListType(Context
.getTypedefType(NewTD
));
2789 /// \brief Determines whether the given declaration is an out-of-scope
2790 /// previous declaration.
2792 /// This routine should be invoked when name lookup has found a
2793 /// previous declaration (PrevDecl) that is not in the scope where a
2794 /// new declaration by the same name is being introduced. If the new
2795 /// declaration occurs in a local scope, previous declarations with
2796 /// linkage may still be considered previous declarations (C99
2797 /// 6.2.2p4-5, C++ [basic.link]p6).
2799 /// \param PrevDecl the previous declaration found by name
2802 /// \param DC the context in which the new declaration is being
2805 /// \returns true if PrevDecl is an out-of-scope previous declaration
2806 /// for a new delcaration with the same name.
2808 isOutOfScopePreviousDeclaration(NamedDecl
*PrevDecl
, DeclContext
*DC
,
2809 ASTContext
&Context
) {
2813 if (!PrevDecl
->hasLinkage())
2816 if (Context
.getLangOptions().CPlusPlus
) {
2817 // C++ [basic.link]p6:
2818 // If there is a visible declaration of an entity with linkage
2819 // having the same name and type, ignoring entities declared
2820 // outside the innermost enclosing namespace scope, the block
2821 // scope declaration declares that same entity and receives the
2822 // linkage of the previous declaration.
2823 DeclContext
*OuterContext
= DC
->getRedeclContext();
2824 if (!OuterContext
->isFunctionOrMethod())
2825 // This rule only applies to block-scope declarations.
2828 DeclContext
*PrevOuterContext
= PrevDecl
->getDeclContext();
2829 if (PrevOuterContext
->isRecord())
2830 // We found a member function: ignore it.
2833 // Find the innermost enclosing namespace for the new and
2834 // previous declarations.
2835 OuterContext
= OuterContext
->getEnclosingNamespaceContext();
2836 PrevOuterContext
= PrevOuterContext
->getEnclosingNamespaceContext();
2838 // The previous declaration is in a different namespace, so it
2839 // isn't the same function.
2840 if (!OuterContext
->Equals(PrevOuterContext
))
2847 static void SetNestedNameSpecifier(DeclaratorDecl
*DD
, Declarator
&D
) {
2848 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
2849 if (!SS
.isSet()) return;
2850 DD
->setQualifierInfo(static_cast<NestedNameSpecifier
*>(SS
.getScopeRep()),
2855 Sema::ActOnVariableDeclarator(Scope
*S
, Declarator
&D
, DeclContext
*DC
,
2856 QualType R
, TypeSourceInfo
*TInfo
,
2857 LookupResult
&Previous
,
2858 MultiTemplateParamsArg TemplateParamLists
,
2859 bool &Redeclaration
) {
2860 DeclarationName Name
= GetNameForDeclarator(D
).getName();
2862 // Check that there are no default arguments (C++ only).
2863 if (getLangOptions().CPlusPlus
)
2864 CheckExtraCXXDefaultArguments(D
);
2866 DeclSpec::SCS SCSpec
= D
.getDeclSpec().getStorageClassSpec();
2867 assert(SCSpec
!= DeclSpec::SCS_typedef
&&
2868 "Parser allowed 'typedef' as storage class VarDecl.");
2869 VarDecl::StorageClass SC
= StorageClassSpecToVarDeclStorageClass(SCSpec
);
2870 if (SCSpec
== DeclSpec::SCS_mutable
) {
2871 // mutable can only appear on non-static class members, so it's always
2873 Diag(D
.getIdentifierLoc(), diag::err_mutable_nonmember
);
2877 SCSpec
= D
.getDeclSpec().getStorageClassSpecAsWritten();
2878 VarDecl::StorageClass SCAsWritten
2879 = StorageClassSpecToVarDeclStorageClass(SCSpec
);
2881 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
2883 Diag(D
.getIdentifierLoc(), diag::err_bad_variable_name
)
2884 << Name
.getAsString();
2888 DiagnoseFunctionSpecifiers(D
);
2890 if (!DC
->isRecord() && S
->getFnParent() == 0) {
2891 // C99 6.9p2: The storage-class specifiers auto and register shall not
2892 // appear in the declaration specifiers in an external declaration.
2893 if (SC
== SC_Auto
|| SC
== SC_Register
) {
2895 // If this is a register variable with an asm label specified, then this
2896 // is a GNU extension.
2897 if (SC
== SC_Register
&& D
.getAsmLabel())
2898 Diag(D
.getIdentifierLoc(), diag::err_unsupported_global_register
);
2900 Diag(D
.getIdentifierLoc(), diag::err_typecheck_sclass_fscope
);
2905 bool isExplicitSpecialization
= false;
2907 if (!getLangOptions().CPlusPlus
) {
2908 NewVD
= VarDecl::Create(Context
, DC
, D
.getIdentifierLoc(),
2909 II
, R
, TInfo
, SC
, SCAsWritten
);
2911 if (D
.isInvalidType())
2912 NewVD
->setInvalidDecl();
2914 if (DC
->isRecord() && !CurContext
->isRecord()) {
2915 // This is an out-of-line definition of a static data member.
2916 if (SC
== SC_Static
) {
2917 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
2918 diag::err_static_out_of_line
)
2919 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
2920 } else if (SC
== SC_None
)
2923 if (SC
== SC_Static
) {
2924 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(DC
)) {
2925 if (RD
->isLocalClass())
2926 Diag(D
.getIdentifierLoc(),
2927 diag::err_static_data_member_not_allowed_in_local_class
)
2928 << Name
<< RD
->getDeclName();
2930 // C++ [class.union]p1: If a union contains a static data member,
2931 // the program is ill-formed.
2933 // We also disallow static data members in anonymous structs.
2934 if (CurContext
->isRecord() && (RD
->isUnion() || !RD
->getDeclName()))
2935 Diag(D
.getIdentifierLoc(),
2936 diag::err_static_data_member_not_allowed_in_union_or_anon_struct
)
2937 << Name
<< RD
->isUnion();
2941 // Match up the template parameter lists with the scope specifier, then
2942 // determine whether we have a template or a template specialization.
2943 isExplicitSpecialization
= false;
2944 unsigned NumMatchedTemplateParamLists
= TemplateParamLists
.size();
2945 bool Invalid
= false;
2946 if (TemplateParameterList
*TemplateParams
2947 = MatchTemplateParametersToScopeSpecifier(
2948 D
.getDeclSpec().getSourceRange().getBegin(),
2949 D
.getCXXScopeSpec(),
2950 TemplateParamLists
.get(),
2951 TemplateParamLists
.size(),
2952 /*never a friend*/ false,
2953 isExplicitSpecialization
,
2955 // All but one template parameter lists have been matching.
2956 --NumMatchedTemplateParamLists
;
2958 if (TemplateParams
->size() > 0) {
2959 // There is no such thing as a variable template.
2960 Diag(D
.getIdentifierLoc(), diag::err_template_variable
)
2962 << SourceRange(TemplateParams
->getTemplateLoc(),
2963 TemplateParams
->getRAngleLoc());
2966 // There is an extraneous 'template<>' for this variable. Complain
2967 // about it, but allow the declaration of the variable.
2968 Diag(TemplateParams
->getTemplateLoc(),
2969 diag::err_template_variable_noparams
)
2971 << SourceRange(TemplateParams
->getTemplateLoc(),
2972 TemplateParams
->getRAngleLoc());
2974 isExplicitSpecialization
= true;
2978 NewVD
= VarDecl::Create(Context
, DC
, D
.getIdentifierLoc(),
2979 II
, R
, TInfo
, SC
, SCAsWritten
);
2981 if (D
.isInvalidType() || Invalid
)
2982 NewVD
->setInvalidDecl();
2984 SetNestedNameSpecifier(NewVD
, D
);
2986 if (NumMatchedTemplateParamLists
> 0 && D
.getCXXScopeSpec().isSet()) {
2987 NewVD
->setTemplateParameterListsInfo(Context
,
2988 NumMatchedTemplateParamLists
,
2989 TemplateParamLists
.release());
2993 if (D
.getDeclSpec().isThreadSpecified()) {
2994 if (NewVD
->hasLocalStorage())
2995 Diag(D
.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global
);
2996 else if (!Context
.Target
.isTLSSupported())
2997 Diag(D
.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported
);
2999 NewVD
->setThreadSpecified(true);
3002 // Set the lexical context. If the declarator has a C++ scope specifier, the
3003 // lexical context will be different from the semantic context.
3004 NewVD
->setLexicalDeclContext(CurContext
);
3006 // Handle attributes prior to checking for duplicates in MergeVarDecl
3007 ProcessDeclAttributes(S
, NewVD
, D
);
3009 // Handle GNU asm-label extension (encoded as an attribute).
3010 if (Expr
*E
= (Expr
*)D
.getAsmLabel()) {
3011 // The parser guarantees this is a string.
3012 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
3013 llvm::StringRef Label
= SE
->getString();
3014 if (S
->getFnParent() != 0) {
3018 Diag(E
->getExprLoc(), diag::warn_asm_label_on_auto_decl
) << Label
;
3021 if (!Context
.Target
.isValidGCCRegisterName(Label
))
3022 Diag(E
->getExprLoc(), diag::err_asm_unknown_register_name
) << Label
;
3026 case SC_PrivateExtern
:
3031 NewVD
->addAttr(::new (Context
) AsmLabelAttr(SE
->getStrTokenLoc(0),
3035 // Diagnose shadowed variables before filtering for scope.
3036 if (!D
.getCXXScopeSpec().isSet())
3037 CheckShadow(S
, NewVD
, Previous
);
3039 // Don't consider existing declarations that are in a different
3040 // scope and are out-of-semantic-context declarations (if the new
3041 // declaration has linkage).
3042 FilterLookupForScope(*this, Previous
, DC
, S
, NewVD
->hasLinkage());
3044 if (!getLangOptions().CPlusPlus
)
3045 CheckVariableDeclaration(NewVD
, Previous
, Redeclaration
);
3047 // Merge the decl with the existing one if appropriate.
3048 if (!Previous
.empty()) {
3049 if (Previous
.isSingleResult() &&
3050 isa
<FieldDecl
>(Previous
.getFoundDecl()) &&
3051 D
.getCXXScopeSpec().isSet()) {
3052 // The user tried to define a non-static data member
3053 // out-of-line (C++ [dcl.meaning]p1).
3054 Diag(NewVD
->getLocation(), diag::err_nonstatic_member_out_of_line
)
3055 << D
.getCXXScopeSpec().getRange();
3057 NewVD
->setInvalidDecl();
3059 } else if (D
.getCXXScopeSpec().isSet()) {
3060 // No previous declaration in the qualifying scope.
3061 Diag(D
.getIdentifierLoc(), diag::err_no_member
)
3062 << Name
<< computeDeclContext(D
.getCXXScopeSpec(), true)
3063 << D
.getCXXScopeSpec().getRange();
3064 NewVD
->setInvalidDecl();
3067 CheckVariableDeclaration(NewVD
, Previous
, Redeclaration
);
3069 // This is an explicit specialization of a static data member. Check it.
3070 if (isExplicitSpecialization
&& !NewVD
->isInvalidDecl() &&
3071 CheckMemberSpecialization(NewVD
, Previous
))
3072 NewVD
->setInvalidDecl();
3075 // attributes declared post-definition are currently ignored
3076 // FIXME: This should be handled in attribute merging, not
3078 if (Previous
.isSingleResult()) {
3079 VarDecl
*Def
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl());
3080 if (Def
&& (Def
= Def
->getDefinition()) &&
3081 Def
!= NewVD
&& D
.hasAttributes()) {
3082 Diag(NewVD
->getLocation(), diag::warn_attribute_precede_definition
);
3083 Diag(Def
->getLocation(), diag::note_previous_definition
);
3087 // If this is a locally-scoped extern C variable, update the map of
3089 if (CurContext
->isFunctionOrMethod() && NewVD
->isExternC() &&
3090 !NewVD
->isInvalidDecl())
3091 RegisterLocallyScopedExternCDecl(NewVD
, Previous
, S
);
3093 // If there's a #pragma GCC visibility in scope, and this isn't a class
3094 // member, set the visibility of this variable.
3095 if (NewVD
->getLinkage() == ExternalLinkage
&& !DC
->isRecord())
3096 AddPushedVisibilityAttribute(NewVD
);
3098 MarkUnusedFileScopedDecl(NewVD
);
3103 /// \brief Diagnose variable or built-in function shadowing. Implements
3106 /// This method is called whenever a VarDecl is added to a "useful"
3109 /// \param S the scope in which the shadowing name is being declared
3110 /// \param R the lookup of the name
3112 void Sema::CheckShadow(Scope
*S
, VarDecl
*D
, const LookupResult
& R
) {
3113 // Return if warning is ignored.
3114 if (Diags
.getDiagnosticLevel(diag::warn_decl_shadow
, R
.getNameLoc()) ==
3115 Diagnostic::Ignored
)
3118 // Don't diagnose declarations at file scope. The scope might not
3119 // have a DeclContext if (e.g.) we're parsing a function prototype.
3120 DeclContext
*NewDC
= static_cast<DeclContext
*>(S
->getEntity());
3121 if (NewDC
&& NewDC
->isFileContext())
3124 // Only diagnose if we're shadowing an unambiguous field or variable.
3125 if (R
.getResultKind() != LookupResult::Found
)
3128 NamedDecl
* ShadowedDecl
= R
.getFoundDecl();
3129 if (!isa
<VarDecl
>(ShadowedDecl
) && !isa
<FieldDecl
>(ShadowedDecl
))
3132 if (VarDecl
*shadowedVar
= dyn_cast
<VarDecl
>(ShadowedDecl
))
3133 if (shadowedVar
->isExternC()) {
3134 // Don't warn for this case:
3145 // For shadowing external vars, make sure that we point to the global
3146 // declaration, not a locally scoped extern declaration.
3147 for (VarDecl::redecl_iterator
3148 I
= shadowedVar
->redecls_begin(), E
= shadowedVar
->redecls_end();
3150 if (I
->isFileVarDecl()) {
3156 DeclContext
*OldDC
= ShadowedDecl
->getDeclContext();
3158 // Only warn about certain kinds of shadowing for class members.
3159 if (NewDC
&& NewDC
->isRecord()) {
3160 // In particular, don't warn about shadowing non-class members.
3161 if (!OldDC
->isRecord())
3164 // TODO: should we warn about static data members shadowing
3165 // static data members from base classes?
3167 // TODO: don't diagnose for inaccessible shadowed members.
3168 // This is hard to do perfectly because we might friend the
3169 // shadowing context, but that's just a false negative.
3172 // Determine what kind of declaration we're shadowing.
3174 if (isa
<RecordDecl
>(OldDC
)) {
3175 if (isa
<FieldDecl
>(ShadowedDecl
))
3178 Kind
= 2; // static data member
3179 } else if (OldDC
->isFileContext())
3184 DeclarationName Name
= R
.getLookupName();
3186 // Emit warning and note.
3187 Diag(R
.getNameLoc(), diag::warn_decl_shadow
) << Name
<< Kind
<< OldDC
;
3188 Diag(ShadowedDecl
->getLocation(), diag::note_previous_declaration
);
3191 /// \brief Check -Wshadow without the advantage of a previous lookup.
3192 void Sema::CheckShadow(Scope
*S
, VarDecl
*D
) {
3193 if (Diags
.getDiagnosticLevel(diag::warn_decl_shadow
, D
->getLocation()) ==
3194 Diagnostic::Ignored
)
3197 LookupResult
R(*this, D
->getDeclName(), D
->getLocation(),
3198 Sema::LookupOrdinaryName
, Sema::ForRedeclaration
);
3200 CheckShadow(S
, D
, R
);
3203 /// \brief Perform semantic checking on a newly-created variable
3206 /// This routine performs all of the type-checking required for a
3207 /// variable declaration once it has been built. It is used both to
3208 /// check variables after they have been parsed and their declarators
3209 /// have been translated into a declaration, and to check variables
3210 /// that have been instantiated from a template.
3212 /// Sets NewVD->isInvalidDecl() if an error was encountered.
3213 void Sema::CheckVariableDeclaration(VarDecl
*NewVD
,
3214 LookupResult
&Previous
,
3215 bool &Redeclaration
) {
3216 // If the decl is already known invalid, don't check it.
3217 if (NewVD
->isInvalidDecl())
3220 QualType T
= NewVD
->getType();
3222 if (T
->isObjCObjectType()) {
3223 Diag(NewVD
->getLocation(), diag::err_statically_allocated_object
);
3224 return NewVD
->setInvalidDecl();
3227 // Emit an error if an address space was applied to decl with local storage.
3228 // This includes arrays of objects with address space qualifiers, but not
3229 // automatic variables that point to other address spaces.
3230 // ISO/IEC TR 18037 S5.1.2
3231 if (NewVD
->hasLocalStorage() && T
.getAddressSpace() != 0) {
3232 Diag(NewVD
->getLocation(), diag::err_as_qualified_auto_decl
);
3233 return NewVD
->setInvalidDecl();
3236 if (NewVD
->hasLocalStorage() && T
.isObjCGCWeak()
3237 && !NewVD
->hasAttr
<BlocksAttr
>())
3238 Diag(NewVD
->getLocation(), diag::warn_attribute_weak_on_local
);
3240 bool isVM
= T
->isVariablyModifiedType();
3241 if (isVM
|| NewVD
->hasAttr
<CleanupAttr
>() ||
3242 NewVD
->hasAttr
<BlocksAttr
>())
3243 getCurFunction()->setHasBranchProtectedScope();
3245 if ((isVM
&& NewVD
->hasLinkage()) ||
3246 (T
->isVariableArrayType() && NewVD
->hasGlobalStorage())) {
3247 bool SizeIsNegative
;
3248 llvm::APSInt Oversized
;
3250 TryToFixInvalidVariablyModifiedType(T
, Context
, SizeIsNegative
,
3253 if (FixedTy
.isNull() && T
->isVariableArrayType()) {
3254 const VariableArrayType
*VAT
= Context
.getAsVariableArrayType(T
);
3255 // FIXME: This won't give the correct result for
3257 SourceRange SizeRange
= VAT
->getSizeExpr()->getSourceRange();
3259 if (NewVD
->isFileVarDecl())
3260 Diag(NewVD
->getLocation(), diag::err_vla_decl_in_file_scope
)
3262 else if (NewVD
->getStorageClass() == SC_Static
)
3263 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_static_storage
)
3266 Diag(NewVD
->getLocation(), diag::err_vla_decl_has_extern_linkage
)
3268 return NewVD
->setInvalidDecl();
3271 if (FixedTy
.isNull()) {
3272 if (NewVD
->isFileVarDecl())
3273 Diag(NewVD
->getLocation(), diag::err_vm_decl_in_file_scope
);
3275 Diag(NewVD
->getLocation(), diag::err_vm_decl_has_extern_linkage
);
3276 return NewVD
->setInvalidDecl();
3279 Diag(NewVD
->getLocation(), diag::warn_illegal_constant_array_size
);
3280 NewVD
->setType(FixedTy
);
3283 if (Previous
.empty() && NewVD
->isExternC()) {
3284 // Since we did not find anything by this name and we're declaring
3285 // an extern "C" variable, look for a non-visible extern "C"
3286 // declaration with the same name.
3287 llvm::DenseMap
<DeclarationName
, NamedDecl
*>::iterator Pos
3288 = LocallyScopedExternalDecls
.find(NewVD
->getDeclName());
3289 if (Pos
!= LocallyScopedExternalDecls
.end())
3290 Previous
.addDecl(Pos
->second
);
3293 if (T
->isVoidType() && !NewVD
->hasExternalStorage()) {
3294 Diag(NewVD
->getLocation(), diag::err_typecheck_decl_incomplete_type
)
3296 return NewVD
->setInvalidDecl();
3299 if (!NewVD
->hasLocalStorage() && NewVD
->hasAttr
<BlocksAttr
>()) {
3300 Diag(NewVD
->getLocation(), diag::err_block_on_nonlocal
);
3301 return NewVD
->setInvalidDecl();
3304 if (isVM
&& NewVD
->hasAttr
<BlocksAttr
>()) {
3305 Diag(NewVD
->getLocation(), diag::err_block_on_vm
);
3306 return NewVD
->setInvalidDecl();
3309 // Function pointers and references cannot have qualified function type, only
3310 // function pointer-to-members can do that.
3312 unsigned PtrOrRef
= 0;
3313 if (const PointerType
*Ptr
= T
->getAs
<PointerType
>())
3314 Pointee
= Ptr
->getPointeeType();
3315 else if (const ReferenceType
*Ref
= T
->getAs
<ReferenceType
>()) {
3316 Pointee
= Ref
->getPointeeType();
3319 if (!Pointee
.isNull() && Pointee
->isFunctionProtoType() &&
3320 Pointee
->getAs
<FunctionProtoType
>()->getTypeQuals() != 0) {
3321 Diag(NewVD
->getLocation(), diag::err_invalid_qualified_function_pointer
)
3323 return NewVD
->setInvalidDecl();
3326 if (!Previous
.empty()) {
3327 Redeclaration
= true;
3328 MergeVarDecl(NewVD
, Previous
);
3332 /// \brief Data used with FindOverriddenMethod
3333 struct FindOverriddenMethodData
{
3335 CXXMethodDecl
*Method
;
3338 /// \brief Member lookup function that determines whether a given C++
3339 /// method overrides a method in a base class, to be used with
3340 /// CXXRecordDecl::lookupInBases().
3341 static bool FindOverriddenMethod(const CXXBaseSpecifier
*Specifier
,
3344 RecordDecl
*BaseRecord
= Specifier
->getType()->getAs
<RecordType
>()->getDecl();
3346 FindOverriddenMethodData
*Data
3347 = reinterpret_cast<FindOverriddenMethodData
*>(UserData
);
3349 DeclarationName Name
= Data
->Method
->getDeclName();
3351 // FIXME: Do we care about other names here too?
3352 if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
3353 // We really want to find the base class destructor here.
3354 QualType T
= Data
->S
->Context
.getTypeDeclType(BaseRecord
);
3355 CanQualType CT
= Data
->S
->Context
.getCanonicalType(T
);
3357 Name
= Data
->S
->Context
.DeclarationNames
.getCXXDestructorName(CT
);
3360 for (Path
.Decls
= BaseRecord
->lookup(Name
);
3361 Path
.Decls
.first
!= Path
.Decls
.second
;
3362 ++Path
.Decls
.first
) {
3363 NamedDecl
*D
= *Path
.Decls
.first
;
3364 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
3365 if (MD
->isVirtual() && !Data
->S
->IsOverload(Data
->Method
, MD
, false))
3373 /// AddOverriddenMethods - See if a method overrides any in the base classes,
3374 /// and if so, check that it's a valid override and remember it.
3375 bool Sema::AddOverriddenMethods(CXXRecordDecl
*DC
, CXXMethodDecl
*MD
) {
3376 // Look for virtual methods in base classes that this method might override.
3378 FindOverriddenMethodData Data
;
3381 bool AddedAny
= false;
3382 if (DC
->lookupInBases(&FindOverriddenMethod
, &Data
, Paths
)) {
3383 for (CXXBasePaths::decl_iterator I
= Paths
.found_decls_begin(),
3384 E
= Paths
.found_decls_end(); I
!= E
; ++I
) {
3385 if (CXXMethodDecl
*OldMD
= dyn_cast
<CXXMethodDecl
>(*I
)) {
3386 if (!CheckOverridingFunctionReturnType(MD
, OldMD
) &&
3387 !CheckOverridingFunctionExceptionSpec(MD
, OldMD
) &&
3388 !CheckIfOverriddenFunctionIsMarkedFinal(MD
, OldMD
)) {
3389 MD
->addOverriddenMethod(OldMD
->getCanonicalDecl());
3399 static void DiagnoseInvalidRedeclaration(Sema
&S
, FunctionDecl
*NewFD
) {
3400 LookupResult
Prev(S
, NewFD
->getDeclName(), NewFD
->getLocation(),
3401 Sema::LookupOrdinaryName
, Sema::ForRedeclaration
);
3402 S
.LookupQualifiedName(Prev
, NewFD
->getDeclContext());
3403 assert(!Prev
.isAmbiguous() &&
3404 "Cannot have an ambiguity in previous-declaration lookup");
3405 for (LookupResult::iterator Func
= Prev
.begin(), FuncEnd
= Prev
.end();
3406 Func
!= FuncEnd
; ++Func
) {
3407 if (isa
<FunctionDecl
>(*Func
) &&
3408 isNearlyMatchingFunction(S
.Context
, cast
<FunctionDecl
>(*Func
), NewFD
))
3409 S
.Diag((*Func
)->getLocation(), diag::note_member_def_close_match
);
3414 Sema::ActOnFunctionDeclarator(Scope
* S
, Declarator
& D
, DeclContext
* DC
,
3415 QualType R
, TypeSourceInfo
*TInfo
,
3416 LookupResult
&Previous
,
3417 MultiTemplateParamsArg TemplateParamLists
,
3418 bool IsFunctionDefinition
, bool &Redeclaration
) {
3419 assert(R
.getTypePtr()->isFunctionType());
3421 // TODO: consider using NameInfo for diagnostic.
3422 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
3423 DeclarationName Name
= NameInfo
.getName();
3424 FunctionDecl::StorageClass SC
= SC_None
;
3425 switch (D
.getDeclSpec().getStorageClassSpec()) {
3426 default: assert(0 && "Unknown storage class!");
3427 case DeclSpec::SCS_auto
:
3428 case DeclSpec::SCS_register
:
3429 case DeclSpec::SCS_mutable
:
3430 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
3431 diag::err_typecheck_sclass_func
);
3434 case DeclSpec::SCS_unspecified
: SC
= SC_None
; break;
3435 case DeclSpec::SCS_extern
: SC
= SC_Extern
; break;
3436 case DeclSpec::SCS_static
: {
3437 if (CurContext
->getRedeclContext()->isFunctionOrMethod()) {
3439 // The declaration of an identifier for a function that has
3440 // block scope shall have no explicit storage-class specifier
3441 // other than extern
3442 // See also (C++ [dcl.stc]p4).
3443 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
3444 diag::err_static_block_func
);
3450 case DeclSpec::SCS_private_extern
: SC
= SC_PrivateExtern
; break;
3453 if (D
.getDeclSpec().isThreadSpecified())
3454 Diag(D
.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread
);
3456 // Do not allow returning a objc interface by-value.
3457 if (R
->getAs
<FunctionType
>()->getResultType()->isObjCObjectType()) {
3458 Diag(D
.getIdentifierLoc(),
3459 diag::err_object_cannot_be_passed_returned_by_value
) << 0
3460 << R
->getAs
<FunctionType
>()->getResultType();
3464 FunctionDecl
*NewFD
;
3465 bool isInline
= D
.getDeclSpec().isInlineSpecified();
3466 bool isFriend
= false;
3467 DeclSpec::SCS SCSpec
= D
.getDeclSpec().getStorageClassSpecAsWritten();
3468 FunctionDecl::StorageClass SCAsWritten
3469 = StorageClassSpecToFunctionDeclStorageClass(SCSpec
);
3470 FunctionTemplateDecl
*FunctionTemplate
= 0;
3471 bool isExplicitSpecialization
= false;
3472 bool isFunctionTemplateSpecialization
= false;
3473 unsigned NumMatchedTemplateParamLists
= 0;
3475 if (!getLangOptions().CPlusPlus
) {
3476 // Determine whether the function was written with a
3477 // prototype. This true when:
3478 // - there is a prototype in the declarator, or
3479 // - the type R of the function is some kind of typedef or other reference
3480 // to a type name (which eventually refers to a function type).
3482 (D
.isFunctionDeclarator() && D
.getFunctionTypeInfo().hasPrototype
) ||
3483 (!isa
<FunctionType
>(R
.getTypePtr()) && R
->isFunctionProtoType());
3485 NewFD
= FunctionDecl::Create(Context
, DC
,
3486 NameInfo
, R
, TInfo
, SC
, SCAsWritten
, isInline
,
3488 if (D
.isInvalidType())
3489 NewFD
->setInvalidDecl();
3491 // Set the lexical context.
3492 NewFD
->setLexicalDeclContext(CurContext
);
3493 // Filter out previous declarations that don't match the scope.
3494 FilterLookupForScope(*this, Previous
, DC
, S
, NewFD
->hasLinkage());
3496 isFriend
= D
.getDeclSpec().isFriendSpecified();
3497 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
3498 bool isExplicit
= D
.getDeclSpec().isExplicitSpecified();
3499 bool isVirtualOkay
= false;
3501 // Check that the return type is not an abstract class type.
3502 // For record types, this is done by the AbstractClassUsageDiagnoser once
3503 // the class has been completely parsed.
3504 if (!DC
->isRecord() &&
3505 RequireNonAbstractType(D
.getIdentifierLoc(),
3506 R
->getAs
<FunctionType
>()->getResultType(),
3507 diag::err_abstract_type_in_decl
,
3508 AbstractReturnType
))
3513 // C++ [class.friend]p5
3514 // A function can be defined in a friend declaration of a
3515 // class . . . . Such a function is implicitly inline.
3516 isInline
|= IsFunctionDefinition
;
3519 if (Name
.getNameKind() == DeclarationName::CXXConstructorName
) {
3520 // This is a C++ constructor declaration.
3521 assert(DC
->isRecord() &&
3522 "Constructors can only be declared in a member context");
3524 R
= CheckConstructorDeclarator(D
, R
, SC
);
3526 // Create the new declaration
3527 NewFD
= CXXConstructorDecl::Create(Context
,
3528 cast
<CXXRecordDecl
>(DC
),
3530 isExplicit
, isInline
,
3531 /*isImplicitlyDeclared=*/false);
3532 } else if (Name
.getNameKind() == DeclarationName::CXXDestructorName
) {
3533 // This is a C++ destructor declaration.
3534 if (DC
->isRecord()) {
3535 R
= CheckDestructorDeclarator(D
, R
, SC
);
3537 NewFD
= CXXDestructorDecl::Create(Context
,
3538 cast
<CXXRecordDecl
>(DC
),
3541 /*isImplicitlyDeclared=*/false);
3542 isVirtualOkay
= true;
3544 Diag(D
.getIdentifierLoc(), diag::err_destructor_not_member
);
3546 // Create a FunctionDecl to satisfy the function definition parsing
3548 NewFD
= FunctionDecl::Create(Context
, DC
, D
.getIdentifierLoc(),
3549 Name
, R
, TInfo
, SC
, SCAsWritten
, isInline
,
3550 /*hasPrototype=*/true);
3553 } else if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
3554 if (!DC
->isRecord()) {
3555 Diag(D
.getIdentifierLoc(),
3556 diag::err_conv_function_not_member
);
3560 CheckConversionDeclarator(D
, R
, SC
);
3561 NewFD
= CXXConversionDecl::Create(Context
, cast
<CXXRecordDecl
>(DC
),
3563 isInline
, isExplicit
);
3565 isVirtualOkay
= true;
3566 } else if (DC
->isRecord()) {
3567 // If the of the function is the same as the name of the record, then this
3568 // must be an invalid constructor that has a return type.
3569 // (The parser checks for a return type and makes the declarator a
3570 // constructor if it has no return type).
3571 // must have an invalid constructor that has a return type
3572 if (Name
.getAsIdentifierInfo() &&
3573 Name
.getAsIdentifierInfo() == cast
<CXXRecordDecl
>(DC
)->getIdentifier()){
3574 Diag(D
.getIdentifierLoc(), diag::err_constructor_return_type
)
3575 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
3576 << SourceRange(D
.getIdentifierLoc());
3580 bool isStatic
= SC
== SC_Static
;
3583 // Any allocation function for a class T is a static member
3584 // (even if not explicitly declared static).
3585 if (Name
.getCXXOverloadedOperator() == OO_New
||
3586 Name
.getCXXOverloadedOperator() == OO_Array_New
)
3589 // [class.free]p6 Any deallocation function for a class X is a static member
3590 // (even if not explicitly declared static).
3591 if (Name
.getCXXOverloadedOperator() == OO_Delete
||
3592 Name
.getCXXOverloadedOperator() == OO_Array_Delete
)
3595 // This is a C++ method declaration.
3596 NewFD
= CXXMethodDecl::Create(Context
, cast
<CXXRecordDecl
>(DC
),
3598 isStatic
, SCAsWritten
, isInline
);
3600 isVirtualOkay
= !isStatic
;
3602 // Determine whether the function was written with a
3603 // prototype. This true when:
3604 // - we're in C++ (where every function has a prototype),
3605 NewFD
= FunctionDecl::Create(Context
, DC
,
3606 NameInfo
, R
, TInfo
, SC
, SCAsWritten
, isInline
,
3607 true/*HasPrototype*/);
3609 SetNestedNameSpecifier(NewFD
, D
);
3610 isExplicitSpecialization
= false;
3611 isFunctionTemplateSpecialization
= false;
3612 NumMatchedTemplateParamLists
= TemplateParamLists
.size();
3613 if (D
.isInvalidType())
3614 NewFD
->setInvalidDecl();
3616 // Set the lexical context. If the declarator has a C++
3617 // scope specifier, or is the object of a friend declaration, the
3618 // lexical context will be different from the semantic context.
3619 NewFD
->setLexicalDeclContext(CurContext
);
3621 // Match up the template parameter lists with the scope specifier, then
3622 // determine whether we have a template or a template specialization.
3623 bool Invalid
= false;
3624 if (TemplateParameterList
*TemplateParams
3625 = MatchTemplateParametersToScopeSpecifier(
3626 D
.getDeclSpec().getSourceRange().getBegin(),
3627 D
.getCXXScopeSpec(),
3628 TemplateParamLists
.get(),
3629 TemplateParamLists
.size(),
3631 isExplicitSpecialization
,
3633 // All but one template parameter lists have been matching.
3634 --NumMatchedTemplateParamLists
;
3636 if (TemplateParams
->size() > 0) {
3637 // This is a function template
3639 // Check that we can declare a template here.
3640 if (CheckTemplateDeclScope(S
, TemplateParams
))
3643 FunctionTemplate
= FunctionTemplateDecl::Create(Context
, DC
,
3644 NewFD
->getLocation(),
3645 Name
, TemplateParams
,
3647 FunctionTemplate
->setLexicalDeclContext(CurContext
);
3648 NewFD
->setDescribedFunctionTemplate(FunctionTemplate
);
3650 // This is a function template specialization.
3651 isFunctionTemplateSpecialization
= true;
3653 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3654 if (isFriend
&& isFunctionTemplateSpecialization
) {
3655 // We want to remove the "template<>", found here.
3656 SourceRange RemoveRange
= TemplateParams
->getSourceRange();
3658 // If we remove the template<> and the name is not a
3659 // template-id, we're actually silently creating a problem:
3660 // the friend declaration will refer to an untemplated decl,
3661 // and clearly the user wants a template specialization. So
3662 // we need to insert '<>' after the name.
3663 SourceLocation InsertLoc
;
3664 if (D
.getName().getKind() != UnqualifiedId::IK_TemplateId
) {
3665 InsertLoc
= D
.getName().getSourceRange().getEnd();
3666 InsertLoc
= PP
.getLocForEndOfToken(InsertLoc
);
3669 Diag(D
.getIdentifierLoc(), diag::err_template_spec_decl_friend
)
3670 << Name
<< RemoveRange
3671 << FixItHint::CreateRemoval(RemoveRange
)
3672 << FixItHint::CreateInsertion(InsertLoc
, "<>");
3677 if (NumMatchedTemplateParamLists
> 0 && D
.getCXXScopeSpec().isSet()) {
3678 NewFD
->setTemplateParameterListsInfo(Context
,
3679 NumMatchedTemplateParamLists
,
3680 TemplateParamLists
.release());
3684 NewFD
->setInvalidDecl();
3685 if (FunctionTemplate
)
3686 FunctionTemplate
->setInvalidDecl();
3689 // C++ [dcl.fct.spec]p5:
3690 // The virtual specifier shall only be used in declarations of
3691 // nonstatic class member functions that appear within a
3692 // member-specification of a class declaration; see 10.3.
3694 if (isVirtual
&& !NewFD
->isInvalidDecl()) {
3695 if (!isVirtualOkay
) {
3696 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
3697 diag::err_virtual_non_function
);
3698 } else if (!CurContext
->isRecord()) {
3699 // 'virtual' was specified outside of the class.
3700 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
3701 diag::err_virtual_out_of_class
)
3702 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
3703 } else if (NewFD
->getDescribedFunctionTemplate()) {
3704 // C++ [temp.mem]p3:
3705 // A member function template shall not be virtual.
3706 Diag(D
.getDeclSpec().getVirtualSpecLoc(),
3707 diag::err_virtual_member_function_template
)
3708 << FixItHint::CreateRemoval(D
.getDeclSpec().getVirtualSpecLoc());
3710 // Okay: Add virtual to the method.
3711 NewFD
->setVirtualAsWritten(true);
3715 // C++ [dcl.fct.spec]p3:
3716 // The inline specifier shall not appear on a block scope function declaration.
3717 if (isInline
&& !NewFD
->isInvalidDecl()) {
3718 if (CurContext
->isFunctionOrMethod()) {
3719 // 'inline' is not allowed on block scope function declaration.
3720 Diag(D
.getDeclSpec().getInlineSpecLoc(),
3721 diag::err_inline_declaration_block_scope
) << Name
3722 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
3726 // C++ [dcl.fct.spec]p6:
3727 // The explicit specifier shall be used only in the declaration of a
3728 // constructor or conversion function within its class definition; see 12.3.1
3730 if (isExplicit
&& !NewFD
->isInvalidDecl()) {
3731 if (!CurContext
->isRecord()) {
3732 // 'explicit' was specified outside of the class.
3733 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
3734 diag::err_explicit_out_of_class
)
3735 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecLoc());
3736 } else if (!isa
<CXXConstructorDecl
>(NewFD
) &&
3737 !isa
<CXXConversionDecl
>(NewFD
)) {
3738 // 'explicit' was specified on a function that wasn't a constructor
3739 // or conversion function.
3740 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
3741 diag::err_explicit_non_ctor_or_conv_function
)
3742 << FixItHint::CreateRemoval(D
.getDeclSpec().getExplicitSpecLoc());
3746 // Filter out previous declarations that don't match the scope.
3747 FilterLookupForScope(*this, Previous
, DC
, S
, NewFD
->hasLinkage());
3750 // For now, claim that the objects have no previous declaration.
3751 if (FunctionTemplate
) {
3752 FunctionTemplate
->setObjectOfFriendDecl(false);
3753 FunctionTemplate
->setAccess(AS_public
);
3755 NewFD
->setObjectOfFriendDecl(false);
3756 NewFD
->setAccess(AS_public
);
3759 if (isa
<CXXMethodDecl
>(NewFD
) && DC
== CurContext
&& IsFunctionDefinition
) {
3760 // A method is implicitly inline if it's defined in its class
3762 NewFD
->setImplicitlyInline();
3765 if (SC
== SC_Static
&& isa
<CXXMethodDecl
>(NewFD
) &&
3766 !CurContext
->isRecord()) {
3767 // C++ [class.static]p1:
3768 // A data or function member of a class may be declared static
3769 // in a class definition, in which case it is a static member of
3772 // Complain about the 'static' specifier if it's on an out-of-line
3773 // member function definition.
3774 Diag(D
.getDeclSpec().getStorageClassSpecLoc(),
3775 diag::err_static_out_of_line
)
3776 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
3780 // Handle GNU asm-label extension (encoded as an attribute).
3781 if (Expr
*E
= (Expr
*) D
.getAsmLabel()) {
3782 // The parser guarantees this is a string.
3783 StringLiteral
*SE
= cast
<StringLiteral
>(E
);
3784 NewFD
->addAttr(::new (Context
) AsmLabelAttr(SE
->getStrTokenLoc(0), Context
,
3788 // Copy the parameter declarations from the declarator D to the function
3789 // declaration NewFD, if they are available. First scavenge them into Params.
3790 llvm::SmallVector
<ParmVarDecl
*, 16> Params
;
3791 if (D
.isFunctionDeclarator()) {
3792 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
3794 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3795 // function that takes no arguments, not a function that takes a
3796 // single void argument.
3797 // We let through "const void" here because Sema::GetTypeForDeclarator
3798 // already checks for that case.
3799 if (FTI
.NumArgs
== 1 && !FTI
.isVariadic
&& FTI
.ArgInfo
[0].Ident
== 0 &&
3800 FTI
.ArgInfo
[0].Param
&&
3801 cast
<ParmVarDecl
>(FTI
.ArgInfo
[0].Param
)->getType()->isVoidType()) {
3802 // Empty arg list, don't push any params.
3803 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.ArgInfo
[0].Param
);
3805 // In C++, the empty parameter-type-list must be spelled "void"; a
3806 // typedef of void is not permitted.
3807 if (getLangOptions().CPlusPlus
&&
3808 Param
->getType().getUnqualifiedType() != Context
.VoidTy
)
3809 Diag(Param
->getLocation(), diag::err_param_typedef_of_void
);
3810 } else if (FTI
.NumArgs
> 0 && FTI
.ArgInfo
[0].Param
!= 0) {
3811 for (unsigned i
= 0, e
= FTI
.NumArgs
; i
!= e
; ++i
) {
3812 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(FTI
.ArgInfo
[i
].Param
);
3813 assert(Param
->getDeclContext() != NewFD
&& "Was set before ?");
3814 Param
->setDeclContext(NewFD
);
3815 Params
.push_back(Param
);
3817 if (Param
->isInvalidDecl())
3818 NewFD
->setInvalidDecl();
3822 } else if (const FunctionProtoType
*FT
= R
->getAs
<FunctionProtoType
>()) {
3823 // When we're declaring a function with a typedef, typeof, etc as in the
3824 // following example, we'll need to synthesize (unnamed)
3825 // parameters for use in the declaration.
3828 // typedef void fn(int);
3832 // Synthesize a parameter for each argument type.
3833 for (FunctionProtoType::arg_type_iterator AI
= FT
->arg_type_begin(),
3834 AE
= FT
->arg_type_end(); AI
!= AE
; ++AI
) {
3835 ParmVarDecl
*Param
=
3836 BuildParmVarDeclForTypedef(NewFD
, D
.getIdentifierLoc(), *AI
);
3837 Params
.push_back(Param
);
3840 assert(R
->isFunctionNoProtoType() && NewFD
->getNumParams() == 0 &&
3841 "Should not need args for typedef of non-prototype fn");
3843 // Finally, we know we have the right number of parameters, install them.
3844 NewFD
->setParams(Params
.data(), Params
.size());
3846 // Process the non-inheritable attributes on this declaration.
3847 ProcessDeclAttributes(S
, NewFD
, D
,
3848 /*NonInheritable=*/true, /*Inheritable=*/false);
3850 if (!getLangOptions().CPlusPlus
) {
3851 // Perform semantic checking on the function declaration.
3852 bool isExplctSpecialization
=false;
3853 CheckFunctionDeclaration(S
, NewFD
, Previous
, isExplctSpecialization
,
3855 assert((NewFD
->isInvalidDecl() || !Redeclaration
||
3856 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
3857 "previous declaration set still overloaded");
3859 // If the declarator is a template-id, translate the parser's template
3860 // argument list into our AST format.
3861 bool HasExplicitTemplateArgs
= false;
3862 TemplateArgumentListInfo TemplateArgs
;
3863 if (D
.getName().getKind() == UnqualifiedId::IK_TemplateId
) {
3864 TemplateIdAnnotation
*TemplateId
= D
.getName().TemplateId
;
3865 TemplateArgs
.setLAngleLoc(TemplateId
->LAngleLoc
);
3866 TemplateArgs
.setRAngleLoc(TemplateId
->RAngleLoc
);
3867 ASTTemplateArgsPtr
TemplateArgsPtr(*this,
3868 TemplateId
->getTemplateArgs(),
3869 TemplateId
->NumArgs
);
3870 translateTemplateArguments(TemplateArgsPtr
,
3872 TemplateArgsPtr
.release();
3874 HasExplicitTemplateArgs
= true;
3876 if (FunctionTemplate
) {
3877 // Function template with explicit template arguments.
3878 Diag(D
.getIdentifierLoc(), diag::err_function_template_partial_spec
)
3879 << SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
);
3881 HasExplicitTemplateArgs
= false;
3882 } else if (!isFunctionTemplateSpecialization
&&
3883 !D
.getDeclSpec().isFriendSpecified()) {
3884 // We have encountered something that the user meant to be a
3885 // specialization (because it has explicitly-specified template
3886 // arguments) but that was not introduced with a "template<>" (or had
3887 // too few of them).
3888 Diag(D
.getIdentifierLoc(), diag::err_template_spec_needs_header
)
3889 << SourceRange(TemplateId
->LAngleLoc
, TemplateId
->RAngleLoc
)
3890 << FixItHint::CreateInsertion(
3891 D
.getDeclSpec().getSourceRange().getBegin(),
3893 isFunctionTemplateSpecialization
= true;
3895 // "friend void foo<>(int);" is an implicit specialization decl.
3896 isFunctionTemplateSpecialization
= true;
3898 } else if (isFriend
&& isFunctionTemplateSpecialization
) {
3899 // This combination is only possible in a recovery case; the user
3900 // wrote something like:
3901 // template <> friend void foo(int);
3902 // which we're recovering from as if the user had written:
3903 // friend void foo<>(int);
3904 // Go ahead and fake up a template id.
3905 HasExplicitTemplateArgs
= true;
3906 TemplateArgs
.setLAngleLoc(D
.getIdentifierLoc());
3907 TemplateArgs
.setRAngleLoc(D
.getIdentifierLoc());
3910 // If it's a friend (and only if it's a friend), it's possible
3911 // that either the specialized function type or the specialized
3912 // template is dependent, and therefore matching will fail. In
3913 // this case, don't check the specialization yet.
3914 if (isFunctionTemplateSpecialization
&& isFriend
&&
3915 (NewFD
->getType()->isDependentType() || DC
->isDependentContext())) {
3916 assert(HasExplicitTemplateArgs
&&
3917 "friend function specialization without template args");
3918 if (CheckDependentFunctionTemplateSpecialization(NewFD
, TemplateArgs
,
3920 NewFD
->setInvalidDecl();
3921 } else if (isFunctionTemplateSpecialization
) {
3922 if (CheckFunctionTemplateSpecialization(NewFD
,
3923 (HasExplicitTemplateArgs
? &TemplateArgs
: 0),
3925 NewFD
->setInvalidDecl();
3926 } else if (isExplicitSpecialization
&& isa
<CXXMethodDecl
>(NewFD
)) {
3927 if (CheckMemberSpecialization(NewFD
, Previous
))
3928 NewFD
->setInvalidDecl();
3931 // Perform semantic checking on the function declaration.
3932 CheckFunctionDeclaration(S
, NewFD
, Previous
, isExplicitSpecialization
,
3935 assert((NewFD
->isInvalidDecl() || !Redeclaration
||
3936 Previous
.getResultKind() != LookupResult::FoundOverloaded
) &&
3937 "previous declaration set still overloaded");
3939 NamedDecl
*PrincipalDecl
= (FunctionTemplate
3940 ? cast
<NamedDecl
>(FunctionTemplate
)
3943 if (isFriend
&& Redeclaration
) {
3944 AccessSpecifier Access
= AS_public
;
3945 if (!NewFD
->isInvalidDecl())
3946 Access
= NewFD
->getPreviousDeclaration()->getAccess();
3948 NewFD
->setAccess(Access
);
3949 if (FunctionTemplate
) FunctionTemplate
->setAccess(Access
);
3951 PrincipalDecl
->setObjectOfFriendDecl(true);
3954 if (NewFD
->isOverloadedOperator() && !DC
->isRecord() &&
3955 PrincipalDecl
->isInIdentifierNamespace(Decl::IDNS_Ordinary
))
3956 PrincipalDecl
->setNonMemberOperator();
3958 // If we have a function template, check the template parameter
3959 // list. This will check and merge default template arguments.
3960 if (FunctionTemplate
) {
3961 FunctionTemplateDecl
*PrevTemplate
= FunctionTemplate
->getPreviousDeclaration();
3962 CheckTemplateParameterList(FunctionTemplate
->getTemplateParameters(),
3963 PrevTemplate
? PrevTemplate
->getTemplateParameters() : 0,
3964 D
.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3965 : TPC_FunctionTemplate
);
3968 if (NewFD
->isInvalidDecl()) {
3969 // Ignore all the rest of this.
3970 } else if (!Redeclaration
) {
3971 // Fake up an access specifier if it's supposed to be a class member.
3972 if (isa
<CXXRecordDecl
>(NewFD
->getDeclContext()))
3973 NewFD
->setAccess(AS_public
);
3975 // Qualified decls generally require a previous declaration.
3976 if (D
.getCXXScopeSpec().isSet()) {
3977 // ...with the major exception of templated-scope or
3978 // dependent-scope friend declarations.
3980 // TODO: we currently also suppress this check in dependent
3981 // contexts because (1) the parameter depth will be off when
3982 // matching friend templates and (2) we might actually be
3983 // selecting a friend based on a dependent factor. But there
3984 // are situations where these conditions don't apply and we
3985 // can actually do this check immediately.
3987 (NumMatchedTemplateParamLists
||
3988 D
.getCXXScopeSpec().getScopeRep()->isDependent() ||
3989 CurContext
->isDependentContext())) {
3992 // The user tried to provide an out-of-line definition for a
3993 // function that is a member of a class or namespace, but there
3994 // was no such member function declared (C++ [class.mfct]p2,
3995 // C++ [namespace.memdef]p2). For example:
4001 // void X::f() { } // ill-formed
4003 // Complain about this problem, and attempt to suggest close
4004 // matches (e.g., those that differ only in cv-qualifiers and
4005 // whether the parameter types are references).
4006 Diag(D
.getIdentifierLoc(), diag::err_member_def_does_not_match
)
4007 << Name
<< DC
<< D
.getCXXScopeSpec().getRange();
4008 NewFD
->setInvalidDecl();
4010 DiagnoseInvalidRedeclaration(*this, NewFD
);
4013 // Unqualified local friend declarations are required to resolve
4015 } else if (isFriend
&& cast
<CXXRecordDecl
>(CurContext
)->isLocalClass()) {
4016 Diag(D
.getIdentifierLoc(), diag::err_no_matching_local_friend
);
4017 NewFD
->setInvalidDecl();
4018 DiagnoseInvalidRedeclaration(*this, NewFD
);
4021 } else if (!IsFunctionDefinition
&& D
.getCXXScopeSpec().isSet() &&
4022 !isFriend
&& !isFunctionTemplateSpecialization
&&
4023 !isExplicitSpecialization
) {
4024 // An out-of-line member function declaration must also be a
4025 // definition (C++ [dcl.meaning]p1).
4026 // Note that this is not the case for explicit specializations of
4027 // function templates or member functions of class templates, per
4028 // C++ [temp.expl.spec]p2. We also allow these declarations as an extension
4029 // for compatibility with old SWIG code which likes to generate them.
4030 Diag(NewFD
->getLocation(), diag::ext_out_of_line_declaration
)
4031 << D
.getCXXScopeSpec().getRange();
4036 // Handle attributes. We need to have merged decls when handling attributes
4037 // (for example to check for conflicts, etc).
4038 // FIXME: This needs to happen before we merge declarations. Then,
4039 // let attribute merging cope with attribute conflicts.
4040 ProcessDeclAttributes(S
, NewFD
, D
,
4041 /*NonInheritable=*/false, /*Inheritable=*/true);
4043 // attributes declared post-definition are currently ignored
4044 // FIXME: This should happen during attribute merging
4045 if (Redeclaration
&& Previous
.isSingleResult()) {
4046 const FunctionDecl
*Def
;
4047 FunctionDecl
*PrevFD
= dyn_cast
<FunctionDecl
>(Previous
.getFoundDecl());
4048 if (PrevFD
&& PrevFD
->hasBody(Def
) && D
.hasAttributes()) {
4049 Diag(NewFD
->getLocation(), diag::warn_attribute_precede_definition
);
4050 Diag(Def
->getLocation(), diag::note_previous_definition
);
4054 AddKnownFunctionAttributes(NewFD
);
4056 if (NewFD
->hasAttr
<OverloadableAttr
>() &&
4057 !NewFD
->getType()->getAs
<FunctionProtoType
>()) {
4058 Diag(NewFD
->getLocation(),
4059 diag::err_attribute_overloadable_no_prototype
)
4062 // Turn this into a variadic function with no parameters.
4063 const FunctionType
*FT
= NewFD
->getType()->getAs
<FunctionType
>();
4064 FunctionProtoType::ExtProtoInfo EPI
;
4065 EPI
.Variadic
= true;
4066 EPI
.ExtInfo
= FT
->getExtInfo();
4068 QualType R
= Context
.getFunctionType(FT
->getResultType(), 0, 0, EPI
);
4072 // If there's a #pragma GCC visibility in scope, and this isn't a class
4073 // member, set the visibility of this function.
4074 if (NewFD
->getLinkage() == ExternalLinkage
&& !DC
->isRecord())
4075 AddPushedVisibilityAttribute(NewFD
);
4077 // If this is a locally-scoped extern C function, update the
4078 // map of such names.
4079 if (CurContext
->isFunctionOrMethod() && NewFD
->isExternC()
4080 && !NewFD
->isInvalidDecl())
4081 RegisterLocallyScopedExternCDecl(NewFD
, Previous
, S
);
4083 // Set this FunctionDecl's range up to the right paren.
4084 NewFD
->setLocEnd(D
.getSourceRange().getEnd());
4086 if (getLangOptions().CPlusPlus
) {
4087 if (FunctionTemplate
) {
4088 if (NewFD
->isInvalidDecl())
4089 FunctionTemplate
->setInvalidDecl();
4090 return FunctionTemplate
;
4094 MarkUnusedFileScopedDecl(NewFD
);
4098 /// \brief Perform semantic checking of a new function declaration.
4100 /// Performs semantic analysis of the new function declaration
4101 /// NewFD. This routine performs all semantic checking that does not
4102 /// require the actual declarator involved in the declaration, and is
4103 /// used both for the declaration of functions as they are parsed
4104 /// (called via ActOnDeclarator) and for the declaration of functions
4105 /// that have been instantiated via C++ template instantiation (called
4106 /// via InstantiateDecl).
4108 /// \param IsExplicitSpecialiation whether this new function declaration is
4109 /// an explicit specialization of the previous declaration.
4111 /// This sets NewFD->isInvalidDecl() to true if there was an error.
4112 void Sema::CheckFunctionDeclaration(Scope
*S
, FunctionDecl
*NewFD
,
4113 LookupResult
&Previous
,
4114 bool IsExplicitSpecialization
,
4115 bool &Redeclaration
) {
4116 // If NewFD is already known erroneous, don't do any of this checking.
4117 if (NewFD
->isInvalidDecl()) {
4118 // If this is a class member, mark the class invalid immediately.
4119 // This avoids some consistency errors later.
4120 if (isa
<CXXMethodDecl
>(NewFD
))
4121 cast
<CXXMethodDecl
>(NewFD
)->getParent()->setInvalidDecl();
4126 if (NewFD
->getResultType()->isVariablyModifiedType()) {
4127 // Functions returning a variably modified type violate C99 6.7.5.2p2
4128 // because all functions have linkage.
4129 Diag(NewFD
->getLocation(), diag::err_vm_func_decl
);
4130 return NewFD
->setInvalidDecl();
4133 if (NewFD
->isMain())
4136 // Check for a previous declaration of this name.
4137 if (Previous
.empty() && NewFD
->isExternC()) {
4138 // Since we did not find anything by this name and we're declaring
4139 // an extern "C" function, look for a non-visible extern "C"
4140 // declaration with the same name.
4141 llvm::DenseMap
<DeclarationName
, NamedDecl
*>::iterator Pos
4142 = LocallyScopedExternalDecls
.find(NewFD
->getDeclName());
4143 if (Pos
!= LocallyScopedExternalDecls
.end())
4144 Previous
.addDecl(Pos
->second
);
4147 // Merge or overload the declaration with an existing declaration of
4148 // the same name, if appropriate.
4149 if (!Previous
.empty()) {
4150 // Determine whether NewFD is an overload of PrevDecl or
4151 // a declaration that requires merging. If it's an overload,
4152 // there's no more work to do here; we'll just add the new
4153 // function to the scope.
4155 NamedDecl
*OldDecl
= 0;
4156 if (!AllowOverloadingOfFunction(Previous
, Context
)) {
4157 Redeclaration
= true;
4158 OldDecl
= Previous
.getFoundDecl();
4160 switch (CheckOverload(S
, NewFD
, Previous
, OldDecl
,
4161 /*NewIsUsingDecl*/ false)) {
4163 Redeclaration
= true;
4166 case Ovl_NonFunction
:
4167 Redeclaration
= true;
4171 Redeclaration
= false;
4175 if (!getLangOptions().CPlusPlus
&& !NewFD
->hasAttr
<OverloadableAttr
>()) {
4176 // If a function name is overloadable in C, then every function
4177 // with that name must be marked "overloadable".
4178 Diag(NewFD
->getLocation(), diag::err_attribute_overloadable_missing
)
4179 << Redeclaration
<< NewFD
;
4180 NamedDecl
*OverloadedDecl
= 0;
4182 OverloadedDecl
= OldDecl
;
4183 else if (!Previous
.empty())
4184 OverloadedDecl
= Previous
.getRepresentativeDecl();
4186 Diag(OverloadedDecl
->getLocation(),
4187 diag::note_attribute_overloadable_prev_overload
);
4188 NewFD
->addAttr(::new (Context
) OverloadableAttr(SourceLocation(),
4193 if (Redeclaration
) {
4194 // NewFD and OldDecl represent declarations that need to be
4196 if (MergeFunctionDecl(NewFD
, OldDecl
))
4197 return NewFD
->setInvalidDecl();
4200 Previous
.addDecl(OldDecl
);
4202 if (FunctionTemplateDecl
*OldTemplateDecl
4203 = dyn_cast
<FunctionTemplateDecl
>(OldDecl
)) {
4204 NewFD
->setPreviousDeclaration(OldTemplateDecl
->getTemplatedDecl());
4205 FunctionTemplateDecl
*NewTemplateDecl
4206 = NewFD
->getDescribedFunctionTemplate();
4207 assert(NewTemplateDecl
&& "Template/non-template mismatch");
4208 if (CXXMethodDecl
*Method
4209 = dyn_cast
<CXXMethodDecl
>(NewTemplateDecl
->getTemplatedDecl())) {
4210 Method
->setAccess(OldTemplateDecl
->getAccess());
4211 NewTemplateDecl
->setAccess(OldTemplateDecl
->getAccess());
4214 // If this is an explicit specialization of a member that is a function
4215 // template, mark it as a member specialization.
4216 if (IsExplicitSpecialization
&&
4217 NewTemplateDecl
->getInstantiatedFromMemberTemplate()) {
4218 NewTemplateDecl
->setMemberSpecialization();
4219 assert(OldTemplateDecl
->isMemberSpecialization());
4222 if (isa
<CXXMethodDecl
>(NewFD
)) // Set access for out-of-line definitions
4223 NewFD
->setAccess(OldDecl
->getAccess());
4224 NewFD
->setPreviousDeclaration(cast
<FunctionDecl
>(OldDecl
));
4229 // Semantic checking for this function declaration (in isolation).
4230 if (getLangOptions().CPlusPlus
) {
4231 // C++-specific checks.
4232 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(NewFD
)) {
4233 CheckConstructor(Constructor
);
4234 } else if (CXXDestructorDecl
*Destructor
=
4235 dyn_cast
<CXXDestructorDecl
>(NewFD
)) {
4236 CXXRecordDecl
*Record
= Destructor
->getParent();
4237 QualType ClassType
= Context
.getTypeDeclType(Record
);
4239 // FIXME: Shouldn't we be able to perform this check even when the class
4240 // type is dependent? Both gcc and edg can handle that.
4241 if (!ClassType
->isDependentType()) {
4242 DeclarationName Name
4243 = Context
.DeclarationNames
.getCXXDestructorName(
4244 Context
.getCanonicalType(ClassType
));
4245 if (NewFD
->getDeclName() != Name
) {
4246 Diag(NewFD
->getLocation(), diag::err_destructor_name
);
4247 return NewFD
->setInvalidDecl();
4250 } else if (CXXConversionDecl
*Conversion
4251 = dyn_cast
<CXXConversionDecl
>(NewFD
)) {
4252 ActOnConversionDeclarator(Conversion
);
4255 // Find any virtual functions that this function overrides.
4256 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(NewFD
)) {
4257 if (!Method
->isFunctionTemplateSpecialization() &&
4258 !Method
->getDescribedFunctionTemplate()) {
4259 if (AddOverriddenMethods(Method
->getParent(), Method
)) {
4260 // If the function was marked as "static", we have a problem.
4261 if (NewFD
->getStorageClass() == SC_Static
) {
4262 Diag(NewFD
->getLocation(), diag::err_static_overrides_virtual
)
4263 << NewFD
->getDeclName();
4264 for (CXXMethodDecl::method_iterator
4265 Overridden
= Method
->begin_overridden_methods(),
4266 OverriddenEnd
= Method
->end_overridden_methods();
4267 Overridden
!= OverriddenEnd
;
4269 Diag((*Overridden
)->getLocation(),
4270 diag::note_overridden_virtual_function
);
4277 // Extra checking for C++ overloaded operators (C++ [over.oper]).
4278 if (NewFD
->isOverloadedOperator() &&
4279 CheckOverloadedOperatorDeclaration(NewFD
))
4280 return NewFD
->setInvalidDecl();
4282 // Extra checking for C++0x literal operators (C++0x [over.literal]).
4283 if (NewFD
->getLiteralIdentifier() &&
4284 CheckLiteralOperatorDeclaration(NewFD
))
4285 return NewFD
->setInvalidDecl();
4287 // In C++, check default arguments now that we have merged decls. Unless
4288 // the lexical context is the class, because in this case this is done
4289 // during delayed parsing anyway.
4290 if (!CurContext
->isRecord())
4291 CheckCXXDefaultArguments(NewFD
);
4293 // If this function declares a builtin function, check the type of this
4294 // declaration against the expected type for the builtin.
4295 if (unsigned BuiltinID
= NewFD
->getBuiltinID()) {
4296 ASTContext::GetBuiltinTypeError Error
;
4297 QualType T
= Context
.GetBuiltinType(BuiltinID
, Error
);
4298 if (!T
.isNull() && !Context
.hasSameType(T
, NewFD
->getType())) {
4299 // The type of this function differs from the type of the builtin,
4300 // so forget about the builtin entirely.
4301 Context
.BuiltinInfo
.ForgetBuiltin(BuiltinID
, Context
.Idents
);
4307 void Sema::CheckMain(FunctionDecl
* FD
) {
4308 // C++ [basic.start.main]p3: A program that declares main to be inline
4309 // or static is ill-formed.
4310 // C99 6.7.4p4: In a hosted environment, the inline function specifier
4311 // shall not appear in a declaration of main.
4312 // static main is not an error under C99, but we should warn about it.
4313 bool isInline
= FD
->isInlineSpecified();
4314 bool isStatic
= FD
->getStorageClass() == SC_Static
;
4315 if (isInline
|| isStatic
) {
4316 unsigned diagID
= diag::warn_unusual_main_decl
;
4317 if (isInline
|| getLangOptions().CPlusPlus
)
4318 diagID
= diag::err_unusual_main_decl
;
4320 int which
= isStatic
+ (isInline
<< 1) - 1;
4321 Diag(FD
->getLocation(), diagID
) << which
;
4324 QualType T
= FD
->getType();
4325 assert(T
->isFunctionType() && "function decl is not of function type");
4326 const FunctionType
* FT
= T
->getAs
<FunctionType
>();
4328 if (!Context
.hasSameUnqualifiedType(FT
->getResultType(), Context
.IntTy
)) {
4329 TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo();
4330 TypeLoc TL
= TSI
->getTypeLoc().IgnoreParens();
4331 const SemaDiagnosticBuilder
& D
= Diag(FD
->getTypeSpecStartLoc(),
4332 diag::err_main_returns_nonint
);
4333 if (FunctionTypeLoc
* PTL
= dyn_cast
<FunctionTypeLoc
>(&TL
)) {
4334 D
<< FixItHint::CreateReplacement(PTL
->getResultLoc().getSourceRange(),
4337 FD
->setInvalidDecl(true);
4340 // Treat protoless main() as nullary.
4341 if (isa
<FunctionNoProtoType
>(FT
)) return;
4343 const FunctionProtoType
* FTP
= cast
<const FunctionProtoType
>(FT
);
4344 unsigned nparams
= FTP
->getNumArgs();
4345 assert(FD
->getNumParams() == nparams
);
4347 bool HasExtraParameters
= (nparams
> 3);
4349 // Darwin passes an undocumented fourth argument of type char**. If
4350 // other platforms start sprouting these, the logic below will start
4353 Context
.Target
.getTriple().getOS() == llvm::Triple::Darwin
)
4354 HasExtraParameters
= false;
4356 if (HasExtraParameters
) {
4357 Diag(FD
->getLocation(), diag::err_main_surplus_args
) << nparams
;
4358 FD
->setInvalidDecl(true);
4362 // FIXME: a lot of the following diagnostics would be improved
4363 // if we had some location information about types.
4366 Context
.getPointerType(Context
.getPointerType(Context
.CharTy
));
4367 QualType Expected
[] = { Context
.IntTy
, CharPP
, CharPP
, CharPP
};
4369 for (unsigned i
= 0; i
< nparams
; ++i
) {
4370 QualType AT
= FTP
->getArgType(i
);
4372 bool mismatch
= true;
4374 if (Context
.hasSameUnqualifiedType(AT
, Expected
[i
]))
4376 else if (Expected
[i
] == CharPP
) {
4377 // As an extension, the following forms are okay:
4379 // char const * const *
4382 QualifierCollector qs
;
4383 const PointerType
* PT
;
4384 if ((PT
= qs
.strip(AT
)->getAs
<PointerType
>()) &&
4385 (PT
= qs
.strip(PT
->getPointeeType())->getAs
<PointerType
>()) &&
4386 (QualType(qs
.strip(PT
->getPointeeType()), 0) == Context
.CharTy
)) {
4388 mismatch
= !qs
.empty();
4393 Diag(FD
->getLocation(), diag::err_main_arg_wrong
) << i
<< Expected
[i
];
4394 // TODO: suggest replacing given type with expected type
4395 FD
->setInvalidDecl(true);
4399 if (nparams
== 1 && !FD
->isInvalidDecl()) {
4400 Diag(FD
->getLocation(), diag::warn_main_one_arg
);
4403 if (!FD
->isInvalidDecl() && FD
->getDescribedFunctionTemplate()) {
4404 Diag(FD
->getLocation(), diag::err_main_template_decl
);
4405 FD
->setInvalidDecl();
4409 bool Sema::CheckForConstantInitializer(Expr
*Init
, QualType DclT
) {
4410 // FIXME: Need strict checking. In C89, we need to check for
4411 // any assignment, increment, decrement, function-calls, or
4412 // commas outside of a sizeof. In C99, it's the same list,
4413 // except that the aforementioned are allowed in unevaluated
4414 // expressions. Everything else falls under the
4415 // "may accept other forms of constant expressions" exception.
4416 // (We never end up here for C++, so the constant expression
4417 // rules there don't matter.)
4418 if (Init
->isConstantInitializer(Context
, false))
4420 Diag(Init
->getExprLoc(), diag::err_init_element_not_constant
)
4421 << Init
->getSourceRange();
4425 void Sema::AddInitializerToDecl(Decl
*dcl
, Expr
*init
) {
4426 AddInitializerToDecl(dcl
, init
, /*DirectInit=*/false);
4429 /// AddInitializerToDecl - Adds the initializer Init to the
4430 /// declaration dcl. If DirectInit is true, this is C++ direct
4431 /// initialization rather than copy initialization.
4432 void Sema::AddInitializerToDecl(Decl
*RealDecl
, Expr
*Init
, bool DirectInit
) {
4433 // If there is no declaration, there was an error parsing it. Just ignore
4438 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(RealDecl
)) {
4439 // With declarators parsed the way they are, the parser cannot
4440 // distinguish between a normal initializer and a pure-specifier.
4441 // Thus this grotesque test.
4443 if ((IL
= dyn_cast
<IntegerLiteral
>(Init
)) && IL
->getValue() == 0 &&
4444 Context
.getCanonicalType(IL
->getType()) == Context
.IntTy
)
4445 CheckPureMethod(Method
, Init
->getSourceRange());
4447 Diag(Method
->getLocation(), diag::err_member_function_initialization
)
4448 << Method
->getDeclName() << Init
->getSourceRange();
4449 Method
->setInvalidDecl();
4454 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
4456 if (getLangOptions().CPlusPlus
&&
4457 RealDecl
->getLexicalDeclContext()->isRecord() &&
4458 isa
<NamedDecl
>(RealDecl
))
4459 Diag(RealDecl
->getLocation(), diag::err_member_initialization
);
4461 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
4462 RealDecl
->setInvalidDecl();
4468 // A definition must end up with a complete type, which means it must be
4469 // complete with the restriction that an array type might be completed by the
4470 // initializer; note that later code assumes this restriction.
4471 QualType BaseDeclType
= VDecl
->getType();
4472 if (const ArrayType
*Array
= Context
.getAsIncompleteArrayType(BaseDeclType
))
4473 BaseDeclType
= Array
->getElementType();
4474 if (RequireCompleteType(VDecl
->getLocation(), BaseDeclType
,
4475 diag::err_typecheck_decl_incomplete_type
)) {
4476 RealDecl
->setInvalidDecl();
4480 // The variable can not have an abstract class type.
4481 if (RequireNonAbstractType(VDecl
->getLocation(), VDecl
->getType(),
4482 diag::err_abstract_type_in_decl
,
4483 AbstractVariableType
))
4484 VDecl
->setInvalidDecl();
4487 if ((Def
= VDecl
->getDefinition()) && Def
!= VDecl
) {
4488 Diag(VDecl
->getLocation(), diag::err_redefinition
)
4489 << VDecl
->getDeclName();
4490 Diag(Def
->getLocation(), diag::note_previous_definition
);
4491 VDecl
->setInvalidDecl();
4495 const VarDecl
* PrevInit
= 0;
4496 if (getLangOptions().CPlusPlus
) {
4497 // C++ [class.static.data]p4
4498 // If a static data member is of const integral or const
4499 // enumeration type, its declaration in the class definition can
4500 // specify a constant-initializer which shall be an integral
4501 // constant expression (5.19). In that case, the member can appear
4502 // in integral constant expressions. The member shall still be
4503 // defined in a namespace scope if it is used in the program and the
4504 // namespace scope definition shall not contain an initializer.
4506 // We already performed a redefinition check above, but for static
4507 // data members we also need to check whether there was an in-class
4508 // declaration with an initializer.
4509 if (VDecl
->isStaticDataMember() && VDecl
->getAnyInitializer(PrevInit
)) {
4510 Diag(VDecl
->getLocation(), diag::err_redefinition
) << VDecl
->getDeclName();
4511 Diag(PrevInit
->getLocation(), diag::note_previous_definition
);
4515 if (VDecl
->hasLocalStorage())
4516 getCurFunction()->setHasBranchProtectedScope();
4518 if (DiagnoseUnexpandedParameterPack(Init
, UPPC_Initializer
)) {
4519 VDecl
->setInvalidDecl();
4524 // Capture the variable that is being initialized and the style of
4526 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
4528 // FIXME: Poor source location information.
4529 InitializationKind Kind
4530 = DirectInit
? InitializationKind::CreateDirect(VDecl
->getLocation(),
4531 Init
->getLocStart(),
4533 : InitializationKind::CreateCopy(VDecl
->getLocation(),
4534 Init
->getLocStart());
4536 // Get the decls type and save a reference for later, since
4537 // CheckInitializerTypes may change it.
4538 QualType DclT
= VDecl
->getType(), SavT
= DclT
;
4539 if (VDecl
->isLocalVarDecl()) {
4540 if (VDecl
->hasExternalStorage()) { // C99 6.7.8p5
4541 Diag(VDecl
->getLocation(), diag::err_block_extern_cant_init
);
4542 VDecl
->setInvalidDecl();
4543 } else if (!VDecl
->isInvalidDecl()) {
4544 InitializationSequence
InitSeq(*this, Entity
, Kind
, &Init
, 1);
4545 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
4546 MultiExprArg(*this, &Init
, 1),
4548 if (Result
.isInvalid()) {
4549 VDecl
->setInvalidDecl();
4553 Init
= Result
.takeAs
<Expr
>();
4555 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
4556 // Don't check invalid declarations to avoid emitting useless diagnostics.
4557 if (!getLangOptions().CPlusPlus
&& !VDecl
->isInvalidDecl()) {
4558 if (VDecl
->getStorageClass() == SC_Static
) // C99 6.7.8p4.
4559 CheckForConstantInitializer(Init
, DclT
);
4562 } else if (VDecl
->isStaticDataMember() &&
4563 VDecl
->getLexicalDeclContext()->isRecord()) {
4564 // This is an in-class initialization for a static data member, e.g.,
4567 // static const int value = 17;
4570 // Try to perform the initialization regardless.
4571 if (!VDecl
->isInvalidDecl()) {
4572 InitializationSequence
InitSeq(*this, Entity
, Kind
, &Init
, 1);
4573 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
4574 MultiExprArg(*this, &Init
, 1),
4576 if (Result
.isInvalid()) {
4577 VDecl
->setInvalidDecl();
4581 Init
= Result
.takeAs
<Expr
>();
4584 // C++ [class.mem]p4:
4585 // A member-declarator can contain a constant-initializer only
4586 // if it declares a static member (9.4) of const integral or
4587 // const enumeration type, see 9.4.2.
4588 QualType T
= VDecl
->getType();
4590 // Do nothing on dependent types.
4591 if (T
->isDependentType()) {
4593 // Require constness.
4594 } else if (!T
.isConstQualified()) {
4595 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_non_const
)
4596 << Init
->getSourceRange();
4597 VDecl
->setInvalidDecl();
4599 // We allow integer constant expressions in all cases.
4600 } else if (T
->isIntegralOrEnumerationType()) {
4601 if (!Init
->isValueDependent()) {
4602 // Check whether the expression is a constant expression.
4605 if (!Init
->isIntegerConstantExpr(Value
, Context
, &Loc
)) {
4606 Diag(Loc
, diag::err_in_class_initializer_non_constant
)
4607 << Init
->getSourceRange();
4608 VDecl
->setInvalidDecl();
4612 // We allow floating-point constants as an extension in C++03, and
4613 // C++0x has far more complicated rules that we don't really
4616 bool Allowed
= false;
4617 if (getLangOptions().CPlusPlus0x
) {
4618 Allowed
= T
->isLiteralType();
4619 } else if (T
->isFloatingType()) { // also permits complex, which is ok
4620 Diag(VDecl
->getLocation(), diag::ext_in_class_initializer_float_type
)
4621 << T
<< Init
->getSourceRange();
4626 Diag(VDecl
->getLocation(), diag::err_in_class_initializer_bad_type
)
4627 << T
<< Init
->getSourceRange();
4628 VDecl
->setInvalidDecl();
4630 // TODO: there are probably expressions that pass here that shouldn't.
4631 } else if (!Init
->isValueDependent() &&
4632 !Init
->isConstantInitializer(Context
, false)) {
4633 Diag(Init
->getExprLoc(), diag::err_in_class_initializer_non_constant
)
4634 << Init
->getSourceRange();
4635 VDecl
->setInvalidDecl();
4638 } else if (VDecl
->isFileVarDecl()) {
4639 if (VDecl
->getStorageClassAsWritten() == SC_Extern
&&
4640 (!getLangOptions().CPlusPlus
||
4641 !Context
.getBaseElementType(VDecl
->getType()).isConstQualified()))
4642 Diag(VDecl
->getLocation(), diag::warn_extern_init
);
4643 if (!VDecl
->isInvalidDecl()) {
4644 InitializationSequence
InitSeq(*this, Entity
, Kind
, &Init
, 1);
4645 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
4646 MultiExprArg(*this, &Init
, 1),
4648 if (Result
.isInvalid()) {
4649 VDecl
->setInvalidDecl();
4653 Init
= Result
.takeAs
<Expr
>();
4656 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
4657 // Don't check invalid declarations to avoid emitting useless diagnostics.
4658 if (!getLangOptions().CPlusPlus
&& !VDecl
->isInvalidDecl()) {
4659 // C99 6.7.8p4. All file scoped initializers need to be constant.
4660 CheckForConstantInitializer(Init
, DclT
);
4663 // If the type changed, it means we had an incomplete type that was
4664 // completed by the initializer. For example:
4665 // int ary[] = { 1, 3, 5 };
4666 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
4667 if (!VDecl
->isInvalidDecl() && (DclT
!= SavT
)) {
4668 VDecl
->setType(DclT
);
4669 Init
->setType(DclT
);
4673 // If this variable is a local declaration with record type, make sure it
4674 // doesn't have a flexible member initialization. We only support this as a
4675 // global/static definition.
4676 if (VDecl
->hasLocalStorage())
4677 if (const RecordType
*RT
= VDecl
->getType()->getAs
<RecordType
>())
4678 if (RT
->getDecl()->hasFlexibleArrayMember()) {
4679 // Check whether the initializer tries to initialize the flexible
4680 // array member itself to anything other than an empty initializer list.
4681 if (InitListExpr
*ILE
= dyn_cast
<InitListExpr
>(Init
)) {
4682 unsigned Index
= std::distance(RT
->getDecl()->field_begin(),
4683 RT
->getDecl()->field_end()) - 1;
4684 if (Index
< ILE
->getNumInits() &&
4685 !(isa
<InitListExpr
>(ILE
->getInit(Index
)) &&
4686 cast
<InitListExpr
>(ILE
->getInit(Index
))->getNumInits() == 0)) {
4687 Diag(VDecl
->getLocation(), diag::err_nonstatic_flexible_variable
);
4688 VDecl
->setInvalidDecl();
4693 // Check any implicit conversions within the expression.
4694 CheckImplicitConversions(Init
, VDecl
->getLocation());
4696 Init
= MaybeCreateExprWithCleanups(Init
);
4697 // Attach the initializer to the decl.
4698 VDecl
->setInit(Init
);
4700 CheckCompleteVariableDeclaration(VDecl
);
4703 /// ActOnInitializerError - Given that there was an error parsing an
4704 /// initializer for the given declaration, try to return to some form
4706 void Sema::ActOnInitializerError(Decl
*D
) {
4707 // Our main concern here is re-establishing invariants like "a
4708 // variable's type is either dependent or complete".
4709 if (!D
|| D
->isInvalidDecl()) return;
4711 VarDecl
*VD
= dyn_cast
<VarDecl
>(D
);
4714 QualType Ty
= VD
->getType();
4715 if (Ty
->isDependentType()) return;
4717 // Require a complete type.
4718 if (RequireCompleteType(VD
->getLocation(),
4719 Context
.getBaseElementType(Ty
),
4720 diag::err_typecheck_decl_incomplete_type
)) {
4721 VD
->setInvalidDecl();
4725 // Require an abstract type.
4726 if (RequireNonAbstractType(VD
->getLocation(), Ty
,
4727 diag::err_abstract_type_in_decl
,
4728 AbstractVariableType
)) {
4729 VD
->setInvalidDecl();
4733 // Don't bother complaining about constructors or destructors,
4737 void Sema::ActOnUninitializedDecl(Decl
*RealDecl
,
4738 bool TypeContainsUndeducedAuto
) {
4739 // If there is no declaration, there was an error parsing it. Just ignore it.
4743 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(RealDecl
)) {
4744 QualType Type
= Var
->getType();
4746 // C++0x [dcl.spec.auto]p3
4747 if (TypeContainsUndeducedAuto
) {
4748 Diag(Var
->getLocation(), diag::err_auto_var_requires_init
)
4749 << Var
->getDeclName() << Type
;
4750 Var
->setInvalidDecl();
4754 switch (Var
->isThisDeclarationADefinition()) {
4755 case VarDecl::Definition
:
4756 if (!Var
->isStaticDataMember() || !Var
->getAnyInitializer())
4759 // We have an out-of-line definition of a static data member
4760 // that has an in-class initializer, so we type-check this like
4765 case VarDecl::DeclarationOnly
:
4766 // It's only a declaration.
4768 // Block scope. C99 6.7p7: If an identifier for an object is
4769 // declared with no linkage (C99 6.2.2p6), the type for the
4770 // object shall be complete.
4771 if (!Type
->isDependentType() && Var
->isLocalVarDecl() &&
4772 !Var
->getLinkage() && !Var
->isInvalidDecl() &&
4773 RequireCompleteType(Var
->getLocation(), Type
,
4774 diag::err_typecheck_decl_incomplete_type
))
4775 Var
->setInvalidDecl();
4777 // Make sure that the type is not abstract.
4778 if (!Type
->isDependentType() && !Var
->isInvalidDecl() &&
4779 RequireNonAbstractType(Var
->getLocation(), Type
,
4780 diag::err_abstract_type_in_decl
,
4781 AbstractVariableType
))
4782 Var
->setInvalidDecl();
4785 case VarDecl::TentativeDefinition
:
4786 // File scope. C99 6.9.2p2: A declaration of an identifier for an
4787 // object that has file scope without an initializer, and without a
4788 // storage-class specifier or with the storage-class specifier "static",
4789 // constitutes a tentative definition. Note: A tentative definition with
4790 // external linkage is valid (C99 6.2.2p5).
4791 if (!Var
->isInvalidDecl()) {
4792 if (const IncompleteArrayType
*ArrayT
4793 = Context
.getAsIncompleteArrayType(Type
)) {
4794 if (RequireCompleteType(Var
->getLocation(),
4795 ArrayT
->getElementType(),
4796 diag::err_illegal_decl_array_incomplete_type
))
4797 Var
->setInvalidDecl();
4798 } else if (Var
->getStorageClass() == SC_Static
) {
4799 // C99 6.9.2p3: If the declaration of an identifier for an object is
4800 // a tentative definition and has internal linkage (C99 6.2.2p3), the
4801 // declared type shall not be an incomplete type.
4802 // NOTE: code such as the following
4804 // struct s { int a; };
4805 // is accepted by gcc. Hence here we issue a warning instead of
4806 // an error and we do not invalidate the static declaration.
4807 // NOTE: to avoid multiple warnings, only check the first declaration.
4808 if (Var
->getPreviousDeclaration() == 0)
4809 RequireCompleteType(Var
->getLocation(), Type
,
4810 diag::ext_typecheck_decl_incomplete_type
);
4814 // Record the tentative definition; we're done.
4815 if (!Var
->isInvalidDecl())
4816 TentativeDefinitions
.push_back(Var
);
4820 // Provide a specific diagnostic for uninitialized variable
4821 // definitions with incomplete array type.
4822 if (Type
->isIncompleteArrayType()) {
4823 Diag(Var
->getLocation(),
4824 diag::err_typecheck_incomplete_array_needs_initializer
);
4825 Var
->setInvalidDecl();
4829 // Provide a specific diagnostic for uninitialized variable
4830 // definitions with reference type.
4831 if (Type
->isReferenceType()) {
4832 Diag(Var
->getLocation(), diag::err_reference_var_requires_init
)
4833 << Var
->getDeclName()
4834 << SourceRange(Var
->getLocation(), Var
->getLocation());
4835 Var
->setInvalidDecl();
4839 // Do not attempt to type-check the default initializer for a
4840 // variable with dependent type.
4841 if (Type
->isDependentType())
4844 if (Var
->isInvalidDecl())
4847 if (RequireCompleteType(Var
->getLocation(),
4848 Context
.getBaseElementType(Type
),
4849 diag::err_typecheck_decl_incomplete_type
)) {
4850 Var
->setInvalidDecl();
4854 // The variable can not have an abstract class type.
4855 if (RequireNonAbstractType(Var
->getLocation(), Type
,
4856 diag::err_abstract_type_in_decl
,
4857 AbstractVariableType
)) {
4858 Var
->setInvalidDecl();
4862 const RecordType
*Record
4863 = Context
.getBaseElementType(Type
)->getAs
<RecordType
>();
4864 if (Record
&& getLangOptions().CPlusPlus
&& !getLangOptions().CPlusPlus0x
&&
4865 cast
<CXXRecordDecl
>(Record
->getDecl())->isPOD()) {
4866 // C++03 [dcl.init]p9:
4867 // If no initializer is specified for an object, and the
4868 // object is of (possibly cv-qualified) non-POD class type (or
4869 // array thereof), the object shall be default-initialized; if
4870 // the object is of const-qualified type, the underlying class
4871 // type shall have a user-declared default
4872 // constructor. Otherwise, if no initializer is specified for
4873 // a non- static object, the object and its subobjects, if
4874 // any, have an indeterminate initial value); if the object
4875 // or any of its subobjects are of const-qualified type, the
4876 // program is ill-formed.
4877 // FIXME: DPG thinks it is very fishy that C++0x disables this.
4879 // Check for jumps past the implicit initializer. C++0x
4880 // clarifies that this applies to a "variable with automatic
4881 // storage duration", not a "local variable".
4882 if (getLangOptions().CPlusPlus
&& Var
->hasLocalStorage())
4883 getCurFunction()->setHasBranchProtectedScope();
4885 InitializedEntity Entity
= InitializedEntity::InitializeVariable(Var
);
4886 InitializationKind Kind
4887 = InitializationKind::CreateDefault(Var
->getLocation());
4889 InitializationSequence
InitSeq(*this, Entity
, Kind
, 0, 0);
4890 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
,
4891 MultiExprArg(*this, 0, 0));
4892 if (Init
.isInvalid())
4893 Var
->setInvalidDecl();
4894 else if (Init
.get())
4895 Var
->setInit(MaybeCreateExprWithCleanups(Init
.get()));
4898 CheckCompleteVariableDeclaration(Var
);
4902 void Sema::CheckCompleteVariableDeclaration(VarDecl
*var
) {
4903 if (var
->isInvalidDecl()) return;
4905 // All the following checks are C++ only.
4906 if (!getLangOptions().CPlusPlus
) return;
4908 QualType baseType
= Context
.getBaseElementType(var
->getType());
4909 if (baseType
->isDependentType()) return;
4911 // __block variables might require us to capture a copy-initializer.
4912 if (var
->hasAttr
<BlocksAttr
>()) {
4913 // It's currently invalid to ever have a __block variable with an
4914 // array type; should we diagnose that here?
4916 // Regardless, we don't want to ignore array nesting when
4917 // constructing this copy.
4918 QualType type
= var
->getType();
4920 if (type
->isStructureOrClassType()) {
4921 SourceLocation poi
= var
->getLocation();
4922 Expr
*varRef
= new (Context
) DeclRefExpr(var
, type
, VK_LValue
, poi
);
4924 PerformCopyInitialization(
4925 InitializedEntity::InitializeBlock(poi
, type
, false),
4926 poi
, Owned(varRef
));
4927 if (!result
.isInvalid()) {
4928 result
= MaybeCreateExprWithCleanups(result
);
4929 Expr
*init
= result
.takeAs
<Expr
>();
4930 Context
.setBlockVarCopyInits(var
, init
);
4935 // Check for global constructors.
4936 if (!var
->getDeclContext()->isDependentContext() &&
4937 var
->hasGlobalStorage() &&
4938 !var
->isStaticLocal() &&
4940 !var
->getInit()->isConstantInitializer(Context
,
4941 baseType
->isReferenceType()))
4942 Diag(var
->getLocation(), diag::warn_global_constructor
)
4943 << var
->getInit()->getSourceRange();
4945 // Require the destructor.
4946 if (const RecordType
*recordType
= baseType
->getAs
<RecordType
>())
4947 FinalizeVarWithDestructor(var
, recordType
);
4950 Sema::DeclGroupPtrTy
4951 Sema::FinalizeDeclaratorGroup(Scope
*S
, const DeclSpec
&DS
,
4952 Decl
**Group
, unsigned NumDecls
) {
4953 llvm::SmallVector
<Decl
*, 8> Decls
;
4955 if (DS
.isTypeSpecOwned())
4956 Decls
.push_back(DS
.getRepAsDecl());
4958 for (unsigned i
= 0; i
!= NumDecls
; ++i
)
4959 if (Decl
*D
= Group
[i
])
4962 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context
,
4963 Decls
.data(), Decls
.size()));
4967 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4968 /// to introduce parameters into function prototype scope.
4969 Decl
*Sema::ActOnParamDeclarator(Scope
*S
, Declarator
&D
) {
4970 const DeclSpec
&DS
= D
.getDeclSpec();
4972 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4973 VarDecl::StorageClass StorageClass
= SC_None
;
4974 VarDecl::StorageClass StorageClassAsWritten
= SC_None
;
4975 if (DS
.getStorageClassSpec() == DeclSpec::SCS_register
) {
4976 StorageClass
= SC_Register
;
4977 StorageClassAsWritten
= SC_Register
;
4978 } else if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
) {
4979 Diag(DS
.getStorageClassSpecLoc(),
4980 diag::err_invalid_storage_class_in_func_decl
);
4981 D
.getMutableDeclSpec().ClearStorageClassSpecs();
4984 if (D
.getDeclSpec().isThreadSpecified())
4985 Diag(D
.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread
);
4987 DiagnoseFunctionSpecifiers(D
);
4989 TagDecl
*OwnedDecl
= 0;
4990 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
, &OwnedDecl
);
4991 QualType parmDeclType
= TInfo
->getType();
4993 if (getLangOptions().CPlusPlus
) {
4994 // Check that there are no default arguments inside the type of this
4996 CheckExtraCXXDefaultArguments(D
);
4998 if (OwnedDecl
&& OwnedDecl
->isDefinition()) {
5000 // Types shall not be defined in return or parameter types.
5001 Diag(OwnedDecl
->getLocation(), diag::err_type_defined_in_param_type
)
5002 << Context
.getTypeDeclType(OwnedDecl
);
5005 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5006 if (D
.getCXXScopeSpec().isSet()) {
5007 Diag(D
.getIdentifierLoc(), diag::err_qualified_param_declarator
)
5008 << D
.getCXXScopeSpec().getRange();
5009 D
.getCXXScopeSpec().clear();
5013 // Ensure we have a valid name
5014 IdentifierInfo
*II
= 0;
5016 II
= D
.getIdentifier();
5018 Diag(D
.getIdentifierLoc(), diag::err_bad_parameter_name
)
5019 << GetNameForDeclarator(D
).getName().getAsString();
5020 D
.setInvalidType(true);
5024 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
5026 LookupResult
R(*this, II
, D
.getIdentifierLoc(), LookupOrdinaryName
,
5029 if (R
.isSingleResult()) {
5030 NamedDecl
*PrevDecl
= R
.getFoundDecl();
5031 if (PrevDecl
->isTemplateParameter()) {
5032 // Maybe we will complain about the shadowed template parameter.
5033 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
5034 // Just pretend that we didn't see the previous declaration.
5036 } else if (S
->isDeclScope(PrevDecl
)) {
5037 Diag(D
.getIdentifierLoc(), diag::err_param_redefinition
) << II
;
5038 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
5040 // Recover by removing the name
5042 D
.SetIdentifier(0, D
.getIdentifierLoc());
5043 D
.setInvalidType(true);
5048 // Temporarily put parameter variables in the translation unit, not
5049 // the enclosing context. This prevents them from accidentally
5050 // looking like class members in C++.
5051 ParmVarDecl
*New
= CheckParameter(Context
.getTranslationUnitDecl(),
5052 TInfo
, parmDeclType
, II
,
5053 D
.getIdentifierLoc(),
5054 StorageClass
, StorageClassAsWritten
);
5056 if (D
.isInvalidType())
5057 New
->setInvalidDecl();
5059 // Add the parameter declaration into this scope.
5062 IdResolver
.AddDecl(New
);
5064 ProcessDeclAttributes(S
, New
, D
);
5066 if (New
->hasAttr
<BlocksAttr
>()) {
5067 Diag(New
->getLocation(), diag::err_block_on_nonlocal
);
5072 /// \brief Synthesizes a variable for a parameter arising from a
5074 ParmVarDecl
*Sema::BuildParmVarDeclForTypedef(DeclContext
*DC
,
5077 ParmVarDecl
*Param
= ParmVarDecl::Create(Context
, DC
, Loc
, 0,
5078 T
, Context
.getTrivialTypeSourceInfo(T
, Loc
),
5079 SC_None
, SC_None
, 0);
5080 Param
->setImplicit();
5084 void Sema::DiagnoseUnusedParameters(ParmVarDecl
* const *Param
,
5085 ParmVarDecl
* const *ParamEnd
) {
5086 // Don't diagnose unused-parameter errors in template instantiations; we
5087 // will already have done so in the template itself.
5088 if (!ActiveTemplateInstantiations
.empty())
5091 for (; Param
!= ParamEnd
; ++Param
) {
5092 if (!(*Param
)->isUsed() && (*Param
)->getDeclName() &&
5093 !(*Param
)->hasAttr
<UnusedAttr
>()) {
5094 Diag((*Param
)->getLocation(), diag::warn_unused_parameter
)
5095 << (*Param
)->getDeclName();
5100 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl
* const *Param
,
5101 ParmVarDecl
* const *ParamEnd
,
5104 if (LangOpts
.NumLargeByValueCopy
== 0) // No check.
5107 // Warn if the return value is pass-by-value and larger than the specified
5109 if (ReturnTy
->isPODType()) {
5110 unsigned Size
= Context
.getTypeSizeInChars(ReturnTy
).getQuantity();
5111 if (Size
> LangOpts
.NumLargeByValueCopy
)
5112 Diag(D
->getLocation(), diag::warn_return_value_size
)
5113 << D
->getDeclName() << Size
;
5116 // Warn if any parameter is pass-by-value and larger than the specified
5118 for (; Param
!= ParamEnd
; ++Param
) {
5119 QualType T
= (*Param
)->getType();
5120 if (!T
->isPODType())
5122 unsigned Size
= Context
.getTypeSizeInChars(T
).getQuantity();
5123 if (Size
> LangOpts
.NumLargeByValueCopy
)
5124 Diag((*Param
)->getLocation(), diag::warn_parameter_size
)
5125 << (*Param
)->getDeclName() << Size
;
5129 ParmVarDecl
*Sema::CheckParameter(DeclContext
*DC
,
5130 TypeSourceInfo
*TSInfo
, QualType T
,
5131 IdentifierInfo
*Name
,
5132 SourceLocation NameLoc
,
5133 VarDecl::StorageClass StorageClass
,
5134 VarDecl::StorageClass StorageClassAsWritten
) {
5135 ParmVarDecl
*New
= ParmVarDecl::Create(Context
, DC
, NameLoc
, Name
,
5136 adjustParameterType(T
), TSInfo
,
5137 StorageClass
, StorageClassAsWritten
,
5140 // Parameters can not be abstract class types.
5141 // For record types, this is done by the AbstractClassUsageDiagnoser once
5142 // the class has been completely parsed.
5143 if (!CurContext
->isRecord() &&
5144 RequireNonAbstractType(NameLoc
, T
, diag::err_abstract_type_in_decl
,
5146 New
->setInvalidDecl();
5148 // Parameter declarators cannot be interface types. All ObjC objects are
5149 // passed by reference.
5150 if (T
->isObjCObjectType()) {
5152 diag::err_object_cannot_be_passed_returned_by_value
) << 1 << T
;
5153 New
->setInvalidDecl();
5156 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5157 // duration shall not be qualified by an address-space qualifier."
5158 // Since all parameters have automatic store duration, they can not have
5159 // an address space.
5160 if (T
.getAddressSpace() != 0) {
5161 Diag(NameLoc
, diag::err_arg_with_address_space
);
5162 New
->setInvalidDecl();
5168 void Sema::ActOnFinishKNRParamDeclarations(Scope
*S
, Declarator
&D
,
5169 SourceLocation LocAfterDecls
) {
5170 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
5172 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
5173 // for a K&R function.
5174 if (!FTI
.hasPrototype
) {
5175 for (int i
= FTI
.NumArgs
; i
!= 0; /* decrement in loop */) {
5177 if (FTI
.ArgInfo
[i
].Param
== 0) {
5178 llvm::SmallString
<256> Code
;
5179 llvm::raw_svector_ostream(Code
) << " int "
5180 << FTI
.ArgInfo
[i
].Ident
->getName()
5182 Diag(FTI
.ArgInfo
[i
].IdentLoc
, diag::ext_param_not_declared
)
5183 << FTI
.ArgInfo
[i
].Ident
5184 << FixItHint::CreateInsertion(LocAfterDecls
, Code
.str());
5186 // Implicitly declare the argument as type 'int' for lack of a better
5189 const char* PrevSpec
; // unused
5190 unsigned DiagID
; // unused
5191 DS
.SetTypeSpecType(DeclSpec::TST_int
, FTI
.ArgInfo
[i
].IdentLoc
,
5193 Declarator
ParamD(DS
, Declarator::KNRTypeListContext
);
5194 ParamD
.SetIdentifier(FTI
.ArgInfo
[i
].Ident
, FTI
.ArgInfo
[i
].IdentLoc
);
5195 FTI
.ArgInfo
[i
].Param
= ActOnParamDeclarator(S
, ParamD
);
5201 Decl
*Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
,
5203 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
5204 assert(D
.isFunctionDeclarator() && "Not a function declarator!");
5205 Scope
*ParentScope
= FnBodyScope
->getParent();
5207 Decl
*DP
= HandleDeclarator(ParentScope
, D
,
5208 MultiTemplateParamsArg(*this),
5209 /*IsFunctionDefinition=*/true);
5210 return ActOnStartOfFunctionDef(FnBodyScope
, DP
);
5213 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl
*FD
) {
5214 // Don't warn about invalid declarations.
5215 if (FD
->isInvalidDecl())
5218 // Or declarations that aren't global.
5219 if (!FD
->isGlobal())
5222 // Don't warn about C++ member functions.
5223 if (isa
<CXXMethodDecl
>(FD
))
5226 // Don't warn about 'main'.
5230 // Don't warn about inline functions.
5231 if (FD
->isInlineSpecified())
5234 // Don't warn about function templates.
5235 if (FD
->getDescribedFunctionTemplate())
5238 // Don't warn about function template specializations.
5239 if (FD
->isFunctionTemplateSpecialization())
5242 bool MissingPrototype
= true;
5243 for (const FunctionDecl
*Prev
= FD
->getPreviousDeclaration();
5244 Prev
; Prev
= Prev
->getPreviousDeclaration()) {
5245 // Ignore any declarations that occur in function or method
5246 // scope, because they aren't visible from the header.
5247 if (Prev
->getDeclContext()->isFunctionOrMethod())
5250 MissingPrototype
= !Prev
->getType()->isFunctionProtoType();
5254 return MissingPrototype
;
5257 Decl
*Sema::ActOnStartOfFunctionDef(Scope
*FnBodyScope
, Decl
*D
) {
5258 // Clear the last template instantiation error context.
5259 LastTemplateInstantiationErrorContext
= ActiveTemplateInstantiation();
5263 FunctionDecl
*FD
= 0;
5265 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
))
5266 FD
= FunTmpl
->getTemplatedDecl();
5268 FD
= cast
<FunctionDecl
>(D
);
5270 // Enter a new function scope
5271 PushFunctionScope();
5273 // See if this is a redefinition.
5274 // But don't complain if we're in GNU89 mode and the previous definition
5275 // was an extern inline function.
5276 const FunctionDecl
*Definition
;
5277 if (FD
->hasBody(Definition
) &&
5278 !canRedefineFunction(Definition
, getLangOptions())) {
5279 if (getLangOptions().GNUMode
&& Definition
->isInlineSpecified() &&
5280 Definition
->getStorageClass() == SC_Extern
)
5281 Diag(FD
->getLocation(), diag::err_redefinition_extern_inline
)
5282 << FD
->getDeclName() << getLangOptions().CPlusPlus
;
5284 Diag(FD
->getLocation(), diag::err_redefinition
) << FD
->getDeclName();
5285 Diag(Definition
->getLocation(), diag::note_previous_definition
);
5288 // Builtin functions cannot be defined.
5289 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
5290 if (!Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
)) {
5291 Diag(FD
->getLocation(), diag::err_builtin_definition
) << FD
;
5292 FD
->setInvalidDecl();
5296 // The return type of a function definition must be complete
5297 // (C99 6.9.1p3, C++ [dcl.fct]p6).
5298 QualType ResultType
= FD
->getResultType();
5299 if (!ResultType
->isDependentType() && !ResultType
->isVoidType() &&
5300 !FD
->isInvalidDecl() &&
5301 RequireCompleteType(FD
->getLocation(), ResultType
,
5302 diag::err_func_def_incomplete_result
))
5303 FD
->setInvalidDecl();
5305 // GNU warning -Wmissing-prototypes:
5306 // Warn if a global function is defined without a previous
5307 // prototype declaration. This warning is issued even if the
5308 // definition itself provides a prototype. The aim is to detect
5309 // global functions that fail to be declared in header files.
5310 if (ShouldWarnAboutMissingPrototype(FD
))
5311 Diag(FD
->getLocation(), diag::warn_missing_prototype
) << FD
;
5314 PushDeclContext(FnBodyScope
, FD
);
5316 // Check the validity of our function parameters
5317 CheckParmsForFunctionDef(FD
->param_begin(), FD
->param_end(),
5318 /*CheckParameterNames=*/true);
5320 // Introduce our parameters into the function scope
5321 for (unsigned p
= 0, NumParams
= FD
->getNumParams(); p
< NumParams
; ++p
) {
5322 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
5323 Param
->setOwningFunction(FD
);
5325 // If this has an identifier, add it to the scope stack.
5326 if (Param
->getIdentifier() && FnBodyScope
) {
5327 CheckShadow(FnBodyScope
, Param
);
5329 PushOnScopeChains(Param
, FnBodyScope
);
5333 // Checking attributes of current function definition
5334 // dllimport attribute.
5335 DLLImportAttr
*DA
= FD
->getAttr
<DLLImportAttr
>();
5336 if (DA
&& (!FD
->getAttr
<DLLExportAttr
>())) {
5337 // dllimport attribute cannot be directly applied to definition.
5338 if (!DA
->isInherited()) {
5339 Diag(FD
->getLocation(),
5340 diag::err_attribute_can_be_applied_only_to_symbol_declaration
)
5342 FD
->setInvalidDecl();
5346 // Visual C++ appears to not think this is an issue, so only issue
5347 // a warning when Microsoft extensions are disabled.
5348 if (!LangOpts
.Microsoft
) {
5349 // If a symbol previously declared dllimport is later defined, the
5350 // attribute is ignored in subsequent references, and a warning is
5352 Diag(FD
->getLocation(),
5353 diag::warn_redeclaration_without_attribute_prev_attribute_ignored
)
5354 << FD
->getName() << "dllimport";
5360 /// \brief Given the set of return statements within a function body,
5361 /// compute the variables that are subject to the named return value
5364 /// Each of the variables that is subject to the named return value
5365 /// optimization will be marked as NRVO variables in the AST, and any
5366 /// return statement that has a marked NRVO variable as its NRVO candidate can
5367 /// use the named return value optimization.
5369 /// This function applies a very simplistic algorithm for NRVO: if every return
5370 /// statement in the function has the same NRVO candidate, that candidate is
5371 /// the NRVO variable.
5373 /// FIXME: Employ a smarter algorithm that accounts for multiple return
5374 /// statements and the lifetimes of the NRVO candidates. We should be able to
5375 /// find a maximal set of NRVO variables.
5376 static void ComputeNRVO(Stmt
*Body
, FunctionScopeInfo
*Scope
) {
5377 ReturnStmt
**Returns
= Scope
->Returns
.data();
5379 const VarDecl
*NRVOCandidate
= 0;
5380 for (unsigned I
= 0, E
= Scope
->Returns
.size(); I
!= E
; ++I
) {
5381 if (!Returns
[I
]->getNRVOCandidate())
5385 NRVOCandidate
= Returns
[I
]->getNRVOCandidate();
5386 else if (NRVOCandidate
!= Returns
[I
]->getNRVOCandidate())
5391 const_cast<VarDecl
*>(NRVOCandidate
)->setNRVOVariable(true);
5394 Decl
*Sema::ActOnFinishFunctionBody(Decl
*D
, Stmt
*BodyArg
) {
5395 return ActOnFinishFunctionBody(D
, move(BodyArg
), false);
5398 Decl
*Sema::ActOnFinishFunctionBody(Decl
*dcl
, Stmt
*Body
,
5399 bool IsInstantiation
) {
5400 FunctionDecl
*FD
= 0;
5401 FunctionTemplateDecl
*FunTmpl
= dyn_cast_or_null
<FunctionTemplateDecl
>(dcl
);
5403 FD
= FunTmpl
->getTemplatedDecl();
5405 FD
= dyn_cast_or_null
<FunctionDecl
>(dcl
);
5407 sema::AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
5412 // C and C++ allow for main to automagically return 0.
5413 // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5414 FD
->setHasImplicitReturnZero(true);
5415 WP
.disableCheckFallThrough();
5418 if (!FD
->isInvalidDecl()) {
5419 DiagnoseUnusedParameters(FD
->param_begin(), FD
->param_end());
5420 DiagnoseSizeOfParametersAndReturnValue(FD
->param_begin(), FD
->param_end(),
5421 FD
->getResultType(), FD
);
5423 // If this is a constructor, we need a vtable.
5424 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(FD
))
5425 MarkVTableUsed(FD
->getLocation(), Constructor
->getParent());
5427 ComputeNRVO(Body
, getCurFunction());
5430 assert(FD
== getCurFunctionDecl() && "Function parsing confused");
5431 } else if (ObjCMethodDecl
*MD
= dyn_cast_or_null
<ObjCMethodDecl
>(dcl
)) {
5432 assert(MD
== getCurMethodDecl() && "Method parsing confused");
5435 MD
->setEndLoc(Body
->getLocEnd());
5436 if (!MD
->isInvalidDecl()) {
5437 DiagnoseUnusedParameters(MD
->param_begin(), MD
->param_end());
5438 DiagnoseSizeOfParametersAndReturnValue(MD
->param_begin(), MD
->param_end(),
5439 MD
->getResultType(), MD
);
5445 // Verify and clean out per-function state.
5447 // Check goto/label use.
5448 FunctionScopeInfo
*CurFn
= getCurFunction();
5449 for (llvm::DenseMap
<IdentifierInfo
*, LabelStmt
*>::iterator
5450 I
= CurFn
->LabelMap
.begin(), E
= CurFn
->LabelMap
.end(); I
!= E
; ++I
) {
5451 LabelStmt
*L
= I
->second
;
5453 // Verify that we have no forward references left. If so, there was a goto
5454 // or address of a label taken, but no definition of it. Label fwd
5455 // definitions are indicated with a null substmt.
5456 if (L
->getSubStmt() != 0) {
5458 Diag(L
->getIdentLoc(), diag::warn_unused_label
) << L
->getName();
5463 Diag(L
->getIdentLoc(), diag::err_undeclared_label_use
) << L
->getName();
5465 // At this point, we have gotos that use the bogus label. Stitch it into
5466 // the function body so that they aren't leaked and that the AST is well
5469 // The whole function wasn't parsed correctly.
5473 // Otherwise, the body is valid: we want to stitch the label decl into the
5474 // function somewhere so that it is properly owned and so that the goto
5475 // has a valid target. Do this by creating a new compound stmt with the
5478 // Give the label a sub-statement.
5479 L
->setSubStmt(new (Context
) NullStmt(L
->getIdentLoc()));
5481 CompoundStmt
*Compound
= isa
<CXXTryStmt
>(Body
) ?
5482 cast
<CXXTryStmt
>(Body
)->getTryBlock() :
5483 cast
<CompoundStmt
>(Body
);
5484 llvm::SmallVector
<Stmt
*, 64> Elements(Compound
->body_begin(),
5485 Compound
->body_end());
5486 Elements
.push_back(L
);
5487 Compound
->setStmts(Context
, Elements
.data(), Elements
.size());
5491 // C++ constructors that have function-try-blocks can't have return
5492 // statements in the handlers of that block. (C++ [except.handle]p14)
5494 if (FD
&& isa
<CXXConstructorDecl
>(FD
) && isa
<CXXTryStmt
>(Body
))
5495 DiagnoseReturnInConstructorExceptionHandler(cast
<CXXTryStmt
>(Body
));
5497 // Verify that that gotos and switch cases don't jump into scopes illegally.
5498 // Verify that that gotos and switch cases don't jump into scopes illegally.
5499 if (getCurFunction()->NeedsScopeChecking() &&
5500 !dcl
->isInvalidDecl() &&
5501 !hasAnyErrorsInThisFunction())
5502 DiagnoseInvalidJumps(Body
);
5504 if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(dcl
)) {
5505 if (!Destructor
->getParent()->isDependentType())
5506 CheckDestructor(Destructor
);
5508 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
5509 Destructor
->getParent());
5512 // If any errors have occurred, clear out any temporaries that may have
5513 // been leftover. This ensures that these temporaries won't be picked up for
5514 // deletion in some later function.
5515 if (PP
.getDiagnostics().hasErrorOccurred())
5516 ExprTemporaries
.clear();
5517 else if (!isa
<FunctionTemplateDecl
>(dcl
)) {
5518 // Since the body is valid, issue any analysis-based warnings that are
5520 QualType ResultType
;
5521 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(dcl
)) {
5522 AnalysisWarnings
.IssueWarnings(WP
, FD
);
5524 ObjCMethodDecl
*MD
= cast
<ObjCMethodDecl
>(dcl
);
5525 AnalysisWarnings
.IssueWarnings(WP
, MD
);
5529 assert(ExprTemporaries
.empty() && "Leftover temporaries in function");
5532 if (!IsInstantiation
)
5535 PopFunctionOrBlockScope();
5537 // If any errors have occurred, clear out any temporaries that may have
5538 // been leftover. This ensures that these temporaries won't be picked up for
5539 // deletion in some later function.
5540 if (getDiagnostics().hasErrorOccurred())
5541 ExprTemporaries
.clear();
5546 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
5547 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
5548 NamedDecl
*Sema::ImplicitlyDefineFunction(SourceLocation Loc
,
5549 IdentifierInfo
&II
, Scope
*S
) {
5550 // Before we produce a declaration for an implicitly defined
5551 // function, see whether there was a locally-scoped declaration of
5552 // this name as a function or variable. If so, use that
5553 // (non-visible) declaration, and complain about it.
5554 llvm::DenseMap
<DeclarationName
, NamedDecl
*>::iterator Pos
5555 = LocallyScopedExternalDecls
.find(&II
);
5556 if (Pos
!= LocallyScopedExternalDecls
.end()) {
5557 Diag(Loc
, diag::warn_use_out_of_scope_declaration
) << Pos
->second
;
5558 Diag(Pos
->second
->getLocation(), diag::note_previous_declaration
);
5562 // Extension in C99. Legal in C90, but warn about it.
5563 if (II
.getName().startswith("__builtin_"))
5564 Diag(Loc
, diag::warn_builtin_unknown
) << &II
;
5565 else if (getLangOptions().C99
)
5566 Diag(Loc
, diag::ext_implicit_function_decl
) << &II
;
5568 Diag(Loc
, diag::warn_implicit_function_decl
) << &II
;
5570 // Set a Declarator for the implicit definition: int foo();
5574 bool Error
= DS
.SetTypeSpecType(DeclSpec::TST_int
, Loc
, Dummy
, DiagID
);
5575 (void)Error
; // Silence warning.
5576 assert(!Error
&& "Error setting up implicit decl!");
5577 Declarator
D(DS
, Declarator::BlockContext
);
5578 D
.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(),
5579 false, false, SourceLocation(), 0,
5580 0, 0, true, SourceLocation(),
5581 false, SourceLocation(),
5582 false, 0,0,0, Loc
, Loc
, D
),
5584 D
.SetIdentifier(&II
, Loc
);
5586 // Insert this function into translation-unit scope.
5588 DeclContext
*PrevDC
= CurContext
;
5589 CurContext
= Context
.getTranslationUnitDecl();
5591 FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(ActOnDeclarator(TUScope
, D
));
5594 CurContext
= PrevDC
;
5596 AddKnownFunctionAttributes(FD
);
5601 /// \brief Adds any function attributes that we know a priori based on
5602 /// the declaration of this function.
5604 /// These attributes can apply both to implicitly-declared builtins
5605 /// (like __builtin___printf_chk) or to library-declared functions
5606 /// like NSLog or printf.
5607 void Sema::AddKnownFunctionAttributes(FunctionDecl
*FD
) {
5608 if (FD
->isInvalidDecl())
5611 // If this is a built-in function, map its builtin attributes to
5612 // actual attributes.
5613 if (unsigned BuiltinID
= FD
->getBuiltinID()) {
5614 // Handle printf-formatting attributes.
5617 if (Context
.BuiltinInfo
.isPrintfLike(BuiltinID
, FormatIdx
, HasVAListArg
)) {
5618 if (!FD
->getAttr
<FormatAttr
>())
5619 FD
->addAttr(::new (Context
) FormatAttr(FD
->getLocation(), Context
,
5620 "printf", FormatIdx
+1,
5621 HasVAListArg
? 0 : FormatIdx
+2));
5623 if (Context
.BuiltinInfo
.isScanfLike(BuiltinID
, FormatIdx
,
5625 if (!FD
->getAttr
<FormatAttr
>())
5626 FD
->addAttr(::new (Context
) FormatAttr(FD
->getLocation(), Context
,
5627 "scanf", FormatIdx
+1,
5628 HasVAListArg
? 0 : FormatIdx
+2));
5631 // Mark const if we don't care about errno and that is the only
5632 // thing preventing the function from being const. This allows
5633 // IRgen to use LLVM intrinsics for such functions.
5634 if (!getLangOptions().MathErrno
&&
5635 Context
.BuiltinInfo
.isConstWithoutErrno(BuiltinID
)) {
5636 if (!FD
->getAttr
<ConstAttr
>())
5637 FD
->addAttr(::new (Context
) ConstAttr(FD
->getLocation(), Context
));
5640 if (Context
.BuiltinInfo
.isNoThrow(BuiltinID
))
5641 FD
->addAttr(::new (Context
) NoThrowAttr(FD
->getLocation(), Context
));
5642 if (Context
.BuiltinInfo
.isConst(BuiltinID
))
5643 FD
->addAttr(::new (Context
) ConstAttr(FD
->getLocation(), Context
));
5646 IdentifierInfo
*Name
= FD
->getIdentifier();
5649 if ((!getLangOptions().CPlusPlus
&&
5650 FD
->getDeclContext()->isTranslationUnit()) ||
5651 (isa
<LinkageSpecDecl
>(FD
->getDeclContext()) &&
5652 cast
<LinkageSpecDecl
>(FD
->getDeclContext())->getLanguage() ==
5653 LinkageSpecDecl::lang_c
)) {
5654 // Okay: this could be a libc/libm/Objective-C function we know
5659 if (Name
->isStr("NSLog") || Name
->isStr("NSLogv")) {
5660 // FIXME: NSLog and NSLogv should be target specific
5661 if (const FormatAttr
*Format
= FD
->getAttr
<FormatAttr
>()) {
5662 // FIXME: We known better than our headers.
5663 const_cast<FormatAttr
*>(Format
)->setType(Context
, "printf");
5665 FD
->addAttr(::new (Context
) FormatAttr(FD
->getLocation(), Context
,
5667 Name
->isStr("NSLogv") ? 0 : 2));
5668 } else if (Name
->isStr("asprintf") || Name
->isStr("vasprintf")) {
5669 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
5670 // target-specific builtins, perhaps?
5671 if (!FD
->getAttr
<FormatAttr
>())
5672 FD
->addAttr(::new (Context
) FormatAttr(FD
->getLocation(), Context
,
5674 Name
->isStr("vasprintf") ? 0 : 3));
5678 TypedefDecl
*Sema::ParseTypedefDecl(Scope
*S
, Declarator
&D
, QualType T
,
5679 TypeSourceInfo
*TInfo
) {
5680 assert(D
.getIdentifier() && "Wrong callback for declspec without declarator");
5681 assert(!T
.isNull() && "GetTypeForDeclarator() returned null type");
5684 assert(D
.isInvalidType() && "no declarator info for valid type");
5685 TInfo
= Context
.getTrivialTypeSourceInfo(T
);
5688 // Scope manipulation handled by caller.
5689 TypedefDecl
*NewTD
= TypedefDecl::Create(Context
, CurContext
,
5690 D
.getIdentifierLoc(),
5694 if (const TagType
*TT
= T
->getAs
<TagType
>()) {
5695 TagDecl
*TD
= TT
->getDecl();
5697 // If the TagDecl that the TypedefDecl points to is an anonymous decl
5698 // keep track of the TypedefDecl.
5699 if (!TD
->getIdentifier() && !TD
->getTypedefForAnonDecl())
5700 TD
->setTypedefForAnonDecl(NewTD
);
5703 if (D
.isInvalidType())
5704 NewTD
->setInvalidDecl();
5709 /// \brief Determine whether a tag with a given kind is acceptable
5710 /// as a redeclaration of the given tag declaration.
5712 /// \returns true if the new tag kind is acceptable, false otherwise.
5713 bool Sema::isAcceptableTagRedeclaration(const TagDecl
*Previous
,
5715 SourceLocation NewTagLoc
,
5716 const IdentifierInfo
&Name
) {
5717 // C++ [dcl.type.elab]p3:
5718 // The class-key or enum keyword present in the
5719 // elaborated-type-specifier shall agree in kind with the
5720 // declaration to which the name in the elaborated-type-specifier
5721 // refers. This rule also applies to the form of
5722 // elaborated-type-specifier that declares a class-name or
5723 // friend class since it can be construed as referring to the
5724 // definition of the class. Thus, in any
5725 // elaborated-type-specifier, the enum keyword shall be used to
5726 // refer to an enumeration (7.2), the union class-key shall be
5727 // used to refer to a union (clause 9), and either the class or
5728 // struct class-key shall be used to refer to a class (clause 9)
5729 // declared using the class or struct class-key.
5730 TagTypeKind OldTag
= Previous
->getTagKind();
5731 if (OldTag
== NewTag
)
5734 if ((OldTag
== TTK_Struct
|| OldTag
== TTK_Class
) &&
5735 (NewTag
== TTK_Struct
|| NewTag
== TTK_Class
)) {
5736 // Warn about the struct/class tag mismatch.
5737 bool isTemplate
= false;
5738 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Previous
))
5739 isTemplate
= Record
->getDescribedClassTemplate();
5741 Diag(NewTagLoc
, diag::warn_struct_class_tag_mismatch
)
5742 << (NewTag
== TTK_Class
)
5743 << isTemplate
<< &Name
5744 << FixItHint::CreateReplacement(SourceRange(NewTagLoc
),
5745 OldTag
== TTK_Class
? "class" : "struct");
5746 Diag(Previous
->getLocation(), diag::note_previous_use
);
5752 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
5753 /// former case, Name will be non-null. In the later case, Name will be null.
5754 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
5755 /// reference/declaration/definition of a tag.
5756 Decl
*Sema::ActOnTag(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
,
5757 SourceLocation KWLoc
, CXXScopeSpec
&SS
,
5758 IdentifierInfo
*Name
, SourceLocation NameLoc
,
5759 AttributeList
*Attr
, AccessSpecifier AS
,
5760 MultiTemplateParamsArg TemplateParameterLists
,
5761 bool &OwnedDecl
, bool &IsDependent
,
5762 bool ScopedEnum
, bool ScopedEnumUsesClassTag
,
5763 TypeResult UnderlyingType
) {
5764 // If this is not a definition, it must have a name.
5765 assert((Name
!= 0 || TUK
== TUK_Definition
) &&
5766 "Nameless record must be a definition!");
5767 assert(TemplateParameterLists
.size() == 0 || TUK
!= TUK_Reference
);
5770 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
5772 // FIXME: Check explicit specializations more carefully.
5773 bool isExplicitSpecialization
= false;
5774 unsigned NumMatchedTemplateParamLists
= TemplateParameterLists
.size();
5775 bool Invalid
= false;
5777 // We only need to do this matching if we have template parameters
5778 // or a scope specifier, which also conveniently avoids this work
5779 // for non-C++ cases.
5780 if (NumMatchedTemplateParamLists
||
5781 (SS
.isNotEmpty() && TUK
!= TUK_Reference
)) {
5782 if (TemplateParameterList
*TemplateParams
5783 = MatchTemplateParametersToScopeSpecifier(KWLoc
, SS
,
5784 TemplateParameterLists
.get(),
5785 TemplateParameterLists
.size(),
5787 isExplicitSpecialization
,
5789 // All but one template parameter lists have been matching.
5790 --NumMatchedTemplateParamLists
;
5792 if (TemplateParams
->size() > 0) {
5793 // This is a declaration or definition of a class template (which may
5794 // be a member of another template).
5799 DeclResult Result
= CheckClassTemplate(S
, TagSpec
, TUK
, KWLoc
,
5800 SS
, Name
, NameLoc
, Attr
,
5803 TemplateParameterLists
.release();
5804 return Result
.get();
5806 // The "template<>" header is extraneous.
5807 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
5808 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
5809 isExplicitSpecialization
= true;
5814 // Figure out the underlying type if this a enum declaration. We need to do
5815 // this early, because it's needed to detect if this is an incompatible
5817 llvm::PointerUnion
<const Type
*, TypeSourceInfo
*> EnumUnderlying
;
5819 if (Kind
== TTK_Enum
) {
5820 if (UnderlyingType
.isInvalid() || (!UnderlyingType
.get() && ScopedEnum
))
5821 // No underlying type explicitly specified, or we failed to parse the
5822 // type, default to int.
5823 EnumUnderlying
= Context
.IntTy
.getTypePtr();
5824 else if (UnderlyingType
.get()) {
5825 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
5826 // integral type; any cv-qualification is ignored.
5827 TypeSourceInfo
*TI
= 0;
5828 QualType T
= GetTypeFromParser(UnderlyingType
.get(), &TI
);
5829 EnumUnderlying
= TI
;
5831 SourceLocation UnderlyingLoc
= TI
->getTypeLoc().getBeginLoc();
5833 if (!T
->isDependentType() && !T
->isIntegralType(Context
)) {
5834 Diag(UnderlyingLoc
, diag::err_enum_invalid_underlying
)
5836 // Recover by falling back to int.
5837 EnumUnderlying
= Context
.IntTy
.getTypePtr();
5840 if (DiagnoseUnexpandedParameterPack(UnderlyingLoc
, TI
,
5841 UPPC_FixedUnderlyingType
))
5842 EnumUnderlying
= Context
.IntTy
.getTypePtr();
5844 } else if (getLangOptions().Microsoft
)
5845 // Microsoft enums are always of int type.
5846 EnumUnderlying
= Context
.IntTy
.getTypePtr();
5849 DeclContext
*SearchDC
= CurContext
;
5850 DeclContext
*DC
= CurContext
;
5851 bool isStdBadAlloc
= false;
5853 RedeclarationKind Redecl
= ForRedeclaration
;
5854 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
)
5855 Redecl
= NotForRedeclaration
;
5857 LookupResult
Previous(*this, Name
, NameLoc
, LookupTagName
, Redecl
);
5859 if (Name
&& SS
.isNotEmpty()) {
5860 // We have a nested-name tag ('struct foo::bar').
5862 // Check for invalid 'foo::'.
5863 if (SS
.isInvalid()) {
5868 // If this is a friend or a reference to a class in a dependent
5869 // context, don't try to make a decl for it.
5870 if (TUK
== TUK_Friend
|| TUK
== TUK_Reference
) {
5871 DC
= computeDeclContext(SS
, false);
5877 DC
= computeDeclContext(SS
, true);
5879 Diag(SS
.getRange().getBegin(), diag::err_dependent_nested_name_spec
)
5885 if (RequireCompleteDeclContext(SS
, DC
))
5889 // Look-up name inside 'foo::'.
5890 LookupQualifiedName(Previous
, DC
);
5892 if (Previous
.isAmbiguous())
5895 if (Previous
.empty()) {
5896 // Name lookup did not find anything. However, if the
5897 // nested-name-specifier refers to the current instantiation,
5898 // and that current instantiation has any dependent base
5899 // classes, we might find something at instantiation time: treat
5900 // this as a dependent elaborated-type-specifier.
5901 // But this only makes any sense for reference-like lookups.
5902 if (Previous
.wasNotFoundInCurrentInstantiation() &&
5903 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)) {
5908 // A tag 'foo::bar' must already exist.
5909 Diag(NameLoc
, diag::err_not_tag_in_scope
)
5910 << Kind
<< Name
<< DC
<< SS
.getRange();
5916 // If this is a named struct, check to see if there was a previous forward
5917 // declaration or definition.
5918 // FIXME: We're looking into outer scopes here, even when we
5919 // shouldn't be. Doing so can result in ambiguities that we
5920 // shouldn't be diagnosing.
5921 LookupName(Previous
, S
);
5923 // Note: there used to be some attempt at recovery here.
5924 if (Previous
.isAmbiguous())
5927 if (!getLangOptions().CPlusPlus
&& TUK
!= TUK_Reference
) {
5928 // FIXME: This makes sure that we ignore the contexts associated
5929 // with C structs, unions, and enums when looking for a matching
5930 // tag declaration or definition. See the similar lookup tweak
5931 // in Sema::LookupName; is there a better way to deal with this?
5932 while (isa
<RecordDecl
>(SearchDC
) || isa
<EnumDecl
>(SearchDC
))
5933 SearchDC
= SearchDC
->getParent();
5935 } else if (S
->isFunctionPrototypeScope()) {
5936 // If this is an enum declaration in function prototype scope, set its
5937 // initial context to the translation unit.
5938 SearchDC
= Context
.getTranslationUnitDecl();
5941 if (Previous
.isSingleResult() &&
5942 Previous
.getFoundDecl()->isTemplateParameter()) {
5943 // Maybe we will complain about the shadowed template parameter.
5944 DiagnoseTemplateParameterShadow(NameLoc
, Previous
.getFoundDecl());
5945 // Just pretend that we didn't see the previous declaration.
5949 if (getLangOptions().CPlusPlus
&& Name
&& DC
&& StdNamespace
&&
5950 DC
->Equals(getStdNamespace()) && Name
->isStr("bad_alloc")) {
5951 // This is a declaration of or a reference to "std::bad_alloc".
5952 isStdBadAlloc
= true;
5954 if (Previous
.empty() && StdBadAlloc
) {
5955 // std::bad_alloc has been implicitly declared (but made invisible to
5956 // name lookup). Fill in this implicit declaration as the previous
5957 // declaration, so that the declarations get chained appropriately.
5958 Previous
.addDecl(getStdBadAlloc());
5962 // If we didn't find a previous declaration, and this is a reference
5963 // (or friend reference), move to the correct scope. In C++, we
5964 // also need to do a redeclaration lookup there, just in case
5965 // there's a shadow friend decl.
5966 if (Name
&& Previous
.empty() &&
5967 (TUK
== TUK_Reference
|| TUK
== TUK_Friend
)) {
5968 if (Invalid
) goto CreateNewDecl
;
5969 assert(SS
.isEmpty());
5971 if (TUK
== TUK_Reference
) {
5972 // C++ [basic.scope.pdecl]p5:
5973 // -- for an elaborated-type-specifier of the form
5975 // class-key identifier
5977 // if the elaborated-type-specifier is used in the
5978 // decl-specifier-seq or parameter-declaration-clause of a
5979 // function defined in namespace scope, the identifier is
5980 // declared as a class-name in the namespace that contains
5981 // the declaration; otherwise, except as a friend
5982 // declaration, the identifier is declared in the smallest
5983 // non-class, non-function-prototype scope that contains the
5986 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
5987 // C structs and unions.
5989 // It is an error in C++ to declare (rather than define) an enum
5990 // type, including via an elaborated type specifier. We'll
5991 // diagnose that later; for now, declare the enum in the same
5992 // scope as we would have picked for any other tag type.
5994 // GNU C also supports this behavior as part of its incomplete
5995 // enum types extension, while GNU C++ does not.
5997 // Find the context where we'll be declaring the tag.
5998 // FIXME: We would like to maintain the current DeclContext as the
6000 while (SearchDC
->isRecord() || SearchDC
->isTransparentContext())
6001 SearchDC
= SearchDC
->getParent();
6003 // Find the scope where we'll be declaring the tag.
6004 while (S
->isClassScope() ||
6005 (getLangOptions().CPlusPlus
&&
6006 S
->isFunctionPrototypeScope()) ||
6007 ((S
->getFlags() & Scope::DeclScope
) == 0) ||
6009 ((DeclContext
*)S
->getEntity())->isTransparentContext()))
6012 assert(TUK
== TUK_Friend
);
6013 // C++ [namespace.memdef]p3:
6014 // If a friend declaration in a non-local class first declares a
6015 // class or function, the friend class or function is a member of
6016 // the innermost enclosing namespace.
6017 SearchDC
= SearchDC
->getEnclosingNamespaceContext();
6020 // In C++, we need to do a redeclaration lookup to properly
6021 // diagnose some problems.
6022 if (getLangOptions().CPlusPlus
) {
6023 Previous
.setRedeclarationKind(ForRedeclaration
);
6024 LookupQualifiedName(Previous
, SearchDC
);
6028 if (!Previous
.empty()) {
6029 NamedDecl
*PrevDecl
= (*Previous
.begin())->getUnderlyingDecl();
6031 // It's okay to have a tag decl in the same scope as a typedef
6032 // which hides a tag decl in the same scope. Finding this
6033 // insanity with a redeclaration lookup can only actually happen
6036 // This is also okay for elaborated-type-specifiers, which is
6037 // technically forbidden by the current standard but which is
6038 // okay according to the likely resolution of an open issue;
6039 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
6040 if (getLangOptions().CPlusPlus
) {
6041 if (TypedefDecl
*TD
= dyn_cast
<TypedefDecl
>(PrevDecl
)) {
6042 if (const TagType
*TT
= TD
->getUnderlyingType()->getAs
<TagType
>()) {
6043 TagDecl
*Tag
= TT
->getDecl();
6044 if (Tag
->getDeclName() == Name
&&
6045 Tag
->getDeclContext()->getRedeclContext()
6046 ->Equals(TD
->getDeclContext()->getRedeclContext())) {
6049 Previous
.addDecl(Tag
);
6050 Previous
.resolveKind();
6056 if (TagDecl
*PrevTagDecl
= dyn_cast
<TagDecl
>(PrevDecl
)) {
6057 // If this is a use of a previous tag, or if the tag is already declared
6058 // in the same scope (so that the definition/declaration completes or
6059 // rementions the tag), reuse the decl.
6060 if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
||
6061 isDeclInScope(PrevDecl
, SearchDC
, S
)) {
6062 // Make sure that this wasn't declared as an enum and now used as a
6063 // struct or something similar.
6064 if (!isAcceptableTagRedeclaration(PrevTagDecl
, Kind
, KWLoc
, *Name
)) {
6066 = (PrevTagDecl
->getTagKind() != TTK_Enum
&&
6069 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
6071 << FixItHint::CreateReplacement(SourceRange(KWLoc
),
6072 PrevTagDecl
->getKindName());
6074 Diag(KWLoc
, diag::err_use_with_wrong_tag
) << Name
;
6075 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
6078 Kind
= PrevTagDecl
->getTagKind();
6080 // Recover by making this an anonymous redefinition.
6087 if (Kind
== TTK_Enum
&& PrevTagDecl
->getTagKind() == TTK_Enum
) {
6088 const EnumDecl
*PrevEnum
= cast
<EnumDecl
>(PrevTagDecl
);
6090 // All conflicts with previous declarations are recovered by
6091 // returning the previous declaration.
6092 if (ScopedEnum
!= PrevEnum
->isScoped()) {
6093 Diag(KWLoc
, diag::err_enum_redeclare_scoped_mismatch
)
6094 << PrevEnum
->isScoped();
6095 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
6098 else if (EnumUnderlying
&& PrevEnum
->isFixed()) {
6100 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
6103 T
= QualType(EnumUnderlying
.get
<const Type
*>(), 0);
6105 if (!Context
.hasSameUnqualifiedType(T
, PrevEnum
->getIntegerType())) {
6106 Diag(NameLoc
.isValid() ? NameLoc
: KWLoc
,
6107 diag::err_enum_redeclare_type_mismatch
)
6109 << PrevEnum
->getIntegerType();
6110 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
6114 else if (!EnumUnderlying
.isNull() != PrevEnum
->isFixed()) {
6115 Diag(KWLoc
, diag::err_enum_redeclare_fixed_mismatch
)
6116 << PrevEnum
->isFixed();
6117 Diag(PrevTagDecl
->getLocation(), diag::note_previous_use
);
6123 // If this is a use, just return the declaration we found.
6125 // FIXME: In the future, return a variant or some other clue
6126 // for the consumer of this Decl to know it doesn't own it.
6127 // For our current ASTs this shouldn't be a problem, but will
6128 // need to be changed with DeclGroups.
6129 if ((TUK
== TUK_Reference
&& !PrevTagDecl
->getFriendObjectKind()) ||
6133 // Diagnose attempts to redefine a tag.
6134 if (TUK
== TUK_Definition
) {
6135 if (TagDecl
*Def
= PrevTagDecl
->getDefinition()) {
6136 // If we're defining a specialization and the previous definition
6137 // is from an implicit instantiation, don't emit an error
6138 // here; we'll catch this in the general case below.
6139 if (!isExplicitSpecialization
||
6140 !isa
<CXXRecordDecl
>(Def
) ||
6141 cast
<CXXRecordDecl
>(Def
)->getTemplateSpecializationKind()
6142 == TSK_ExplicitSpecialization
) {
6143 Diag(NameLoc
, diag::err_redefinition
) << Name
;
6144 Diag(Def
->getLocation(), diag::note_previous_definition
);
6145 // If this is a redefinition, recover by making this
6146 // struct be anonymous, which will make any later
6147 // references get the previous definition.
6153 // If the type is currently being defined, complain
6154 // about a nested redefinition.
6156 = cast
<TagType
>(Context
.getTagDeclType(PrevTagDecl
));
6157 if (Tag
->isBeingDefined()) {
6158 Diag(NameLoc
, diag::err_nested_redefinition
) << Name
;
6159 Diag(PrevTagDecl
->getLocation(),
6160 diag::note_previous_definition
);
6167 // Okay, this is definition of a previously declared or referenced
6168 // tag PrevDecl. We're going to create a new Decl for it.
6171 // If we get here we have (another) forward declaration or we
6172 // have a definition. Just create a new decl.
6175 // If we get here, this is a definition of a new tag type in a nested
6176 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
6177 // new decl/type. We set PrevDecl to NULL so that the entities
6178 // have distinct types.
6181 // If we get here, we're going to create a new Decl. If PrevDecl
6182 // is non-NULL, it's a definition of the tag declared by
6183 // PrevDecl. If it's NULL, we have a new definition.
6186 // Otherwise, PrevDecl is not a tag, but was found with tag
6187 // lookup. This is only actually possible in C++, where a few
6188 // things like templates still live in the tag namespace.
6190 assert(getLangOptions().CPlusPlus
);
6192 // Use a better diagnostic if an elaborated-type-specifier
6193 // found the wrong kind of type on the first
6194 // (non-redeclaration) lookup.
6195 if ((TUK
== TUK_Reference
|| TUK
== TUK_Friend
) &&
6196 !Previous
.isForRedeclaration()) {
6198 if (isa
<TypedefDecl
>(PrevDecl
)) Kind
= 1;
6199 else if (isa
<ClassTemplateDecl
>(PrevDecl
)) Kind
= 2;
6200 Diag(NameLoc
, diag::err_tag_reference_non_tag
) << Kind
;
6201 Diag(PrevDecl
->getLocation(), diag::note_declared_at
);
6204 // Otherwise, only diagnose if the declaration is in scope.
6205 } else if (!isDeclInScope(PrevDecl
, SearchDC
, S
)) {
6208 // Diagnose implicit declarations introduced by elaborated types.
6209 } else if (TUK
== TUK_Reference
|| TUK
== TUK_Friend
) {
6211 if (isa
<TypedefDecl
>(PrevDecl
)) Kind
= 1;
6212 else if (isa
<ClassTemplateDecl
>(PrevDecl
)) Kind
= 2;
6213 Diag(NameLoc
, diag::err_tag_reference_conflict
) << Kind
;
6214 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
6217 // Otherwise it's a declaration. Call out a particularly common
6219 } else if (isa
<TypedefDecl
>(PrevDecl
)) {
6220 Diag(NameLoc
, diag::err_tag_definition_of_typedef
)
6222 << cast
<TypedefDecl
>(PrevDecl
)->getUnderlyingType();
6223 Diag(PrevDecl
->getLocation(), diag::note_previous_decl
) << PrevDecl
;
6226 // Otherwise, diagnose.
6228 // The tag name clashes with something else in the target scope,
6229 // issue an error and recover by making this tag be anonymous.
6230 Diag(NameLoc
, diag::err_redefinition_different_kind
) << Name
;
6231 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
6236 // The existing declaration isn't relevant to us; we're in a
6237 // new scope, so clear out the previous declaration.
6244 TagDecl
*PrevDecl
= 0;
6245 if (Previous
.isSingleResult())
6246 PrevDecl
= cast
<TagDecl
>(Previous
.getFoundDecl());
6248 // If there is an identifier, use the location of the identifier as the
6249 // location of the decl, otherwise use the location of the struct/union
6251 SourceLocation Loc
= NameLoc
.isValid() ? NameLoc
: KWLoc
;
6253 // Otherwise, create a new declaration. If there is a previous
6254 // declaration of the same entity, the two will be linked via
6258 bool IsForwardReference
= false;
6259 if (Kind
== TTK_Enum
) {
6260 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6261 // enum X { A, B, C } D; D should chain to X.
6262 New
= EnumDecl::Create(Context
, SearchDC
, Loc
, Name
, KWLoc
,
6263 cast_or_null
<EnumDecl
>(PrevDecl
), ScopedEnum
,
6264 ScopedEnumUsesClassTag
, !EnumUnderlying
.isNull());
6265 // If this is an undefined enum, warn.
6266 if (TUK
!= TUK_Definition
&& !Invalid
) {
6268 if (getLangOptions().CPlusPlus0x
&& cast
<EnumDecl
>(New
)->isFixed()) {
6269 // C++0x: 7.2p2: opaque-enum-declaration.
6270 // Conflicts are diagnosed above. Do nothing.
6272 else if (PrevDecl
&& (Def
= cast
<EnumDecl
>(PrevDecl
)->getDefinition())) {
6273 Diag(Loc
, diag::ext_forward_ref_enum_def
)
6275 Diag(Def
->getLocation(), diag::note_previous_definition
);
6277 unsigned DiagID
= diag::ext_forward_ref_enum
;
6278 if (getLangOptions().Microsoft
)
6279 DiagID
= diag::ext_ms_forward_ref_enum
;
6280 else if (getLangOptions().CPlusPlus
)
6281 DiagID
= diag::err_forward_ref_enum
;
6284 // If this is a forward-declared reference to an enumeration, make a
6285 // note of it; we won't actually be introducing the declaration into
6286 // the declaration context.
6287 if (TUK
== TUK_Reference
)
6288 IsForwardReference
= true;
6292 if (EnumUnderlying
) {
6293 EnumDecl
*ED
= cast
<EnumDecl
>(New
);
6294 if (TypeSourceInfo
*TI
= EnumUnderlying
.dyn_cast
<TypeSourceInfo
*>())
6295 ED
->setIntegerTypeSourceInfo(TI
);
6297 ED
->setIntegerType(QualType(EnumUnderlying
.get
<const Type
*>(), 0));
6298 ED
->setPromotionType(ED
->getIntegerType());
6302 // struct/union/class
6304 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
6305 // struct X { int A; } D; D should chain to X.
6306 if (getLangOptions().CPlusPlus
) {
6307 // FIXME: Look for a way to use RecordDecl for simple structs.
6308 New
= CXXRecordDecl::Create(Context
, Kind
, SearchDC
, Loc
, Name
, KWLoc
,
6309 cast_or_null
<CXXRecordDecl
>(PrevDecl
));
6311 if (isStdBadAlloc
&& (!StdBadAlloc
|| getStdBadAlloc()->isImplicit()))
6312 StdBadAlloc
= cast
<CXXRecordDecl
>(New
);
6314 New
= RecordDecl::Create(Context
, Kind
, SearchDC
, Loc
, Name
, KWLoc
,
6315 cast_or_null
<RecordDecl
>(PrevDecl
));
6318 // Maybe add qualifier info.
6319 if (SS
.isNotEmpty()) {
6321 NestedNameSpecifier
*NNS
6322 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
6323 New
->setQualifierInfo(NNS
, SS
.getRange());
6324 if (NumMatchedTemplateParamLists
> 0) {
6325 New
->setTemplateParameterListsInfo(Context
,
6326 NumMatchedTemplateParamLists
,
6327 (TemplateParameterList
**) TemplateParameterLists
.release());
6334 if (RecordDecl
*RD
= dyn_cast
<RecordDecl
>(New
)) {
6335 // Add alignment attributes if necessary; these attributes are checked when
6336 // the ASTContext lays out the structure.
6338 // It is important for implementing the correct semantics that this
6339 // happen here (in act on tag decl). The #pragma pack stack is
6340 // maintained as a result of parser callbacks which can occur at
6341 // many points during the parsing of a struct declaration (because
6342 // the #pragma tokens are effectively skipped over during the
6343 // parsing of the struct).
6344 AddAlignmentAttributesForRecord(RD
);
6347 // If this is a specialization of a member class (of a class template),
6348 // check the specialization.
6349 if (isExplicitSpecialization
&& CheckMemberSpecialization(New
, Previous
))
6353 New
->setInvalidDecl();
6356 ProcessDeclAttributeList(S
, New
, Attr
);
6358 // If we're declaring or defining a tag in function prototype scope
6359 // in C, note that this type can only be used within the function.
6360 if (Name
&& S
->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus
)
6361 Diag(Loc
, diag::warn_decl_in_param_list
) << Context
.getTagDeclType(New
);
6363 // Set the lexical context. If the tag has a C++ scope specifier, the
6364 // lexical context will be different from the semantic context.
6365 New
->setLexicalDeclContext(CurContext
);
6367 // Mark this as a friend decl if applicable.
6368 if (TUK
== TUK_Friend
)
6369 New
->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous
.empty());
6371 // Set the access specifier.
6372 if (!Invalid
&& SearchDC
->isRecord())
6373 SetMemberAccessSpecifier(New
, PrevDecl
, AS
);
6375 if (TUK
== TUK_Definition
)
6376 New
->startDefinition();
6378 // If this has an identifier, add it to the scope stack.
6379 if (TUK
== TUK_Friend
) {
6380 // We might be replacing an existing declaration in the lookup tables;
6381 // if so, borrow its access specifier.
6383 New
->setAccess(PrevDecl
->getAccess());
6385 DeclContext
*DC
= New
->getDeclContext()->getRedeclContext();
6386 DC
->makeDeclVisibleInContext(New
, /* Recoverable = */ false);
6387 if (Name
) // can be null along some error paths
6388 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
6389 PushOnScopeChains(New
, EnclosingScope
, /* AddToContext = */ false);
6391 S
= getNonFieldDeclScope(S
);
6392 PushOnScopeChains(New
, S
, !IsForwardReference
);
6393 if (IsForwardReference
)
6394 SearchDC
->makeDeclVisibleInContext(New
, /* Recoverable = */ false);
6397 CurContext
->addDecl(New
);
6400 // If this is the C FILE type, notify the AST context.
6401 if (IdentifierInfo
*II
= New
->getIdentifier())
6402 if (!New
->isInvalidDecl() &&
6403 New
->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6405 Context
.setFILEDecl(New
);
6411 void Sema::ActOnTagStartDefinition(Scope
*S
, Decl
*TagD
) {
6412 AdjustDeclIfTemplate(TagD
);
6413 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
6415 // Enter the tag context.
6416 PushDeclContext(S
, Tag
);
6419 void Sema::ActOnStartCXXMemberDeclarations(Scope
*S
, Decl
*TagD
,
6420 ClassVirtSpecifiers
&CVS
,
6421 SourceLocation LBraceLoc
) {
6422 AdjustDeclIfTemplate(TagD
);
6423 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(TagD
);
6425 FieldCollector
->StartClass();
6427 if (!Record
->getIdentifier())
6430 if (CVS
.isFinalSpecified())
6431 Record
->addAttr(new (Context
) FinalAttr(CVS
.getFinalLoc(), Context
));
6432 if (CVS
.isExplicitSpecified())
6433 Record
->addAttr(new (Context
) ExplicitAttr(CVS
.getExplicitLoc(), Context
));
6436 // [...] The class-name is also inserted into the scope of the
6437 // class itself; this is known as the injected-class-name. For
6438 // purposes of access checking, the injected-class-name is treated
6439 // as if it were a public member name.
6440 CXXRecordDecl
*InjectedClassName
6441 = CXXRecordDecl::Create(Context
, Record
->getTagKind(),
6442 CurContext
, Record
->getLocation(),
6443 Record
->getIdentifier(),
6444 Record
->getTagKeywordLoc(),
6446 /*DelayTypeCreation=*/true);
6447 Context
.getTypeDeclType(InjectedClassName
, Record
);
6448 InjectedClassName
->setImplicit();
6449 InjectedClassName
->setAccess(AS_public
);
6450 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate())
6451 InjectedClassName
->setDescribedClassTemplate(Template
);
6452 PushOnScopeChains(InjectedClassName
, S
);
6453 assert(InjectedClassName
->isInjectedClassName() &&
6454 "Broken injected-class-name");
6457 void Sema::ActOnTagFinishDefinition(Scope
*S
, Decl
*TagD
,
6458 SourceLocation RBraceLoc
) {
6459 AdjustDeclIfTemplate(TagD
);
6460 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
6461 Tag
->setRBraceLoc(RBraceLoc
);
6463 if (isa
<CXXRecordDecl
>(Tag
))
6464 FieldCollector
->FinishClass();
6466 // Exit this scope of this tag's definition.
6469 // Notify the consumer that we've defined a tag.
6470 Consumer
.HandleTagDeclDefinition(Tag
);
6473 void Sema::ActOnTagDefinitionError(Scope
*S
, Decl
*TagD
) {
6474 AdjustDeclIfTemplate(TagD
);
6475 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
6476 Tag
->setInvalidDecl();
6478 // We're undoing ActOnTagStartDefinition here, not
6479 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
6480 // the FieldCollector.
6485 // Note that FieldName may be null for anonymous bitfields.
6486 bool Sema::VerifyBitField(SourceLocation FieldLoc
, IdentifierInfo
*FieldName
,
6487 QualType FieldTy
, const Expr
*BitWidth
,
6489 // Default to true; that shouldn't confuse checks for emptiness
6493 // C99 6.7.2.1p4 - verify the field type.
6494 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
6495 if (!FieldTy
->isDependentType() && !FieldTy
->isIntegralOrEnumerationType()) {
6496 // Handle incomplete types with specific error.
6497 if (RequireCompleteType(FieldLoc
, FieldTy
, diag::err_field_incomplete
))
6500 return Diag(FieldLoc
, diag::err_not_integral_type_bitfield
)
6501 << FieldName
<< FieldTy
<< BitWidth
->getSourceRange();
6502 return Diag(FieldLoc
, diag::err_not_integral_type_anon_bitfield
)
6503 << FieldTy
<< BitWidth
->getSourceRange();
6504 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr
*>(BitWidth
),
6505 UPPC_BitFieldWidth
))
6508 // If the bit-width is type- or value-dependent, don't try to check
6510 if (BitWidth
->isValueDependent() || BitWidth
->isTypeDependent())
6514 if (VerifyIntegerConstantExpression(BitWidth
, &Value
))
6517 if (Value
!= 0 && ZeroWidth
)
6520 // Zero-width bitfield is ok for anonymous field.
6521 if (Value
== 0 && FieldName
)
6522 return Diag(FieldLoc
, diag::err_bitfield_has_zero_width
) << FieldName
;
6524 if (Value
.isSigned() && Value
.isNegative()) {
6526 return Diag(FieldLoc
, diag::err_bitfield_has_negative_width
)
6527 << FieldName
<< Value
.toString(10);
6528 return Diag(FieldLoc
, diag::err_anon_bitfield_has_negative_width
)
6529 << Value
.toString(10);
6532 if (!FieldTy
->isDependentType()) {
6533 uint64_t TypeSize
= Context
.getTypeSize(FieldTy
);
6534 if (Value
.getZExtValue() > TypeSize
) {
6535 if (!getLangOptions().CPlusPlus
) {
6537 return Diag(FieldLoc
, diag::err_bitfield_width_exceeds_type_size
)
6538 << FieldName
<< (unsigned)Value
.getZExtValue()
6539 << (unsigned)TypeSize
;
6541 return Diag(FieldLoc
, diag::err_anon_bitfield_width_exceeds_type_size
)
6542 << (unsigned)Value
.getZExtValue() << (unsigned)TypeSize
;
6546 Diag(FieldLoc
, diag::warn_bitfield_width_exceeds_type_size
)
6547 << FieldName
<< (unsigned)Value
.getZExtValue()
6548 << (unsigned)TypeSize
;
6550 Diag(FieldLoc
, diag::warn_anon_bitfield_width_exceeds_type_size
)
6551 << (unsigned)Value
.getZExtValue() << (unsigned)TypeSize
;
6558 /// ActOnField - Each field of a struct/union/class is passed into this in order
6559 /// to create a FieldDecl object for it.
6560 Decl
*Sema::ActOnField(Scope
*S
, Decl
*TagD
,
6561 SourceLocation DeclStart
,
6562 Declarator
&D
, ExprTy
*BitfieldWidth
) {
6563 FieldDecl
*Res
= HandleField(S
, cast_or_null
<RecordDecl
>(TagD
),
6564 DeclStart
, D
, static_cast<Expr
*>(BitfieldWidth
),
6569 /// HandleField - Analyze a field of a C struct or a C++ data member.
6571 FieldDecl
*Sema::HandleField(Scope
*S
, RecordDecl
*Record
,
6572 SourceLocation DeclStart
,
6573 Declarator
&D
, Expr
*BitWidth
,
6574 AccessSpecifier AS
) {
6575 IdentifierInfo
*II
= D
.getIdentifier();
6576 SourceLocation Loc
= DeclStart
;
6577 if (II
) Loc
= D
.getIdentifierLoc();
6579 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6580 QualType T
= TInfo
->getType();
6581 if (getLangOptions().CPlusPlus
) {
6582 CheckExtraCXXDefaultArguments(D
);
6584 if (DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
6585 UPPC_DataMemberType
)) {
6588 TInfo
= Context
.getTrivialTypeSourceInfo(T
, Loc
);
6592 DiagnoseFunctionSpecifiers(D
);
6594 if (D
.getDeclSpec().isThreadSpecified())
6595 Diag(D
.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread
);
6597 // Check to see if this name was declared as a member previously
6598 LookupResult
Previous(*this, II
, Loc
, LookupMemberName
, ForRedeclaration
);
6599 LookupName(Previous
, S
);
6600 assert((Previous
.empty() || Previous
.isOverloadedResult() ||
6601 Previous
.isSingleResult())
6602 && "Lookup of member name should be either overloaded, single or null");
6604 // If the name is overloaded then get any declaration else get the single result
6605 NamedDecl
*PrevDecl
= Previous
.isOverloadedResult() ?
6606 Previous
.getRepresentativeDecl() : Previous
.getAsSingle
<NamedDecl
>();
6608 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
6609 // Maybe we will complain about the shadowed template parameter.
6610 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
6611 // Just pretend that we didn't see the previous declaration.
6615 if (PrevDecl
&& !isDeclInScope(PrevDecl
, Record
, S
))
6619 = (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable
);
6620 SourceLocation TSSL
= D
.getSourceRange().getBegin();
6622 = CheckFieldDecl(II
, T
, TInfo
, Record
, Loc
, Mutable
, BitWidth
, TSSL
,
6625 if (NewFD
->isInvalidDecl())
6626 Record
->setInvalidDecl();
6628 if (NewFD
->isInvalidDecl() && PrevDecl
) {
6629 // Don't introduce NewFD into scope; there's already something
6630 // with the same name in the same scope.
6632 PushOnScopeChains(NewFD
, S
);
6634 Record
->addDecl(NewFD
);
6639 /// \brief Build a new FieldDecl and check its well-formedness.
6641 /// This routine builds a new FieldDecl given the fields name, type,
6642 /// record, etc. \p PrevDecl should refer to any previous declaration
6643 /// with the same name and in the same scope as the field to be
6646 /// \returns a new FieldDecl.
6648 /// \todo The Declarator argument is a hack. It will be removed once
6649 FieldDecl
*Sema::CheckFieldDecl(DeclarationName Name
, QualType T
,
6650 TypeSourceInfo
*TInfo
,
6651 RecordDecl
*Record
, SourceLocation Loc
,
6652 bool Mutable
, Expr
*BitWidth
,
6653 SourceLocation TSSL
,
6654 AccessSpecifier AS
, NamedDecl
*PrevDecl
,
6656 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
6657 bool InvalidDecl
= false;
6658 if (D
) InvalidDecl
= D
->isInvalidType();
6660 // If we receive a broken type, recover by assuming 'int' and
6661 // marking this declaration as invalid.
6667 QualType EltTy
= Context
.getBaseElementType(T
);
6668 if (!EltTy
->isDependentType() &&
6669 RequireCompleteType(Loc
, EltTy
, diag::err_field_incomplete
)) {
6670 // Fields of incomplete type force their record to be invalid.
6671 Record
->setInvalidDecl();
6675 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6676 // than a variably modified type.
6677 if (!InvalidDecl
&& T
->isVariablyModifiedType()) {
6678 bool SizeIsNegative
;
6679 llvm::APSInt Oversized
;
6680 QualType FixedTy
= TryToFixInvalidVariablyModifiedType(T
, Context
,
6683 if (!FixedTy
.isNull()) {
6684 Diag(Loc
, diag::warn_illegal_constant_array_size
);
6688 Diag(Loc
, diag::err_typecheck_negative_array_size
);
6689 else if (Oversized
.getBoolValue())
6690 Diag(Loc
, diag::err_array_too_large
)
6691 << Oversized
.toString(10);
6693 Diag(Loc
, diag::err_typecheck_field_variable_size
);
6698 // Fields can not have abstract class types
6699 if (!InvalidDecl
&& RequireNonAbstractType(Loc
, T
,
6700 diag::err_abstract_type_in_decl
,
6704 bool ZeroWidth
= false;
6705 // If this is declared as a bit-field, check the bit-field.
6706 if (!InvalidDecl
&& BitWidth
&&
6707 VerifyBitField(Loc
, II
, T
, BitWidth
, &ZeroWidth
)) {
6713 // Check that 'mutable' is consistent with the type of the declaration.
6714 if (!InvalidDecl
&& Mutable
) {
6715 unsigned DiagID
= 0;
6716 if (T
->isReferenceType())
6717 DiagID
= diag::err_mutable_reference
;
6718 else if (T
.isConstQualified())
6719 DiagID
= diag::err_mutable_const
;
6722 SourceLocation ErrLoc
= Loc
;
6723 if (D
&& D
->getDeclSpec().getStorageClassSpecLoc().isValid())
6724 ErrLoc
= D
->getDeclSpec().getStorageClassSpecLoc();
6725 Diag(ErrLoc
, DiagID
);
6731 FieldDecl
*NewFD
= FieldDecl::Create(Context
, Record
, Loc
, II
, T
, TInfo
,
6734 NewFD
->setInvalidDecl();
6736 if (PrevDecl
&& !isa
<TagDecl
>(PrevDecl
)) {
6737 Diag(Loc
, diag::err_duplicate_member
) << II
;
6738 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
6739 NewFD
->setInvalidDecl();
6742 if (!InvalidDecl
&& getLangOptions().CPlusPlus
) {
6743 if (Record
->isUnion()) {
6744 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
6745 CXXRecordDecl
* RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
6746 if (RDecl
->getDefinition()) {
6747 // C++ [class.union]p1: An object of a class with a non-trivial
6748 // constructor, a non-trivial copy constructor, a non-trivial
6749 // destructor, or a non-trivial copy assignment operator
6750 // cannot be a member of a union, nor can an array of such
6752 // TODO: C++0x alters this restriction significantly.
6753 if (CheckNontrivialField(NewFD
))
6754 NewFD
->setInvalidDecl();
6758 // C++ [class.union]p1: If a union contains a member of reference type,
6759 // the program is ill-formed.
6760 if (EltTy
->isReferenceType()) {
6761 Diag(NewFD
->getLocation(), diag::err_union_member_of_reference_type
)
6762 << NewFD
->getDeclName() << EltTy
;
6763 NewFD
->setInvalidDecl();
6768 // FIXME: We need to pass in the attributes given an AST
6769 // representation, not a parser representation.
6771 // FIXME: What to pass instead of TUScope?
6772 ProcessDeclAttributes(TUScope
, NewFD
, *D
);
6774 if (T
.isObjCGCWeak())
6775 Diag(Loc
, diag::warn_attribute_weak_on_field
);
6777 NewFD
->setAccess(AS
);
6781 bool Sema::CheckNontrivialField(FieldDecl
*FD
) {
6783 assert(getLangOptions().CPlusPlus
&& "valid check only for C++");
6785 if (FD
->isInvalidDecl())
6788 QualType EltTy
= Context
.getBaseElementType(FD
->getType());
6789 if (const RecordType
*RT
= EltTy
->getAs
<RecordType
>()) {
6790 CXXRecordDecl
* RDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
6791 if (RDecl
->getDefinition()) {
6792 // We check for copy constructors before constructors
6793 // because otherwise we'll never get complaints about
6794 // copy constructors.
6796 CXXSpecialMember member
= CXXInvalid
;
6797 if (!RDecl
->hasTrivialCopyConstructor())
6798 member
= CXXCopyConstructor
;
6799 else if (!RDecl
->hasTrivialConstructor())
6800 member
= CXXConstructor
;
6801 else if (!RDecl
->hasTrivialCopyAssignment())
6802 member
= CXXCopyAssignment
;
6803 else if (!RDecl
->hasTrivialDestructor())
6804 member
= CXXDestructor
;
6806 if (member
!= CXXInvalid
) {
6807 Diag(FD
->getLocation(), diag::err_illegal_union_or_anon_struct_member
)
6808 << (int)FD
->getParent()->isUnion() << FD
->getDeclName() << member
;
6809 DiagnoseNontrivial(RT
, member
);
6818 /// DiagnoseNontrivial - Given that a class has a non-trivial
6819 /// special member, figure out why.
6820 void Sema::DiagnoseNontrivial(const RecordType
* T
, CXXSpecialMember member
) {
6822 CXXRecordDecl
* RD
= cast
<CXXRecordDecl
>(T
->getDecl());
6824 // Check whether the member was user-declared.
6829 case CXXConstructor
:
6830 if (RD
->hasUserDeclaredConstructor()) {
6831 typedef CXXRecordDecl::ctor_iterator ctor_iter
;
6832 for (ctor_iter ci
= RD
->ctor_begin(), ce
= RD
->ctor_end(); ci
!= ce
;++ci
){
6833 const FunctionDecl
*body
= 0;
6835 if (!body
|| !cast
<CXXConstructorDecl
>(body
)->isImplicitlyDefined()) {
6836 SourceLocation CtorLoc
= ci
->getLocation();
6837 Diag(CtorLoc
, diag::note_nontrivial_user_defined
) << QT
<< member
;
6842 assert(0 && "found no user-declared constructors");
6847 case CXXCopyConstructor
:
6848 if (RD
->hasUserDeclaredCopyConstructor()) {
6849 SourceLocation CtorLoc
=
6850 RD
->getCopyConstructor(Context
, 0)->getLocation();
6851 Diag(CtorLoc
, diag::note_nontrivial_user_defined
) << QT
<< member
;
6856 case CXXCopyAssignment
:
6857 if (RD
->hasUserDeclaredCopyAssignment()) {
6858 // FIXME: this should use the location of the copy
6859 // assignment, not the type.
6860 SourceLocation TyLoc
= RD
->getSourceRange().getBegin();
6861 Diag(TyLoc
, diag::note_nontrivial_user_defined
) << QT
<< member
;
6867 if (RD
->hasUserDeclaredDestructor()) {
6868 SourceLocation DtorLoc
= LookupDestructor(RD
)->getLocation();
6869 Diag(DtorLoc
, diag::note_nontrivial_user_defined
) << QT
<< member
;
6875 typedef CXXRecordDecl::base_class_iterator base_iter
;
6877 // Virtual bases and members inhibit trivial copying/construction,
6878 // but not trivial destruction.
6879 if (member
!= CXXDestructor
) {
6880 // Check for virtual bases. vbases includes indirect virtual bases,
6881 // so we just iterate through the direct bases.
6882 for (base_iter bi
= RD
->bases_begin(), be
= RD
->bases_end(); bi
!= be
; ++bi
)
6883 if (bi
->isVirtual()) {
6884 SourceLocation BaseLoc
= bi
->getSourceRange().getBegin();
6885 Diag(BaseLoc
, diag::note_nontrivial_has_virtual
) << QT
<< 1;
6889 // Check for virtual methods.
6890 typedef CXXRecordDecl::method_iterator meth_iter
;
6891 for (meth_iter mi
= RD
->method_begin(), me
= RD
->method_end(); mi
!= me
;
6893 if (mi
->isVirtual()) {
6894 SourceLocation MLoc
= mi
->getSourceRange().getBegin();
6895 Diag(MLoc
, diag::note_nontrivial_has_virtual
) << QT
<< 0;
6901 bool (CXXRecordDecl::*hasTrivial
)() const;
6903 case CXXConstructor
:
6904 hasTrivial
= &CXXRecordDecl::hasTrivialConstructor
; break;
6905 case CXXCopyConstructor
:
6906 hasTrivial
= &CXXRecordDecl::hasTrivialCopyConstructor
; break;
6907 case CXXCopyAssignment
:
6908 hasTrivial
= &CXXRecordDecl::hasTrivialCopyAssignment
; break;
6910 hasTrivial
= &CXXRecordDecl::hasTrivialDestructor
; break;
6912 assert(0 && "unexpected special member"); return;
6915 // Check for nontrivial bases (and recurse).
6916 for (base_iter bi
= RD
->bases_begin(), be
= RD
->bases_end(); bi
!= be
; ++bi
) {
6917 const RecordType
*BaseRT
= bi
->getType()->getAs
<RecordType
>();
6918 assert(BaseRT
&& "Don't know how to handle dependent bases");
6919 CXXRecordDecl
*BaseRecTy
= cast
<CXXRecordDecl
>(BaseRT
->getDecl());
6920 if (!(BaseRecTy
->*hasTrivial
)()) {
6921 SourceLocation BaseLoc
= bi
->getSourceRange().getBegin();
6922 Diag(BaseLoc
, diag::note_nontrivial_has_nontrivial
) << QT
<< 1 << member
;
6923 DiagnoseNontrivial(BaseRT
, member
);
6928 // Check for nontrivial members (and recurse).
6929 typedef RecordDecl::field_iterator field_iter
;
6930 for (field_iter fi
= RD
->field_begin(), fe
= RD
->field_end(); fi
!= fe
;
6932 QualType EltTy
= Context
.getBaseElementType((*fi
)->getType());
6933 if (const RecordType
*EltRT
= EltTy
->getAs
<RecordType
>()) {
6934 CXXRecordDecl
* EltRD
= cast
<CXXRecordDecl
>(EltRT
->getDecl());
6936 if (!(EltRD
->*hasTrivial
)()) {
6937 SourceLocation FLoc
= (*fi
)->getLocation();
6938 Diag(FLoc
, diag::note_nontrivial_has_nontrivial
) << QT
<< 0 << member
;
6939 DiagnoseNontrivial(EltRT
, member
);
6945 assert(0 && "found no explanation for non-trivial member");
6948 /// TranslateIvarVisibility - Translate visibility from a token ID to an
6950 static ObjCIvarDecl::AccessControl
6951 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility
) {
6952 switch (ivarVisibility
) {
6953 default: assert(0 && "Unknown visitibility kind");
6954 case tok::objc_private
: return ObjCIvarDecl::Private
;
6955 case tok::objc_public
: return ObjCIvarDecl::Public
;
6956 case tok::objc_protected
: return ObjCIvarDecl::Protected
;
6957 case tok::objc_package
: return ObjCIvarDecl::Package
;
6961 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
6962 /// in order to create an IvarDecl object for it.
6963 Decl
*Sema::ActOnIvar(Scope
*S
,
6964 SourceLocation DeclStart
,
6966 Declarator
&D
, ExprTy
*BitfieldWidth
,
6967 tok::ObjCKeywordKind Visibility
) {
6969 IdentifierInfo
*II
= D
.getIdentifier();
6970 Expr
*BitWidth
= (Expr
*)BitfieldWidth
;
6971 SourceLocation Loc
= DeclStart
;
6972 if (II
) Loc
= D
.getIdentifierLoc();
6974 // FIXME: Unnamed fields can be handled in various different ways, for
6975 // example, unnamed unions inject all members into the struct namespace!
6977 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6978 QualType T
= TInfo
->getType();
6981 // 6.7.2.1p3, 6.7.2.1p4
6982 if (VerifyBitField(Loc
, II
, T
, BitWidth
)) {
6992 if (T
->isReferenceType()) {
6993 Diag(Loc
, diag::err_ivar_reference_type
);
6996 // C99 6.7.2.1p8: A member of a structure or union may have any type other
6997 // than a variably modified type.
6998 else if (T
->isVariablyModifiedType()) {
6999 Diag(Loc
, diag::err_typecheck_ivar_variable_size
);
7003 // Get the visibility (access control) for this ivar.
7004 ObjCIvarDecl::AccessControl ac
=
7005 Visibility
!= tok::objc_not_keyword
? TranslateIvarVisibility(Visibility
)
7006 : ObjCIvarDecl::None
;
7007 // Must set ivar's DeclContext to its enclosing interface.
7008 ObjCContainerDecl
*EnclosingDecl
= cast
<ObjCContainerDecl
>(IntfDecl
);
7009 ObjCContainerDecl
*EnclosingContext
;
7010 if (ObjCImplementationDecl
*IMPDecl
=
7011 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
7012 if (!LangOpts
.ObjCNonFragileABI2
) {
7013 // Case of ivar declared in an implementation. Context is that of its class.
7014 EnclosingContext
= IMPDecl
->getClassInterface();
7015 assert(EnclosingContext
&& "Implementation has no class interface!");
7018 EnclosingContext
= EnclosingDecl
;
7020 if (ObjCCategoryDecl
*CDecl
=
7021 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
7022 if (!LangOpts
.ObjCNonFragileABI2
|| !CDecl
->IsClassExtension()) {
7023 Diag(Loc
, diag::err_misplaced_ivar
) << CDecl
->IsClassExtension();
7027 EnclosingContext
= EnclosingDecl
;
7030 // Construct the decl.
7031 ObjCIvarDecl
*NewID
= ObjCIvarDecl::Create(Context
,
7032 EnclosingContext
, Loc
, II
, T
,
7033 TInfo
, ac
, (Expr
*)BitfieldWidth
);
7036 NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, Loc
, LookupMemberName
,
7038 if (PrevDecl
&& isDeclInScope(PrevDecl
, EnclosingContext
, S
)
7039 && !isa
<TagDecl
>(PrevDecl
)) {
7040 Diag(Loc
, diag::err_duplicate_member
) << II
;
7041 Diag(PrevDecl
->getLocation(), diag::note_previous_declaration
);
7042 NewID
->setInvalidDecl();
7046 // Process attributes attached to the ivar.
7047 ProcessDeclAttributes(S
, NewID
, D
);
7049 if (D
.isInvalidType())
7050 NewID
->setInvalidDecl();
7053 // FIXME: When interfaces are DeclContexts, we'll need to add
7054 // these to the interface.
7056 IdResolver
.AddDecl(NewID
);
7062 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
7063 /// class and class extensions. For every class @interface and class
7064 /// extension @interface, if the last ivar is a bitfield of any type,
7065 /// then add an implicit `char :0` ivar to the end of that interface.
7066 void Sema::ActOnLastBitfield(SourceLocation DeclLoc
, Decl
*EnclosingDecl
,
7067 llvm::SmallVectorImpl
<Decl
*> &AllIvarDecls
) {
7068 if (!LangOpts
.ObjCNonFragileABI2
|| AllIvarDecls
.empty())
7071 Decl
*ivarDecl
= AllIvarDecls
[AllIvarDecls
.size()-1];
7072 ObjCIvarDecl
*Ivar
= cast
<ObjCIvarDecl
>(ivarDecl
);
7074 if (!Ivar
->isBitField())
7076 uint64_t BitFieldSize
=
7077 Ivar
->getBitWidth()->EvaluateAsInt(Context
).getZExtValue();
7078 if (BitFieldSize
== 0)
7080 ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(EnclosingDecl
);
7082 if (ObjCCategoryDecl
*CD
= dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
7083 if (!CD
->IsClassExtension())
7086 // No need to add this to end of @implementation.
7090 // All conditions are met. Add a new bitfield to the tail end of ivars.
7091 llvm::APInt
Zero(Context
.getTypeSize(Context
.CharTy
), 0);
7092 Expr
* BW
= IntegerLiteral::Create(Context
, Zero
, Context
.CharTy
, DeclLoc
);
7094 Ivar
= ObjCIvarDecl::Create(Context
, cast
<ObjCContainerDecl
>(EnclosingDecl
),
7097 Context
.CreateTypeSourceInfo(Context
.CharTy
),
7098 ObjCIvarDecl::Private
, BW
,
7100 AllIvarDecls
.push_back(Ivar
);
7103 void Sema::ActOnFields(Scope
* S
,
7104 SourceLocation RecLoc
, Decl
*EnclosingDecl
,
7105 Decl
**Fields
, unsigned NumFields
,
7106 SourceLocation LBrac
, SourceLocation RBrac
,
7107 AttributeList
*Attr
) {
7108 assert(EnclosingDecl
&& "missing record or interface decl");
7110 // If the decl this is being inserted into is invalid, then it may be a
7111 // redeclaration or some other bogus case. Don't try to add fields to it.
7112 if (EnclosingDecl
->isInvalidDecl()) {
7113 // FIXME: Deallocate fields?
7118 // Verify that all the fields are okay.
7119 unsigned NumNamedMembers
= 0;
7120 llvm::SmallVector
<FieldDecl
*, 32> RecFields
;
7122 RecordDecl
*Record
= dyn_cast
<RecordDecl
>(EnclosingDecl
);
7123 for (unsigned i
= 0; i
!= NumFields
; ++i
) {
7124 FieldDecl
*FD
= cast
<FieldDecl
>(Fields
[i
]);
7126 // Get the type for the field.
7127 const Type
*FDTy
= FD
->getType().getTypePtr();
7129 if (!FD
->isAnonymousStructOrUnion()) {
7130 // Remember all fields written by the user.
7131 RecFields
.push_back(FD
);
7134 // If the field is already invalid for some reason, don't emit more
7135 // diagnostics about it.
7136 if (FD
->isInvalidDecl()) {
7137 EnclosingDecl
->setInvalidDecl();
7142 // A structure or union shall not contain a member with
7143 // incomplete or function type (hence, a structure shall not
7144 // contain an instance of itself, but may contain a pointer to
7145 // an instance of itself), except that the last member of a
7146 // structure with more than one named member may have incomplete
7147 // array type; such a structure (and any union containing,
7148 // possibly recursively, a member that is such a structure)
7149 // shall not be a member of a structure or an element of an
7151 if (FDTy
->isFunctionType()) {
7152 // Field declared as a function.
7153 Diag(FD
->getLocation(), diag::err_field_declared_as_function
)
7154 << FD
->getDeclName();
7155 FD
->setInvalidDecl();
7156 EnclosingDecl
->setInvalidDecl();
7158 } else if (FDTy
->isIncompleteArrayType() && Record
&&
7159 ((i
== NumFields
- 1 && !Record
->isUnion()) ||
7160 (getLangOptions().Microsoft
&&
7161 (i
== NumFields
- 1 || Record
->isUnion())))) {
7162 // Flexible array member.
7163 // Microsoft is more permissive regarding flexible array.
7164 // It will accept flexible array in union and also
7165 // as the sole element of a struct/class.
7166 if (getLangOptions().Microsoft
) {
7167 if (Record
->isUnion())
7168 Diag(FD
->getLocation(), diag::ext_flexible_array_union
)
7169 << FD
->getDeclName();
7170 else if (NumFields
== 1)
7171 Diag(FD
->getLocation(), diag::ext_flexible_array_empty_aggregate
)
7172 << FD
->getDeclName() << Record
->getTagKind();
7173 } else if (NumNamedMembers
< 1) {
7174 Diag(FD
->getLocation(), diag::err_flexible_array_empty_struct
)
7175 << FD
->getDeclName();
7176 FD
->setInvalidDecl();
7177 EnclosingDecl
->setInvalidDecl();
7180 if (!FD
->getType()->isDependentType() &&
7181 !Context
.getBaseElementType(FD
->getType())->isPODType()) {
7182 Diag(FD
->getLocation(), diag::err_flexible_array_has_nonpod_type
)
7183 << FD
->getDeclName() << FD
->getType();
7184 FD
->setInvalidDecl();
7185 EnclosingDecl
->setInvalidDecl();
7188 // Okay, we have a legal flexible array member at the end of the struct.
7190 Record
->setHasFlexibleArrayMember(true);
7191 } else if (!FDTy
->isDependentType() &&
7192 RequireCompleteType(FD
->getLocation(), FD
->getType(),
7193 diag::err_field_incomplete
)) {
7195 FD
->setInvalidDecl();
7196 EnclosingDecl
->setInvalidDecl();
7198 } else if (const RecordType
*FDTTy
= FDTy
->getAs
<RecordType
>()) {
7199 if (FDTTy
->getDecl()->hasFlexibleArrayMember()) {
7200 // If this is a member of a union, then entire union becomes "flexible".
7201 if (Record
&& Record
->isUnion()) {
7202 Record
->setHasFlexibleArrayMember(true);
7204 // If this is a struct/class and this is not the last element, reject
7205 // it. Note that GCC supports variable sized arrays in the middle of
7207 if (i
!= NumFields
-1)
7208 Diag(FD
->getLocation(), diag::ext_variable_sized_type_in_struct
)
7209 << FD
->getDeclName() << FD
->getType();
7211 // We support flexible arrays at the end of structs in
7212 // other structs as an extension.
7213 Diag(FD
->getLocation(), diag::ext_flexible_array_in_struct
)
7214 << FD
->getDeclName();
7216 Record
->setHasFlexibleArrayMember(true);
7220 if (Record
&& FDTTy
->getDecl()->hasObjectMember())
7221 Record
->setHasObjectMember(true);
7222 } else if (FDTy
->isObjCObjectType()) {
7223 /// A field cannot be an Objective-c object
7224 Diag(FD
->getLocation(), diag::err_statically_allocated_object
);
7225 FD
->setInvalidDecl();
7226 EnclosingDecl
->setInvalidDecl();
7228 } else if (getLangOptions().ObjC1
&&
7229 getLangOptions().getGCMode() != LangOptions::NonGC
&&
7231 (FD
->getType()->isObjCObjectPointerType() ||
7232 FD
->getType().isObjCGCStrong()))
7233 Record
->setHasObjectMember(true);
7234 else if (Context
.getAsArrayType(FD
->getType())) {
7235 QualType BaseType
= Context
.getBaseElementType(FD
->getType());
7236 if (Record
&& BaseType
->isRecordType() &&
7237 BaseType
->getAs
<RecordType
>()->getDecl()->hasObjectMember())
7238 Record
->setHasObjectMember(true);
7240 // Keep track of the number of named members.
7241 if (FD
->getIdentifier())
7245 // Okay, we successfully defined 'Record'.
7247 bool Completed
= false;
7248 if (CXXRecordDecl
*CXXRecord
= dyn_cast
<CXXRecordDecl
>(Record
)) {
7249 if (!CXXRecord
->isInvalidDecl()) {
7250 // Set access bits correctly on the directly-declared conversions.
7251 UnresolvedSetImpl
*Convs
= CXXRecord
->getConversionFunctions();
7252 for (UnresolvedSetIterator I
= Convs
->begin(), E
= Convs
->end();
7254 Convs
->setAccess(I
, (*I
)->getAccess());
7256 if (!CXXRecord
->isDependentType()) {
7257 // Add any implicitly-declared members to this class.
7258 AddImplicitlyDeclaredMembersToClass(CXXRecord
);
7260 // If we have virtual base classes, we may end up finding multiple
7261 // final overriders for a given virtual function. Check for this
7263 if (CXXRecord
->getNumVBases()) {
7264 CXXFinalOverriderMap FinalOverriders
;
7265 CXXRecord
->getFinalOverriders(FinalOverriders
);
7267 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
7268 MEnd
= FinalOverriders
.end();
7270 for (OverridingMethods::iterator SO
= M
->second
.begin(),
7271 SOEnd
= M
->second
.end();
7272 SO
!= SOEnd
; ++SO
) {
7273 assert(SO
->second
.size() > 0 &&
7274 "Virtual function without overridding functions?");
7275 if (SO
->second
.size() == 1)
7278 // C++ [class.virtual]p2:
7279 // In a derived class, if a virtual member function of a base
7280 // class subobject has more than one final overrider the
7281 // program is ill-formed.
7282 Diag(Record
->getLocation(), diag::err_multiple_final_overriders
)
7283 << (NamedDecl
*)M
->first
<< Record
;
7284 Diag(M
->first
->getLocation(),
7285 diag::note_overridden_virtual_function
);
7286 for (OverridingMethods::overriding_iterator
7287 OM
= SO
->second
.begin(),
7288 OMEnd
= SO
->second
.end();
7290 Diag(OM
->Method
->getLocation(), diag::note_final_overrider
)
7291 << (NamedDecl
*)M
->first
<< OM
->Method
->getParent();
7293 Record
->setInvalidDecl();
7296 CXXRecord
->completeDefinition(&FinalOverriders
);
7304 Record
->completeDefinition();
7306 ObjCIvarDecl
**ClsFields
=
7307 reinterpret_cast<ObjCIvarDecl
**>(RecFields
.data());
7308 if (ObjCInterfaceDecl
*ID
= dyn_cast
<ObjCInterfaceDecl
>(EnclosingDecl
)) {
7309 ID
->setLocEnd(RBrac
);
7310 // Add ivar's to class's DeclContext.
7311 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
7312 ClsFields
[i
]->setLexicalDeclContext(ID
);
7313 ID
->addDecl(ClsFields
[i
]);
7315 // Must enforce the rule that ivars in the base classes may not be
7317 if (ID
->getSuperClass())
7318 DiagnoseDuplicateIvars(ID
, ID
->getSuperClass());
7319 } else if (ObjCImplementationDecl
*IMPDecl
=
7320 dyn_cast
<ObjCImplementationDecl
>(EnclosingDecl
)) {
7321 assert(IMPDecl
&& "ActOnFields - missing ObjCImplementationDecl");
7322 for (unsigned I
= 0, N
= RecFields
.size(); I
!= N
; ++I
)
7323 // Ivar declared in @implementation never belongs to the implementation.
7324 // Only it is in implementation's lexical context.
7325 ClsFields
[I
]->setLexicalDeclContext(IMPDecl
);
7326 CheckImplementationIvars(IMPDecl
, ClsFields
, RecFields
.size(), RBrac
);
7327 } else if (ObjCCategoryDecl
*CDecl
=
7328 dyn_cast
<ObjCCategoryDecl
>(EnclosingDecl
)) {
7329 // case of ivars in class extension; all other cases have been
7330 // reported as errors elsewhere.
7331 // FIXME. Class extension does not have a LocEnd field.
7332 // CDecl->setLocEnd(RBrac);
7333 // Add ivar's to class extension's DeclContext.
7334 for (unsigned i
= 0, e
= RecFields
.size(); i
!= e
; ++i
) {
7335 ClsFields
[i
]->setLexicalDeclContext(CDecl
);
7336 CDecl
->addDecl(ClsFields
[i
]);
7342 ProcessDeclAttributeList(S
, Record
, Attr
);
7344 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
7345 // set the visibility of this record.
7346 if (Record
&& !Record
->getDeclContext()->isRecord())
7347 AddPushedVisibilityAttribute(Record
);
7350 /// \brief Determine whether the given integral value is representable within
7351 /// the given type T.
7352 static bool isRepresentableIntegerValue(ASTContext
&Context
,
7353 llvm::APSInt
&Value
,
7355 assert(T
->isIntegralType(Context
) && "Integral type required!");
7356 unsigned BitWidth
= Context
.getIntWidth(T
);
7358 if (Value
.isUnsigned() || Value
.isNonNegative()) {
7359 if (T
->isSignedIntegerType())
7361 return Value
.getActiveBits() <= BitWidth
;
7363 return Value
.getMinSignedBits() <= BitWidth
;
7366 // \brief Given an integral type, return the next larger integral type
7367 // (or a NULL type of no such type exists).
7368 static QualType
getNextLargerIntegralType(ASTContext
&Context
, QualType T
) {
7369 // FIXME: Int128/UInt128 support, which also needs to be introduced into
7370 // enum checking below.
7371 assert(T
->isIntegralType(Context
) && "Integral type required!");
7372 const unsigned NumTypes
= 4;
7373 QualType SignedIntegralTypes
[NumTypes
] = {
7374 Context
.ShortTy
, Context
.IntTy
, Context
.LongTy
, Context
.LongLongTy
7376 QualType UnsignedIntegralTypes
[NumTypes
] = {
7377 Context
.UnsignedShortTy
, Context
.UnsignedIntTy
, Context
.UnsignedLongTy
,
7378 Context
.UnsignedLongLongTy
7381 unsigned BitWidth
= Context
.getTypeSize(T
);
7382 QualType
*Types
= T
->isSignedIntegerType()? SignedIntegralTypes
7383 : UnsignedIntegralTypes
;
7384 for (unsigned I
= 0; I
!= NumTypes
; ++I
)
7385 if (Context
.getTypeSize(Types
[I
]) > BitWidth
)
7391 EnumConstantDecl
*Sema::CheckEnumConstant(EnumDecl
*Enum
,
7392 EnumConstantDecl
*LastEnumConst
,
7393 SourceLocation IdLoc
,
7396 unsigned IntWidth
= Context
.Target
.getIntWidth();
7397 llvm::APSInt
EnumVal(IntWidth
);
7400 if (Val
&& DiagnoseUnexpandedParameterPack(Val
, UPPC_EnumeratorValue
))
7404 if (Enum
->isDependentType() || Val
->isTypeDependent())
7405 EltTy
= Context
.DependentTy
;
7407 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
7408 SourceLocation ExpLoc
;
7409 if (!Val
->isValueDependent() &&
7410 VerifyIntegerConstantExpression(Val
, &EnumVal
)) {
7413 if (!getLangOptions().CPlusPlus
) {
7415 // The expression that defines the value of an enumeration constant
7416 // shall be an integer constant expression that has a value
7417 // representable as an int.
7419 // Complain if the value is not representable in an int.
7420 if (!isRepresentableIntegerValue(Context
, EnumVal
, Context
.IntTy
))
7421 Diag(IdLoc
, diag::ext_enum_value_not_int
)
7422 << EnumVal
.toString(10) << Val
->getSourceRange()
7423 << (EnumVal
.isUnsigned() || EnumVal
.isNonNegative());
7424 else if (!Context
.hasSameType(Val
->getType(), Context
.IntTy
)) {
7425 // Force the type of the expression to 'int'.
7426 ImpCastExprToType(Val
, Context
.IntTy
, CK_IntegralCast
);
7430 if (Enum
->isFixed()) {
7431 EltTy
= Enum
->getIntegerType();
7433 // C++0x [dcl.enum]p5:
7434 // ... if the initializing value of an enumerator cannot be
7435 // represented by the underlying type, the program is ill-formed.
7436 if (!isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
7437 if (getLangOptions().Microsoft
) {
7438 Diag(IdLoc
, diag::ext_enumerator_too_large
) << EltTy
;
7439 ImpCastExprToType(Val
, EltTy
, CK_IntegralCast
);
7441 Diag(IdLoc
, diag::err_enumerator_too_large
)
7444 ImpCastExprToType(Val
, EltTy
, CK_IntegralCast
);
7447 // C++0x [dcl.enum]p5:
7448 // If the underlying type is not fixed, the type of each enumerator
7449 // is the type of its initializing value:
7450 // - If an initializer is specified for an enumerator, the
7451 // initializing value has the same type as the expression.
7452 EltTy
= Val
->getType();
7459 if (Enum
->isDependentType())
7460 EltTy
= Context
.DependentTy
;
7461 else if (!LastEnumConst
) {
7462 // C++0x [dcl.enum]p5:
7463 // If the underlying type is not fixed, the type of each enumerator
7464 // is the type of its initializing value:
7465 // - If no initializer is specified for the first enumerator, the
7466 // initializing value has an unspecified integral type.
7468 // GCC uses 'int' for its unspecified integral type, as does
7470 if (Enum
->isFixed()) {
7471 EltTy
= Enum
->getIntegerType();
7474 EltTy
= Context
.IntTy
;
7477 // Assign the last value + 1.
7478 EnumVal
= LastEnumConst
->getInitVal();
7480 EltTy
= LastEnumConst
->getType();
7482 // Check for overflow on increment.
7483 if (EnumVal
< LastEnumConst
->getInitVal()) {
7484 // C++0x [dcl.enum]p5:
7485 // If the underlying type is not fixed, the type of each enumerator
7486 // is the type of its initializing value:
7488 // - Otherwise the type of the initializing value is the same as
7489 // the type of the initializing value of the preceding enumerator
7490 // unless the incremented value is not representable in that type,
7491 // in which case the type is an unspecified integral type
7492 // sufficient to contain the incremented value. If no such type
7493 // exists, the program is ill-formed.
7494 QualType T
= getNextLargerIntegralType(Context
, EltTy
);
7495 if (T
.isNull() || Enum
->isFixed()) {
7496 // There is no integral type larger enough to represent this
7497 // value. Complain, then allow the value to wrap around.
7498 EnumVal
= LastEnumConst
->getInitVal();
7499 EnumVal
= EnumVal
.zext(EnumVal
.getBitWidth() * 2);
7501 if (Enum
->isFixed())
7502 // When the underlying type is fixed, this is ill-formed.
7503 Diag(IdLoc
, diag::err_enumerator_wrapped
)
7504 << EnumVal
.toString(10)
7507 Diag(IdLoc
, diag::warn_enumerator_too_large
)
7508 << EnumVal
.toString(10);
7513 // Retrieve the last enumerator's value, extent that type to the
7514 // type that is supposed to be large enough to represent the incremented
7515 // value, then increment.
7516 EnumVal
= LastEnumConst
->getInitVal();
7517 EnumVal
.setIsSigned(EltTy
->isSignedIntegerType());
7518 EnumVal
= EnumVal
.zextOrTrunc(Context
.getIntWidth(EltTy
));
7521 // If we're not in C++, diagnose the overflow of enumerator values,
7522 // which in C99 means that the enumerator value is not representable in
7523 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
7524 // permits enumerator values that are representable in some larger
7526 if (!getLangOptions().CPlusPlus
&& !T
.isNull())
7527 Diag(IdLoc
, diag::warn_enum_value_overflow
);
7528 } else if (!getLangOptions().CPlusPlus
&&
7529 !isRepresentableIntegerValue(Context
, EnumVal
, EltTy
)) {
7530 // Enforce C99 6.7.2.2p2 even when we compute the next value.
7531 Diag(IdLoc
, diag::ext_enum_value_not_int
)
7532 << EnumVal
.toString(10) << 1;
7537 if (!EltTy
->isDependentType()) {
7538 // Make the enumerator value match the signedness and size of the
7539 // enumerator's type.
7540 EnumVal
= EnumVal
.zextOrTrunc(Context
.getIntWidth(EltTy
));
7541 EnumVal
.setIsSigned(EltTy
->isSignedIntegerType());
7544 return EnumConstantDecl::Create(Context
, Enum
, IdLoc
, Id
, EltTy
,
7549 Decl
*Sema::ActOnEnumConstant(Scope
*S
, Decl
*theEnumDecl
, Decl
*lastEnumConst
,
7550 SourceLocation IdLoc
, IdentifierInfo
*Id
,
7551 AttributeList
*Attr
,
7552 SourceLocation EqualLoc
, ExprTy
*val
) {
7553 EnumDecl
*TheEnumDecl
= cast
<EnumDecl
>(theEnumDecl
);
7554 EnumConstantDecl
*LastEnumConst
=
7555 cast_or_null
<EnumConstantDecl
>(lastEnumConst
);
7556 Expr
*Val
= static_cast<Expr
*>(val
);
7558 // The scope passed in may not be a decl scope. Zip up the scope tree until
7559 // we find one that is.
7560 S
= getNonFieldDeclScope(S
);
7562 // Verify that there isn't already something declared with this name in this
7564 NamedDecl
*PrevDecl
= LookupSingleName(S
, Id
, IdLoc
, LookupOrdinaryName
,
7566 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
7567 // Maybe we will complain about the shadowed template parameter.
7568 DiagnoseTemplateParameterShadow(IdLoc
, PrevDecl
);
7569 // Just pretend that we didn't see the previous declaration.
7574 // When in C++, we may get a TagDecl with the same name; in this case the
7575 // enum constant will 'hide' the tag.
7576 assert((getLangOptions().CPlusPlus
|| !isa
<TagDecl
>(PrevDecl
)) &&
7577 "Received TagDecl when not in C++!");
7578 if (!isa
<TagDecl
>(PrevDecl
) && isDeclInScope(PrevDecl
, CurContext
, S
)) {
7579 if (isa
<EnumConstantDecl
>(PrevDecl
))
7580 Diag(IdLoc
, diag::err_redefinition_of_enumerator
) << Id
;
7582 Diag(IdLoc
, diag::err_redefinition
) << Id
;
7583 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
7588 // C++ [class.mem]p13:
7589 // If T is the name of a class, then each of the following shall have a
7590 // name different from T:
7591 // - every enumerator of every member of class T that is an enumerated
7593 if (CXXRecordDecl
*Record
7594 = dyn_cast
<CXXRecordDecl
>(
7595 TheEnumDecl
->getDeclContext()->getRedeclContext()))
7596 if (Record
->getIdentifier() && Record
->getIdentifier() == Id
)
7597 Diag(IdLoc
, diag::err_member_name_of_class
) << Id
;
7599 EnumConstantDecl
*New
=
7600 CheckEnumConstant(TheEnumDecl
, LastEnumConst
, IdLoc
, Id
, Val
);
7603 // Process attributes.
7604 if (Attr
) ProcessDeclAttributeList(S
, New
, Attr
);
7606 // Register this decl in the current scope stack.
7607 New
->setAccess(TheEnumDecl
->getAccess());
7608 PushOnScopeChains(New
, S
);
7614 void Sema::ActOnEnumBody(SourceLocation EnumLoc
, SourceLocation LBraceLoc
,
7615 SourceLocation RBraceLoc
, Decl
*EnumDeclX
,
7616 Decl
**Elements
, unsigned NumElements
,
7617 Scope
*S
, AttributeList
*Attr
) {
7618 EnumDecl
*Enum
= cast
<EnumDecl
>(EnumDeclX
);
7619 QualType EnumType
= Context
.getTypeDeclType(Enum
);
7622 ProcessDeclAttributeList(S
, Enum
, Attr
);
7624 if (Enum
->isDependentType()) {
7625 for (unsigned i
= 0; i
!= NumElements
; ++i
) {
7626 EnumConstantDecl
*ECD
=
7627 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
7630 ECD
->setType(EnumType
);
7633 Enum
->completeDefinition(Context
.DependentTy
, Context
.DependentTy
, 0, 0);
7637 // TODO: If the result value doesn't fit in an int, it must be a long or long
7638 // long value. ISO C does not support this, but GCC does as an extension,
7640 unsigned IntWidth
= Context
.Target
.getIntWidth();
7641 unsigned CharWidth
= Context
.Target
.getCharWidth();
7642 unsigned ShortWidth
= Context
.Target
.getShortWidth();
7644 // Verify that all the values are okay, compute the size of the values, and
7645 // reverse the list.
7646 unsigned NumNegativeBits
= 0;
7647 unsigned NumPositiveBits
= 0;
7649 // Keep track of whether all elements have type int.
7650 bool AllElementsInt
= true;
7652 for (unsigned i
= 0; i
!= NumElements
; ++i
) {
7653 EnumConstantDecl
*ECD
=
7654 cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
7655 if (!ECD
) continue; // Already issued a diagnostic.
7657 const llvm::APSInt
&InitVal
= ECD
->getInitVal();
7659 // Keep track of the size of positive and negative values.
7660 if (InitVal
.isUnsigned() || InitVal
.isNonNegative())
7661 NumPositiveBits
= std::max(NumPositiveBits
,
7662 (unsigned)InitVal
.getActiveBits());
7664 NumNegativeBits
= std::max(NumNegativeBits
,
7665 (unsigned)InitVal
.getMinSignedBits());
7667 // Keep track of whether every enum element has type int (very commmon).
7669 AllElementsInt
= ECD
->getType() == Context
.IntTy
;
7672 // Figure out the type that should be used for this enum.
7676 // C++0x N3000 [conv.prom]p3:
7677 // An rvalue of an unscoped enumeration type whose underlying
7678 // type is not fixed can be converted to an rvalue of the first
7679 // of the following types that can represent all the values of
7680 // the enumeration: int, unsigned int, long int, unsigned long
7681 // int, long long int, or unsigned long long int.
7683 // An identifier declared as an enumeration constant has type int.
7684 // The C99 rule is modified by a gcc extension
7685 QualType BestPromotionType
;
7687 bool Packed
= Enum
->getAttr
<PackedAttr
>() ? true : false;
7688 // -fshort-enums is the equivalent to specifying the packed attribute on all
7689 // enum definitions.
7690 if (LangOpts
.ShortEnums
)
7693 if (Enum
->isFixed()) {
7694 BestType
= BestPromotionType
= Enum
->getIntegerType();
7695 // We don't need to set BestWidth, because BestType is going to be the type
7696 // of the enumerators, but we do anyway because otherwise some compilers
7697 // warn that it might be used uninitialized.
7698 BestWidth
= CharWidth
;
7700 else if (NumNegativeBits
) {
7701 // If there is a negative value, figure out the smallest integer type (of
7702 // int/long/longlong) that fits.
7703 // If it's packed, check also if it fits a char or a short.
7704 if (Packed
&& NumNegativeBits
<= CharWidth
&& NumPositiveBits
< CharWidth
) {
7705 BestType
= Context
.SignedCharTy
;
7706 BestWidth
= CharWidth
;
7707 } else if (Packed
&& NumNegativeBits
<= ShortWidth
&&
7708 NumPositiveBits
< ShortWidth
) {
7709 BestType
= Context
.ShortTy
;
7710 BestWidth
= ShortWidth
;
7711 } else if (NumNegativeBits
<= IntWidth
&& NumPositiveBits
< IntWidth
) {
7712 BestType
= Context
.IntTy
;
7713 BestWidth
= IntWidth
;
7715 BestWidth
= Context
.Target
.getLongWidth();
7717 if (NumNegativeBits
<= BestWidth
&& NumPositiveBits
< BestWidth
) {
7718 BestType
= Context
.LongTy
;
7720 BestWidth
= Context
.Target
.getLongLongWidth();
7722 if (NumNegativeBits
> BestWidth
|| NumPositiveBits
>= BestWidth
)
7723 Diag(Enum
->getLocation(), diag::warn_enum_too_large
);
7724 BestType
= Context
.LongLongTy
;
7727 BestPromotionType
= (BestWidth
<= IntWidth
? Context
.IntTy
: BestType
);
7729 // If there is no negative value, figure out the smallest type that fits
7730 // all of the enumerator values.
7731 // If it's packed, check also if it fits a char or a short.
7732 if (Packed
&& NumPositiveBits
<= CharWidth
) {
7733 BestType
= Context
.UnsignedCharTy
;
7734 BestPromotionType
= Context
.IntTy
;
7735 BestWidth
= CharWidth
;
7736 } else if (Packed
&& NumPositiveBits
<= ShortWidth
) {
7737 BestType
= Context
.UnsignedShortTy
;
7738 BestPromotionType
= Context
.IntTy
;
7739 BestWidth
= ShortWidth
;
7740 } else if (NumPositiveBits
<= IntWidth
) {
7741 BestType
= Context
.UnsignedIntTy
;
7742 BestWidth
= IntWidth
;
7744 = (NumPositiveBits
== BestWidth
|| !getLangOptions().CPlusPlus
)
7745 ? Context
.UnsignedIntTy
: Context
.IntTy
;
7746 } else if (NumPositiveBits
<=
7747 (BestWidth
= Context
.Target
.getLongWidth())) {
7748 BestType
= Context
.UnsignedLongTy
;
7750 = (NumPositiveBits
== BestWidth
|| !getLangOptions().CPlusPlus
)
7751 ? Context
.UnsignedLongTy
: Context
.LongTy
;
7753 BestWidth
= Context
.Target
.getLongLongWidth();
7754 assert(NumPositiveBits
<= BestWidth
&&
7755 "How could an initializer get larger than ULL?");
7756 BestType
= Context
.UnsignedLongLongTy
;
7758 = (NumPositiveBits
== BestWidth
|| !getLangOptions().CPlusPlus
)
7759 ? Context
.UnsignedLongLongTy
: Context
.LongLongTy
;
7763 // Loop over all of the enumerator constants, changing their types to match
7764 // the type of the enum if needed.
7765 for (unsigned i
= 0; i
!= NumElements
; ++i
) {
7766 EnumConstantDecl
*ECD
= cast_or_null
<EnumConstantDecl
>(Elements
[i
]);
7767 if (!ECD
) continue; // Already issued a diagnostic.
7769 // Standard C says the enumerators have int type, but we allow, as an
7770 // extension, the enumerators to be larger than int size. If each
7771 // enumerator value fits in an int, type it as an int, otherwise type it the
7772 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
7773 // that X has type 'int', not 'unsigned'.
7775 // Determine whether the value fits into an int.
7776 llvm::APSInt InitVal
= ECD
->getInitVal();
7778 // If it fits into an integer type, force it. Otherwise force it to match
7779 // the enum decl type.
7783 if (!getLangOptions().CPlusPlus
&&
7784 isRepresentableIntegerValue(Context
, InitVal
, Context
.IntTy
)) {
7785 NewTy
= Context
.IntTy
;
7786 NewWidth
= IntWidth
;
7788 } else if (ECD
->getType() == BestType
) {
7789 // Already the right type!
7790 if (getLangOptions().CPlusPlus
)
7791 // C++ [dcl.enum]p4: Following the closing brace of an
7792 // enum-specifier, each enumerator has the type of its
7794 ECD
->setType(EnumType
);
7798 NewWidth
= BestWidth
;
7799 NewSign
= BestType
->isSignedIntegerType();
7802 // Adjust the APSInt value.
7803 InitVal
= InitVal
.extOrTrunc(NewWidth
);
7804 InitVal
.setIsSigned(NewSign
);
7805 ECD
->setInitVal(InitVal
);
7807 // Adjust the Expr initializer and type.
7808 if (ECD
->getInitExpr() &&
7809 !Context
.hasSameType(NewTy
, ECD
->getInitExpr()->getType()))
7810 ECD
->setInitExpr(ImplicitCastExpr::Create(Context
, NewTy
,
7815 if (getLangOptions().CPlusPlus
)
7816 // C++ [dcl.enum]p4: Following the closing brace of an
7817 // enum-specifier, each enumerator has the type of its
7819 ECD
->setType(EnumType
);
7821 ECD
->setType(NewTy
);
7824 Enum
->completeDefinition(BestType
, BestPromotionType
,
7825 NumPositiveBits
, NumNegativeBits
);
7828 Decl
*Sema::ActOnFileScopeAsmDecl(SourceLocation Loc
, Expr
*expr
) {
7829 StringLiteral
*AsmString
= cast
<StringLiteral
>(expr
);
7831 FileScopeAsmDecl
*New
= FileScopeAsmDecl::Create(Context
, CurContext
,
7833 CurContext
->addDecl(New
);
7837 void Sema::ActOnPragmaWeakID(IdentifierInfo
* Name
,
7838 SourceLocation PragmaLoc
,
7839 SourceLocation NameLoc
) {
7840 Decl
*PrevDecl
= LookupSingleName(TUScope
, Name
, NameLoc
, LookupOrdinaryName
);
7843 PrevDecl
->addAttr(::new (Context
) WeakAttr(PragmaLoc
, Context
));
7845 (void)WeakUndeclaredIdentifiers
.insert(
7846 std::pair
<IdentifierInfo
*,WeakInfo
>
7847 (Name
, WeakInfo((IdentifierInfo
*)0, NameLoc
)));
7851 void Sema::ActOnPragmaWeakAlias(IdentifierInfo
* Name
,
7852 IdentifierInfo
* AliasName
,
7853 SourceLocation PragmaLoc
,
7854 SourceLocation NameLoc
,
7855 SourceLocation AliasNameLoc
) {
7856 Decl
*PrevDecl
= LookupSingleName(TUScope
, AliasName
, AliasNameLoc
,
7857 LookupOrdinaryName
);
7858 WeakInfo W
= WeakInfo(Name
, NameLoc
);
7861 if (!PrevDecl
->hasAttr
<AliasAttr
>())
7862 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(PrevDecl
))
7863 DeclApplyPragmaWeak(TUScope
, ND
, W
);
7865 (void)WeakUndeclaredIdentifiers
.insert(
7866 std::pair
<IdentifierInfo
*,WeakInfo
>(AliasName
, W
));