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 "TypeLocBuilder.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/EvaluatedExprVisitor.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/ParsedTemplate.h"
33 #include "clang/Parse/ParseDiagnostic.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/TargetInfo.h"
38 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/HeaderSearch.h"
41 #include "clang/Lex/ModuleLoader.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/Triple.h"
47 using namespace clang;
50 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
52 Decl *Group[2] = { OwnedType, Ptr };
53 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
63 TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) {
64 WantExpressionKeywords = false;
65 WantCXXNamedCasts = false;
66 WantRemainingKeywords = false;
69 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
70 if (NamedDecl *ND = candidate.getCorrectionDecl())
71 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
72 (AllowInvalidDecl || !ND->isInvalidDecl());
74 return candidate.isKeyword();
78 bool AllowInvalidDecl;
83 /// \brief If the identifier refers to a type name within this scope,
84 /// return the declaration of that type.
86 /// This routine performs ordinary name lookup of the identifier II
87 /// within the given scope, with optional C++ scope specifier SS, to
88 /// determine whether the name refers to a type. If so, returns an
89 /// opaque pointer (actually a QualType) corresponding to that
90 /// type. Otherwise, returns NULL.
92 /// If name lookup results in an ambiguity, this routine will complain
93 /// and then return NULL.
94 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
95 Scope *S, CXXScopeSpec *SS,
96 bool isClassName, bool HasTrailingDot,
97 ParsedType ObjectTypePtr,
98 bool IsCtorOrDtorName,
99 bool WantNontrivialTypeSourceInfo,
100 IdentifierInfo **CorrectedII) {
101 // Determine where we will perform name lookup.
102 DeclContext *LookupCtx = 0;
104 QualType ObjectType = ObjectTypePtr.get();
105 if (ObjectType->isRecordType())
106 LookupCtx = computeDeclContext(ObjectType);
107 } else if (SS && SS->isNotEmpty()) {
108 LookupCtx = computeDeclContext(*SS, false);
111 if (isDependentScopeSpecifier(*SS)) {
113 // A qualified-id that refers to a type and in which the
114 // nested-name-specifier depends on a template-parameter (14.6.2)
115 // shall be prefixed by the keyword typename to indicate that the
116 // qualified-id denotes a type, forming an
117 // elaborated-type-specifier (7.1.5.3).
119 // We therefore do not perform any name lookup if the result would
120 // refer to a member of an unknown specialization.
121 if (!isClassName && !IsCtorOrDtorName)
124 // We know from the grammar that this name refers to a type,
125 // so build a dependent node to describe the type.
126 if (WantNontrivialTypeSourceInfo)
127 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
129 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
131 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
134 return ParsedType::make(T);
140 if (!LookupCtx->isDependentContext() &&
141 RequireCompleteDeclContext(*SS, LookupCtx))
145 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
146 // lookup for class-names.
147 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
149 LookupResult Result(*this, &II, NameLoc, Kind);
151 // Perform "qualified" name lookup into the declaration context we
152 // computed, which is either the type of the base of a member access
153 // expression or the declaration context associated with a prior
154 // nested-name-specifier.
155 LookupQualifiedName(Result, LookupCtx);
157 if (ObjectTypePtr && Result.empty()) {
158 // C++ [basic.lookup.classref]p3:
159 // If the unqualified-id is ~type-name, the type-name is looked up
160 // in the context of the entire postfix-expression. If the type T of
161 // the object expression is of a class type C, the type-name is also
162 // looked up in the scope of class C. At least one of the lookups shall
163 // find a name that refers to (possibly cv-qualified) T.
164 LookupName(Result, S);
167 // Perform unqualified name lookup.
168 LookupName(Result, S);
171 NamedDecl *IIDecl = 0;
172 switch (Result.getResultKind()) {
173 case LookupResult::NotFound:
174 case LookupResult::NotFoundInCurrentInstantiation:
176 TypeNameValidatorCCC Validator(true);
177 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
178 Kind, S, SS, Validator);
179 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
181 bool MemberOfUnknownSpecialization;
182 UnqualifiedId TemplateName;
183 TemplateName.setIdentifier(NewII, NameLoc);
184 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
185 CXXScopeSpec NewSS, *NewSSPtr = SS;
187 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
190 if (Correction && (NNS || NewII != &II) &&
191 // Ignore a correction to a template type as the to-be-corrected
192 // identifier is not a template (typo correction for template names
193 // is handled elsewhere).
194 !(getLangOpts().CPlusPlus && NewSSPtr &&
195 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
196 false, Template, MemberOfUnknownSpecialization))) {
197 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
198 isClassName, HasTrailingDot, ObjectTypePtr,
200 WantNontrivialTypeSourceInfo);
202 std::string CorrectedStr(Correction.getAsString(getLangOpts()));
203 std::string CorrectedQuotedStr(
204 Correction.getQuoted(getLangOpts()));
205 Diag(NameLoc, diag::err_unknown_typename_suggest)
206 << Result.getLookupName() << CorrectedQuotedStr
207 << FixItHint::CreateReplacement(SourceRange(NameLoc),
209 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl())
210 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
211 << CorrectedQuotedStr;
214 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
215 *CorrectedII = NewII;
220 // If typo correction failed or was not performed, fall through
221 case LookupResult::FoundOverloaded:
222 case LookupResult::FoundUnresolvedValue:
223 Result.suppressDiagnostics();
226 case LookupResult::Ambiguous:
227 // Recover from type-hiding ambiguities by hiding the type. We'll
228 // do the lookup again when looking for an object, and we can
229 // diagnose the error then. If we don't do this, then the error
230 // about hiding the type will be immediately followed by an error
231 // that only makes sense if the identifier was treated like a type.
232 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
233 Result.suppressDiagnostics();
237 // Look to see if we have a type anywhere in the list of results.
238 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
239 Res != ResEnd; ++Res) {
240 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
242 (*Res)->getLocation().getRawEncoding() <
243 IIDecl->getLocation().getRawEncoding())
249 // None of the entities we found is a type, so there is no way
250 // to even assume that the result is a type. In this case, don't
251 // complain about the ambiguity. The parser will either try to
252 // perform this lookup again (e.g., as an object name), which
253 // will produce the ambiguity, or will complain that it expected
255 Result.suppressDiagnostics();
259 // We found a type within the ambiguous lookup; diagnose the
260 // ambiguity and then return that type. This might be the right
261 // answer, or it might not be, but it suppresses any attempt to
262 // perform the name lookup again.
265 case LookupResult::Found:
266 IIDecl = Result.getFoundDecl();
270 assert(IIDecl && "Didn't find decl");
273 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
274 DiagnoseUseOfDecl(IIDecl, NameLoc);
277 T = Context.getTypeDeclType(TD);
279 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
280 // constructor or destructor name (in such a case, the scope specifier
281 // will be attached to the enclosing Expr or Decl node).
282 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
283 if (WantNontrivialTypeSourceInfo) {
284 // Construct a type with type-source information.
285 TypeLocBuilder Builder;
286 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
288 T = getElaboratedType(ETK_None, *SS, T);
289 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
290 ElabTL.setElaboratedKeywordLoc(SourceLocation());
291 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
292 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
294 T = getElaboratedType(ETK_None, *SS, T);
297 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
298 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
300 T = Context.getObjCInterfaceType(IDecl);
304 // If it's not plausibly a type, suppress diagnostics.
305 Result.suppressDiagnostics();
308 return ParsedType::make(T);
311 /// isTagName() - This method is called *for error recovery purposes only*
312 /// to determine if the specified name is a valid tag name ("struct foo"). If
313 /// so, this returns the TST for the tag corresponding to it (TST_enum,
314 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C
315 /// where the user forgot to specify the tag.
316 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
317 // Do a tag name lookup in this scope.
318 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
319 LookupName(R, S, false);
320 R.suppressDiagnostics();
321 if (R.getResultKind() == LookupResult::Found)
322 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
323 switch (TD->getTagKind()) {
324 case TTK_Struct: return DeclSpec::TST_struct;
325 case TTK_Union: return DeclSpec::TST_union;
326 case TTK_Class: return DeclSpec::TST_class;
327 case TTK_Enum: return DeclSpec::TST_enum;
331 return DeclSpec::TST_unspecified;
334 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
335 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
336 /// then downgrade the missing typename error to a warning.
337 /// This is needed for MSVC compatibility; Example:
339 /// template<class T> class A {
341 /// typedef int TYPE;
343 /// template<class T> class B : public A<T> {
345 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
348 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
349 if (CurContext->isRecord()) {
350 const Type *Ty = SS->getScopeRep()->getAsType();
352 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
353 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
354 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
355 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
357 return S->isFunctionPrototypeScope();
359 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
362 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
363 SourceLocation IILoc,
366 ParsedType &SuggestedType) {
367 // We don't have anything to suggest (yet).
368 SuggestedType = ParsedType();
370 // There may have been a typo in the name of the type. Look up typo
371 // results, in case we have something that we can suggest.
372 TypeNameValidatorCCC Validator(false);
373 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc),
374 LookupOrdinaryName, S, SS,
376 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
377 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
379 if (Corrected.isKeyword()) {
380 // We corrected to a keyword.
381 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
382 Diag(IILoc, diag::err_unknown_typename_suggest)
383 << &II << CorrectedQuotedStr;
385 NamedDecl *Result = Corrected.getCorrectionDecl();
386 // We found a similarly-named type or interface; suggest that.
387 if (!SS || !SS->isSet())
388 Diag(IILoc, diag::err_unknown_typename_suggest)
389 << &II << CorrectedQuotedStr
390 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
391 else if (DeclContext *DC = computeDeclContext(*SS, false))
392 Diag(IILoc, diag::err_unknown_nested_typename_suggest)
393 << &II << DC << CorrectedQuotedStr << SS->getRange()
394 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr);
396 llvm_unreachable("could not have corrected a typo here");
398 Diag(Result->getLocation(), diag::note_previous_decl)
399 << CorrectedQuotedStr;
401 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS,
402 false, false, ParsedType(),
403 /*IsCtorOrDtorName=*/false,
404 /*NonTrivialTypeSourceInfo=*/true);
409 if (getLangOpts().CPlusPlus) {
410 // See if II is a class template that the user forgot to pass arguments to.
412 Name.setIdentifier(&II, IILoc);
413 CXXScopeSpec EmptySS;
414 TemplateTy TemplateResult;
415 bool MemberOfUnknownSpecialization;
416 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
417 Name, ParsedType(), true, TemplateResult,
418 MemberOfUnknownSpecialization) == TNK_Type_template) {
419 TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
420 Diag(IILoc, diag::err_template_missing_args) << TplName;
421 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
422 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
423 << TplDecl->getTemplateParameters()->getSourceRange();
429 // FIXME: Should we move the logic that tries to recover from a missing tag
430 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
432 if (!SS || (!SS->isSet() && !SS->isInvalid()))
433 Diag(IILoc, diag::err_unknown_typename) << &II;
434 else if (DeclContext *DC = computeDeclContext(*SS, false))
435 Diag(IILoc, diag::err_typename_nested_not_found)
436 << &II << DC << SS->getRange();
437 else if (isDependentScopeSpecifier(*SS)) {
438 unsigned DiagID = diag::err_typename_missing;
439 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
440 DiagID = diag::warn_typename_missing;
442 Diag(SS->getRange().getBegin(), DiagID)
443 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
444 << SourceRange(SS->getRange().getBegin(), IILoc)
445 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
446 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc)
449 assert(SS && SS->isInvalid() &&
450 "Invalid scope specifier has already been diagnosed");
456 /// \brief Determine whether the given result set contains either a type name
458 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
459 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
460 NextToken.is(tok::less);
462 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
463 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
466 if (CheckTemplate && isa<TemplateDecl>(*I))
473 Sema::NameClassification Sema::ClassifyName(Scope *S,
475 IdentifierInfo *&Name,
476 SourceLocation NameLoc,
477 const Token &NextToken) {
478 DeclarationNameInfo NameInfo(Name, NameLoc);
479 ObjCMethodDecl *CurMethod = getCurMethodDecl();
481 if (NextToken.is(tok::coloncolon)) {
482 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
483 QualType(), false, SS, 0, false);
487 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
488 LookupParsedName(Result, S, &SS, !CurMethod);
490 // Perform lookup for Objective-C instance variables (including automatically
491 // synthesized instance variables), if we're in an Objective-C method.
492 // FIXME: This lookup really, really needs to be folded in to the normal
493 // unqualified lookup mechanism.
494 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
495 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
496 if (E.get() || E.isInvalid())
500 bool SecondTry = false;
501 bool IsFilteredTemplateName = false;
504 switch (Result.getResultKind()) {
505 case LookupResult::NotFound:
506 // If an unqualified-id is followed by a '(', then we have a function
508 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
509 // In C++, this is an ADL-only call.
511 if (getLangOpts().CPlusPlus)
512 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
515 // If the expression that precedes the parenthesized argument list in a
516 // function call consists solely of an identifier, and if no
517 // declaration is visible for this identifier, the identifier is
518 // implicitly declared exactly as if, in the innermost block containing
519 // the function call, the declaration
521 // extern int identifier ();
525 // We also allow this in C99 as an extension.
526 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
528 Result.resolveKind();
529 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
533 // In C, we first see whether there is a tag type by the same name, in
534 // which case it's likely that the user just forget to write "enum",
535 // "struct", or "union".
536 if (!getLangOpts().CPlusPlus && !SecondTry) {
537 Result.clear(LookupTagName);
538 LookupParsedName(Result, S, &SS);
539 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) {
540 const char *TagName = 0;
541 const char *FixItTagName = 0;
542 switch (Tag->getTagKind()) {
545 FixItTagName = "class ";
550 FixItTagName = "enum ";
555 FixItTagName = "struct ";
560 FixItTagName = "union ";
564 Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
565 << Name << TagName << getLangOpts().CPlusPlus
566 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
570 Result.clear(LookupOrdinaryName);
573 // Perform typo correction to determine if there is another name that is
574 // close to this name.
577 CorrectionCandidateCallback DefaultValidator;
578 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
579 Result.getLookupKind(), S,
580 &SS, DefaultValidator)) {
581 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
582 unsigned QualifiedDiag = diag::err_no_member_suggest;
583 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
586 NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
587 NamedDecl *UnderlyingFirstDecl
588 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
589 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
590 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
591 UnqualifiedDiag = diag::err_no_template_suggest;
592 QualifiedDiag = diag::err_no_member_template_suggest;
593 } else if (UnderlyingFirstDecl &&
594 (isa<TypeDecl>(UnderlyingFirstDecl) ||
595 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
596 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
597 UnqualifiedDiag = diag::err_unknown_typename_suggest;
598 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
602 Diag(NameLoc, UnqualifiedDiag)
603 << Name << CorrectedQuotedStr
604 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
606 Diag(NameLoc, QualifiedDiag)
607 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
609 << FixItHint::CreateReplacement(NameLoc, CorrectedStr);
611 // Update the name, so that the caller has the new name.
612 Name = Corrected.getCorrectionAsIdentifierInfo();
614 // Typo correction corrected to a keyword.
615 if (Corrected.isKeyword())
616 return Corrected.getCorrectionAsIdentifierInfo();
618 // Also update the LookupResult...
619 // FIXME: This should probably go away at some point
621 Result.setLookupName(Corrected.getCorrection());
623 Result.addDecl(FirstDecl);
624 Diag(FirstDecl->getLocation(), diag::note_previous_decl)
625 << CorrectedQuotedStr;
628 // If we found an Objective-C instance variable, let
629 // LookupInObjCMethod build the appropriate expression to
630 // reference the ivar.
631 // FIXME: This is a gross hack.
632 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
634 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
642 // We failed to correct; just fall through and let the parser deal with it.
643 Result.suppressDiagnostics();
644 return NameClassification::Unknown();
646 case LookupResult::NotFoundInCurrentInstantiation: {
647 // We performed name lookup into the current instantiation, and there were
648 // dependent bases, so we treat this result the same way as any other
649 // dependent nested-name-specifier.
652 // A name used in a template declaration or definition and that is
653 // dependent on a template-parameter is assumed not to name a type
654 // unless the applicable name lookup finds a type name or the name is
655 // qualified by the keyword typename.
657 // FIXME: If the next token is '<', we might want to ask the parser to
658 // perform some heroics to see if we actually have a
659 // template-argument-list, which would indicate a missing 'template'
661 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
662 NameInfo, /*TemplateArgs=*/0);
665 case LookupResult::Found:
666 case LookupResult::FoundOverloaded:
667 case LookupResult::FoundUnresolvedValue:
670 case LookupResult::Ambiguous:
671 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
672 hasAnyAcceptableTemplateNames(Result)) {
673 // C++ [temp.local]p3:
674 // A lookup that finds an injected-class-name (10.2) can result in an
675 // ambiguity in certain cases (for example, if it is found in more than
676 // one base class). If all of the injected-class-names that are found
677 // refer to specializations of the same class template, and if the name
678 // is followed by a template-argument-list, the reference refers to the
679 // class template itself and not a specialization thereof, and is not
682 // This filtering can make an ambiguous result into an unambiguous one,
683 // so try again after filtering out template names.
684 FilterAcceptableTemplateNames(Result);
685 if (!Result.isAmbiguous()) {
686 IsFilteredTemplateName = true;
691 // Diagnose the ambiguity and return an error.
692 return NameClassification::Error();
695 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
696 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
697 // C++ [temp.names]p3:
698 // After name lookup (3.4) finds that a name is a template-name or that
699 // an operator-function-id or a literal- operator-id refers to a set of
700 // overloaded functions any member of which is a function template if
701 // this is followed by a <, the < is always taken as the delimiter of a
702 // template-argument-list and never as the less-than operator.
703 if (!IsFilteredTemplateName)
704 FilterAcceptableTemplateNames(Result);
706 if (!Result.empty()) {
707 bool IsFunctionTemplate;
708 TemplateName Template;
709 if (Result.end() - Result.begin() > 1) {
710 IsFunctionTemplate = true;
711 Template = Context.getOverloadedTemplateName(Result.begin(),
715 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
716 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
718 if (SS.isSet() && !SS.isInvalid())
719 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
720 /*TemplateKeyword=*/false,
723 Template = TemplateName(TD);
726 if (IsFunctionTemplate) {
727 // Function templates always go through overload resolution, at which
728 // point we'll perform the various checks (e.g., accessibility) we need
729 // to based on which function we selected.
730 Result.suppressDiagnostics();
732 return NameClassification::FunctionTemplate(Template);
735 return NameClassification::TypeTemplate(Template);
739 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
740 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
741 DiagnoseUseOfDecl(Type, NameLoc);
742 QualType T = Context.getTypeDeclType(Type);
743 return ParsedType::make(T);
746 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
748 // FIXME: It's unfortunate that we don't have a Type node for handling this.
749 if (ObjCCompatibleAliasDecl *Alias
750 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
751 Class = Alias->getClassInterface();
755 DiagnoseUseOfDecl(Class, NameLoc);
757 if (NextToken.is(tok::period)) {
758 // Interface. <something> is parsed as a property reference expression.
759 // Just return "unknown" as a fall-through for now.
760 Result.suppressDiagnostics();
761 return NameClassification::Unknown();
764 QualType T = Context.getObjCInterfaceType(Class);
765 return ParsedType::make(T);
768 if (!Result.empty() && (*Result.begin())->isCXXClassMember())
769 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
771 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
772 return BuildDeclarationNameExpr(SS, Result, ADL);
775 // Determines the context to return to after temporarily entering a
776 // context. This depends in an unnecessarily complicated way on the
777 // exact ordering of callbacks from the parser.
778 DeclContext *Sema::getContainingDC(DeclContext *DC) {
780 // Functions defined inline within classes aren't parsed until we've
781 // finished parsing the top-level class, so the top-level class is
782 // the context we'll need to return to.
783 if (isa<FunctionDecl>(DC)) {
784 DC = DC->getLexicalParent();
786 // A function not defined within a class will always return to its
788 if (!isa<CXXRecordDecl>(DC))
791 // A C++ inline method/friend is parsed *after* the topmost class
792 // it was declared in is fully parsed ("complete"); the topmost
793 // class is the context we need to return to.
794 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
797 // Return the declaration context of the topmost class the inline method is
802 return DC->getLexicalParent();
805 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
806 assert(getContainingDC(DC) == CurContext &&
807 "The next DeclContext should be lexically contained in the current one.");
812 void Sema::PopDeclContext() {
813 assert(CurContext && "DeclContext imbalance!");
815 CurContext = getContainingDC(CurContext);
816 assert(CurContext && "Popped translation unit!");
819 /// EnterDeclaratorContext - Used when we must lookup names in the context
820 /// of a declarator's nested name specifier.
822 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
823 // C++0x [basic.lookup.unqual]p13:
824 // A name used in the definition of a static data member of class
825 // X (after the qualified-id of the static member) is looked up as
826 // if the name was used in a member function of X.
827 // C++0x [basic.lookup.unqual]p14:
828 // If a variable member of a namespace is defined outside of the
829 // scope of its namespace then any name used in the definition of
830 // the variable member (after the declarator-id) is looked up as
831 // if the definition of the variable member occurred in its
833 // Both of these imply that we should push a scope whose context
834 // is the semantic context of the declaration. We can't use
835 // PushDeclContext here because that context is not necessarily
836 // lexically contained in the current context. Fortunately,
837 // the containing scope should have the appropriate information.
839 assert(!S->getEntity() && "scope already has entity");
842 Scope *Ancestor = S->getParent();
843 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
844 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
851 void Sema::ExitDeclaratorContext(Scope *S) {
852 assert(S->getEntity() == CurContext && "Context imbalance!");
854 // Switch back to the lexical context. The safety of this is
855 // enforced by an assert in EnterDeclaratorContext.
856 Scope *Ancestor = S->getParent();
857 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
858 CurContext = (DeclContext*) Ancestor->getEntity();
860 // We don't need to do anything with the scope, which is going to
865 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
866 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
867 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
868 // We assume that the caller has already called
869 // ActOnReenterTemplateScope
870 FD = TFD->getTemplatedDecl();
875 // Same implementation as PushDeclContext, but enters the context
876 // from the lexical parent, rather than the top-level class.
877 assert(CurContext == FD->getLexicalParent() &&
878 "The next DeclContext should be lexically contained in the current one.");
880 S->setEntity(CurContext);
882 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
883 ParmVarDecl *Param = FD->getParamDecl(P);
884 // If the parameter has an identifier, then add it to the scope
885 if (Param->getIdentifier()) {
887 IdResolver.AddDecl(Param);
893 void Sema::ActOnExitFunctionContext() {
894 // Same implementation as PopDeclContext, but returns to the lexical parent,
895 // rather than the top-level class.
896 assert(CurContext && "DeclContext imbalance!");
897 CurContext = CurContext->getLexicalParent();
898 assert(CurContext && "Popped translation unit!");
902 /// \brief Determine whether we allow overloading of the function
903 /// PrevDecl with another declaration.
905 /// This routine determines whether overloading is possible, not
906 /// whether some new function is actually an overload. It will return
907 /// true in C++ (where we can always provide overloads) or, as an
908 /// extension, in C when the previous function is already an
909 /// overloaded function declaration or has the "overloadable"
911 static bool AllowOverloadingOfFunction(LookupResult &Previous,
912 ASTContext &Context) {
913 if (Context.getLangOpts().CPlusPlus)
916 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
919 return (Previous.getResultKind() == LookupResult::Found
920 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
923 /// Add this decl to the scope shadowed decl chains.
924 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
925 // Move up the scope chain until we find the nearest enclosing
926 // non-transparent context. The declaration will be introduced into this
928 while (S->getEntity() &&
929 ((DeclContext *)S->getEntity())->isTransparentContext())
932 // Add scoped declarations into their context, so that they can be
933 // found later. Declarations without a context won't be inserted
936 CurContext->addDecl(D);
938 // Out-of-line definitions shouldn't be pushed into scope in C++.
939 // Out-of-line variable and function definitions shouldn't even in C.
940 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
942 !D->getDeclContext()->getRedeclContext()->Equals(
943 D->getLexicalDeclContext()->getRedeclContext()))
946 // Template instantiations should also not be pushed into scope.
947 if (isa<FunctionDecl>(D) &&
948 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
951 // If this replaces anything in the current scope,
952 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
953 IEnd = IdResolver.end();
954 for (; I != IEnd; ++I) {
955 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
957 IdResolver.RemoveDecl(*I);
959 // Should only need to replace one decl.
966 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
967 // Implicitly-generated labels may end up getting generated in an order that
968 // isn't strictly lexical, which breaks name lookup. Be careful to insert
969 // the label at the appropriate place in the identifier chain.
970 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
971 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
972 if (IDC == CurContext) {
973 if (!S->isDeclScope(*I))
975 } else if (IDC->Encloses(CurContext))
979 IdResolver.InsertDeclAfter(I, D);
981 IdResolver.AddDecl(D);
985 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
986 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
990 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S,
991 bool ExplicitInstantiationOrSpecialization) {
992 return IdResolver.isDeclInScope(D, Ctx, Context, S,
993 ExplicitInstantiationOrSpecialization);
996 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
997 DeclContext *TargetDC = DC->getPrimaryContext();
999 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity())
1000 if (ScopeDC->getPrimaryContext() == TargetDC)
1002 } while ((S = S->getParent()));
1007 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1011 /// Filters out lookup results that don't fall within the given scope
1012 /// as determined by isDeclInScope.
1013 void Sema::FilterLookupForScope(LookupResult &R,
1014 DeclContext *Ctx, Scope *S,
1015 bool ConsiderLinkage,
1016 bool ExplicitInstantiationOrSpecialization) {
1017 LookupResult::Filter F = R.makeFilter();
1018 while (F.hasNext()) {
1019 NamedDecl *D = F.next();
1021 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1024 if (ConsiderLinkage &&
1025 isOutOfScopePreviousDeclaration(D, Ctx, Context))
1034 static bool isUsingDecl(NamedDecl *D) {
1035 return isa<UsingShadowDecl>(D) ||
1036 isa<UnresolvedUsingTypenameDecl>(D) ||
1037 isa<UnresolvedUsingValueDecl>(D);
1040 /// Removes using shadow declarations from the lookup results.
1041 static void RemoveUsingDecls(LookupResult &R) {
1042 LookupResult::Filter F = R.makeFilter();
1044 if (isUsingDecl(F.next()))
1050 /// \brief Check for this common pattern:
1053 /// S(const S&); // DO NOT IMPLEMENT
1054 /// void operator=(const S&); // DO NOT IMPLEMENT
1057 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1058 // FIXME: Should check for private access too but access is set after we get
1060 if (D->doesThisDeclarationHaveABody())
1063 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1064 return CD->isCopyConstructor();
1065 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1066 return Method->isCopyAssignmentOperator();
1070 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1073 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1076 // Ignore class templates.
1077 if (D->getDeclContext()->isDependentContext() ||
1078 D->getLexicalDeclContext()->isDependentContext())
1081 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1082 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1085 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1086 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1089 // 'static inline' functions are used in headers; don't warn.
1090 if (FD->getStorageClass() == SC_Static &&
1091 FD->isInlineSpecified())
1095 if (FD->doesThisDeclarationHaveABody() &&
1096 Context.DeclMustBeEmitted(FD))
1098 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1099 if (!VD->isFileVarDecl() ||
1100 VD->getType().isConstant(Context) ||
1101 Context.DeclMustBeEmitted(VD))
1104 if (VD->isStaticDataMember() &&
1105 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1112 // Only warn for unused decls internal to the translation unit.
1113 if (D->getLinkage() == ExternalLinkage)
1119 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1123 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1124 const FunctionDecl *First = FD->getFirstDeclaration();
1125 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1126 return; // First should already be in the vector.
1129 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1130 const VarDecl *First = VD->getFirstDeclaration();
1131 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1132 return; // First should already be in the vector.
1135 if (ShouldWarnIfUnusedFileScopedDecl(D))
1136 UnusedFileScopedDecls.push_back(D);
1139 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1140 if (D->isInvalidDecl())
1143 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1146 if (isa<LabelDecl>(D))
1149 // White-list anything that isn't a local variable.
1150 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1151 !D->getDeclContext()->isFunctionOrMethod())
1154 // Types of valid local variables should be complete, so this should succeed.
1155 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1157 // White-list anything with an __attribute__((unused)) type.
1158 QualType Ty = VD->getType();
1160 // Only look at the outermost level of typedef.
1161 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
1162 if (TT->getDecl()->hasAttr<UnusedAttr>())
1166 // If we failed to complete the type for some reason, or if the type is
1167 // dependent, don't diagnose the variable.
1168 if (Ty->isIncompleteType() || Ty->isDependentType())
1171 if (const TagType *TT = Ty->getAs<TagType>()) {
1172 const TagDecl *Tag = TT->getDecl();
1173 if (Tag->hasAttr<UnusedAttr>())
1176 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1177 if (!RD->hasTrivialDestructor())
1180 if (const Expr *Init = VD->getInit()) {
1181 const CXXConstructExpr *Construct =
1182 dyn_cast<CXXConstructExpr>(Init);
1183 if (Construct && !Construct->isElidable()) {
1184 CXXConstructorDecl *CD = Construct->getConstructor();
1185 if (!CD->isTrivial())
1192 // TODO: __attribute__((unused)) templates?
1198 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1200 if (isa<LabelDecl>(D)) {
1201 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1202 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1203 if (AfterColon.isInvalid())
1205 Hint = FixItHint::CreateRemoval(CharSourceRange::
1206 getCharRange(D->getLocStart(), AfterColon));
1211 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1212 /// unless they are marked attr(unused).
1213 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1215 if (!ShouldDiagnoseUnusedDecl(D))
1218 GenerateFixForUnusedDecl(D, Context, Hint);
1221 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1222 DiagID = diag::warn_unused_exception_param;
1223 else if (isa<LabelDecl>(D))
1224 DiagID = diag::warn_unused_label;
1226 DiagID = diag::warn_unused_variable;
1228 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1231 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1232 // Verify that we have no forward references left. If so, there was a goto
1233 // or address of a label taken, but no definition of it. Label fwd
1234 // definitions are indicated with a null substmt.
1235 if (L->getStmt() == 0)
1236 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1239 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1240 if (S->decl_empty()) return;
1241 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1242 "Scope shouldn't contain decls!");
1244 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1247 assert(TmpD && "This decl didn't get pushed??");
1249 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1250 NamedDecl *D = cast<NamedDecl>(TmpD);
1252 if (!D->getDeclName()) continue;
1254 // Diagnose unused variables in this scope.
1255 if (!S->hasErrorOccurred())
1256 DiagnoseUnusedDecl(D);
1258 // If this was a forward reference to a label, verify it was defined.
1259 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1260 CheckPoppedLabel(LD, *this);
1262 // Remove this name from our lexical scope.
1263 IdResolver.RemoveDecl(D);
1267 void Sema::ActOnStartFunctionDeclarator() {
1268 ++InFunctionDeclarator;
1271 void Sema::ActOnEndFunctionDeclarator() {
1272 assert(InFunctionDeclarator);
1273 --InFunctionDeclarator;
1276 /// \brief Look for an Objective-C class in the translation unit.
1278 /// \param Id The name of the Objective-C class we're looking for. If
1279 /// typo-correction fixes this name, the Id will be updated
1280 /// to the fixed name.
1282 /// \param IdLoc The location of the name in the translation unit.
1284 /// \param TypoCorrection If true, this routine will attempt typo correction
1285 /// if there is no class with the given name.
1287 /// \returns The declaration of the named Objective-C class, or NULL if the
1288 /// class could not be found.
1289 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1290 SourceLocation IdLoc,
1291 bool DoTypoCorrection) {
1292 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1293 // creation from this context.
1294 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1296 if (!IDecl && DoTypoCorrection) {
1297 // Perform typo correction at the given location, but only if we
1298 // find an Objective-C class name.
1299 DeclFilterCCC<ObjCInterfaceDecl> Validator;
1300 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1301 LookupOrdinaryName, TUScope, NULL,
1303 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1304 Diag(IdLoc, diag::err_undef_interface_suggest)
1305 << Id << IDecl->getDeclName()
1306 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
1307 Diag(IDecl->getLocation(), diag::note_previous_decl)
1308 << IDecl->getDeclName();
1310 Id = IDecl->getIdentifier();
1313 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1314 // This routine must always return a class definition, if any.
1315 if (Def && Def->getDefinition())
1316 Def = Def->getDefinition();
1320 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1321 /// from S, where a non-field would be declared. This routine copes
1322 /// with the difference between C and C++ scoping rules in structs and
1323 /// unions. For example, the following code is well-formed in C but
1324 /// ill-formed in C++:
1330 /// void test_S6() {
1335 /// For the declaration of BAR, this routine will return a different
1336 /// scope. The scope S will be the scope of the unnamed enumeration
1337 /// within S6. In C++, this routine will return the scope associated
1338 /// with S6, because the enumeration's scope is a transparent
1339 /// context but structures can contain non-field names. In C, this
1340 /// routine will return the translation unit scope, since the
1341 /// enumeration's scope is a transparent context and structures cannot
1342 /// contain non-field names.
1343 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1344 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1346 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
1347 (S->isClassScope() && !getLangOpts().CPlusPlus))
1352 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1353 /// file scope. lazily create a decl for it. ForRedeclaration is true
1354 /// if we're creating this built-in in anticipation of redeclaring the
1356 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1357 Scope *S, bool ForRedeclaration,
1358 SourceLocation Loc) {
1359 Builtin::ID BID = (Builtin::ID)bid;
1361 ASTContext::GetBuiltinTypeError Error;
1362 QualType R = Context.GetBuiltinType(BID, Error);
1364 case ASTContext::GE_None:
1368 case ASTContext::GE_Missing_stdio:
1369 if (ForRedeclaration)
1370 Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1371 << Context.BuiltinInfo.GetName(BID);
1374 case ASTContext::GE_Missing_setjmp:
1375 if (ForRedeclaration)
1376 Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1377 << Context.BuiltinInfo.GetName(BID);
1380 case ASTContext::GE_Missing_ucontext:
1381 if (ForRedeclaration)
1382 Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1383 << Context.BuiltinInfo.GetName(BID);
1387 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1388 Diag(Loc, diag::ext_implicit_lib_function_decl)
1389 << Context.BuiltinInfo.GetName(BID)
1391 if (Context.BuiltinInfo.getHeaderName(BID) &&
1392 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1393 != DiagnosticsEngine::Ignored)
1394 Diag(Loc, diag::note_please_include_header)
1395 << Context.BuiltinInfo.getHeaderName(BID)
1396 << Context.BuiltinInfo.GetName(BID);
1399 FunctionDecl *New = FunctionDecl::Create(Context,
1400 Context.getTranslationUnitDecl(),
1401 Loc, Loc, II, R, /*TInfo=*/0,
1404 /*hasPrototype=*/true);
1407 // Create Decl objects for each parameter, adding them to the
1409 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1410 SmallVector<ParmVarDecl*, 16> Params;
1411 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1413 ParmVarDecl::Create(Context, New, SourceLocation(),
1414 SourceLocation(), 0,
1415 FT->getArgType(i), /*TInfo=*/0,
1416 SC_None, SC_None, 0);
1417 parm->setScopeInfo(0, i);
1418 Params.push_back(parm);
1420 New->setParams(Params);
1423 AddKnownFunctionAttributes(New);
1425 // TUScope is the translation-unit scope to insert this function into.
1426 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1427 // relate Scopes to DeclContexts, and probably eliminate CurContext
1428 // entirely, but we're not there yet.
1429 DeclContext *SavedContext = CurContext;
1430 CurContext = Context.getTranslationUnitDecl();
1431 PushOnScopeChains(New, TUScope);
1432 CurContext = SavedContext;
1436 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1438 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1439 OldType = OldTypedef->getUnderlyingType();
1441 OldType = Context.getTypeDeclType(Old);
1442 QualType NewType = New->getUnderlyingType();
1444 if (NewType->isVariablyModifiedType()) {
1445 // Must not redefine a typedef with a variably-modified type.
1446 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1447 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1449 if (Old->getLocation().isValid())
1450 Diag(Old->getLocation(), diag::note_previous_definition);
1451 New->setInvalidDecl();
1455 if (OldType != NewType &&
1456 !OldType->isDependentType() &&
1457 !NewType->isDependentType() &&
1458 !Context.hasSameType(OldType, NewType)) {
1459 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1460 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1461 << Kind << NewType << OldType;
1462 if (Old->getLocation().isValid())
1463 Diag(Old->getLocation(), diag::note_previous_definition);
1464 New->setInvalidDecl();
1470 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1471 /// same name and scope as a previous declaration 'Old'. Figure out
1472 /// how to resolve this situation, merging decls or emitting
1473 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1475 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1476 // If the new decl is known invalid already, don't bother doing any
1478 if (New->isInvalidDecl()) return;
1480 // Allow multiple definitions for ObjC built-in typedefs.
1481 // FIXME: Verify the underlying types are equivalent!
1482 if (getLangOpts().ObjC1) {
1483 const IdentifierInfo *TypeID = New->getIdentifier();
1484 switch (TypeID->getLength()) {
1487 if (!TypeID->isStr("id"))
1489 Context.setObjCIdRedefinitionType(New->getUnderlyingType());
1490 // Install the built-in type for 'id', ignoring the current definition.
1491 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1494 if (!TypeID->isStr("Class"))
1496 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1497 // Install the built-in type for 'Class', ignoring the current definition.
1498 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1501 if (!TypeID->isStr("SEL"))
1503 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1504 // Install the built-in type for 'SEL', ignoring the current definition.
1505 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1508 // Fall through - the typedef name was not a builtin type.
1511 // Verify the old decl was also a type.
1512 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1514 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1515 << New->getDeclName();
1517 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1518 if (OldD->getLocation().isValid())
1519 Diag(OldD->getLocation(), diag::note_previous_definition);
1521 return New->setInvalidDecl();
1524 // If the old declaration is invalid, just give up here.
1525 if (Old->isInvalidDecl())
1526 return New->setInvalidDecl();
1528 // If the typedef types are not identical, reject them in all languages and
1529 // with any extensions enabled.
1530 if (isIncompatibleTypedef(Old, New))
1533 // The types match. Link up the redeclaration chain if the old
1534 // declaration was a typedef.
1535 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old))
1536 New->setPreviousDeclaration(Typedef);
1538 if (getLangOpts().MicrosoftExt)
1541 if (getLangOpts().CPlusPlus) {
1542 // C++ [dcl.typedef]p2:
1543 // In a given non-class scope, a typedef specifier can be used to
1544 // redefine the name of any type declared in that scope to refer
1545 // to the type to which it already refers.
1546 if (!isa<CXXRecordDecl>(CurContext))
1549 // C++0x [dcl.typedef]p4:
1550 // In a given class scope, a typedef specifier can be used to redefine
1551 // any class-name declared in that scope that is not also a typedef-name
1552 // to refer to the type to which it already refers.
1554 // This wording came in via DR424, which was a correction to the
1555 // wording in DR56, which accidentally banned code like:
1558 // typedef struct A { } A;
1561 // in the C++03 standard. We implement the C++0x semantics, which
1562 // allow the above but disallow
1569 // since that was the intent of DR56.
1570 if (!isa<TypedefNameDecl>(Old))
1573 Diag(New->getLocation(), diag::err_redefinition)
1574 << New->getDeclName();
1575 Diag(Old->getLocation(), diag::note_previous_definition);
1576 return New->setInvalidDecl();
1579 // Modules always permit redefinition of typedefs, as does C11.
1580 if (getLangOpts().Modules || getLangOpts().C11)
1583 // If we have a redefinition of a typedef in C, emit a warning. This warning
1584 // is normally mapped to an error, but can be controlled with
1585 // -Wtypedef-redefinition. If either the original or the redefinition is
1586 // in a system header, don't emit this for compatibility with GCC.
1587 if (getDiagnostics().getSuppressSystemWarnings() &&
1588 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1589 Context.getSourceManager().isInSystemHeader(New->getLocation())))
1592 Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1593 << New->getDeclName();
1594 Diag(Old->getLocation(), diag::note_previous_definition);
1598 /// DeclhasAttr - returns true if decl Declaration already has the target
1601 DeclHasAttr(const Decl *D, const Attr *A) {
1602 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1603 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1604 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1605 if ((*i)->getKind() == A->getKind()) {
1607 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1611 // FIXME: Don't hardcode this check
1612 if (OA && isa<OwnershipAttr>(*i))
1613 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1620 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
1621 void Sema::mergeDeclAttributes(Decl *New, Decl *Old,
1622 bool MergeDeprecation) {
1623 if (!Old->hasAttrs())
1626 bool foundAny = New->hasAttrs();
1628 // Ensure that any moving of objects within the allocated map is done before
1630 if (!foundAny) New->setAttrs(AttrVec());
1632 for (specific_attr_iterator<InheritableAttr>
1633 i = Old->specific_attr_begin<InheritableAttr>(),
1634 e = Old->specific_attr_end<InheritableAttr>();
1636 // Ignore deprecated/unavailable/availability attributes if requested.
1637 if (!MergeDeprecation &&
1638 (isa<DeprecatedAttr>(*i) ||
1639 isa<UnavailableAttr>(*i) ||
1640 isa<AvailabilityAttr>(*i)))
1643 if (!DeclHasAttr(New, *i)) {
1644 InheritableAttr *newAttr = cast<InheritableAttr>((*i)->clone(Context));
1645 newAttr->setInherited(true);
1646 New->addAttr(newAttr);
1651 if (!foundAny) New->dropAttrs();
1654 /// mergeParamDeclAttributes - Copy attributes from the old parameter
1656 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
1657 const ParmVarDecl *oldDecl,
1659 if (!oldDecl->hasAttrs())
1662 bool foundAny = newDecl->hasAttrs();
1664 // Ensure that any moving of objects within the allocated map is
1665 // done before we process them.
1666 if (!foundAny) newDecl->setAttrs(AttrVec());
1668 for (specific_attr_iterator<InheritableParamAttr>
1669 i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
1670 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
1671 if (!DeclHasAttr(newDecl, *i)) {
1672 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C));
1673 newAttr->setInherited(true);
1674 newDecl->addAttr(newAttr);
1679 if (!foundAny) newDecl->dropAttrs();
1684 /// Used in MergeFunctionDecl to keep track of function parameters in
1686 struct GNUCompatibleParamWarning {
1687 ParmVarDecl *OldParm;
1688 ParmVarDecl *NewParm;
1689 QualType PromotedType;
1694 /// getSpecialMember - get the special member enum for a method.
1695 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
1696 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
1697 if (Ctor->isDefaultConstructor())
1698 return Sema::CXXDefaultConstructor;
1700 if (Ctor->isCopyConstructor())
1701 return Sema::CXXCopyConstructor;
1703 if (Ctor->isMoveConstructor())
1704 return Sema::CXXMoveConstructor;
1705 } else if (isa<CXXDestructorDecl>(MD)) {
1706 return Sema::CXXDestructor;
1707 } else if (MD->isCopyAssignmentOperator()) {
1708 return Sema::CXXCopyAssignment;
1709 } else if (MD->isMoveAssignmentOperator()) {
1710 return Sema::CXXMoveAssignment;
1713 return Sema::CXXInvalid;
1716 /// canRedefineFunction - checks if a function can be redefined. Currently,
1717 /// only extern inline functions can be redefined, and even then only in
1719 static bool canRedefineFunction(const FunctionDecl *FD,
1720 const LangOptions& LangOpts) {
1721 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
1722 !LangOpts.CPlusPlus &&
1723 FD->isInlineSpecified() &&
1724 FD->getStorageClass() == SC_Extern);
1727 /// MergeFunctionDecl - We just parsed a function 'New' from
1728 /// declarator D which has the same name and scope as a previous
1729 /// declaration 'Old'. Figure out how to resolve this situation,
1730 /// merging decls or emitting diagnostics as appropriate.
1732 /// In C++, New and Old must be declarations that are not
1733 /// overloaded. Use IsOverload to determine whether New and Old are
1734 /// overloaded, and to select the Old declaration that New should be
1737 /// Returns true if there was an error, false otherwise.
1738 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) {
1739 // Verify the old decl was also a function.
1740 FunctionDecl *Old = 0;
1741 if (FunctionTemplateDecl *OldFunctionTemplate
1742 = dyn_cast<FunctionTemplateDecl>(OldD))
1743 Old = OldFunctionTemplate->getTemplatedDecl();
1745 Old = dyn_cast<FunctionDecl>(OldD);
1747 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
1748 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
1749 Diag(Shadow->getTargetDecl()->getLocation(),
1750 diag::note_using_decl_target);
1751 Diag(Shadow->getUsingDecl()->getLocation(),
1752 diag::note_using_decl) << 0;
1756 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1757 << New->getDeclName();
1758 Diag(OldD->getLocation(), diag::note_previous_definition);
1762 // Determine whether the previous declaration was a definition,
1763 // implicit declaration, or a declaration.
1764 diag::kind PrevDiag;
1765 if (Old->isThisDeclarationADefinition())
1766 PrevDiag = diag::note_previous_definition;
1767 else if (Old->isImplicit())
1768 PrevDiag = diag::note_previous_implicit_declaration;
1770 PrevDiag = diag::note_previous_declaration;
1772 QualType OldQType = Context.getCanonicalType(Old->getType());
1773 QualType NewQType = Context.getCanonicalType(New->getType());
1775 // Don't complain about this if we're in GNU89 mode and the old function
1776 // is an extern inline function.
1777 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1778 New->getStorageClass() == SC_Static &&
1779 Old->getStorageClass() != SC_Static &&
1780 !canRedefineFunction(Old, getLangOpts())) {
1781 if (getLangOpts().MicrosoftExt) {
1782 Diag(New->getLocation(), diag::warn_static_non_static) << New;
1783 Diag(Old->getLocation(), PrevDiag);
1785 Diag(New->getLocation(), diag::err_static_non_static) << New;
1786 Diag(Old->getLocation(), PrevDiag);
1791 // If a function is first declared with a calling convention, but is
1792 // later declared or defined without one, the second decl assumes the
1793 // calling convention of the first.
1795 // For the new decl, we have to look at the NON-canonical type to tell the
1796 // difference between a function that really doesn't have a calling
1797 // convention and one that is declared cdecl. That's because in
1798 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1799 // because it is the default calling convention.
1801 // Note also that we DO NOT return at this point, because we still have
1802 // other tests to run.
1803 const FunctionType *OldType = cast<FunctionType>(OldQType);
1804 const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1805 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1806 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1807 bool RequiresAdjustment = false;
1808 if (OldTypeInfo.getCC() != CC_Default &&
1809 NewTypeInfo.getCC() == CC_Default) {
1810 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
1811 RequiresAdjustment = true;
1812 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1813 NewTypeInfo.getCC())) {
1814 // Calling conventions really aren't compatible, so complain.
1815 Diag(New->getLocation(), diag::err_cconv_change)
1816 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1817 << (OldTypeInfo.getCC() == CC_Default)
1818 << (OldTypeInfo.getCC() == CC_Default ? "" :
1819 FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1820 Diag(Old->getLocation(), diag::note_previous_declaration);
1824 // FIXME: diagnose the other way around?
1825 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
1826 NewTypeInfo = NewTypeInfo.withNoReturn(true);
1827 RequiresAdjustment = true;
1830 // Merge regparm attribute.
1831 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
1832 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
1833 if (NewTypeInfo.getHasRegParm()) {
1834 Diag(New->getLocation(), diag::err_regparm_mismatch)
1835 << NewType->getRegParmType()
1836 << OldType->getRegParmType();
1837 Diag(Old->getLocation(), diag::note_previous_declaration);
1841 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
1842 RequiresAdjustment = true;
1845 // Merge ns_returns_retained attribute.
1846 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
1847 if (NewTypeInfo.getProducesResult()) {
1848 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
1849 Diag(Old->getLocation(), diag::note_previous_declaration);
1853 NewTypeInfo = NewTypeInfo.withProducesResult(true);
1854 RequiresAdjustment = true;
1857 if (RequiresAdjustment) {
1858 NewType = Context.adjustFunctionType(NewType, NewTypeInfo);
1859 New->setType(QualType(NewType, 0));
1860 NewQType = Context.getCanonicalType(New->getType());
1863 if (getLangOpts().CPlusPlus) {
1865 // Certain function declarations cannot be overloaded:
1866 // -- Function declarations that differ only in the return type
1867 // cannot be overloaded.
1868 QualType OldReturnType = OldType->getResultType();
1869 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
1871 if (OldReturnType != NewReturnType) {
1872 if (NewReturnType->isObjCObjectPointerType()
1873 && OldReturnType->isObjCObjectPointerType())
1874 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
1875 if (ResQT.isNull()) {
1876 if (New->isCXXClassMember() && New->isOutOfLine())
1877 Diag(New->getLocation(),
1878 diag::err_member_def_does_not_match_ret_type) << New;
1880 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1881 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1888 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1889 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1890 if (OldMethod && NewMethod) {
1891 // Preserve triviality.
1892 NewMethod->setTrivial(OldMethod->isTrivial());
1894 // MSVC allows explicit template specialization at class scope:
1895 // 2 CXMethodDecls referring to the same function will be injected.
1896 // We don't want a redeclartion error.
1897 bool IsClassScopeExplicitSpecialization =
1898 OldMethod->isFunctionTemplateSpecialization() &&
1899 NewMethod->isFunctionTemplateSpecialization();
1900 bool isFriend = NewMethod->getFriendObjectKind();
1902 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
1903 !IsClassScopeExplicitSpecialization) {
1904 // -- Member function declarations with the same name and the
1905 // same parameter types cannot be overloaded if any of them
1906 // is a static member function declaration.
1907 if (OldMethod->isStatic() || NewMethod->isStatic()) {
1908 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1909 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1913 // C++ [class.mem]p1:
1914 // [...] A member shall not be declared twice in the
1915 // member-specification, except that a nested class or member
1916 // class template can be declared and then later defined.
1918 if (isa<CXXConstructorDecl>(OldMethod))
1919 NewDiag = diag::err_constructor_redeclared;
1920 else if (isa<CXXDestructorDecl>(NewMethod))
1921 NewDiag = diag::err_destructor_redeclared;
1922 else if (isa<CXXConversionDecl>(NewMethod))
1923 NewDiag = diag::err_conv_function_redeclared;
1925 NewDiag = diag::err_member_redeclared;
1927 Diag(New->getLocation(), NewDiag);
1928 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1930 // Complain if this is an explicit declaration of a special
1931 // member that was initially declared implicitly.
1933 // As an exception, it's okay to befriend such methods in order
1934 // to permit the implicit constructor/destructor/operator calls.
1935 } else if (OldMethod->isImplicit()) {
1937 NewMethod->setImplicit();
1939 Diag(NewMethod->getLocation(),
1940 diag::err_definition_of_implicitly_declared_member)
1941 << New << getSpecialMember(OldMethod);
1944 } else if (OldMethod->isExplicitlyDefaulted()) {
1945 Diag(NewMethod->getLocation(),
1946 diag::err_definition_of_explicitly_defaulted_member)
1947 << getSpecialMember(OldMethod);
1953 // All declarations for a function shall agree exactly in both the
1954 // return type and the parameter-type-list.
1955 // We also want to respect all the extended bits except noreturn.
1957 // noreturn should now match unless the old type info didn't have it.
1958 QualType OldQTypeForComparison = OldQType;
1959 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
1960 assert(OldQType == QualType(OldType, 0));
1961 const FunctionType *OldTypeForComparison
1962 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
1963 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
1964 assert(OldQTypeForComparison.isCanonical());
1967 if (OldQTypeForComparison == NewQType)
1968 return MergeCompatibleFunctionDecls(New, Old, S);
1970 // Fall through for conflicting redeclarations and redefinitions.
1973 // C: Function types need to be compatible, not identical. This handles
1974 // duplicate function decls like "void f(int); void f(enum X);" properly.
1975 if (!getLangOpts().CPlusPlus &&
1976 Context.typesAreCompatible(OldQType, NewQType)) {
1977 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1978 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1979 const FunctionProtoType *OldProto = 0;
1980 if (isa<FunctionNoProtoType>(NewFuncType) &&
1981 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1982 // The old declaration provided a function prototype, but the
1983 // new declaration does not. Merge in the prototype.
1984 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1985 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1986 OldProto->arg_type_end());
1987 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1988 ParamTypes.data(), ParamTypes.size(),
1989 OldProto->getExtProtoInfo());
1990 New->setType(NewQType);
1991 New->setHasInheritedPrototype();
1993 // Synthesize a parameter for each argument type.
1994 SmallVector<ParmVarDecl*, 16> Params;
1995 for (FunctionProtoType::arg_type_iterator
1996 ParamType = OldProto->arg_type_begin(),
1997 ParamEnd = OldProto->arg_type_end();
1998 ParamType != ParamEnd; ++ParamType) {
1999 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2001 SourceLocation(), 0,
2002 *ParamType, /*TInfo=*/0,
2005 Param->setScopeInfo(0, Params.size());
2006 Param->setImplicit();
2007 Params.push_back(Param);
2010 New->setParams(Params);
2013 return MergeCompatibleFunctionDecls(New, Old, S);
2016 // GNU C permits a K&R definition to follow a prototype declaration
2017 // if the declared types of the parameters in the K&R definition
2018 // match the types in the prototype declaration, even when the
2019 // promoted types of the parameters from the K&R definition differ
2020 // from the types in the prototype. GCC then keeps the types from
2023 // If a variadic prototype is followed by a non-variadic K&R definition,
2024 // the K&R definition becomes variadic. This is sort of an edge case, but
2025 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2027 if (!getLangOpts().CPlusPlus &&
2028 Old->hasPrototype() && !New->hasPrototype() &&
2029 New->getType()->getAs<FunctionProtoType>() &&
2030 Old->getNumParams() == New->getNumParams()) {
2031 SmallVector<QualType, 16> ArgTypes;
2032 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2033 const FunctionProtoType *OldProto
2034 = Old->getType()->getAs<FunctionProtoType>();
2035 const FunctionProtoType *NewProto
2036 = New->getType()->getAs<FunctionProtoType>();
2038 // Determine whether this is the GNU C extension.
2039 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2040 NewProto->getResultType());
2041 bool LooseCompatible = !MergedReturn.isNull();
2042 for (unsigned Idx = 0, End = Old->getNumParams();
2043 LooseCompatible && Idx != End; ++Idx) {
2044 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2045 ParmVarDecl *NewParm = New->getParamDecl(Idx);
2046 if (Context.typesAreCompatible(OldParm->getType(),
2047 NewProto->getArgType(Idx))) {
2048 ArgTypes.push_back(NewParm->getType());
2049 } else if (Context.typesAreCompatible(OldParm->getType(),
2051 /*CompareUnqualified=*/true)) {
2052 GNUCompatibleParamWarning Warn
2053 = { OldParm, NewParm, NewProto->getArgType(Idx) };
2054 Warnings.push_back(Warn);
2055 ArgTypes.push_back(NewParm->getType());
2057 LooseCompatible = false;
2060 if (LooseCompatible) {
2061 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2062 Diag(Warnings[Warn].NewParm->getLocation(),
2063 diag::ext_param_promoted_not_compatible_with_prototype)
2064 << Warnings[Warn].PromotedType
2065 << Warnings[Warn].OldParm->getType();
2066 if (Warnings[Warn].OldParm->getLocation().isValid())
2067 Diag(Warnings[Warn].OldParm->getLocation(),
2068 diag::note_previous_declaration);
2071 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
2073 OldProto->getExtProtoInfo()));
2074 return MergeCompatibleFunctionDecls(New, Old, S);
2077 // Fall through to diagnose conflicting types.
2080 // A function that has already been declared has been redeclared or defined
2081 // with a different type- show appropriate diagnostic
2082 if (unsigned BuiltinID = Old->getBuiltinID()) {
2083 // The user has declared a builtin function with an incompatible
2085 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2086 // The function the user is redeclaring is a library-defined
2087 // function like 'malloc' or 'printf'. Warn about the
2088 // redeclaration, then pretend that we don't know about this
2089 // library built-in.
2090 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2091 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2092 << Old << Old->getType();
2093 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2094 Old->setInvalidDecl();
2098 PrevDiag = diag::note_previous_builtin_declaration;
2101 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2102 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2106 /// \brief Completes the merge of two function declarations that are
2107 /// known to be compatible.
2109 /// This routine handles the merging of attributes and other
2110 /// properties of function declarations form the old declaration to
2111 /// the new declaration, once we know that New is in fact a
2112 /// redeclaration of Old.
2115 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2117 // Merge the attributes
2118 mergeDeclAttributes(New, Old);
2120 // Merge the storage class.
2121 if (Old->getStorageClass() != SC_Extern &&
2122 Old->getStorageClass() != SC_None)
2123 New->setStorageClass(Old->getStorageClass());
2125 // Merge "pure" flag.
2129 // Merge attributes from the parameters. These can mismatch with K&R
2131 if (New->getNumParams() == Old->getNumParams())
2132 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2133 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2136 if (getLangOpts().CPlusPlus)
2137 return MergeCXXFunctionDecl(New, Old, S);
2143 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2144 ObjCMethodDecl *oldMethod) {
2145 // We don't want to merge unavailable and deprecated attributes
2146 // except from interface to implementation.
2147 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext());
2149 // Merge the attributes.
2150 mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation);
2152 // Merge attributes from the parameters.
2153 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin();
2154 for (ObjCMethodDecl::param_iterator
2155 ni = newMethod->param_begin(), ne = newMethod->param_end();
2156 ni != ne; ++ni, ++oi)
2157 mergeParamDeclAttributes(*ni, *oi, Context);
2159 CheckObjCMethodOverride(newMethod, oldMethod, true);
2162 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2163 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
2164 /// emitting diagnostics as appropriate.
2166 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2167 /// to here in AddInitializerToDecl. We can't check them before the initializer
2169 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) {
2170 if (New->isInvalidDecl() || Old->isInvalidDecl())
2174 if (getLangOpts().CPlusPlus) {
2175 AutoType *AT = New->getType()->getContainedAutoType();
2176 if (AT && !AT->isDeduced()) {
2177 // We don't know what the new type is until the initializer is attached.
2179 } else if (Context.hasSameType(New->getType(), Old->getType())) {
2180 // These could still be something that needs exception specs checked.
2181 return MergeVarDeclExceptionSpecs(New, Old);
2183 // C++ [basic.link]p10:
2184 // [...] the types specified by all declarations referring to a given
2185 // object or function shall be identical, except that declarations for an
2186 // array object can specify array types that differ by the presence or
2187 // absence of a major array bound (8.3.4).
2188 else if (Old->getType()->isIncompleteArrayType() &&
2189 New->getType()->isArrayType()) {
2190 CanQual<ArrayType> OldArray
2191 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2192 CanQual<ArrayType> NewArray
2193 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2194 if (OldArray->getElementType() == NewArray->getElementType())
2195 MergedT = New->getType();
2196 } else if (Old->getType()->isArrayType() &&
2197 New->getType()->isIncompleteArrayType()) {
2198 CanQual<ArrayType> OldArray
2199 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
2200 CanQual<ArrayType> NewArray
2201 = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
2202 if (OldArray->getElementType() == NewArray->getElementType())
2203 MergedT = Old->getType();
2204 } else if (New->getType()->isObjCObjectPointerType()
2205 && Old->getType()->isObjCObjectPointerType()) {
2206 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2210 MergedT = Context.mergeTypes(New->getType(), Old->getType());
2212 if (MergedT.isNull()) {
2213 Diag(New->getLocation(), diag::err_redefinition_different_type)
2214 << New->getDeclName();
2215 Diag(Old->getLocation(), diag::note_previous_definition);
2216 return New->setInvalidDecl();
2218 New->setType(MergedT);
2221 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2222 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
2223 /// situation, merging decls or emitting diagnostics as appropriate.
2225 /// Tentative definition rules (C99 6.9.2p2) are checked by
2226 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2227 /// definitions here, since the initializer hasn't been attached.
2229 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2230 // If the new decl is already invalid, don't do any other checking.
2231 if (New->isInvalidDecl())
2234 // Verify the old decl was also a variable.
2236 if (!Previous.isSingleResult() ||
2237 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
2238 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2239 << New->getDeclName();
2240 Diag(Previous.getRepresentativeDecl()->getLocation(),
2241 diag::note_previous_definition);
2242 return New->setInvalidDecl();
2245 // C++ [class.mem]p1:
2246 // A member shall not be declared twice in the member-specification [...]
2248 // Here, we need only consider static data members.
2249 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
2250 Diag(New->getLocation(), diag::err_duplicate_member)
2251 << New->getIdentifier();
2252 Diag(Old->getLocation(), diag::note_previous_declaration);
2253 New->setInvalidDecl();
2256 mergeDeclAttributes(New, Old);
2257 // Warn if an already-declared variable is made a weak_import in a subsequent
2259 if (New->getAttr<WeakImportAttr>() &&
2260 Old->getStorageClass() == SC_None &&
2261 !Old->getAttr<WeakImportAttr>()) {
2262 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
2263 Diag(Old->getLocation(), diag::note_previous_definition);
2264 // Remove weak_import attribute on new declaration.
2265 New->dropAttr<WeakImportAttr>();
2269 MergeVarDeclTypes(New, Old);
2270 if (New->isInvalidDecl())
2273 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
2274 if (New->getStorageClass() == SC_Static &&
2275 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) {
2276 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
2277 Diag(Old->getLocation(), diag::note_previous_definition);
2278 return New->setInvalidDecl();
2281 // For an identifier declared with the storage-class specifier
2282 // extern in a scope in which a prior declaration of that
2283 // identifier is visible,23) if the prior declaration specifies
2284 // internal or external linkage, the linkage of the identifier at
2285 // the later declaration is the same as the linkage specified at
2286 // the prior declaration. If no prior declaration is visible, or
2287 // if the prior declaration specifies no linkage, then the
2288 // identifier has external linkage.
2289 if (New->hasExternalStorage() && Old->hasLinkage())
2291 else if (New->getStorageClass() != SC_Static &&
2292 Old->getStorageClass() == SC_Static) {
2293 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
2294 Diag(Old->getLocation(), diag::note_previous_definition);
2295 return New->setInvalidDecl();
2298 // Check if extern is followed by non-extern and vice-versa.
2299 if (New->hasExternalStorage() &&
2300 !Old->hasLinkage() && Old->isLocalVarDecl()) {
2301 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
2302 Diag(Old->getLocation(), diag::note_previous_definition);
2303 return New->setInvalidDecl();
2305 if (Old->hasExternalStorage() &&
2306 !New->hasLinkage() && New->isLocalVarDecl()) {
2307 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
2308 Diag(Old->getLocation(), diag::note_previous_definition);
2309 return New->setInvalidDecl();
2312 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
2314 // FIXME: The test for external storage here seems wrong? We still
2315 // need to check for mismatches.
2316 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
2317 // Don't complain about out-of-line definitions of static members.
2318 !(Old->getLexicalDeclContext()->isRecord() &&
2319 !New->getLexicalDeclContext()->isRecord())) {
2320 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
2321 Diag(Old->getLocation(), diag::note_previous_definition);
2322 return New->setInvalidDecl();
2325 if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
2326 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
2327 Diag(Old->getLocation(), diag::note_previous_definition);
2328 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
2329 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
2330 Diag(Old->getLocation(), diag::note_previous_definition);
2333 // C++ doesn't have tentative definitions, so go right ahead and check here.
2335 if (getLangOpts().CPlusPlus &&
2336 New->isThisDeclarationADefinition() == VarDecl::Definition &&
2337 (Def = Old->getDefinition())) {
2338 Diag(New->getLocation(), diag::err_redefinition)
2339 << New->getDeclName();
2340 Diag(Def->getLocation(), diag::note_previous_definition);
2341 New->setInvalidDecl();
2345 // For an identifier declared with the storage-class specifier extern in a
2346 // scope in which a prior declaration of that identifier is visible, if
2347 // the prior declaration specifies internal or external linkage, the linkage
2348 // of the identifier at the later declaration is the same as the linkage
2349 // specified at the prior declaration.
2350 // FIXME. revisit this code.
2351 if (New->hasExternalStorage() &&
2352 Old->getLinkage() == InternalLinkage &&
2353 New->getDeclContext() == Old->getDeclContext())
2354 New->setStorageClass(Old->getStorageClass());
2356 // Keep a chain of previous declarations.
2357 New->setPreviousDeclaration(Old);
2359 // Inherit access appropriately.
2360 New->setAccess(Old->getAccess());
2363 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2364 /// no declarator (e.g. "struct foo;") is parsed.
2365 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2367 return ParsedFreeStandingDeclSpec(S, AS, DS,
2368 MultiTemplateParamsArg(*this, 0, 0));
2371 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
2372 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template
2373 /// parameters to cope with template friend declarations.
2374 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
2376 MultiTemplateParamsArg TemplateParams) {
2379 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
2380 DS.getTypeSpecType() == DeclSpec::TST_struct ||
2381 DS.getTypeSpecType() == DeclSpec::TST_union ||
2382 DS.getTypeSpecType() == DeclSpec::TST_enum) {
2383 TagD = DS.getRepAsDecl();
2385 if (!TagD) // We probably had an error
2388 // Note that the above type specs guarantee that the
2389 // type rep is a Decl, whereas in many of the others
2391 if (isa<TagDecl>(TagD))
2392 Tag = cast<TagDecl>(TagD);
2393 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
2394 Tag = CTD->getTemplatedDecl();
2398 Tag->setFreeStanding();
2399 if (Tag->isInvalidDecl())
2403 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
2404 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
2405 // or incomplete types shall not be restrict-qualified."
2406 if (TypeQuals & DeclSpec::TQ_restrict)
2407 Diag(DS.getRestrictSpecLoc(),
2408 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
2409 << DS.getSourceRange();
2412 if (DS.isConstexprSpecified()) {
2413 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
2414 // and definitions of functions and variables.
2416 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
2417 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
2418 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
2419 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3);
2421 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
2422 // Don't emit warnings after this error.
2426 if (DS.isFriendSpecified()) {
2427 // If we're dealing with a decl but not a TagDecl, assume that
2428 // whatever routines created it handled the friendship aspect.
2431 return ActOnFriendTypeDecl(S, DS, TemplateParams);
2434 // Track whether we warned about the fact that there aren't any
2436 bool emittedWarning = false;
2438 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
2439 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
2440 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
2441 if (getLangOpts().CPlusPlus ||
2442 Record->getDeclContext()->isRecord())
2443 return BuildAnonymousStructOrUnion(S, DS, AS, Record);
2445 Diag(DS.getLocStart(), diag::ext_no_declarators)
2446 << DS.getSourceRange();
2447 emittedWarning = true;
2451 // Check for Microsoft C extension: anonymous struct.
2452 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
2453 CurContext->isRecord() &&
2454 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
2455 // Handle 2 kinds of anonymous struct:
2458 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
2459 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
2460 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
2461 (DS.getTypeSpecType() == DeclSpec::TST_typename &&
2462 DS.getRepAsType().get()->isStructureType())) {
2463 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
2464 << DS.getSourceRange();
2465 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
2469 if (getLangOpts().CPlusPlus &&
2470 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
2471 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
2472 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
2473 !Enum->getIdentifier() && !Enum->isInvalidDecl()) {
2474 Diag(Enum->getLocation(), diag::ext_no_declarators)
2475 << DS.getSourceRange();
2476 emittedWarning = true;
2479 // Skip all the checks below if we have a type error.
2480 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD;
2482 if (!DS.isMissingDeclaratorOk()) {
2483 // Warn about typedefs of enums without names, since this is an
2484 // extension in both Microsoft and GNU.
2485 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
2486 Tag && isa<EnumDecl>(Tag)) {
2487 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
2488 << DS.getSourceRange();
2492 Diag(DS.getLocStart(), diag::ext_no_declarators)
2493 << DS.getSourceRange();
2494 emittedWarning = true;
2497 // We're going to complain about a bunch of spurious specifiers;
2498 // only do this if we're declaring a tag, because otherwise we
2499 // should be getting diag::ext_no_declarators.
2500 if (emittedWarning || (TagD && TagD->isInvalidDecl()))
2503 // Note that a linkage-specification sets a storage class, but
2504 // 'extern "C" struct foo;' is actually valid and not theoretically
2506 if (DeclSpec::SCS scs = DS.getStorageClassSpec())
2507 if (!DS.isExternInLinkageSpec())
2508 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier)
2509 << DeclSpec::getSpecifierName(scs);
2511 if (DS.isThreadSpecified())
2512 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread";
2513 if (DS.getTypeQualifiers()) {
2514 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2515 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const";
2516 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2517 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile";
2518 // Restrict is covered above.
2520 if (DS.isInlineSpecified())
2521 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline";
2522 if (DS.isVirtualSpecified())
2523 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual";
2524 if (DS.isExplicitSpecified())
2525 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit";
2527 if (DS.isModulePrivateSpecified() &&
2528 Tag && Tag->getDeclContext()->isFunctionOrMethod())
2529 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
2530 << Tag->getTagKind()
2531 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
2533 // Warn about ignored type attributes, for example:
2534 // __attribute__((aligned)) struct A;
2535 // Attributes should be placed after tag to apply to type declaration.
2536 if (!DS.getAttributes().empty()) {
2537 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
2538 if (TypeSpecType == DeclSpec::TST_class ||
2539 TypeSpecType == DeclSpec::TST_struct ||
2540 TypeSpecType == DeclSpec::TST_union ||
2541 TypeSpecType == DeclSpec::TST_enum) {
2542 AttributeList* attrs = DS.getAttributes().getList();
2544 Diag(attrs->getScopeLoc(),
2545 diag::warn_declspec_attribute_ignored)
2547 << (TypeSpecType == DeclSpec::TST_class ? 0 :
2548 TypeSpecType == DeclSpec::TST_struct ? 1 :
2549 TypeSpecType == DeclSpec::TST_union ? 2 : 3);
2550 attrs = attrs->getNext();
2558 /// We are trying to inject an anonymous member into the given scope;
2559 /// check if there's an existing declaration that can't be overloaded.
2561 /// \return true if this is a forbidden redeclaration
2562 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
2565 DeclarationName Name,
2566 SourceLocation NameLoc,
2567 unsigned diagnostic) {
2568 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
2569 Sema::ForRedeclaration);
2570 if (!SemaRef.LookupName(R, S)) return false;
2572 if (R.getAsSingle<TagDecl>())
2575 // Pick a representative declaration.
2576 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
2577 assert(PrevDecl && "Expected a non-null Decl");
2579 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
2582 SemaRef.Diag(NameLoc, diagnostic) << Name;
2583 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
2588 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
2589 /// anonymous struct or union AnonRecord into the owning context Owner
2590 /// and scope S. This routine will be invoked just after we realize
2591 /// that an unnamed union or struct is actually an anonymous union or
2598 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
2599 /// // f into the surrounding scope.x
2602 /// This routine is recursive, injecting the names of nested anonymous
2603 /// structs/unions into the owning context and scope as well.
2604 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
2606 RecordDecl *AnonRecord,
2608 SmallVector<NamedDecl*, 2> &Chaining,
2609 bool MSAnonStruct) {
2611 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
2612 : diag::err_anonymous_struct_member_redecl;
2614 bool Invalid = false;
2616 // Look every FieldDecl and IndirectFieldDecl with a name.
2617 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
2618 DEnd = AnonRecord->decls_end();
2620 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
2621 cast<NamedDecl>(*D)->getDeclName()) {
2622 ValueDecl *VD = cast<ValueDecl>(*D);
2623 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
2624 VD->getLocation(), diagKind)) {
2625 // C++ [class.union]p2:
2626 // The names of the members of an anonymous union shall be
2627 // distinct from the names of any other entity in the
2628 // scope in which the anonymous union is declared.
2631 // C++ [class.union]p2:
2632 // For the purpose of name lookup, after the anonymous union
2633 // definition, the members of the anonymous union are
2634 // considered to have been defined in the scope in which the
2635 // anonymous union is declared.
2636 unsigned OldChainingSize = Chaining.size();
2637 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
2638 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
2639 PE = IF->chain_end(); PI != PE; ++PI)
2640 Chaining.push_back(*PI);
2642 Chaining.push_back(VD);
2644 assert(Chaining.size() >= 2);
2645 NamedDecl **NamedChain =
2646 new (SemaRef.Context)NamedDecl*[Chaining.size()];
2647 for (unsigned i = 0; i < Chaining.size(); i++)
2648 NamedChain[i] = Chaining[i];
2650 IndirectFieldDecl* IndirectField =
2651 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
2652 VD->getIdentifier(), VD->getType(),
2653 NamedChain, Chaining.size());
2655 IndirectField->setAccess(AS);
2656 IndirectField->setImplicit();
2657 SemaRef.PushOnScopeChains(IndirectField, S);
2659 // That includes picking up the appropriate access specifier.
2660 if (AS != AS_none) IndirectField->setAccess(AS);
2662 Chaining.resize(OldChainingSize);
2670 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
2671 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
2672 /// illegal input values are mapped to SC_None.
2674 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2675 switch (StorageClassSpec) {
2676 case DeclSpec::SCS_unspecified: return SC_None;
2677 case DeclSpec::SCS_extern: return SC_Extern;
2678 case DeclSpec::SCS_static: return SC_Static;
2679 case DeclSpec::SCS_auto: return SC_Auto;
2680 case DeclSpec::SCS_register: return SC_Register;
2681 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2682 // Illegal SCSs map to None: error reporting is up to the caller.
2683 case DeclSpec::SCS_mutable: // Fall through.
2684 case DeclSpec::SCS_typedef: return SC_None;
2686 llvm_unreachable("unknown storage class specifier");
2689 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
2690 /// a StorageClass. Any error reporting is up to the caller:
2691 /// illegal input values are mapped to SC_None.
2693 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
2694 switch (StorageClassSpec) {
2695 case DeclSpec::SCS_unspecified: return SC_None;
2696 case DeclSpec::SCS_extern: return SC_Extern;
2697 case DeclSpec::SCS_static: return SC_Static;
2698 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
2699 // Illegal SCSs map to None: error reporting is up to the caller.
2700 case DeclSpec::SCS_auto: // Fall through.
2701 case DeclSpec::SCS_mutable: // Fall through.
2702 case DeclSpec::SCS_register: // Fall through.
2703 case DeclSpec::SCS_typedef: return SC_None;
2705 llvm_unreachable("unknown storage class specifier");
2708 /// BuildAnonymousStructOrUnion - Handle the declaration of an
2709 /// anonymous structure or union. Anonymous unions are a C++ feature
2710 /// (C++ [class.union]) and a C11 feature; anonymous structures
2711 /// are a C11 feature and GNU C++ extension.
2712 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2714 RecordDecl *Record) {
2715 DeclContext *Owner = Record->getDeclContext();
2717 // Diagnose whether this anonymous struct/union is an extension.
2718 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
2719 Diag(Record->getLocation(), diag::ext_anonymous_union);
2720 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
2721 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
2722 else if (!Record->isUnion() && !getLangOpts().C11)
2723 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
2725 // C and C++ require different kinds of checks for anonymous
2727 bool Invalid = false;
2728 if (getLangOpts().CPlusPlus) {
2729 const char* PrevSpec = 0;
2731 if (Record->isUnion()) {
2732 // C++ [class.union]p6:
2733 // Anonymous unions declared in a named namespace or in the
2734 // global namespace shall be declared static.
2735 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
2736 (isa<TranslationUnitDecl>(Owner) ||
2737 (isa<NamespaceDecl>(Owner) &&
2738 cast<NamespaceDecl>(Owner)->getDeclName()))) {
2739 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
2740 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
2742 // Recover by adding 'static'.
2743 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
2746 // C++ [class.union]p6:
2747 // A storage class is not allowed in a declaration of an
2748 // anonymous union in a class scope.
2749 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
2750 isa<RecordDecl>(Owner)) {
2751 Diag(DS.getStorageClassSpecLoc(),
2752 diag::err_anonymous_union_with_storage_spec)
2753 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
2755 // Recover by removing the storage specifier.
2756 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
2762 // Ignore const/volatile/restrict qualifiers.
2763 if (DS.getTypeQualifiers()) {
2764 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
2765 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
2766 << Record->isUnion() << 0
2767 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
2768 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
2769 Diag(DS.getVolatileSpecLoc(),
2770 diag::ext_anonymous_struct_union_qualified)
2771 << Record->isUnion() << 1
2772 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
2773 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
2774 Diag(DS.getRestrictSpecLoc(),
2775 diag::ext_anonymous_struct_union_qualified)
2776 << Record->isUnion() << 2
2777 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
2779 DS.ClearTypeQualifiers();
2782 // C++ [class.union]p2:
2783 // The member-specification of an anonymous union shall only
2784 // define non-static data members. [Note: nested types and
2785 // functions cannot be declared within an anonymous union. ]
2786 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
2787 MemEnd = Record->decls_end();
2788 Mem != MemEnd; ++Mem) {
2789 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
2790 // C++ [class.union]p3:
2791 // An anonymous union shall not have private or protected
2792 // members (clause 11).
2793 assert(FD->getAccess() != AS_none);
2794 if (FD->getAccess() != AS_public) {
2795 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
2796 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
2800 // C++ [class.union]p1
2801 // An object of a class with a non-trivial constructor, a non-trivial
2802 // copy constructor, a non-trivial destructor, or a non-trivial copy
2803 // assignment operator cannot be a member of a union, nor can an
2804 // array of such objects.
2805 if (CheckNontrivialField(FD))
2807 } else if ((*Mem)->isImplicit()) {
2808 // Any implicit members are fine.
2809 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
2810 // This is a type that showed up in an
2811 // elaborated-type-specifier inside the anonymous struct or
2812 // union, but which actually declares a type outside of the
2813 // anonymous struct or union. It's okay.
2814 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
2815 if (!MemRecord->isAnonymousStructOrUnion() &&
2816 MemRecord->getDeclName()) {
2817 // Visual C++ allows type definition in anonymous struct or union.
2818 if (getLangOpts().MicrosoftExt)
2819 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
2820 << (int)Record->isUnion();
2822 // This is a nested type declaration.
2823 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
2824 << (int)Record->isUnion();
2828 } else if (isa<AccessSpecDecl>(*Mem)) {
2829 // Any access specifier is fine.
2831 // We have something that isn't a non-static data
2832 // member. Complain about it.
2833 unsigned DK = diag::err_anonymous_record_bad_member;
2834 if (isa<TypeDecl>(*Mem))
2835 DK = diag::err_anonymous_record_with_type;
2836 else if (isa<FunctionDecl>(*Mem))
2837 DK = diag::err_anonymous_record_with_function;
2838 else if (isa<VarDecl>(*Mem))
2839 DK = diag::err_anonymous_record_with_static;
2841 // Visual C++ allows type definition in anonymous struct or union.
2842 if (getLangOpts().MicrosoftExt &&
2843 DK == diag::err_anonymous_record_with_type)
2844 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
2845 << (int)Record->isUnion();
2847 Diag((*Mem)->getLocation(), DK)
2848 << (int)Record->isUnion();
2855 if (!Record->isUnion() && !Owner->isRecord()) {
2856 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
2857 << (int)getLangOpts().CPlusPlus;
2861 // Mock up a declarator.
2862 Declarator Dc(DS, Declarator::MemberContext);
2863 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2864 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
2866 // Create a declaration for this anonymous struct/union.
2867 NamedDecl *Anon = 0;
2868 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
2869 Anon = FieldDecl::Create(Context, OwningClass,
2871 Record->getLocation(),
2872 /*IdentifierInfo=*/0,
2873 Context.getTypeDeclType(Record),
2875 /*BitWidth=*/0, /*Mutable=*/false,
2877 Anon->setAccess(AS);
2878 if (getLangOpts().CPlusPlus)
2879 FieldCollector->Add(cast<FieldDecl>(Anon));
2881 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
2882 assert(SCSpec != DeclSpec::SCS_typedef &&
2883 "Parser allowed 'typedef' as storage class VarDecl.");
2884 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2885 if (SCSpec == DeclSpec::SCS_mutable) {
2886 // mutable can only appear on non-static class members, so it's always
2888 Diag(Record->getLocation(), diag::err_mutable_nonmember);
2892 SCSpec = DS.getStorageClassSpecAsWritten();
2893 VarDecl::StorageClass SCAsWritten
2894 = StorageClassSpecToVarDeclStorageClass(SCSpec);
2896 Anon = VarDecl::Create(Context, Owner,
2898 Record->getLocation(), /*IdentifierInfo=*/0,
2899 Context.getTypeDeclType(Record),
2900 TInfo, SC, SCAsWritten);
2902 // Default-initialize the implicit variable. This initialization will be
2903 // trivial in almost all cases, except if a union member has an in-class
2905 // union { int n = 0; };
2906 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
2908 Anon->setImplicit();
2910 // Add the anonymous struct/union object to the current
2911 // context. We'll be referencing this object when we refer to one of
2913 Owner->addDecl(Anon);
2915 // Inject the members of the anonymous struct/union into the owning
2916 // context and into the identifier resolver chain for name lookup
2918 SmallVector<NamedDecl*, 2> Chain;
2919 Chain.push_back(Anon);
2921 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
2925 // Mark this as an anonymous struct/union type. Note that we do not
2926 // do this until after we have already checked and injected the
2927 // members of this anonymous struct/union type, because otherwise
2928 // the members could be injected twice: once by DeclContext when it
2929 // builds its lookup table, and once by
2930 // InjectAnonymousStructOrUnionMembers.
2931 Record->setAnonymousStructOrUnion(true);
2934 Anon->setInvalidDecl();
2939 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
2940 /// Microsoft C anonymous structure.
2941 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
2944 /// struct A { int a; };
2945 /// struct B { struct A; int b; };
2952 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2953 RecordDecl *Record) {
2955 // If there is no Record, get the record via the typedef.
2957 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
2959 // Mock up a declarator.
2960 Declarator Dc(DS, Declarator::TypeNameContext);
2961 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
2962 assert(TInfo && "couldn't build declarator info for anonymous struct");
2964 // Create a declaration for this anonymous struct.
2965 NamedDecl* Anon = FieldDecl::Create(Context,
2966 cast<RecordDecl>(CurContext),
2969 /*IdentifierInfo=*/0,
2970 Context.getTypeDeclType(Record),
2972 /*BitWidth=*/0, /*Mutable=*/false,
2974 Anon->setImplicit();
2976 // Add the anonymous struct object to the current context.
2977 CurContext->addDecl(Anon);
2979 // Inject the members of the anonymous struct into the current
2980 // context and into the identifier resolver chain for name lookup
2982 SmallVector<NamedDecl*, 2> Chain;
2983 Chain.push_back(Anon);
2985 RecordDecl *RecordDef = Record->getDefinition();
2986 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
2989 Anon->setInvalidDecl();
2994 /// GetNameForDeclarator - Determine the full declaration name for the
2995 /// given Declarator.
2996 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
2997 return GetNameFromUnqualifiedId(D.getName());
3000 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3002 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3003 DeclarationNameInfo NameInfo;
3004 NameInfo.setLoc(Name.StartLocation);
3006 switch (Name.getKind()) {
3008 case UnqualifiedId::IK_ImplicitSelfParam:
3009 case UnqualifiedId::IK_Identifier:
3010 NameInfo.setName(Name.Identifier);
3011 NameInfo.setLoc(Name.StartLocation);
3014 case UnqualifiedId::IK_OperatorFunctionId:
3015 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3016 Name.OperatorFunctionId.Operator));
3017 NameInfo.setLoc(Name.StartLocation);
3018 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3019 = Name.OperatorFunctionId.SymbolLocations[0];
3020 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3021 = Name.EndLocation.getRawEncoding();
3024 case UnqualifiedId::IK_LiteralOperatorId:
3025 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3027 NameInfo.setLoc(Name.StartLocation);
3028 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3031 case UnqualifiedId::IK_ConversionFunctionId: {
3032 TypeSourceInfo *TInfo;
3033 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3035 return DeclarationNameInfo();
3036 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3037 Context.getCanonicalType(Ty)));
3038 NameInfo.setLoc(Name.StartLocation);
3039 NameInfo.setNamedTypeInfo(TInfo);
3043 case UnqualifiedId::IK_ConstructorName: {
3044 TypeSourceInfo *TInfo;
3045 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3047 return DeclarationNameInfo();
3048 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3049 Context.getCanonicalType(Ty)));
3050 NameInfo.setLoc(Name.StartLocation);
3051 NameInfo.setNamedTypeInfo(TInfo);
3055 case UnqualifiedId::IK_ConstructorTemplateId: {
3056 // In well-formed code, we can only have a constructor
3057 // template-id that refers to the current context, so go there
3058 // to find the actual type being constructed.
3059 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3060 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3061 return DeclarationNameInfo();
3063 // Determine the type of the class being constructed.
3064 QualType CurClassType = Context.getTypeDeclType(CurClass);
3066 // FIXME: Check two things: that the template-id names the same type as
3067 // CurClassType, and that the template-id does not occur when the name
3070 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3071 Context.getCanonicalType(CurClassType)));
3072 NameInfo.setLoc(Name.StartLocation);
3073 // FIXME: should we retrieve TypeSourceInfo?
3074 NameInfo.setNamedTypeInfo(0);
3078 case UnqualifiedId::IK_DestructorName: {
3079 TypeSourceInfo *TInfo;
3080 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3082 return DeclarationNameInfo();
3083 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3084 Context.getCanonicalType(Ty)));
3085 NameInfo.setLoc(Name.StartLocation);
3086 NameInfo.setNamedTypeInfo(TInfo);
3090 case UnqualifiedId::IK_TemplateId: {
3091 TemplateName TName = Name.TemplateId->Template.get();
3092 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3093 return Context.getNameForTemplate(TName, TNameLoc);
3096 } // switch (Name.getKind())
3098 llvm_unreachable("Unknown name kind");
3101 static QualType getCoreType(QualType Ty) {
3103 if (Ty->isPointerType() || Ty->isReferenceType())
3104 Ty = Ty->getPointeeType();
3105 else if (Ty->isArrayType())
3106 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3108 return Ty.withoutLocalFastQualifiers();
3112 /// hasSimilarParameters - Determine whether the C++ functions Declaration
3113 /// and Definition have "nearly" matching parameters. This heuristic is
3114 /// used to improve diagnostics in the case where an out-of-line function
3115 /// definition doesn't match any declaration within the class or namespace.
3116 /// Also sets Params to the list of indices to the parameters that differ
3117 /// between the declaration and the definition. If hasSimilarParameters
3118 /// returns true and Params is empty, then all of the parameters match.
3119 static bool hasSimilarParameters(ASTContext &Context,
3120 FunctionDecl *Declaration,
3121 FunctionDecl *Definition,
3122 llvm::SmallVectorImpl<unsigned> &Params) {
3124 if (Declaration->param_size() != Definition->param_size())
3126 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3127 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3128 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3130 // The parameter types are identical
3131 if (Context.hasSameType(DefParamTy, DeclParamTy))
3134 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3135 QualType DefParamBaseTy = getCoreType(DefParamTy);
3136 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3137 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3139 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3140 (DeclTyName && DeclTyName == DefTyName))
3141 Params.push_back(Idx);
3142 else // The two parameters aren't even close
3149 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3150 /// declarator needs to be rebuilt in the current instantiation.
3151 /// Any bits of declarator which appear before the name are valid for
3152 /// consideration here. That's specifically the type in the decl spec
3153 /// and the base type in any member-pointer chunks.
3154 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3155 DeclarationName Name) {
3156 // The types we specifically need to rebuild are:
3157 // - typenames, typeofs, and decltypes
3158 // - types which will become injected class names
3159 // Of course, we also need to rebuild any type referencing such a
3160 // type. It's safest to just say "dependent", but we call out a
3163 DeclSpec &DS = D.getMutableDeclSpec();
3164 switch (DS.getTypeSpecType()) {
3165 case DeclSpec::TST_typename:
3166 case DeclSpec::TST_typeofType:
3167 case DeclSpec::TST_decltype:
3168 case DeclSpec::TST_underlyingType:
3169 case DeclSpec::TST_atomic: {
3170 // Grab the type from the parser.
3171 TypeSourceInfo *TSI = 0;
3172 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
3173 if (T.isNull() || !T->isDependentType()) break;
3175 // Make sure there's a type source info. This isn't really much
3176 // of a waste; most dependent types should have type source info
3177 // attached already.
3179 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
3181 // Rebuild the type in the current instantiation.
3182 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
3183 if (!TSI) return true;
3185 // Store the new type back in the decl spec.
3186 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
3187 DS.UpdateTypeRep(LocType);
3191 case DeclSpec::TST_typeofExpr: {
3192 Expr *E = DS.getRepAsExpr();
3193 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
3194 if (Result.isInvalid()) return true;
3195 DS.UpdateExprRep(Result.get());
3200 // Nothing to do for these decl specs.
3204 // It doesn't matter what order we do this in.
3205 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3206 DeclaratorChunk &Chunk = D.getTypeObject(I);
3208 // The only type information in the declarator which can come
3209 // before the declaration name is the base type of a member
3211 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
3214 // Rebuild the scope specifier in-place.
3215 CXXScopeSpec &SS = Chunk.Mem.Scope();
3216 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
3223 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
3224 D.setFunctionDefinitionKind(FDK_Declaration);
3225 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this));
3227 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
3228 Dcl->getDeclContext()->isFileContext())
3229 Dcl->setTopLevelDeclInObjCContainer();
3234 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
3235 /// If T is the name of a class, then each of the following shall have a
3236 /// name different from T:
3237 /// - every static data member of class T;
3238 /// - every member function of class T
3239 /// - every member of class T that is itself a type;
3240 /// \returns true if the declaration name violates these rules.
3241 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
3242 DeclarationNameInfo NameInfo) {
3243 DeclarationName Name = NameInfo.getName();
3245 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
3246 if (Record->getIdentifier() && Record->getDeclName() == Name) {
3247 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
3254 /// \brief Diagnose a declaration whose declarator-id has the given
3255 /// nested-name-specifier.
3257 /// \param SS The nested-name-specifier of the declarator-id.
3259 /// \param DC The declaration context to which the nested-name-specifier
3262 /// \param Name The name of the entity being declared.
3264 /// \param Loc The location of the name of the entity being declared.
3266 /// \returns true if we cannot safely recover from this error, false otherwise.
3267 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
3268 DeclarationName Name,
3269 SourceLocation Loc) {
3270 DeclContext *Cur = CurContext;
3271 while (isa<LinkageSpecDecl>(Cur))
3272 Cur = Cur->getParent();
3274 // C++ [dcl.meaning]p1:
3275 // A declarator-id shall not be qualified except for the definition
3276 // of a member function (9.3) or static data member (9.4) outside of
3277 // its class, the definition or explicit instantiation of a function
3278 // or variable member of a namespace outside of its namespace, or the
3279 // definition of an explicit specialization outside of its namespace,
3280 // or the declaration of a friend function that is a member of
3281 // another class or namespace (11.3). [...]
3283 // The user provided a superfluous scope specifier that refers back to the
3284 // class or namespaces in which the entity is already declared.
3289 if (Cur->Equals(DC)) {
3290 Diag(Loc, diag::warn_member_extra_qualification)
3291 << Name << FixItHint::CreateRemoval(SS.getRange());
3296 // Check whether the qualifying scope encloses the scope of the original
3298 if (!Cur->Encloses(DC)) {
3299 if (Cur->isRecord())
3300 Diag(Loc, diag::err_member_qualification)
3301 << Name << SS.getRange();
3302 else if (isa<TranslationUnitDecl>(DC))
3303 Diag(Loc, diag::err_invalid_declarator_global_scope)
3304 << Name << SS.getRange();
3305 else if (isa<FunctionDecl>(Cur))
3306 Diag(Loc, diag::err_invalid_declarator_in_function)
3307 << Name << SS.getRange();
3309 Diag(Loc, diag::err_invalid_declarator_scope)
3310 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
3315 if (Cur->isRecord()) {
3316 // Cannot qualify members within a class.
3317 Diag(Loc, diag::err_member_qualification)
3318 << Name << SS.getRange();
3321 // C++ constructors and destructors with incorrect scopes can break
3322 // our AST invariants by having the wrong underlying types. If
3323 // that's the case, then drop this declaration entirely.
3324 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
3325 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
3326 !Context.hasSameType(Name.getCXXNameType(),
3327 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
3333 // C++11 [dcl.meaning]p1:
3334 // [...] "The nested-name-specifier of the qualified declarator-id shall
3335 // not begin with a decltype-specifer"
3336 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
3337 while (SpecLoc.getPrefix())
3338 SpecLoc = SpecLoc.getPrefix();
3339 if (dyn_cast_or_null<DecltypeType>(
3340 SpecLoc.getNestedNameSpecifier()->getAsType()))
3341 Diag(Loc, diag::err_decltype_in_declarator)
3342 << SpecLoc.getTypeLoc().getSourceRange();
3347 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D,
3348 MultiTemplateParamsArg TemplateParamLists) {
3349 // TODO: consider using NameInfo for diagnostic.
3350 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3351 DeclarationName Name = NameInfo.getName();
3353 // All of these full declarators require an identifier. If it doesn't have
3354 // one, the ParsedFreeStandingDeclSpec action should be used.
3356 if (!D.isInvalidType()) // Reject this if we think it is valid.
3357 Diag(D.getDeclSpec().getLocStart(),
3358 diag::err_declarator_need_ident)
3359 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
3361 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
3364 // The scope passed in may not be a decl scope. Zip up the scope tree until
3365 // we find one that is.
3366 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3367 (S->getFlags() & Scope::TemplateParamScope) != 0)
3370 DeclContext *DC = CurContext;
3371 if (D.getCXXScopeSpec().isInvalid())
3373 else if (D.getCXXScopeSpec().isSet()) {
3374 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
3375 UPPC_DeclarationQualifier))
3378 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
3379 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
3381 // If we could not compute the declaration context, it's because the
3382 // declaration context is dependent but does not refer to a class,
3383 // class template, or class template partial specialization. Complain
3384 // and return early, to avoid the coming semantic disaster.
3385 Diag(D.getIdentifierLoc(),
3386 diag::err_template_qualified_declarator_no_match)
3387 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
3388 << D.getCXXScopeSpec().getRange();
3391 bool IsDependentContext = DC->isDependentContext();
3393 if (!IsDependentContext &&
3394 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
3397 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
3398 Diag(D.getIdentifierLoc(),
3399 diag::err_member_def_undefined_record)
3400 << Name << DC << D.getCXXScopeSpec().getRange();
3402 } else if (!D.getDeclSpec().isFriendSpecified()) {
3403 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
3404 Name, D.getIdentifierLoc())) {
3412 // Check whether we need to rebuild the type of the given
3413 // declaration in the current instantiation.
3414 if (EnteringContext && IsDependentContext &&
3415 TemplateParamLists.size() != 0) {
3416 ContextRAII SavedContext(*this, DC);
3417 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
3422 if (DiagnoseClassNameShadow(DC, NameInfo))
3423 // If this is a typedef, we'll end up spewing multiple diagnostics.
3424 // Just return early; it's safer.
3425 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3430 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3431 QualType R = TInfo->getType();
3433 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
3434 UPPC_DeclarationType))
3437 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
3440 // See if this is a redefinition of a variable in the same scope.
3441 if (!D.getCXXScopeSpec().isSet()) {
3442 bool IsLinkageLookup = false;
3444 // If the declaration we're planning to build will be a function
3445 // or object with linkage, then look for another declaration with
3446 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
3447 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3449 else if (R->isFunctionType()) {
3450 if (CurContext->isFunctionOrMethod() ||
3451 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3452 IsLinkageLookup = true;
3453 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
3454 IsLinkageLookup = true;
3455 else if (CurContext->getRedeclContext()->isTranslationUnit() &&
3456 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
3457 IsLinkageLookup = true;
3459 if (IsLinkageLookup)
3460 Previous.clear(LookupRedeclarationWithLinkage);
3462 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
3463 } else { // Something like "int foo::x;"
3464 LookupQualifiedName(Previous, DC);
3466 // C++ [dcl.meaning]p1:
3467 // When the declarator-id is qualified, the declaration shall refer to a
3468 // previously declared member of the class or namespace to which the
3469 // qualifier refers (or, in the case of a namespace, of an element of the
3470 // inline namespace set of that namespace (7.3.1)) or to a specialization
3473 // Note that we already checked the context above, and that we do not have
3474 // enough information to make sure that Previous contains the declaration
3475 // we want to match. For example, given:
3482 // void X::f(int) { } // ill-formed
3484 // In this case, Previous will point to the overload set
3485 // containing the two f's declared in X, but neither of them
3488 // C++ [dcl.meaning]p1:
3489 // [...] the member shall not merely have been introduced by a
3490 // using-declaration in the scope of the class or namespace nominated by
3491 // the nested-name-specifier of the declarator-id.
3492 RemoveUsingDecls(Previous);
3495 if (Previous.isSingleResult() &&
3496 Previous.getFoundDecl()->isTemplateParameter()) {
3497 // Maybe we will complain about the shadowed template parameter.
3498 if (!D.isInvalidType())
3499 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
3500 Previous.getFoundDecl());
3502 // Just pretend that we didn't see the previous declaration.
3506 // In C++, the previous declaration we find might be a tag type
3507 // (class or enum). In this case, the new declaration will hide the
3508 // tag type. Note that this does does not apply if we're declaring a
3509 // typedef (C++ [dcl.typedef]p4).
3510 if (Previous.isSingleTagDecl() &&
3511 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
3514 bool AddToScope = true;
3515 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
3516 if (TemplateParamLists.size()) {
3517 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
3521 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
3522 } else if (R->isFunctionType()) {
3523 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
3524 move(TemplateParamLists),
3527 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
3528 move(TemplateParamLists));
3534 // If this has an identifier and is not an invalid redeclaration or
3535 // function template specialization, add it to the scope stack.
3536 if (New->getDeclName() && AddToScope &&
3537 !(D.isRedeclaration() && New->isInvalidDecl()))
3538 PushOnScopeChains(New, S);
3543 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3544 /// types into constant array types in certain situations which would otherwise
3545 /// be errors (for GCC compatibility).
3546 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3547 ASTContext &Context,
3548 bool &SizeIsNegative,
3549 llvm::APSInt &Oversized) {
3550 // This method tries to turn a variable array into a constant
3551 // array even when the size isn't an ICE. This is necessary
3552 // for compatibility with code that depends on gcc's buggy
3553 // constant expression folding, like struct {char x[(int)(char*)2];}
3554 SizeIsNegative = false;
3557 if (T->isDependentType())
3560 QualifierCollector Qs;
3561 const Type *Ty = Qs.strip(T);
3563 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
3564 QualType Pointee = PTy->getPointeeType();
3565 QualType FixedType =
3566 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
3568 if (FixedType.isNull()) return FixedType;
3569 FixedType = Context.getPointerType(FixedType);
3570 return Qs.apply(Context, FixedType);
3572 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
3573 QualType Inner = PTy->getInnerType();
3574 QualType FixedType =
3575 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
3577 if (FixedType.isNull()) return FixedType;
3578 FixedType = Context.getParenType(FixedType);
3579 return Qs.apply(Context, FixedType);
3582 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3585 // FIXME: We should probably handle this case
3586 if (VLATy->getElementType()->isVariablyModifiedType())
3590 if (!VLATy->getSizeExpr() ||
3591 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
3594 // Check whether the array size is negative.
3595 if (Res.isSigned() && Res.isNegative()) {
3596 SizeIsNegative = true;
3600 // Check whether the array is too large to be addressed.
3601 unsigned ActiveSizeBits
3602 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
3604 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
3609 return Context.getConstantArrayType(VLATy->getElementType(),
3610 Res, ArrayType::Normal, 0);
3613 /// \brief Register the given locally-scoped external C declaration so
3614 /// that it can be found later for redeclarations
3616 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
3617 const LookupResult &Previous,
3619 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
3620 "Decl is not a locally-scoped decl!");
3621 // Note that we have a locally-scoped external with this name.
3622 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
3624 if (!Previous.isSingleResult())
3627 NamedDecl *PrevDecl = Previous.getFoundDecl();
3629 // If there was a previous declaration of this variable, it may be
3630 // in our identifier chain. Update the identifier chain with the new
3632 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
3633 // The previous declaration was found on the identifer resolver
3634 // chain, so remove it from its scope.
3636 if (S->isDeclScope(PrevDecl)) {
3637 // Special case for redeclarations in the SAME scope.
3638 // Because this declaration is going to be added to the identifier chain
3639 // later, we should temporarily take it OFF the chain.
3640 IdResolver.RemoveDecl(ND);
3643 // Find the scope for the original declaration.
3644 while (S && !S->isDeclScope(PrevDecl))
3649 S->RemoveDecl(PrevDecl);
3653 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
3654 Sema::findLocallyScopedExternalDecl(DeclarationName Name) {
3655 if (ExternalSource) {
3656 // Load locally-scoped external decls from the external source.
3657 SmallVector<NamedDecl *, 4> Decls;
3658 ExternalSource->ReadLocallyScopedExternalDecls(Decls);
3659 for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
3660 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3661 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName());
3662 if (Pos == LocallyScopedExternalDecls.end())
3663 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I];
3667 return LocallyScopedExternalDecls.find(Name);
3670 /// \brief Diagnose function specifiers on a declaration of an identifier that
3671 /// does not identify a function.
3672 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
3673 // FIXME: We should probably indicate the identifier in question to avoid
3674 // confusion for constructs like "inline int a(), b;"
3675 if (D.getDeclSpec().isInlineSpecified())
3676 Diag(D.getDeclSpec().getInlineSpecLoc(),
3677 diag::err_inline_non_function);
3679 if (D.getDeclSpec().isVirtualSpecified())
3680 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3681 diag::err_virtual_non_function);
3683 if (D.getDeclSpec().isExplicitSpecified())
3684 Diag(D.getDeclSpec().getExplicitSpecLoc(),
3685 diag::err_explicit_non_function);
3689 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
3690 TypeSourceInfo *TInfo, LookupResult &Previous) {
3691 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
3692 if (D.getCXXScopeSpec().isSet()) {
3693 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
3694 << D.getCXXScopeSpec().getRange();
3696 // Pretend we didn't see the scope specifier.
3701 if (getLangOpts().CPlusPlus) {
3702 // Check that there are no default arguments (C++ only).
3703 CheckExtraCXXDefaultArguments(D);
3706 DiagnoseFunctionSpecifiers(D);
3708 if (D.getDeclSpec().isThreadSpecified())
3709 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3710 if (D.getDeclSpec().isConstexprSpecified())
3711 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
3714 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
3715 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
3716 << D.getName().getSourceRange();
3720 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
3721 if (!NewTD) return 0;
3723 // Handle attributes prior to checking for duplicates in MergeVarDecl
3724 ProcessDeclAttributes(S, NewTD, D);
3726 CheckTypedefForVariablyModifiedType(S, NewTD);
3728 bool Redeclaration = D.isRedeclaration();
3729 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
3730 D.setRedeclaration(Redeclaration);
3735 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
3736 // C99 6.7.7p2: If a typedef name specifies a variably modified type
3737 // then it shall have block scope.
3738 // Note that variably modified types must be fixed before merging the decl so
3739 // that redeclarations will match.
3740 QualType T = NewTD->getUnderlyingType();
3741 if (T->isVariablyModifiedType()) {
3742 getCurFunction()->setHasBranchProtectedScope();
3744 if (S->getFnParent() == 0) {
3745 bool SizeIsNegative;
3746 llvm::APSInt Oversized;
3748 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
3750 if (!FixedTy.isNull()) {
3751 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
3752 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
3755 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
3756 else if (T->isVariableArrayType())
3757 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
3758 else if (Oversized.getBoolValue())
3759 Diag(NewTD->getLocation(), diag::err_array_too_large)
3760 << Oversized.toString(10);
3762 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
3763 NewTD->setInvalidDecl();
3770 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
3771 /// declares a typedef-name, either using the 'typedef' type specifier or via
3772 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
3774 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
3775 LookupResult &Previous, bool &Redeclaration) {
3776 // Merge the decl with the existing one if appropriate. If the decl is
3777 // in an outer scope, it isn't the same thing.
3778 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
3779 /*ExplicitInstantiationOrSpecialization=*/false);
3780 if (!Previous.empty()) {
3781 Redeclaration = true;
3782 MergeTypedefNameDecl(NewTD, Previous);
3785 // If this is the C FILE type, notify the AST context.
3786 if (IdentifierInfo *II = NewTD->getIdentifier())
3787 if (!NewTD->isInvalidDecl() &&
3788 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
3789 if (II->isStr("FILE"))
3790 Context.setFILEDecl(NewTD);
3791 else if (II->isStr("jmp_buf"))
3792 Context.setjmp_bufDecl(NewTD);
3793 else if (II->isStr("sigjmp_buf"))
3794 Context.setsigjmp_bufDecl(NewTD);
3795 else if (II->isStr("ucontext_t"))
3796 Context.setucontext_tDecl(NewTD);
3797 else if (II->isStr("__builtin_va_list"))
3798 Context.setBuiltinVaListType(Context.getTypedefType(NewTD));
3804 /// \brief Determines whether the given declaration is an out-of-scope
3805 /// previous declaration.
3807 /// This routine should be invoked when name lookup has found a
3808 /// previous declaration (PrevDecl) that is not in the scope where a
3809 /// new declaration by the same name is being introduced. If the new
3810 /// declaration occurs in a local scope, previous declarations with
3811 /// linkage may still be considered previous declarations (C99
3812 /// 6.2.2p4-5, C++ [basic.link]p6).
3814 /// \param PrevDecl the previous declaration found by name
3817 /// \param DC the context in which the new declaration is being
3820 /// \returns true if PrevDecl is an out-of-scope previous declaration
3821 /// for a new delcaration with the same name.
3823 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
3824 ASTContext &Context) {
3828 if (!PrevDecl->hasLinkage())
3831 if (Context.getLangOpts().CPlusPlus) {
3832 // C++ [basic.link]p6:
3833 // If there is a visible declaration of an entity with linkage
3834 // having the same name and type, ignoring entities declared
3835 // outside the innermost enclosing namespace scope, the block
3836 // scope declaration declares that same entity and receives the
3837 // linkage of the previous declaration.
3838 DeclContext *OuterContext = DC->getRedeclContext();
3839 if (!OuterContext->isFunctionOrMethod())
3840 // This rule only applies to block-scope declarations.
3843 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
3844 if (PrevOuterContext->isRecord())
3845 // We found a member function: ignore it.
3848 // Find the innermost enclosing namespace for the new and
3849 // previous declarations.
3850 OuterContext = OuterContext->getEnclosingNamespaceContext();
3851 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
3853 // The previous declaration is in a different namespace, so it
3854 // isn't the same function.
3855 if (!OuterContext->Equals(PrevOuterContext))
3862 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
3863 CXXScopeSpec &SS = D.getCXXScopeSpec();
3864 if (!SS.isSet()) return;
3865 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
3868 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
3869 QualType type = decl->getType();
3870 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
3871 if (lifetime == Qualifiers::OCL_Autoreleasing) {
3872 // Various kinds of declaration aren't allowed to be __autoreleasing.
3873 unsigned kind = -1U;
3874 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3875 if (var->hasAttr<BlocksAttr>())
3876 kind = 0; // __block
3877 else if (!var->hasLocalStorage())
3879 } else if (isa<ObjCIvarDecl>(decl)) {
3881 } else if (isa<FieldDecl>(decl)) {
3886 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
3889 } else if (lifetime == Qualifiers::OCL_None) {
3890 // Try to infer lifetime.
3891 if (!type->isObjCLifetimeType())
3894 lifetime = type->getObjCARCImplicitLifetime();
3895 type = Context.getLifetimeQualifiedType(type, lifetime);
3896 decl->setType(type);
3899 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
3900 // Thread-local variables cannot have lifetime.
3901 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
3902 var->isThreadSpecified()) {
3903 Diag(var->getLocation(), diag::err_arc_thread_ownership)
3913 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
3914 TypeSourceInfo *TInfo, LookupResult &Previous,
3915 MultiTemplateParamsArg TemplateParamLists) {
3916 QualType R = TInfo->getType();
3917 DeclarationName Name = GetNameForDeclarator(D).getName();
3919 // Check that there are no default arguments (C++ only).
3920 if (getLangOpts().CPlusPlus)
3921 CheckExtraCXXDefaultArguments(D);
3923 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
3924 assert(SCSpec != DeclSpec::SCS_typedef &&
3925 "Parser allowed 'typedef' as storage class VarDecl.");
3926 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
3927 if (SCSpec == DeclSpec::SCS_mutable) {
3928 // mutable can only appear on non-static class members, so it's always
3930 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
3934 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
3935 VarDecl::StorageClass SCAsWritten
3936 = StorageClassSpecToVarDeclStorageClass(SCSpec);
3938 IdentifierInfo *II = Name.getAsIdentifierInfo();
3940 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
3945 DiagnoseFunctionSpecifiers(D);
3947 if (!DC->isRecord() && S->getFnParent() == 0) {
3948 // C99 6.9p2: The storage-class specifiers auto and register shall not
3949 // appear in the declaration specifiers in an external declaration.
3950 if (SC == SC_Auto || SC == SC_Register) {
3952 // If this is a register variable with an asm label specified, then this
3953 // is a GNU extension.
3954 if (SC == SC_Register && D.getAsmLabel())
3955 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
3957 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
3962 if (getLangOpts().OpenCL) {
3963 // Set up the special work-group-local storage class for variables in the
3964 // OpenCL __local address space.
3965 if (R.getAddressSpace() == LangAS::opencl_local)
3966 SC = SC_OpenCLWorkGroupLocal;
3969 bool isExplicitSpecialization = false;
3971 if (!getLangOpts().CPlusPlus) {
3972 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
3973 D.getIdentifierLoc(), II,
3974 R, TInfo, SC, SCAsWritten);
3976 if (D.isInvalidType())
3977 NewVD->setInvalidDecl();
3979 if (DC->isRecord() && !CurContext->isRecord()) {
3980 // This is an out-of-line definition of a static data member.
3981 if (SC == SC_Static) {
3982 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3983 diag::err_static_out_of_line)
3984 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3985 } else if (SC == SC_None)
3988 if (SC == SC_Static && CurContext->isRecord()) {
3989 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
3990 if (RD->isLocalClass())
3991 Diag(D.getIdentifierLoc(),
3992 diag::err_static_data_member_not_allowed_in_local_class)
3993 << Name << RD->getDeclName();
3995 // C++98 [class.union]p1: If a union contains a static data member,
3996 // the program is ill-formed. C++11 drops this restriction.
3998 Diag(D.getIdentifierLoc(),
3999 getLangOpts().CPlusPlus0x
4000 ? diag::warn_cxx98_compat_static_data_member_in_union
4001 : diag::ext_static_data_member_in_union) << Name;
4002 // We conservatively disallow static data members in anonymous structs.
4003 else if (!RD->getDeclName())
4004 Diag(D.getIdentifierLoc(),
4005 diag::err_static_data_member_not_allowed_in_anon_struct)
4006 << Name << RD->isUnion();
4010 // Match up the template parameter lists with the scope specifier, then
4011 // determine whether we have a template or a template specialization.
4012 isExplicitSpecialization = false;
4013 bool Invalid = false;
4014 if (TemplateParameterList *TemplateParams
4015 = MatchTemplateParametersToScopeSpecifier(
4016 D.getDeclSpec().getLocStart(),
4017 D.getIdentifierLoc(),
4018 D.getCXXScopeSpec(),
4019 TemplateParamLists.get(),
4020 TemplateParamLists.size(),
4021 /*never a friend*/ false,
4022 isExplicitSpecialization,
4024 if (TemplateParams->size() > 0) {
4025 // There is no such thing as a variable template.
4026 Diag(D.getIdentifierLoc(), diag::err_template_variable)
4028 << SourceRange(TemplateParams->getTemplateLoc(),
4029 TemplateParams->getRAngleLoc());
4032 // There is an extraneous 'template<>' for this variable. Complain
4033 // about it, but allow the declaration of the variable.
4034 Diag(TemplateParams->getTemplateLoc(),
4035 diag::err_template_variable_noparams)
4037 << SourceRange(TemplateParams->getTemplateLoc(),
4038 TemplateParams->getRAngleLoc());
4042 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
4043 D.getIdentifierLoc(), II,
4044 R, TInfo, SC, SCAsWritten);
4046 // If this decl has an auto type in need of deduction, make a note of the
4047 // Decl so we can diagnose uses of it in its own initializer.
4048 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
4049 R->getContainedAutoType())
4050 ParsingInitForAutoVars.insert(NewVD);
4052 if (D.isInvalidType() || Invalid)
4053 NewVD->setInvalidDecl();
4055 SetNestedNameSpecifier(NewVD, D);
4057 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) {
4058 NewVD->setTemplateParameterListsInfo(Context,
4059 TemplateParamLists.size(),
4060 TemplateParamLists.release());
4063 if (D.getDeclSpec().isConstexprSpecified())
4064 NewVD->setConstexpr(true);
4067 // Set the lexical context. If the declarator has a C++ scope specifier, the
4068 // lexical context will be different from the semantic context.
4069 NewVD->setLexicalDeclContext(CurContext);
4071 if (D.getDeclSpec().isThreadSpecified()) {
4072 if (NewVD->hasLocalStorage())
4073 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
4074 else if (!Context.getTargetInfo().isTLSSupported())
4075 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
4077 NewVD->setThreadSpecified(true);
4080 if (D.getDeclSpec().isModulePrivateSpecified()) {
4081 if (isExplicitSpecialization)
4082 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
4084 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4085 else if (NewVD->hasLocalStorage())
4086 Diag(NewVD->getLocation(), diag::err_module_private_local)
4087 << 0 << NewVD->getDeclName()
4088 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
4089 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
4091 NewVD->setModulePrivate();
4094 // Handle attributes prior to checking for duplicates in MergeVarDecl
4095 ProcessDeclAttributes(S, NewVD, D);
4097 // In auto-retain/release, infer strong retension for variables of
4099 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
4100 NewVD->setInvalidDecl();
4102 // Handle GNU asm-label extension (encoded as an attribute).
4103 if (Expr *E = (Expr*)D.getAsmLabel()) {
4104 // The parser guarantees this is a string.
4105 StringLiteral *SE = cast<StringLiteral>(E);
4106 StringRef Label = SE->getString();
4107 if (S->getFnParent() != 0) {
4111 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
4114 if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
4115 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
4119 case SC_PrivateExtern:
4120 case SC_OpenCLWorkGroupLocal:
4125 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
4127 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
4128 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
4129 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
4130 if (I != ExtnameUndeclaredIdentifiers.end()) {
4131 NewVD->addAttr(I->second);
4132 ExtnameUndeclaredIdentifiers.erase(I);
4136 // Diagnose shadowed variables before filtering for scope.
4137 if (!D.getCXXScopeSpec().isSet())
4138 CheckShadow(S, NewVD, Previous);
4140 // Don't consider existing declarations that are in a different
4141 // scope and are out-of-semantic-context declarations (if the new
4142 // declaration has linkage).
4143 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(),
4144 isExplicitSpecialization);
4146 if (!getLangOpts().CPlusPlus) {
4147 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4149 // Merge the decl with the existing one if appropriate.
4150 if (!Previous.empty()) {
4151 if (Previous.isSingleResult() &&
4152 isa<FieldDecl>(Previous.getFoundDecl()) &&
4153 D.getCXXScopeSpec().isSet()) {
4154 // The user tried to define a non-static data member
4155 // out-of-line (C++ [dcl.meaning]p1).
4156 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
4157 << D.getCXXScopeSpec().getRange();
4159 NewVD->setInvalidDecl();
4161 } else if (D.getCXXScopeSpec().isSet()) {
4162 // No previous declaration in the qualifying scope.
4163 Diag(D.getIdentifierLoc(), diag::err_no_member)
4164 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
4165 << D.getCXXScopeSpec().getRange();
4166 NewVD->setInvalidDecl();
4169 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
4171 // This is an explicit specialization of a static data member. Check it.
4172 if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
4173 CheckMemberSpecialization(NewVD, Previous))
4174 NewVD->setInvalidDecl();
4177 // attributes declared post-definition are currently ignored
4178 // FIXME: This should be handled in attribute merging, not
4180 if (Previous.isSingleResult()) {
4181 VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
4182 if (Def && (Def = Def->getDefinition()) &&
4183 Def != NewVD && D.hasAttributes()) {
4184 Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
4185 Diag(Def->getLocation(), diag::note_previous_definition);
4189 // If this is a locally-scoped extern C variable, update the map of
4191 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
4192 !NewVD->isInvalidDecl())
4193 RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
4195 // If there's a #pragma GCC visibility in scope, and this isn't a class
4196 // member, set the visibility of this variable.
4197 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord())
4198 AddPushedVisibilityAttribute(NewVD);
4200 MarkUnusedFileScopedDecl(NewVD);
4205 /// \brief Diagnose variable or built-in function shadowing. Implements
4208 /// This method is called whenever a VarDecl is added to a "useful"
4211 /// \param S the scope in which the shadowing name is being declared
4212 /// \param R the lookup of the name
4214 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
4215 // Return if warning is ignored.
4216 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
4217 DiagnosticsEngine::Ignored)
4220 // Don't diagnose declarations at file scope.
4221 if (D->hasGlobalStorage())
4224 DeclContext *NewDC = D->getDeclContext();
4226 // Only diagnose if we're shadowing an unambiguous field or variable.
4227 if (R.getResultKind() != LookupResult::Found)
4230 NamedDecl* ShadowedDecl = R.getFoundDecl();
4231 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
4234 // Fields are not shadowed by variables in C++ static methods.
4235 if (isa<FieldDecl>(ShadowedDecl))
4236 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
4240 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
4241 if (shadowedVar->isExternC()) {
4242 // For shadowing external vars, make sure that we point to the global
4243 // declaration, not a locally scoped extern declaration.
4244 for (VarDecl::redecl_iterator
4245 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
4247 if (I->isFileVarDecl()) {
4253 DeclContext *OldDC = ShadowedDecl->getDeclContext();
4255 // Only warn about certain kinds of shadowing for class members.
4256 if (NewDC && NewDC->isRecord()) {
4257 // In particular, don't warn about shadowing non-class members.
4258 if (!OldDC->isRecord())
4261 // TODO: should we warn about static data members shadowing
4262 // static data members from base classes?
4264 // TODO: don't diagnose for inaccessible shadowed members.
4265 // This is hard to do perfectly because we might friend the
4266 // shadowing context, but that's just a false negative.
4269 // Determine what kind of declaration we're shadowing.
4271 if (isa<RecordDecl>(OldDC)) {
4272 if (isa<FieldDecl>(ShadowedDecl))
4275 Kind = 2; // static data member
4276 } else if (OldDC->isFileContext())
4281 DeclarationName Name = R.getLookupName();
4283 // Emit warning and note.
4284 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
4285 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
4288 /// \brief Check -Wshadow without the advantage of a previous lookup.
4289 void Sema::CheckShadow(Scope *S, VarDecl *D) {
4290 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
4291 DiagnosticsEngine::Ignored)
4294 LookupResult R(*this, D->getDeclName(), D->getLocation(),
4295 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4297 CheckShadow(S, D, R);
4300 /// \brief Perform semantic checking on a newly-created variable
4303 /// This routine performs all of the type-checking required for a
4304 /// variable declaration once it has been built. It is used both to
4305 /// check variables after they have been parsed and their declarators
4306 /// have been translated into a declaration, and to check variables
4307 /// that have been instantiated from a template.
4309 /// Sets NewVD->isInvalidDecl() if an error was encountered.
4311 /// Returns true if the variable declaration is a redeclaration.
4312 bool Sema::CheckVariableDeclaration(VarDecl *NewVD,
4313 LookupResult &Previous) {
4314 // If the decl is already known invalid, don't check it.
4315 if (NewVD->isInvalidDecl())
4318 QualType T = NewVD->getType();
4320 if (T->isObjCObjectType()) {
4321 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
4322 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
4323 T = Context.getObjCObjectPointerType(T);
4327 // Emit an error if an address space was applied to decl with local storage.
4328 // This includes arrays of objects with address space qualifiers, but not
4329 // automatic variables that point to other address spaces.
4330 // ISO/IEC TR 18037 S5.1.2
4331 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
4332 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
4333 NewVD->setInvalidDecl();
4337 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
4338 && !NewVD->hasAttr<BlocksAttr>()) {
4339 if (getLangOpts().getGC() != LangOptions::NonGC)
4340 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
4342 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
4345 bool isVM = T->isVariablyModifiedType();
4346 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
4347 NewVD->hasAttr<BlocksAttr>())
4348 getCurFunction()->setHasBranchProtectedScope();
4350 if ((isVM && NewVD->hasLinkage()) ||
4351 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
4352 bool SizeIsNegative;
4353 llvm::APSInt Oversized;
4355 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
4358 if (FixedTy.isNull() && T->isVariableArrayType()) {
4359 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
4360 // FIXME: This won't give the correct result for
4362 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
4364 if (NewVD->isFileVarDecl())
4365 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
4367 else if (NewVD->getStorageClass() == SC_Static)
4368 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
4371 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
4373 NewVD->setInvalidDecl();
4377 if (FixedTy.isNull()) {
4378 if (NewVD->isFileVarDecl())
4379 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
4381 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
4382 NewVD->setInvalidDecl();
4386 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
4387 NewVD->setType(FixedTy);
4390 if (Previous.empty() && NewVD->isExternC()) {
4391 // Since we did not find anything by this name and we're declaring
4392 // an extern "C" variable, look for a non-visible extern "C"
4393 // declaration with the same name.
4394 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4395 = findLocallyScopedExternalDecl(NewVD->getDeclName());
4396 if (Pos != LocallyScopedExternalDecls.end())
4397 Previous.addDecl(Pos->second);
4400 if (T->isVoidType() && !NewVD->hasExternalStorage()) {
4401 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
4403 NewVD->setInvalidDecl();
4407 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
4408 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
4409 NewVD->setInvalidDecl();
4413 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
4414 Diag(NewVD->getLocation(), diag::err_block_on_vm);
4415 NewVD->setInvalidDecl();
4419 if (NewVD->isConstexpr() && !T->isDependentType() &&
4420 RequireLiteralType(NewVD->getLocation(), T,
4421 PDiag(diag::err_constexpr_var_non_literal))) {
4422 NewVD->setInvalidDecl();
4426 if (!Previous.empty()) {
4427 MergeVarDecl(NewVD, Previous);
4433 /// \brief Data used with FindOverriddenMethod
4434 struct FindOverriddenMethodData {
4436 CXXMethodDecl *Method;
4439 /// \brief Member lookup function that determines whether a given C++
4440 /// method overrides a method in a base class, to be used with
4441 /// CXXRecordDecl::lookupInBases().
4442 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
4445 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4447 FindOverriddenMethodData *Data
4448 = reinterpret_cast<FindOverriddenMethodData*>(UserData);
4450 DeclarationName Name = Data->Method->getDeclName();
4452 // FIXME: Do we care about other names here too?
4453 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4454 // We really want to find the base class destructor here.
4455 QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
4456 CanQualType CT = Data->S->Context.getCanonicalType(T);
4458 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
4461 for (Path.Decls = BaseRecord->lookup(Name);
4462 Path.Decls.first != Path.Decls.second;
4463 ++Path.Decls.first) {
4464 NamedDecl *D = *Path.Decls.first;
4465 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4466 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
4474 /// AddOverriddenMethods - See if a method overrides any in the base classes,
4475 /// and if so, check that it's a valid override and remember it.
4476 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4477 // Look for virtual methods in base classes that this method might override.
4479 FindOverriddenMethodData Data;
4482 bool AddedAny = false;
4483 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
4484 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
4485 E = Paths.found_decls_end(); I != E; ++I) {
4486 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
4487 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
4488 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
4489 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
4490 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
4501 // Struct for holding all of the extra arguments needed by
4502 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
4503 struct ActOnFDArgs {
4506 MultiTemplateParamsArg TemplateParamLists;
4513 // Callback to only accept typo corrections that have a non-zero edit distance.
4514 // Also only accept corrections that have the same parent decl.
4515 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
4517 DifferentNameValidatorCCC(CXXRecordDecl *Parent)
4518 : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
4520 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
4521 if (candidate.getEditDistance() == 0)
4524 if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) {
4525 CXXRecordDecl *Parent = MD->getParent();
4526 return Parent && Parent->getCanonicalDecl() == ExpectedParent;
4529 return !ExpectedParent;
4533 CXXRecordDecl *ExpectedParent;
4538 /// \brief Generate diagnostics for an invalid function redeclaration.
4540 /// This routine handles generating the diagnostic messages for an invalid
4541 /// function redeclaration, including finding possible similar declarations
4542 /// or performing typo correction if there are no previous declarations with
4545 /// Returns a NamedDecl iff typo correction was performed and substituting in
4546 /// the new declaration name does not cause new errors.
4547 static NamedDecl* DiagnoseInvalidRedeclaration(
4548 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
4549 ActOnFDArgs &ExtraArgs) {
4550 NamedDecl *Result = NULL;
4551 DeclarationName Name = NewFD->getDeclName();
4552 DeclContext *NewDC = NewFD->getDeclContext();
4553 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
4554 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
4555 llvm::SmallVector<unsigned, 1> MismatchedParams;
4556 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches;
4557 TypoCorrection Correction;
4558 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus &&
4559 ExtraArgs.D.getDeclSpec().isFriendSpecified());
4560 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend
4561 : diag::err_member_def_does_not_match;
4563 NewFD->setInvalidDecl();
4564 SemaRef.LookupQualifiedName(Prev, NewDC);
4565 assert(!Prev.isAmbiguous() &&
4566 "Cannot have an ambiguity in previous-declaration lookup");
4567 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
4568 DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0);
4569 if (!Prev.empty()) {
4570 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
4571 Func != FuncEnd; ++Func) {
4572 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
4574 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
4575 // Add 1 to the index so that 0 can mean the mismatch didn't
4576 // involve a parameter
4578 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
4579 NearMatches.push_back(std::make_pair(FD, ParamNum));
4582 // If the qualified name lookup yielded nothing, try typo correction
4583 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(),
4584 Prev.getLookupKind(), 0, 0,
4585 Validator, NewDC))) {
4587 Sema::SFINAETrap Trap(SemaRef);
4589 // Set up everything for the call to ActOnFunctionDeclarator
4590 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
4591 ExtraArgs.D.getIdentifierLoc());
4593 Previous.setLookupName(Correction.getCorrection());
4594 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
4595 CDeclEnd = Correction.end();
4596 CDecl != CDeclEnd; ++CDecl) {
4597 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
4598 if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD,
4599 MismatchedParams)) {
4600 Previous.addDecl(FD);
4603 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
4604 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
4605 // pieces need to verify the typo-corrected C++ declaraction and hopefully
4606 // eliminate the need for the parameter pack ExtraArgs.
4607 Result = SemaRef.ActOnFunctionDeclarator(
4608 ExtraArgs.S, ExtraArgs.D,
4609 Correction.getCorrectionDecl()->getDeclContext(),
4610 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
4611 ExtraArgs.AddToScope);
4612 if (Trap.hasErrorOccurred()) {
4613 // Pretend the typo correction never occurred
4614 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
4615 ExtraArgs.D.getIdentifierLoc());
4616 ExtraArgs.D.setRedeclaration(wasRedeclaration);
4618 Previous.setLookupName(Name);
4621 for (LookupResult::iterator Func = Previous.begin(),
4622 FuncEnd = Previous.end();
4623 Func != FuncEnd; ++Func) {
4624 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func))
4625 NearMatches.push_back(std::make_pair(FD, 0));
4628 if (NearMatches.empty()) {
4629 // Ignore the correction if it didn't yield any close FunctionDecl matches
4630 Correction = TypoCorrection();
4632 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest
4633 : diag::err_member_def_does_not_match_suggest;
4638 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4639 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts())
4640 << FixItHint::CreateReplacement(
4641 NewFD->getLocation(),
4642 Correction.getAsString(SemaRef.getLangOpts()));
4644 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
4645 << Name << NewDC << NewFD->getLocation();
4647 bool NewFDisConst = false;
4648 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
4649 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const;
4651 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator
4652 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
4653 NearMatch != NearMatchEnd; ++NearMatch) {
4654 FunctionDecl *FD = NearMatch->first;
4655 bool FDisConst = false;
4656 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
4657 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const;
4659 if (unsigned Idx = NearMatch->second) {
4660 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
4661 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
4662 if (Loc.isInvalid()) Loc = FD->getLocation();
4663 SemaRef.Diag(Loc, diag::note_member_def_close_param_match)
4664 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType();
4665 } else if (Correction) {
4666 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl)
4667 << Correction.getQuoted(SemaRef.getLangOpts());
4668 } else if (FDisConst != NewFDisConst) {
4669 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
4670 << NewFDisConst << FD->getSourceRange().getEnd();
4672 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match);
4677 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
4679 switch (D.getDeclSpec().getStorageClassSpec()) {
4680 default: llvm_unreachable("Unknown storage class!");
4681 case DeclSpec::SCS_auto:
4682 case DeclSpec::SCS_register:
4683 case DeclSpec::SCS_mutable:
4684 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4685 diag::err_typecheck_sclass_func);
4688 case DeclSpec::SCS_unspecified: break;
4689 case DeclSpec::SCS_extern: return SC_Extern;
4690 case DeclSpec::SCS_static: {
4691 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4693 // The declaration of an identifier for a function that has
4694 // block scope shall have no explicit storage-class specifier
4695 // other than extern
4696 // See also (C++ [dcl.stc]p4).
4697 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4698 diag::err_static_block_func);
4703 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4706 // No explicit storage class has already been returned
4710 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
4711 DeclContext *DC, QualType &R,
4712 TypeSourceInfo *TInfo,
4713 FunctionDecl::StorageClass SC,
4714 bool &IsVirtualOkay) {
4715 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
4716 DeclarationName Name = NameInfo.getName();
4718 FunctionDecl *NewFD = 0;
4719 bool isInline = D.getDeclSpec().isInlineSpecified();
4720 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
4721 FunctionDecl::StorageClass SCAsWritten
4722 = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
4724 if (!SemaRef.getLangOpts().CPlusPlus) {
4725 // Determine whether the function was written with a
4726 // prototype. This true when:
4727 // - there is a prototype in the declarator, or
4728 // - the type R of the function is some kind of typedef or other reference
4729 // to a type name (which eventually refers to a function type).
4731 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
4732 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
4734 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
4735 D.getLocStart(), NameInfo, R,
4736 TInfo, SC, SCAsWritten, isInline,
4738 if (D.isInvalidType())
4739 NewFD->setInvalidDecl();
4741 // Set the lexical context.
4742 NewFD->setLexicalDeclContext(SemaRef.CurContext);
4747 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4748 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4750 // Check that the return type is not an abstract class type.
4751 // For record types, this is done by the AbstractClassUsageDiagnoser once
4752 // the class has been completely parsed.
4753 if (!DC->isRecord() &&
4754 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
4755 R->getAs<FunctionType>()->getResultType(),
4756 diag::err_abstract_type_in_decl,
4757 SemaRef.AbstractReturnType))
4760 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
4761 // This is a C++ constructor declaration.
4762 assert(DC->isRecord() &&
4763 "Constructors can only be declared in a member context");
4765 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
4766 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4767 D.getLocStart(), NameInfo,
4768 R, TInfo, isExplicit, isInline,
4769 /*isImplicitlyDeclared=*/false,
4772 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4773 // This is a C++ destructor declaration.
4774 if (DC->isRecord()) {
4775 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
4776 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
4777 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
4778 SemaRef.Context, Record,
4780 NameInfo, R, TInfo, isInline,
4781 /*isImplicitlyDeclared=*/false);
4783 // If the class is complete, then we now create the implicit exception
4784 // specification. If the class is incomplete or dependent, we can't do
4786 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() &&
4787 Record->getDefinition() && !Record->isBeingDefined() &&
4788 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
4789 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
4792 IsVirtualOkay = true;
4796 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
4799 // Create a FunctionDecl to satisfy the function definition parsing
4801 return FunctionDecl::Create(SemaRef.Context, DC,
4803 D.getIdentifierLoc(), Name, R, TInfo,
4804 SC, SCAsWritten, isInline,
4805 /*hasPrototype=*/true, isConstexpr);
4808 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4809 if (!DC->isRecord()) {
4810 SemaRef.Diag(D.getIdentifierLoc(),
4811 diag::err_conv_function_not_member);
4815 SemaRef.CheckConversionDeclarator(D, R, SC);
4816 IsVirtualOkay = true;
4817 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4818 D.getLocStart(), NameInfo,
4819 R, TInfo, isInline, isExplicit,
4820 isConstexpr, SourceLocation());
4822 } else if (DC->isRecord()) {
4823 // If the name of the function is the same as the name of the record,
4824 // then this must be an invalid constructor that has a return type.
4825 // (The parser checks for a return type and makes the declarator a
4826 // constructor if it has no return type).
4827 if (Name.getAsIdentifierInfo() &&
4828 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
4829 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
4830 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4831 << SourceRange(D.getIdentifierLoc());
4835 bool isStatic = SC == SC_Static;
4838 // Any allocation function for a class T is a static member
4839 // (even if not explicitly declared static).
4840 if (Name.getCXXOverloadedOperator() == OO_New ||
4841 Name.getCXXOverloadedOperator() == OO_Array_New)
4844 // [class.free]p6 Any deallocation function for a class X is a static member
4845 // (even if not explicitly declared static).
4846 if (Name.getCXXOverloadedOperator() == OO_Delete ||
4847 Name.getCXXOverloadedOperator() == OO_Array_Delete)
4850 IsVirtualOkay = !isStatic;
4852 // This is a C++ method declaration.
4853 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
4854 D.getLocStart(), NameInfo, R,
4855 TInfo, isStatic, SCAsWritten, isInline,
4856 isConstexpr, SourceLocation());
4859 // Determine whether the function was written with a
4860 // prototype. This true when:
4861 // - we're in C++ (where every function has a prototype),
4862 return FunctionDecl::Create(SemaRef.Context, DC,
4864 NameInfo, R, TInfo, SC, SCAsWritten, isInline,
4865 true/*HasPrototype*/, isConstexpr);
4870 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4871 TypeSourceInfo *TInfo, LookupResult &Previous,
4872 MultiTemplateParamsArg TemplateParamLists,
4874 QualType R = TInfo->getType();
4876 assert(R.getTypePtr()->isFunctionType());
4878 // TODO: consider using NameInfo for diagnostic.
4879 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4880 DeclarationName Name = NameInfo.getName();
4881 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
4883 if (D.getDeclSpec().isThreadSpecified())
4884 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4886 // Do not allow returning a objc interface by-value.
4887 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) {
4888 Diag(D.getIdentifierLoc(),
4889 diag::err_object_cannot_be_passed_returned_by_value) << 0
4890 << R->getAs<FunctionType>()->getResultType()
4891 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
4893 QualType T = R->getAs<FunctionType>()->getResultType();
4894 T = Context.getObjCObjectPointerType(T);
4895 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) {
4896 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4897 R = Context.getFunctionType(T, FPT->arg_type_begin(),
4898 FPT->getNumArgs(), EPI);
4900 else if (isa<FunctionNoProtoType>(R))
4901 R = Context.getFunctionNoProtoType(T);
4904 bool isFriend = false;
4905 FunctionTemplateDecl *FunctionTemplate = 0;
4906 bool isExplicitSpecialization = false;
4907 bool isFunctionTemplateSpecialization = false;
4908 bool isDependentClassScopeExplicitSpecialization = false;
4909 bool isVirtualOkay = false;
4911 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
4913 if (!NewFD) return 0;
4915 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
4916 NewFD->setTopLevelDeclInObjCContainer();
4918 if (getLangOpts().CPlusPlus) {
4919 bool isInline = D.getDeclSpec().isInlineSpecified();
4920 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4921 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
4922 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
4923 isFriend = D.getDeclSpec().isFriendSpecified();
4924 if (isFriend && !isInline && D.isFunctionDefinition()) {
4925 // C++ [class.friend]p5
4926 // A function can be defined in a friend declaration of a
4927 // class . . . . Such a function is implicitly inline.
4928 NewFD->setImplicitlyInline();
4931 SetNestedNameSpecifier(NewFD, D);
4932 isExplicitSpecialization = false;
4933 isFunctionTemplateSpecialization = false;
4934 if (D.isInvalidType())
4935 NewFD->setInvalidDecl();
4937 // Set the lexical context. If the declarator has a C++
4938 // scope specifier, or is the object of a friend declaration, the
4939 // lexical context will be different from the semantic context.
4940 NewFD->setLexicalDeclContext(CurContext);
4942 // Match up the template parameter lists with the scope specifier, then
4943 // determine whether we have a template or a template specialization.
4944 bool Invalid = false;
4945 if (TemplateParameterList *TemplateParams
4946 = MatchTemplateParametersToScopeSpecifier(
4947 D.getDeclSpec().getLocStart(),
4948 D.getIdentifierLoc(),
4949 D.getCXXScopeSpec(),
4950 TemplateParamLists.get(),
4951 TemplateParamLists.size(),
4953 isExplicitSpecialization,
4955 if (TemplateParams->size() > 0) {
4956 // This is a function template
4958 // Check that we can declare a template here.
4959 if (CheckTemplateDeclScope(S, TemplateParams))
4962 // A destructor cannot be a template.
4963 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
4964 Diag(NewFD->getLocation(), diag::err_destructor_template);
4968 // If we're adding a template to a dependent context, we may need to
4969 // rebuilding some of the types used within the template parameter list,
4970 // now that we know what the current instantiation is.
4971 if (DC->isDependentContext()) {
4972 ContextRAII SavedContext(*this, DC);
4973 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
4978 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
4979 NewFD->getLocation(),
4980 Name, TemplateParams,
4982 FunctionTemplate->setLexicalDeclContext(CurContext);
4983 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
4985 // For source fidelity, store the other template param lists.
4986 if (TemplateParamLists.size() > 1) {
4987 NewFD->setTemplateParameterListsInfo(Context,
4988 TemplateParamLists.size() - 1,
4989 TemplateParamLists.release());
4992 // This is a function template specialization.
4993 isFunctionTemplateSpecialization = true;
4994 // For source fidelity, store all the template param lists.
4995 NewFD->setTemplateParameterListsInfo(Context,
4996 TemplateParamLists.size(),
4997 TemplateParamLists.release());
4999 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
5001 // We want to remove the "template<>", found here.
5002 SourceRange RemoveRange = TemplateParams->getSourceRange();
5004 // If we remove the template<> and the name is not a
5005 // template-id, we're actually silently creating a problem:
5006 // the friend declaration will refer to an untemplated decl,
5007 // and clearly the user wants a template specialization. So
5008 // we need to insert '<>' after the name.
5009 SourceLocation InsertLoc;
5010 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5011 InsertLoc = D.getName().getSourceRange().getEnd();
5012 InsertLoc = PP.getLocForEndOfToken(InsertLoc);
5015 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
5016 << Name << RemoveRange
5017 << FixItHint::CreateRemoval(RemoveRange)
5018 << FixItHint::CreateInsertion(InsertLoc, "<>");
5023 // All template param lists were matched against the scope specifier:
5024 // this is NOT (an explicit specialization of) a template.
5025 if (TemplateParamLists.size() > 0)
5026 // For source fidelity, store all the template param lists.
5027 NewFD->setTemplateParameterListsInfo(Context,
5028 TemplateParamLists.size(),
5029 TemplateParamLists.release());
5033 NewFD->setInvalidDecl();
5034 if (FunctionTemplate)
5035 FunctionTemplate->setInvalidDecl();
5038 // If we see "T var();" at block scope, where T is a class type, it is
5039 // probably an attempt to initialize a variable, not a function declaration.
5040 // We don't catch this case earlier, since there is no ambiguity here.
5041 if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration &&
5042 CurContext->isFunctionOrMethod() &&
5043 D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() &&
5044 D.getDeclSpec().getStorageClassSpecAsWritten()
5045 == DeclSpec::SCS_unspecified) {
5046 QualType T = R->getAs<FunctionType>()->getResultType();
5047 DeclaratorChunk &C = D.getTypeObject(0);
5048 if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic &&
5049 !C.Fun.TrailingReturnType &&
5050 C.Fun.getExceptionSpecType() == EST_None) {
5051 SourceRange ParenRange(C.Loc, C.EndLoc);
5052 Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange;
5054 // If the declaration looks like:
5057 // and name lookup finds a function named 'f', then the ',' was
5058 // probably intended to be a ';'.
5059 if (!D.isFirstDeclarator() && D.getIdentifier()) {
5060 FullSourceLoc Comma(D.getCommaLoc(), SourceMgr);
5061 FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr);
5062 if (Comma.getFileID() != Name.getFileID() ||
5063 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
5064 LookupResult Result(*this, D.getIdentifier(), SourceLocation(),
5065 LookupOrdinaryName);
5066 if (LookupName(Result, S))
5067 Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
5068 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD;
5071 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5072 // Empty parens mean value-initialization, and no parens mean default
5073 // initialization. These are equivalent if the default constructor is
5074 // user-provided, or if zero-initialization is a no-op.
5075 if (RD && RD->hasDefinition() &&
5076 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
5077 Diag(C.Loc, diag::note_empty_parens_default_ctor)
5078 << FixItHint::CreateRemoval(ParenRange);
5079 else if (const char *Init = getFixItZeroInitializerForType(T))
5080 Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5081 << FixItHint::CreateReplacement(ParenRange, Init);
5082 else if (LangOpts.CPlusPlus0x)
5083 Diag(C.Loc, diag::note_empty_parens_zero_initialize)
5084 << FixItHint::CreateReplacement(ParenRange, "{}");
5088 // C++ [dcl.fct.spec]p5:
5089 // The virtual specifier shall only be used in declarations of
5090 // nonstatic class member functions that appear within a
5091 // member-specification of a class declaration; see 10.3.
5093 if (isVirtual && !NewFD->isInvalidDecl()) {
5094 if (!isVirtualOkay) {
5095 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5096 diag::err_virtual_non_function);
5097 } else if (!CurContext->isRecord()) {
5098 // 'virtual' was specified outside of the class.
5099 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5100 diag::err_virtual_out_of_class)
5101 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5102 } else if (NewFD->getDescribedFunctionTemplate()) {
5103 // C++ [temp.mem]p3:
5104 // A member function template shall not be virtual.
5105 Diag(D.getDeclSpec().getVirtualSpecLoc(),
5106 diag::err_virtual_member_function_template)
5107 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
5109 // Okay: Add virtual to the method.
5110 NewFD->setVirtualAsWritten(true);
5114 // C++ [dcl.fct.spec]p3:
5115 // The inline specifier shall not appear on a block scope function
5117 if (isInline && !NewFD->isInvalidDecl()) {
5118 if (CurContext->isFunctionOrMethod()) {
5119 // 'inline' is not allowed on block scope function declaration.
5120 Diag(D.getDeclSpec().getInlineSpecLoc(),
5121 diag::err_inline_declaration_block_scope) << Name
5122 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5126 // C++ [dcl.fct.spec]p6:
5127 // The explicit specifier shall be used only in the declaration of a
5128 // constructor or conversion function within its class definition;
5129 // see 12.3.1 and 12.3.2.
5130 if (isExplicit && !NewFD->isInvalidDecl()) {
5131 if (!CurContext->isRecord()) {
5132 // 'explicit' was specified outside of the class.
5133 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5134 diag::err_explicit_out_of_class)
5135 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5136 } else if (!isa<CXXConstructorDecl>(NewFD) &&
5137 !isa<CXXConversionDecl>(NewFD)) {
5138 // 'explicit' was specified on a function that wasn't a constructor
5139 // or conversion function.
5140 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5141 diag::err_explicit_non_ctor_or_conv_function)
5142 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
5147 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors
5148 // are implicitly inline.
5149 NewFD->setImplicitlyInline();
5151 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to
5152 // be either constructors or to return a literal type. Therefore,
5153 // destructors cannot be declared constexpr.
5154 if (isa<CXXDestructorDecl>(NewFD))
5155 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
5158 // If __module_private__ was specified, mark the function accordingly.
5159 if (D.getDeclSpec().isModulePrivateSpecified()) {
5160 if (isFunctionTemplateSpecialization) {
5161 SourceLocation ModulePrivateLoc
5162 = D.getDeclSpec().getModulePrivateSpecLoc();
5163 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
5165 << FixItHint::CreateRemoval(ModulePrivateLoc);
5167 NewFD->setModulePrivate();
5168 if (FunctionTemplate)
5169 FunctionTemplate->setModulePrivate();
5174 // For now, claim that the objects have no previous declaration.
5175 if (FunctionTemplate) {
5176 FunctionTemplate->setObjectOfFriendDecl(false);
5177 FunctionTemplate->setAccess(AS_public);
5179 NewFD->setObjectOfFriendDecl(false);
5180 NewFD->setAccess(AS_public);
5183 // If a function is defined as defaulted or deleted, mark it as such now.
5184 switch (D.getFunctionDefinitionKind()) {
5185 case FDK_Declaration:
5186 case FDK_Definition:
5190 NewFD->setDefaulted();
5194 NewFD->setDeletedAsWritten();
5198 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
5199 D.isFunctionDefinition()) {
5200 // C++ [class.mfct]p2:
5201 // A member function may be defined (8.4) in its class definition, in
5202 // which case it is an inline member function (7.1.2)
5203 NewFD->setImplicitlyInline();
5206 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
5207 !CurContext->isRecord()) {
5208 // C++ [class.static]p1:
5209 // A data or function member of a class may be declared static
5210 // in a class definition, in which case it is a static member of
5213 // Complain about the 'static' specifier if it's on an out-of-line
5214 // member function definition.
5215 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5216 diag::err_static_out_of_line)
5217 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5221 // Filter out previous declarations that don't match the scope.
5222 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(),
5223 isExplicitSpecialization ||
5224 isFunctionTemplateSpecialization);
5226 // Handle GNU asm-label extension (encoded as an attribute).
5227 if (Expr *E = (Expr*) D.getAsmLabel()) {
5228 // The parser guarantees this is a string.
5229 StringLiteral *SE = cast<StringLiteral>(E);
5230 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
5232 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5233 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5234 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
5235 if (I != ExtnameUndeclaredIdentifiers.end()) {
5236 NewFD->addAttr(I->second);
5237 ExtnameUndeclaredIdentifiers.erase(I);
5241 // Copy the parameter declarations from the declarator D to the function
5242 // declaration NewFD, if they are available. First scavenge them into Params.
5243 SmallVector<ParmVarDecl*, 16> Params;
5244 if (D.isFunctionDeclarator()) {
5245 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5247 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
5248 // function that takes no arguments, not a function that takes a
5249 // single void argument.
5250 // We let through "const void" here because Sema::GetTypeForDeclarator
5251 // already checks for that case.
5252 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5253 FTI.ArgInfo[0].Param &&
5254 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
5255 // Empty arg list, don't push any params.
5256 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param);
5258 // In C++, the empty parameter-type-list must be spelled "void"; a
5259 // typedef of void is not permitted.
5260 if (getLangOpts().CPlusPlus &&
5261 Param->getType().getUnqualifiedType() != Context.VoidTy) {
5262 bool IsTypeAlias = false;
5263 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
5264 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
5265 else if (const TemplateSpecializationType *TST =
5266 Param->getType()->getAs<TemplateSpecializationType>())
5267 IsTypeAlias = TST->isTypeAlias();
5268 Diag(Param->getLocation(), diag::err_param_typedef_of_void)
5271 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
5272 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
5273 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
5274 assert(Param->getDeclContext() != NewFD && "Was set before ?");
5275 Param->setDeclContext(NewFD);
5276 Params.push_back(Param);
5278 if (Param->isInvalidDecl())
5279 NewFD->setInvalidDecl();
5283 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
5284 // When we're declaring a function with a typedef, typeof, etc as in the
5285 // following example, we'll need to synthesize (unnamed)
5286 // parameters for use in the declaration.
5289 // typedef void fn(int);
5293 // Synthesize a parameter for each argument type.
5294 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5295 AE = FT->arg_type_end(); AI != AE; ++AI) {
5296 ParmVarDecl *Param =
5297 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
5298 Param->setScopeInfo(0, Params.size());
5299 Params.push_back(Param);
5302 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
5303 "Should not need args for typedef of non-prototype fn");
5306 // Finally, we know we have the right number of parameters, install them.
5307 NewFD->setParams(Params);
5309 // Find all anonymous symbols defined during the declaration of this function
5310 // and add to NewFD. This lets us track decls such 'enum Y' in:
5312 // void f(enum Y {AA} x) {}
5314 // which would otherwise incorrectly end up in the translation unit scope.
5315 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
5316 DeclsInPrototypeScope.clear();
5318 // Process the non-inheritable attributes on this declaration.
5319 ProcessDeclAttributes(S, NewFD, D,
5320 /*NonInheritable=*/true, /*Inheritable=*/false);
5322 // Functions returning a variably modified type violate C99 6.7.5.2p2
5323 // because all functions have linkage.
5324 if (!NewFD->isInvalidDecl() &&
5325 NewFD->getResultType()->isVariablyModifiedType()) {
5326 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
5327 NewFD->setInvalidDecl();
5330 if (!getLangOpts().CPlusPlus) {
5331 // Perform semantic checking on the function declaration.
5332 bool isExplicitSpecialization=false;
5333 if (!NewFD->isInvalidDecl()) {
5334 if (NewFD->isMain())
5335 CheckMain(NewFD, D.getDeclSpec());
5336 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5337 isExplicitSpecialization));
5339 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5340 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5341 "previous declaration set still overloaded");
5343 // If the declarator is a template-id, translate the parser's template
5344 // argument list into our AST format.
5345 bool HasExplicitTemplateArgs = false;
5346 TemplateArgumentListInfo TemplateArgs;
5347 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5348 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5349 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5350 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5351 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5352 TemplateId->getTemplateArgs(),
5353 TemplateId->NumArgs);
5354 translateTemplateArguments(TemplateArgsPtr,
5356 TemplateArgsPtr.release();
5358 HasExplicitTemplateArgs = true;
5360 if (NewFD->isInvalidDecl()) {
5361 HasExplicitTemplateArgs = false;
5362 } else if (FunctionTemplate) {
5363 // Function template with explicit template arguments.
5364 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
5365 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
5367 HasExplicitTemplateArgs = false;
5368 } else if (!isFunctionTemplateSpecialization &&
5369 !D.getDeclSpec().isFriendSpecified()) {
5370 // We have encountered something that the user meant to be a
5371 // specialization (because it has explicitly-specified template
5372 // arguments) but that was not introduced with a "template<>" (or had
5373 // too few of them).
5374 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5375 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5376 << FixItHint::CreateInsertion(
5377 D.getDeclSpec().getLocStart(),
5379 isFunctionTemplateSpecialization = true;
5381 // "friend void foo<>(int);" is an implicit specialization decl.
5382 isFunctionTemplateSpecialization = true;
5384 } else if (isFriend && isFunctionTemplateSpecialization) {
5385 // This combination is only possible in a recovery case; the user
5386 // wrote something like:
5387 // template <> friend void foo(int);
5388 // which we're recovering from as if the user had written:
5389 // friend void foo<>(int);
5390 // Go ahead and fake up a template id.
5391 HasExplicitTemplateArgs = true;
5392 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
5393 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
5396 // If it's a friend (and only if it's a friend), it's possible
5397 // that either the specialized function type or the specialized
5398 // template is dependent, and therefore matching will fail. In
5399 // this case, don't check the specialization yet.
5400 bool InstantiationDependent = false;
5401 if (isFunctionTemplateSpecialization && isFriend &&
5402 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
5403 TemplateSpecializationType::anyDependentTemplateArguments(
5404 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
5405 InstantiationDependent))) {
5406 assert(HasExplicitTemplateArgs &&
5407 "friend function specialization without template args");
5408 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
5410 NewFD->setInvalidDecl();
5411 } else if (isFunctionTemplateSpecialization) {
5412 if (CurContext->isDependentContext() && CurContext->isRecord()
5414 isDependentClassScopeExplicitSpecialization = true;
5415 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
5416 diag::ext_function_specialization_in_class :
5417 diag::err_function_specialization_in_class)
5418 << NewFD->getDeclName();
5419 } else if (CheckFunctionTemplateSpecialization(NewFD,
5420 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5422 NewFD->setInvalidDecl();
5425 // A storage-class-specifier shall not be specified in an explicit
5426 // specialization (14.7.3)
5427 if (SC != SC_None) {
5428 if (SC != NewFD->getStorageClass())
5429 Diag(NewFD->getLocation(),
5430 diag::err_explicit_specialization_inconsistent_storage_class)
5432 << FixItHint::CreateRemoval(
5433 D.getDeclSpec().getStorageClassSpecLoc());
5436 Diag(NewFD->getLocation(),
5437 diag::ext_explicit_specialization_storage_class)
5438 << FixItHint::CreateRemoval(
5439 D.getDeclSpec().getStorageClassSpecLoc());
5442 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
5443 if (CheckMemberSpecialization(NewFD, Previous))
5444 NewFD->setInvalidDecl();
5447 // Perform semantic checking on the function declaration.
5448 if (!isDependentClassScopeExplicitSpecialization) {
5449 if (NewFD->isInvalidDecl()) {
5450 // If this is a class member, mark the class invalid immediately.
5451 // This avoids some consistency errors later.
5452 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
5453 methodDecl->getParent()->setInvalidDecl();
5455 if (NewFD->isMain())
5456 CheckMain(NewFD, D.getDeclSpec());
5457 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
5458 isExplicitSpecialization));
5462 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
5463 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
5464 "previous declaration set still overloaded");
5466 NamedDecl *PrincipalDecl = (FunctionTemplate
5467 ? cast<NamedDecl>(FunctionTemplate)
5470 if (isFriend && D.isRedeclaration()) {
5471 AccessSpecifier Access = AS_public;
5472 if (!NewFD->isInvalidDecl())
5473 Access = NewFD->getPreviousDecl()->getAccess();
5475 NewFD->setAccess(Access);
5476 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
5478 PrincipalDecl->setObjectOfFriendDecl(true);
5481 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
5482 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5483 PrincipalDecl->setNonMemberOperator();
5485 // If we have a function template, check the template parameter
5486 // list. This will check and merge default template arguments.
5487 if (FunctionTemplate) {
5488 FunctionTemplateDecl *PrevTemplate =
5489 FunctionTemplate->getPreviousDecl();
5490 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
5491 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
5492 D.getDeclSpec().isFriendSpecified()
5493 ? (D.isFunctionDefinition()
5494 ? TPC_FriendFunctionTemplateDefinition
5495 : TPC_FriendFunctionTemplate)
5496 : (D.getCXXScopeSpec().isSet() &&
5497 DC && DC->isRecord() &&
5498 DC->isDependentContext())
5499 ? TPC_ClassTemplateMember
5500 : TPC_FunctionTemplate);
5503 if (NewFD->isInvalidDecl()) {
5504 // Ignore all the rest of this.
5505 } else if (!D.isRedeclaration()) {
5506 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
5508 // Fake up an access specifier if it's supposed to be a class member.
5509 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
5510 NewFD->setAccess(AS_public);
5512 // Qualified decls generally require a previous declaration.
5513 if (D.getCXXScopeSpec().isSet()) {
5514 // ...with the major exception of templated-scope or
5515 // dependent-scope friend declarations.
5517 // TODO: we currently also suppress this check in dependent
5518 // contexts because (1) the parameter depth will be off when
5519 // matching friend templates and (2) we might actually be
5520 // selecting a friend based on a dependent factor. But there
5521 // are situations where these conditions don't apply and we
5522 // can actually do this check immediately.
5524 (TemplateParamLists.size() ||
5525 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
5526 CurContext->isDependentContext())) {
5529 // The user tried to provide an out-of-line definition for a
5530 // function that is a member of a class or namespace, but there
5531 // was no such member function declared (C++ [class.mfct]p2,
5532 // C++ [namespace.memdef]p2). For example:
5538 // void X::f() { } // ill-formed
5540 // Complain about this problem, and attempt to suggest close
5541 // matches (e.g., those that differ only in cv-qualifiers and
5542 // whether the parameter types are references).
5544 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5547 AddToScope = ExtraArgs.AddToScope;
5552 // Unqualified local friend declarations are required to resolve
5554 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
5555 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous,
5558 AddToScope = ExtraArgs.AddToScope;
5563 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
5564 !isFriend && !isFunctionTemplateSpecialization &&
5565 !isExplicitSpecialization) {
5566 // An out-of-line member function declaration must also be a
5567 // definition (C++ [dcl.meaning]p1).
5568 // Note that this is not the case for explicit specializations of
5569 // function templates or member functions of class templates, per
5570 // C++ [temp.expl.spec]p2. We also allow these declarations as an
5571 // extension for compatibility with old SWIG code which likes to
5573 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
5574 << D.getCXXScopeSpec().getRange();
5579 // Handle attributes. We need to have merged decls when handling attributes
5580 // (for example to check for conflicts, etc).
5581 // FIXME: This needs to happen before we merge declarations. Then,
5582 // let attribute merging cope with attribute conflicts.
5583 ProcessDeclAttributes(S, NewFD, D,
5584 /*NonInheritable=*/false, /*Inheritable=*/true);
5586 // attributes declared post-definition are currently ignored
5587 // FIXME: This should happen during attribute merging
5588 if (D.isRedeclaration() && Previous.isSingleResult()) {
5589 const FunctionDecl *Def;
5590 FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
5591 if (PrevFD && PrevFD->isDefined(Def) && D.hasAttributes()) {
5592 Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
5593 Diag(Def->getLocation(), diag::note_previous_definition);
5597 AddKnownFunctionAttributes(NewFD);
5599 if (NewFD->hasAttr<OverloadableAttr>() &&
5600 !NewFD->getType()->getAs<FunctionProtoType>()) {
5601 Diag(NewFD->getLocation(),
5602 diag::err_attribute_overloadable_no_prototype)
5605 // Turn this into a variadic function with no parameters.
5606 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
5607 FunctionProtoType::ExtProtoInfo EPI;
5608 EPI.Variadic = true;
5609 EPI.ExtInfo = FT->getExtInfo();
5611 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI);
5615 // If there's a #pragma GCC visibility in scope, and this isn't a class
5616 // member, set the visibility of this function.
5617 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord())
5618 AddPushedVisibilityAttribute(NewFD);
5620 // If there's a #pragma clang arc_cf_code_audited in scope, consider
5621 // marking the function.
5622 AddCFAuditedAttribute(NewFD);
5624 // If this is a locally-scoped extern C function, update the
5625 // map of such names.
5626 if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
5627 && !NewFD->isInvalidDecl())
5628 RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
5630 // Set this FunctionDecl's range up to the right paren.
5631 NewFD->setRangeEnd(D.getSourceRange().getEnd());
5633 if (getLangOpts().CPlusPlus) {
5634 if (FunctionTemplate) {
5635 if (NewFD->isInvalidDecl())
5636 FunctionTemplate->setInvalidDecl();
5637 return FunctionTemplate;
5641 MarkUnusedFileScopedDecl(NewFD);
5643 if (getLangOpts().CUDA)
5644 if (IdentifierInfo *II = NewFD->getIdentifier())
5645 if (!NewFD->isInvalidDecl() &&
5646 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5647 if (II->isStr("cudaConfigureCall")) {
5648 if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
5649 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
5651 Context.setcudaConfigureCallDecl(NewFD);
5655 // Here we have an function template explicit specialization at class scope.
5656 // The actually specialization will be postponed to template instatiation
5657 // time via the ClassScopeFunctionSpecializationDecl node.
5658 if (isDependentClassScopeExplicitSpecialization) {
5659 ClassScopeFunctionSpecializationDecl *NewSpec =
5660 ClassScopeFunctionSpecializationDecl::Create(
5661 Context, CurContext, SourceLocation(),
5662 cast<CXXMethodDecl>(NewFD));
5663 CurContext->addDecl(NewSpec);
5670 /// \brief Perform semantic checking of a new function declaration.
5672 /// Performs semantic analysis of the new function declaration
5673 /// NewFD. This routine performs all semantic checking that does not
5674 /// require the actual declarator involved in the declaration, and is
5675 /// used both for the declaration of functions as they are parsed
5676 /// (called via ActOnDeclarator) and for the declaration of functions
5677 /// that have been instantiated via C++ template instantiation (called
5678 /// via InstantiateDecl).
5680 /// \param IsExplicitSpecialiation whether this new function declaration is
5681 /// an explicit specialization of the previous declaration.
5683 /// This sets NewFD->isInvalidDecl() to true if there was an error.
5685 /// Returns true if the function declaration is a redeclaration.
5686 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
5687 LookupResult &Previous,
5688 bool IsExplicitSpecialization) {
5689 assert(!NewFD->getResultType()->isVariablyModifiedType()
5690 && "Variably modified return types are not handled here");
5692 // Check for a previous declaration of this name.
5693 if (Previous.empty() && NewFD->isExternC()) {
5694 // Since we did not find anything by this name and we're declaring
5695 // an extern "C" function, look for a non-visible extern "C"
5696 // declaration with the same name.
5697 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
5698 = findLocallyScopedExternalDecl(NewFD->getDeclName());
5699 if (Pos != LocallyScopedExternalDecls.end())
5700 Previous.addDecl(Pos->second);
5703 bool Redeclaration = false;
5705 // Merge or overload the declaration with an existing declaration of
5706 // the same name, if appropriate.
5707 if (!Previous.empty()) {
5708 // Determine whether NewFD is an overload of PrevDecl or
5709 // a declaration that requires merging. If it's an overload,
5710 // there's no more work to do here; we'll just add the new
5711 // function to the scope.
5713 NamedDecl *OldDecl = 0;
5714 if (!AllowOverloadingOfFunction(Previous, Context)) {
5715 Redeclaration = true;
5716 OldDecl = Previous.getFoundDecl();
5718 switch (CheckOverload(S, NewFD, Previous, OldDecl,
5719 /*NewIsUsingDecl*/ false)) {
5721 Redeclaration = true;
5724 case Ovl_NonFunction:
5725 Redeclaration = true;
5729 Redeclaration = false;
5733 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
5734 // If a function name is overloadable in C, then every function
5735 // with that name must be marked "overloadable".
5736 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
5737 << Redeclaration << NewFD;
5738 NamedDecl *OverloadedDecl = 0;
5740 OverloadedDecl = OldDecl;
5741 else if (!Previous.empty())
5742 OverloadedDecl = Previous.getRepresentativeDecl();
5744 Diag(OverloadedDecl->getLocation(),
5745 diag::note_attribute_overloadable_prev_overload);
5746 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
5751 if (Redeclaration) {
5752 // NewFD and OldDecl represent declarations that need to be
5754 if (MergeFunctionDecl(NewFD, OldDecl, S)) {
5755 NewFD->setInvalidDecl();
5756 return Redeclaration;
5760 Previous.addDecl(OldDecl);
5762 if (FunctionTemplateDecl *OldTemplateDecl
5763 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
5764 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
5765 FunctionTemplateDecl *NewTemplateDecl
5766 = NewFD->getDescribedFunctionTemplate();
5767 assert(NewTemplateDecl && "Template/non-template mismatch");
5768 if (CXXMethodDecl *Method
5769 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
5770 Method->setAccess(OldTemplateDecl->getAccess());
5771 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
5774 // If this is an explicit specialization of a member that is a function
5775 // template, mark it as a member specialization.
5776 if (IsExplicitSpecialization &&
5777 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
5778 NewTemplateDecl->setMemberSpecialization();
5779 assert(OldTemplateDecl->isMemberSpecialization());
5783 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
5784 NewFD->setAccess(OldDecl->getAccess());
5785 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
5790 // Semantic checking for this function declaration (in isolation).
5791 if (getLangOpts().CPlusPlus) {
5792 // C++-specific checks.
5793 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
5794 CheckConstructor(Constructor);
5795 } else if (CXXDestructorDecl *Destructor =
5796 dyn_cast<CXXDestructorDecl>(NewFD)) {
5797 CXXRecordDecl *Record = Destructor->getParent();
5798 QualType ClassType = Context.getTypeDeclType(Record);
5800 // FIXME: Shouldn't we be able to perform this check even when the class
5801 // type is dependent? Both gcc and edg can handle that.
5802 if (!ClassType->isDependentType()) {
5803 DeclarationName Name
5804 = Context.DeclarationNames.getCXXDestructorName(
5805 Context.getCanonicalType(ClassType));
5806 if (NewFD->getDeclName() != Name) {
5807 Diag(NewFD->getLocation(), diag::err_destructor_name);
5808 NewFD->setInvalidDecl();
5809 return Redeclaration;
5812 } else if (CXXConversionDecl *Conversion
5813 = dyn_cast<CXXConversionDecl>(NewFD)) {
5814 ActOnConversionDeclarator(Conversion);
5817 // Find any virtual functions that this function overrides.
5818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
5819 if (!Method->isFunctionTemplateSpecialization() &&
5820 !Method->getDescribedFunctionTemplate()) {
5821 if (AddOverriddenMethods(Method->getParent(), Method)) {
5822 // If the function was marked as "static", we have a problem.
5823 if (NewFD->getStorageClass() == SC_Static) {
5824 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual)
5825 << NewFD->getDeclName();
5826 for (CXXMethodDecl::method_iterator
5827 Overridden = Method->begin_overridden_methods(),
5828 OverriddenEnd = Method->end_overridden_methods();
5829 Overridden != OverriddenEnd;
5831 Diag((*Overridden)->getLocation(),
5832 diag::note_overridden_virtual_function);
5839 // Extra checking for C++ overloaded operators (C++ [over.oper]).
5840 if (NewFD->isOverloadedOperator() &&
5841 CheckOverloadedOperatorDeclaration(NewFD)) {
5842 NewFD->setInvalidDecl();
5843 return Redeclaration;
5846 // Extra checking for C++0x literal operators (C++0x [over.literal]).
5847 if (NewFD->getLiteralIdentifier() &&
5848 CheckLiteralOperatorDeclaration(NewFD)) {
5849 NewFD->setInvalidDecl();
5850 return Redeclaration;
5853 // In C++, check default arguments now that we have merged decls. Unless
5854 // the lexical context is the class, because in this case this is done
5855 // during delayed parsing anyway.
5856 if (!CurContext->isRecord())
5857 CheckCXXDefaultArguments(NewFD);
5859 // If this function declares a builtin function, check the type of this
5860 // declaration against the expected type for the builtin.
5861 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
5862 ASTContext::GetBuiltinTypeError Error;
5863 QualType T = Context.GetBuiltinType(BuiltinID, Error);
5864 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
5865 // The type of this function differs from the type of the builtin,
5866 // so forget about the builtin entirely.
5867 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
5871 // If this function is declared as being extern "C", then check to see if
5872 // the function returns a UDT (class, struct, or union type) that is not C
5873 // compatible, and if it does, warn the user.
5874 if (NewFD->isExternC()) {
5875 QualType R = NewFD->getResultType();
5876 if (!R.isPODType(Context) &&
5878 Diag( NewFD->getLocation(), diag::warn_return_value_udt )
5882 return Redeclaration;
5885 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
5886 // C++11 [basic.start.main]p3: A program that declares main to be inline,
5887 // static or constexpr is ill-formed.
5888 // C99 6.7.4p4: In a hosted environment, the inline function specifier
5889 // shall not appear in a declaration of main.
5890 // static main is not an error under C99, but we should warn about it.
5891 if (FD->getStorageClass() == SC_Static)
5892 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
5893 ? diag::err_static_main : diag::warn_static_main)
5894 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5895 if (FD->isInlineSpecified())
5896 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
5897 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
5898 if (FD->isConstexpr()) {
5899 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
5900 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
5901 FD->setConstexpr(false);
5904 QualType T = FD->getType();
5905 assert(T->isFunctionType() && "function decl is not of function type");
5906 const FunctionType* FT = T->castAs<FunctionType>();
5908 // All the standards say that main() should should return 'int'.
5909 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
5910 // In C and C++, main magically returns 0 if you fall off the end;
5911 // set the flag which tells us that.
5912 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
5913 FD->setHasImplicitReturnZero(true);
5915 // In C with GNU extensions we allow main() to have non-integer return
5916 // type, but we should warn about the extension, and we disable the
5917 // implicit-return-zero rule.
5918 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
5919 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
5921 // Otherwise, this is just a flat-out error.
5923 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
5924 FD->setInvalidDecl(true);
5927 // Treat protoless main() as nullary.
5928 if (isa<FunctionNoProtoType>(FT)) return;
5930 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
5931 unsigned nparams = FTP->getNumArgs();
5932 assert(FD->getNumParams() == nparams);
5934 bool HasExtraParameters = (nparams > 3);
5936 // Darwin passes an undocumented fourth argument of type char**. If
5937 // other platforms start sprouting these, the logic below will start
5939 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
5940 HasExtraParameters = false;
5942 if (HasExtraParameters) {
5943 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
5944 FD->setInvalidDecl(true);
5948 // FIXME: a lot of the following diagnostics would be improved
5949 // if we had some location information about types.
5952 Context.getPointerType(Context.getPointerType(Context.CharTy));
5953 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
5955 for (unsigned i = 0; i < nparams; ++i) {
5956 QualType AT = FTP->getArgType(i);
5958 bool mismatch = true;
5960 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
5962 else if (Expected[i] == CharPP) {
5963 // As an extension, the following forms are okay:
5965 // char const * const *
5968 QualifierCollector qs;
5969 const PointerType* PT;
5970 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
5971 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
5972 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
5974 mismatch = !qs.empty();
5979 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
5980 // TODO: suggest replacing given type with expected type
5981 FD->setInvalidDecl(true);
5985 if (nparams == 1 && !FD->isInvalidDecl()) {
5986 Diag(FD->getLocation(), diag::warn_main_one_arg);
5989 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
5990 Diag(FD->getLocation(), diag::err_main_template_decl);
5991 FD->setInvalidDecl();
5995 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
5996 // FIXME: Need strict checking. In C89, we need to check for
5997 // any assignment, increment, decrement, function-calls, or
5998 // commas outside of a sizeof. In C99, it's the same list,
5999 // except that the aforementioned are allowed in unevaluated
6000 // expressions. Everything else falls under the
6001 // "may accept other forms of constant expressions" exception.
6002 // (We never end up here for C++, so the constant expression
6003 // rules there don't matter.)
6004 if (Init->isConstantInitializer(Context, false))
6006 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
6007 << Init->getSourceRange();
6012 // Visits an initialization expression to see if OrigDecl is evaluated in
6013 // its own initialization and throws a warning if it does.
6014 class SelfReferenceChecker
6015 : public EvaluatedExprVisitor<SelfReferenceChecker> {
6022 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
6024 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
6025 S(S), OrigDecl(OrigDecl) {
6027 isRecordType = false;
6028 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
6029 isPODType = VD->getType().isPODType(S.Context);
6030 isRecordType = VD->getType()->isRecordType();
6034 void VisitExpr(Expr *E) {
6035 if (isa<ObjCMessageExpr>(*E)) return;
6038 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6039 ValueDecl *VD = ME->getMemberDecl();
6040 if (isa<EnumConstantDecl>(VD) || isa<VarDecl>(VD)) return;
6041 expr = ME->getBase();
6043 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(expr)) {
6044 HandleDeclRefExpr(DRE);
6048 Inherited::VisitExpr(E);
6051 void VisitMemberExpr(MemberExpr *E) {
6052 if (E->getType()->canDecayToPointerType()) return;
6053 ValueDecl *VD = E->getMemberDecl();
6054 if (isa<FieldDecl>(VD) || isa<CXXMethodDecl>(VD))
6055 if (DeclRefExpr *DRE
6056 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) {
6057 HandleDeclRefExpr(DRE);
6060 Inherited::VisitMemberExpr(E);
6063 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
6064 if ((!isRecordType &&E->getCastKind() == CK_LValueToRValue) ||
6065 (isRecordType && E->getCastKind() == CK_NoOp)) {
6066 Expr* SubExpr = E->getSubExpr()->IgnoreParenImpCasts();
6067 if (MemberExpr *ME = dyn_cast<MemberExpr>(SubExpr))
6068 SubExpr = ME->getBase()->IgnoreParenImpCasts();
6069 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
6070 HandleDeclRefExpr(DRE);
6074 Inherited::VisitImplicitCastExpr(E);
6077 void VisitUnaryOperator(UnaryOperator *E) {
6078 // For POD record types, addresses of its own members are well-defined.
6079 if (isRecordType && isPODType) return;
6080 Inherited::VisitUnaryOperator(E);
6083 void HandleDeclRefExpr(DeclRefExpr *DRE) {
6084 Decl* ReferenceDecl = DRE->getDecl();
6085 if (OrigDecl != ReferenceDecl) return;
6086 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName,
6087 Sema::NotForRedeclaration);
6088 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
6089 S.PDiag(diag::warn_uninit_self_reference_in_init)
6090 << Result.getLookupName()
6091 << OrigDecl->getLocation()
6092 << DRE->getSourceRange());
6097 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
6098 void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) {
6099 SelfReferenceChecker(*this, OrigDecl).VisitExpr(E);
6102 /// AddInitializerToDecl - Adds the initializer Init to the
6103 /// declaration dcl. If DirectInit is true, this is C++ direct
6104 /// initialization rather than copy initialization.
6105 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
6106 bool DirectInit, bool TypeMayContainAuto) {
6107 // If there is no declaration, there was an error parsing it. Just ignore
6109 if (RealDecl == 0 || RealDecl->isInvalidDecl())
6112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
6113 // With declarators parsed the way they are, the parser cannot
6114 // distinguish between a normal initializer and a pure-specifier.
6115 // Thus this grotesque test.
6117 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
6118 Context.getCanonicalType(IL->getType()) == Context.IntTy)
6119 CheckPureMethod(Method, Init->getSourceRange());
6121 Diag(Method->getLocation(), diag::err_member_function_initialization)
6122 << Method->getDeclName() << Init->getSourceRange();
6123 Method->setInvalidDecl();
6128 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6130 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
6131 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6132 RealDecl->setInvalidDecl();
6136 // Check for self-references within variable initializers.
6137 // Variables declared within a function/method body are handled
6138 // by a dataflow analysis.
6139 if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal())
6140 CheckSelfReference(RealDecl, Init);
6142 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
6144 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6145 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
6146 Expr *DeduceInit = Init;
6147 // Initializer could be a C++ direct-initializer. Deduction only works if it
6148 // contains exactly one expression.
6149 if (CXXDirectInit) {
6150 if (CXXDirectInit->getNumExprs() == 0) {
6151 // It isn't possible to write this directly, but it is possible to
6152 // end up in this situation with "auto x(some_pack...);"
6153 Diag(CXXDirectInit->getLocStart(),
6154 diag::err_auto_var_init_no_expression)
6155 << VDecl->getDeclName() << VDecl->getType()
6156 << VDecl->getSourceRange();
6157 RealDecl->setInvalidDecl();
6159 } else if (CXXDirectInit->getNumExprs() > 1) {
6160 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
6161 diag::err_auto_var_init_multiple_expressions)
6162 << VDecl->getDeclName() << VDecl->getType()
6163 << VDecl->getSourceRange();
6164 RealDecl->setInvalidDecl();
6167 DeduceInit = CXXDirectInit->getExpr(0);
6170 TypeSourceInfo *DeducedType = 0;
6171 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
6173 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
6175 RealDecl->setInvalidDecl();
6178 VDecl->setTypeSourceInfo(DeducedType);
6179 VDecl->setType(DeducedType->getType());
6180 VDecl->ClearLinkageCache();
6182 // In ARC, infer lifetime.
6183 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
6184 VDecl->setInvalidDecl();
6186 // If this is a redeclaration, check that the type we just deduced matches
6187 // the previously declared type.
6188 if (VarDecl *Old = VDecl->getPreviousDecl())
6189 MergeVarDeclTypes(VDecl, Old);
6192 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
6193 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
6194 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
6195 VDecl->setInvalidDecl();
6199 if (!VDecl->getType()->isDependentType()) {
6200 // A definition must end up with a complete type, which means it must be
6201 // complete with the restriction that an array type might be completed by
6202 // the initializer; note that later code assumes this restriction.
6203 QualType BaseDeclType = VDecl->getType();
6204 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
6205 BaseDeclType = Array->getElementType();
6206 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
6207 diag::err_typecheck_decl_incomplete_type)) {
6208 RealDecl->setInvalidDecl();
6212 // The variable can not have an abstract class type.
6213 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6214 diag::err_abstract_type_in_decl,
6215 AbstractVariableType))
6216 VDecl->setInvalidDecl();
6220 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
6221 Diag(VDecl->getLocation(), diag::err_redefinition)
6222 << VDecl->getDeclName();
6223 Diag(Def->getLocation(), diag::note_previous_definition);
6224 VDecl->setInvalidDecl();
6228 const VarDecl* PrevInit = 0;
6229 if (getLangOpts().CPlusPlus) {
6230 // C++ [class.static.data]p4
6231 // If a static data member is of const integral or const
6232 // enumeration type, its declaration in the class definition can
6233 // specify a constant-initializer which shall be an integral
6234 // constant expression (5.19). In that case, the member can appear
6235 // in integral constant expressions. The member shall still be
6236 // defined in a namespace scope if it is used in the program and the
6237 // namespace scope definition shall not contain an initializer.
6239 // We already performed a redefinition check above, but for static
6240 // data members we also need to check whether there was an in-class
6241 // declaration with an initializer.
6242 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6243 Diag(VDecl->getLocation(), diag::err_redefinition)
6244 << VDecl->getDeclName();
6245 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6249 if (VDecl->hasLocalStorage())
6250 getCurFunction()->setHasBranchProtectedScope();
6252 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
6253 VDecl->setInvalidDecl();
6258 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
6259 // a kernel function cannot be initialized."
6260 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
6261 Diag(VDecl->getLocation(), diag::err_local_cant_init);
6262 VDecl->setInvalidDecl();
6266 // Get the decls type and save a reference for later, since
6267 // CheckInitializerTypes may change it.
6268 QualType DclT = VDecl->getType(), SavT = DclT;
6270 // Top-level message sends default to 'id' when we're in a debugger
6271 // and we are assigning it to a variable of 'id' type.
6272 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType())
6273 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) {
6274 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
6275 if (Result.isInvalid()) {
6276 VDecl->setInvalidDecl();
6279 Init = Result.take();
6282 // Perform the initialization.
6283 if (!VDecl->isInvalidDecl()) {
6284 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6285 InitializationKind Kind
6287 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
6288 Init->getLocStart(),
6290 : InitializationKind::CreateDirectList(
6291 VDecl->getLocation())
6292 : InitializationKind::CreateCopy(VDecl->getLocation(),
6293 Init->getLocStart());
6295 Expr **Args = &Init;
6296 unsigned NumArgs = 1;
6297 if (CXXDirectInit) {
6298 Args = CXXDirectInit->getExprs();
6299 NumArgs = CXXDirectInit->getNumExprs();
6301 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs);
6302 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6303 MultiExprArg(*this, Args,NumArgs),
6305 if (Result.isInvalid()) {
6306 VDecl->setInvalidDecl();
6310 Init = Result.takeAs<Expr>();
6313 // If the type changed, it means we had an incomplete type that was
6314 // completed by the initializer. For example:
6315 // int ary[] = { 1, 3, 5 };
6316 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
6317 if (!VDecl->isInvalidDecl() && (DclT != SavT))
6318 VDecl->setType(DclT);
6320 // Check any implicit conversions within the expression.
6321 CheckImplicitConversions(Init, VDecl->getLocation());
6323 if (!VDecl->isInvalidDecl())
6324 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
6326 Init = MaybeCreateExprWithCleanups(Init);
6327 // Attach the initializer to the decl.
6328 VDecl->setInit(Init);
6330 if (VDecl->isLocalVarDecl()) {
6331 // C99 6.7.8p4: All the expressions in an initializer for an object that has
6332 // static storage duration shall be constant expressions or string literals.
6333 // C++ does not have this restriction.
6334 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() &&
6335 VDecl->getStorageClass() == SC_Static)
6336 CheckForConstantInitializer(Init, DclT);
6337 } else if (VDecl->isStaticDataMember() &&
6338 VDecl->getLexicalDeclContext()->isRecord()) {
6339 // This is an in-class initialization for a static data member, e.g.,
6342 // static const int value = 17;
6345 // C++ [class.mem]p4:
6346 // A member-declarator can contain a constant-initializer only
6347 // if it declares a static member (9.4) of const integral or
6348 // const enumeration type, see 9.4.2.
6350 // C++11 [class.static.data]p3:
6351 // If a non-volatile const static data member is of integral or
6352 // enumeration type, its declaration in the class definition can
6353 // specify a brace-or-equal-initializer in which every initalizer-clause
6354 // that is an assignment-expression is a constant expression. A static
6355 // data member of literal type can be declared in the class definition
6356 // with the constexpr specifier; if so, its declaration shall specify a
6357 // brace-or-equal-initializer in which every initializer-clause that is
6358 // an assignment-expression is a constant expression.
6360 // Do nothing on dependent types.
6361 if (DclT->isDependentType()) {
6363 // Allow any 'static constexpr' members, whether or not they are of literal
6364 // type. We separately check that every constexpr variable is of literal
6366 } else if (VDecl->isConstexpr()) {
6368 // Require constness.
6369 } else if (!DclT.isConstQualified()) {
6370 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
6371 << Init->getSourceRange();
6372 VDecl->setInvalidDecl();
6374 // We allow integer constant expressions in all cases.
6375 } else if (DclT->isIntegralOrEnumerationType()) {
6376 // Check whether the expression is a constant expression.
6378 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified())
6379 // In C++11, a non-constexpr const static data member with an
6380 // in-class initializer cannot be volatile.
6381 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
6382 else if (Init->isValueDependent())
6383 ; // Nothing to check.
6384 else if (Init->isIntegerConstantExpr(Context, &Loc))
6385 ; // Ok, it's an ICE!
6386 else if (Init->isEvaluatable(Context)) {
6387 // If we can constant fold the initializer through heroics, accept it,
6388 // but report this as a use of an extension for -pedantic.
6389 Diag(Loc, diag::ext_in_class_initializer_non_constant)
6390 << Init->getSourceRange();
6392 // Otherwise, this is some crazy unknown case. Report the issue at the
6393 // location provided by the isIntegerConstantExpr failed check.
6394 Diag(Loc, diag::err_in_class_initializer_non_constant)
6395 << Init->getSourceRange();
6396 VDecl->setInvalidDecl();
6399 // We allow foldable floating-point constants as an extension.
6400 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
6401 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
6402 << DclT << Init->getSourceRange();
6403 if (getLangOpts().CPlusPlus0x)
6404 Diag(VDecl->getLocation(),
6405 diag::note_in_class_initializer_float_type_constexpr)
6406 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6408 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
6409 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
6410 << Init->getSourceRange();
6411 VDecl->setInvalidDecl();
6414 // Suggest adding 'constexpr' in C++11 for literal types.
6415 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) {
6416 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
6417 << DclT << Init->getSourceRange()
6418 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
6419 VDecl->setConstexpr(true);
6422 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
6423 << DclT << Init->getSourceRange();
6424 VDecl->setInvalidDecl();
6426 } else if (VDecl->isFileVarDecl()) {
6427 if (VDecl->getStorageClassAsWritten() == SC_Extern &&
6428 (!getLangOpts().CPlusPlus ||
6429 !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
6430 Diag(VDecl->getLocation(), diag::warn_extern_init);
6432 // C99 6.7.8p4. All file scoped initializers need to be constant.
6433 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
6434 CheckForConstantInitializer(Init, DclT);
6437 // We will represent direct-initialization similarly to copy-initialization:
6438 // int x(1); -as-> int x = 1;
6439 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6441 // Clients that want to distinguish between the two forms, can check for
6442 // direct initializer using VarDecl::getInitStyle().
6443 // A major benefit is that clients that don't particularly care about which
6444 // exactly form was it (like the CodeGen) can handle both cases without
6445 // special case code.
6448 // The form of initialization (using parentheses or '=') is generally
6449 // insignificant, but does matter when the entity being initialized has a
6451 if (CXXDirectInit) {
6452 assert(DirectInit && "Call-style initializer must be direct init.");
6453 VDecl->setInitStyle(VarDecl::CallInit);
6454 } else if (DirectInit) {
6455 // This must be list-initialization. No other way is direct-initialization.
6456 VDecl->setInitStyle(VarDecl::ListInit);
6459 CheckCompleteVariableDeclaration(VDecl);
6462 /// ActOnInitializerError - Given that there was an error parsing an
6463 /// initializer for the given declaration, try to return to some form
6465 void Sema::ActOnInitializerError(Decl *D) {
6466 // Our main concern here is re-establishing invariants like "a
6467 // variable's type is either dependent or complete".
6468 if (!D || D->isInvalidDecl()) return;
6470 VarDecl *VD = dyn_cast<VarDecl>(D);
6473 // Auto types are meaningless if we can't make sense of the initializer.
6474 if (ParsingInitForAutoVars.count(D)) {
6475 D->setInvalidDecl();
6479 QualType Ty = VD->getType();
6480 if (Ty->isDependentType()) return;
6482 // Require a complete type.
6483 if (RequireCompleteType(VD->getLocation(),
6484 Context.getBaseElementType(Ty),
6485 diag::err_typecheck_decl_incomplete_type)) {
6486 VD->setInvalidDecl();
6490 // Require an abstract type.
6491 if (RequireNonAbstractType(VD->getLocation(), Ty,
6492 diag::err_abstract_type_in_decl,
6493 AbstractVariableType)) {
6494 VD->setInvalidDecl();
6498 // Don't bother complaining about constructors or destructors,
6502 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
6503 bool TypeMayContainAuto) {
6504 // If there is no declaration, there was an error parsing it. Just ignore it.
6508 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
6509 QualType Type = Var->getType();
6511 // C++11 [dcl.spec.auto]p3
6512 if (TypeMayContainAuto && Type->getContainedAutoType()) {
6513 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
6514 << Var->getDeclName() << Type;
6515 Var->setInvalidDecl();
6519 // C++11 [class.static.data]p3: A static data member can be declared with
6520 // the constexpr specifier; if so, its declaration shall specify
6521 // a brace-or-equal-initializer.
6522 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
6523 // the definition of a variable [...] or the declaration of a static data
6525 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
6526 if (Var->isStaticDataMember())
6527 Diag(Var->getLocation(),
6528 diag::err_constexpr_static_mem_var_requires_init)
6529 << Var->getDeclName();
6531 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
6532 Var->setInvalidDecl();
6536 switch (Var->isThisDeclarationADefinition()) {
6537 case VarDecl::Definition:
6538 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
6541 // We have an out-of-line definition of a static data member
6542 // that has an in-class initializer, so we type-check this like
6547 case VarDecl::DeclarationOnly:
6548 // It's only a declaration.
6550 // Block scope. C99 6.7p7: If an identifier for an object is
6551 // declared with no linkage (C99 6.2.2p6), the type for the
6552 // object shall be complete.
6553 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
6554 !Var->getLinkage() && !Var->isInvalidDecl() &&
6555 RequireCompleteType(Var->getLocation(), Type,
6556 diag::err_typecheck_decl_incomplete_type))
6557 Var->setInvalidDecl();
6559 // Make sure that the type is not abstract.
6560 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
6561 RequireNonAbstractType(Var->getLocation(), Type,
6562 diag::err_abstract_type_in_decl,
6563 AbstractVariableType))
6564 Var->setInvalidDecl();
6567 case VarDecl::TentativeDefinition:
6568 // File scope. C99 6.9.2p2: A declaration of an identifier for an
6569 // object that has file scope without an initializer, and without a
6570 // storage-class specifier or with the storage-class specifier "static",
6571 // constitutes a tentative definition. Note: A tentative definition with
6572 // external linkage is valid (C99 6.2.2p5).
6573 if (!Var->isInvalidDecl()) {
6574 if (const IncompleteArrayType *ArrayT
6575 = Context.getAsIncompleteArrayType(Type)) {
6576 if (RequireCompleteType(Var->getLocation(),
6577 ArrayT->getElementType(),
6578 diag::err_illegal_decl_array_incomplete_type))
6579 Var->setInvalidDecl();
6580 } else if (Var->getStorageClass() == SC_Static) {
6581 // C99 6.9.2p3: If the declaration of an identifier for an object is
6582 // a tentative definition and has internal linkage (C99 6.2.2p3), the
6583 // declared type shall not be an incomplete type.
6584 // NOTE: code such as the following
6586 // struct s { int a; };
6587 // is accepted by gcc. Hence here we issue a warning instead of
6588 // an error and we do not invalidate the static declaration.
6589 // NOTE: to avoid multiple warnings, only check the first declaration.
6590 if (Var->getPreviousDecl() == 0)
6591 RequireCompleteType(Var->getLocation(), Type,
6592 diag::ext_typecheck_decl_incomplete_type);
6596 // Record the tentative definition; we're done.
6597 if (!Var->isInvalidDecl())
6598 TentativeDefinitions.push_back(Var);
6602 // Provide a specific diagnostic for uninitialized variable
6603 // definitions with incomplete array type.
6604 if (Type->isIncompleteArrayType()) {
6605 Diag(Var->getLocation(),
6606 diag::err_typecheck_incomplete_array_needs_initializer);
6607 Var->setInvalidDecl();
6611 // Provide a specific diagnostic for uninitialized variable
6612 // definitions with reference type.
6613 if (Type->isReferenceType()) {
6614 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
6615 << Var->getDeclName()
6616 << SourceRange(Var->getLocation(), Var->getLocation());
6617 Var->setInvalidDecl();
6621 // Do not attempt to type-check the default initializer for a
6622 // variable with dependent type.
6623 if (Type->isDependentType())
6626 if (Var->isInvalidDecl())
6629 if (RequireCompleteType(Var->getLocation(),
6630 Context.getBaseElementType(Type),
6631 diag::err_typecheck_decl_incomplete_type)) {
6632 Var->setInvalidDecl();
6636 // The variable can not have an abstract class type.
6637 if (RequireNonAbstractType(Var->getLocation(), Type,
6638 diag::err_abstract_type_in_decl,
6639 AbstractVariableType)) {
6640 Var->setInvalidDecl();
6644 // Check for jumps past the implicit initializer. C++0x
6645 // clarifies that this applies to a "variable with automatic
6646 // storage duration", not a "local variable".
6647 // C++11 [stmt.dcl]p3
6648 // A program that jumps from a point where a variable with automatic
6649 // storage duration is not in scope to a point where it is in scope is
6650 // ill-formed unless the variable has scalar type, class type with a
6651 // trivial default constructor and a trivial destructor, a cv-qualified
6652 // version of one of these types, or an array of one of the preceding
6653 // types and is declared without an initializer.
6654 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
6655 if (const RecordType *Record
6656 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
6657 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
6658 // Mark the function for further checking even if the looser rules of
6659 // C++11 do not require such checks, so that we can diagnose
6660 // incompatibilities with C++98.
6661 if (!CXXRecord->isPOD())
6662 getCurFunction()->setHasBranchProtectedScope();
6666 // C++03 [dcl.init]p9:
6667 // If no initializer is specified for an object, and the
6668 // object is of (possibly cv-qualified) non-POD class type (or
6669 // array thereof), the object shall be default-initialized; if
6670 // the object is of const-qualified type, the underlying class
6671 // type shall have a user-declared default
6672 // constructor. Otherwise, if no initializer is specified for
6673 // a non- static object, the object and its subobjects, if
6674 // any, have an indeterminate initial value); if the object
6675 // or any of its subobjects are of const-qualified type, the
6676 // program is ill-formed.
6677 // C++0x [dcl.init]p11:
6678 // If no initializer is specified for an object, the object is
6679 // default-initialized; [...].
6680 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
6681 InitializationKind Kind
6682 = InitializationKind::CreateDefault(Var->getLocation());
6684 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
6685 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
6686 MultiExprArg(*this, 0, 0));
6687 if (Init.isInvalid())
6688 Var->setInvalidDecl();
6689 else if (Init.get()) {
6690 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
6691 // This is important for template substitution.
6692 Var->setInitStyle(VarDecl::CallInit);
6695 CheckCompleteVariableDeclaration(Var);
6699 void Sema::ActOnCXXForRangeDecl(Decl *D) {
6700 VarDecl *VD = dyn_cast<VarDecl>(D);
6702 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
6703 D->setInvalidDecl();
6707 VD->setCXXForRangeDecl(true);
6709 // for-range-declaration cannot be given a storage class specifier.
6711 switch (VD->getStorageClassAsWritten()) {
6720 case SC_PrivateExtern:
6729 case SC_OpenCLWorkGroupLocal:
6730 llvm_unreachable("Unexpected storage class");
6732 if (VD->isConstexpr())
6735 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
6736 << VD->getDeclName() << Error;
6737 D->setInvalidDecl();
6741 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
6742 if (var->isInvalidDecl()) return;
6744 // In ARC, don't allow jumps past the implicit initialization of a
6745 // local retaining variable.
6746 if (getLangOpts().ObjCAutoRefCount &&
6747 var->hasLocalStorage()) {
6748 switch (var->getType().getObjCLifetime()) {
6749 case Qualifiers::OCL_None:
6750 case Qualifiers::OCL_ExplicitNone:
6751 case Qualifiers::OCL_Autoreleasing:
6754 case Qualifiers::OCL_Weak:
6755 case Qualifiers::OCL_Strong:
6756 getCurFunction()->setHasBranchProtectedScope();
6761 // All the following checks are C++ only.
6762 if (!getLangOpts().CPlusPlus) return;
6764 QualType baseType = Context.getBaseElementType(var->getType());
6765 if (baseType->isDependentType()) return;
6767 // __block variables might require us to capture a copy-initializer.
6768 if (var->hasAttr<BlocksAttr>()) {
6769 // It's currently invalid to ever have a __block variable with an
6770 // array type; should we diagnose that here?
6772 // Regardless, we don't want to ignore array nesting when
6773 // constructing this copy.
6774 QualType type = var->getType();
6776 if (type->isStructureOrClassType()) {
6777 SourceLocation poi = var->getLocation();
6778 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
6780 PerformCopyInitialization(
6781 InitializedEntity::InitializeBlock(poi, type, false),
6782 poi, Owned(varRef));
6783 if (!result.isInvalid()) {
6784 result = MaybeCreateExprWithCleanups(result);
6785 Expr *init = result.takeAs<Expr>();
6786 Context.setBlockVarCopyInits(var, init);
6791 Expr *Init = var->getInit();
6792 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
6794 if (!var->getDeclContext()->isDependentContext() && Init) {
6795 if (IsGlobal && !var->isConstexpr() &&
6796 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
6798 != DiagnosticsEngine::Ignored &&
6799 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
6800 Diag(var->getLocation(), diag::warn_global_constructor)
6801 << Init->getSourceRange();
6803 if (var->isConstexpr()) {
6804 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
6805 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
6806 SourceLocation DiagLoc = var->getLocation();
6807 // If the note doesn't add any useful information other than a source
6808 // location, fold it into the primary diagnostic.
6809 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6810 diag::note_invalid_subexpr_in_const_expr) {
6811 DiagLoc = Notes[0].first;
6814 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
6815 << var << Init->getSourceRange();
6816 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6817 Diag(Notes[I].first, Notes[I].second);
6819 } else if (var->isUsableInConstantExpressions(Context)) {
6820 // Check whether the initializer of a const variable of integral or
6821 // enumeration type is an ICE now, since we can't tell whether it was
6822 // initialized by a constant expression if we check later.
6823 var->checkInitIsICE();
6827 // Require the destructor.
6828 if (const RecordType *recordType = baseType->getAs<RecordType>())
6829 FinalizeVarWithDestructor(var, recordType);
6832 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
6833 /// any semantic actions necessary after any initializer has been attached.
6835 Sema::FinalizeDeclaration(Decl *ThisDecl) {
6836 // Note that we are no longer parsing the initializer for this declaration.
6837 ParsingInitForAutoVars.erase(ThisDecl);
6840 Sema::DeclGroupPtrTy
6841 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
6842 Decl **Group, unsigned NumDecls) {
6843 SmallVector<Decl*, 8> Decls;
6845 if (DS.isTypeSpecOwned())
6846 Decls.push_back(DS.getRepAsDecl());
6848 for (unsigned i = 0; i != NumDecls; ++i)
6849 if (Decl *D = Group[i])
6852 return BuildDeclaratorGroup(Decls.data(), Decls.size(),
6853 DS.getTypeSpecType() == DeclSpec::TST_auto);
6856 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
6857 /// group, performing any necessary semantic checking.
6858 Sema::DeclGroupPtrTy
6859 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls,
6860 bool TypeMayContainAuto) {
6861 // C++0x [dcl.spec.auto]p7:
6862 // If the type deduced for the template parameter U is not the same in each
6863 // deduction, the program is ill-formed.
6864 // FIXME: When initializer-list support is added, a distinction is needed
6865 // between the deduced type U and the deduced type which 'auto' stands for.
6866 // auto a = 0, b = { 1, 2, 3 };
6867 // is legal because the deduced type U is 'int' in both cases.
6868 if (TypeMayContainAuto && NumDecls > 1) {
6870 CanQualType DeducedCanon;
6871 VarDecl *DeducedDecl = 0;
6872 for (unsigned i = 0; i != NumDecls; ++i) {
6873 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
6874 AutoType *AT = D->getType()->getContainedAutoType();
6875 // Don't reissue diagnostics when instantiating a template.
6876 if (AT && D->isInvalidDecl())
6878 if (AT && AT->isDeduced()) {
6879 QualType U = AT->getDeducedType();
6880 CanQualType UCanon = Context.getCanonicalType(U);
6881 if (Deduced.isNull()) {
6883 DeducedCanon = UCanon;
6885 } else if (DeducedCanon != UCanon) {
6886 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
6887 diag::err_auto_different_deductions)
6888 << Deduced << DeducedDecl->getDeclName()
6889 << U << D->getDeclName()
6890 << DeducedDecl->getInit()->getSourceRange()
6891 << D->getInit()->getSourceRange();
6892 D->setInvalidDecl();
6900 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls));
6904 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
6905 /// to introduce parameters into function prototype scope.
6906 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
6907 const DeclSpec &DS = D.getDeclSpec();
6909 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
6910 // C++03 [dcl.stc]p2 also permits 'auto'.
6911 VarDecl::StorageClass StorageClass = SC_None;
6912 VarDecl::StorageClass StorageClassAsWritten = SC_None;
6913 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
6914 StorageClass = SC_Register;
6915 StorageClassAsWritten = SC_Register;
6916 } else if (getLangOpts().CPlusPlus &&
6917 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
6918 StorageClass = SC_Auto;
6919 StorageClassAsWritten = SC_Auto;
6920 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
6921 Diag(DS.getStorageClassSpecLoc(),
6922 diag::err_invalid_storage_class_in_func_decl);
6923 D.getMutableDeclSpec().ClearStorageClassSpecs();
6926 if (D.getDeclSpec().isThreadSpecified())
6927 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
6928 if (D.getDeclSpec().isConstexprSpecified())
6929 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6932 DiagnoseFunctionSpecifiers(D);
6934 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6935 QualType parmDeclType = TInfo->getType();
6937 if (getLangOpts().CPlusPlus) {
6938 // Check that there are no default arguments inside the type of this
6940 CheckExtraCXXDefaultArguments(D);
6942 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
6943 if (D.getCXXScopeSpec().isSet()) {
6944 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
6945 << D.getCXXScopeSpec().getRange();
6946 D.getCXXScopeSpec().clear();
6950 // Ensure we have a valid name
6951 IdentifierInfo *II = 0;
6953 II = D.getIdentifier();
6955 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
6956 << GetNameForDeclarator(D).getName().getAsString();
6957 D.setInvalidType(true);
6961 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
6963 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
6966 if (R.isSingleResult()) {
6967 NamedDecl *PrevDecl = R.getFoundDecl();
6968 if (PrevDecl->isTemplateParameter()) {
6969 // Maybe we will complain about the shadowed template parameter.
6970 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
6971 // Just pretend that we didn't see the previous declaration.
6973 } else if (S->isDeclScope(PrevDecl)) {
6974 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
6975 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
6977 // Recover by removing the name
6979 D.SetIdentifier(0, D.getIdentifierLoc());
6980 D.setInvalidType(true);
6985 // Temporarily put parameter variables in the translation unit, not
6986 // the enclosing context. This prevents them from accidentally
6987 // looking like class members in C++.
6988 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
6990 D.getIdentifierLoc(), II,
6991 parmDeclType, TInfo,
6992 StorageClass, StorageClassAsWritten);
6994 if (D.isInvalidType())
6995 New->setInvalidDecl();
6997 assert(S->isFunctionPrototypeScope());
6998 assert(S->getFunctionPrototypeDepth() >= 1);
6999 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
7000 S->getNextFunctionPrototypeIndex());
7002 // Add the parameter declaration into this scope.
7005 IdResolver.AddDecl(New);
7007 ProcessDeclAttributes(S, New, D);
7009 if (D.getDeclSpec().isModulePrivateSpecified())
7010 Diag(New->getLocation(), diag::err_module_private_local)
7011 << 1 << New->getDeclName()
7012 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7013 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7015 if (New->hasAttr<BlocksAttr>()) {
7016 Diag(New->getLocation(), diag::err_block_on_nonlocal);
7021 /// \brief Synthesizes a variable for a parameter arising from a
7023 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
7026 /* FIXME: setting StartLoc == Loc.
7027 Would it be worth to modify callers so as to provide proper source
7028 location for the unnamed parameters, embedding the parameter's type? */
7029 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
7030 T, Context.getTrivialTypeSourceInfo(T, Loc),
7031 SC_None, SC_None, 0);
7032 Param->setImplicit();
7036 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
7037 ParmVarDecl * const *ParamEnd) {
7038 // Don't diagnose unused-parameter errors in template instantiations; we
7039 // will already have done so in the template itself.
7040 if (!ActiveTemplateInstantiations.empty())
7043 for (; Param != ParamEnd; ++Param) {
7044 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
7045 !(*Param)->hasAttr<UnusedAttr>()) {
7046 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
7047 << (*Param)->getDeclName();
7052 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
7053 ParmVarDecl * const *ParamEnd,
7056 if (LangOpts.NumLargeByValueCopy == 0) // No check.
7059 // Warn if the return value is pass-by-value and larger than the specified
7061 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
7062 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
7063 if (Size > LangOpts.NumLargeByValueCopy)
7064 Diag(D->getLocation(), diag::warn_return_value_size)
7065 << D->getDeclName() << Size;
7068 // Warn if any parameter is pass-by-value and larger than the specified
7070 for (; Param != ParamEnd; ++Param) {
7071 QualType T = (*Param)->getType();
7072 if (T->isDependentType() || !T.isPODType(Context))
7074 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
7075 if (Size > LangOpts.NumLargeByValueCopy)
7076 Diag((*Param)->getLocation(), diag::warn_parameter_size)
7077 << (*Param)->getDeclName() << Size;
7081 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
7082 SourceLocation NameLoc, IdentifierInfo *Name,
7083 QualType T, TypeSourceInfo *TSInfo,
7084 VarDecl::StorageClass StorageClass,
7085 VarDecl::StorageClass StorageClassAsWritten) {
7086 // In ARC, infer a lifetime qualifier for appropriate parameter types.
7087 if (getLangOpts().ObjCAutoRefCount &&
7088 T.getObjCLifetime() == Qualifiers::OCL_None &&
7089 T->isObjCLifetimeType()) {
7091 Qualifiers::ObjCLifetime lifetime;
7093 // Special cases for arrays:
7094 // - if it's const, use __unsafe_unretained
7095 // - otherwise, it's an error
7096 if (T->isArrayType()) {
7097 if (!T.isConstQualified()) {
7098 DelayedDiagnostics.add(
7099 sema::DelayedDiagnostic::makeForbiddenType(
7100 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
7102 lifetime = Qualifiers::OCL_ExplicitNone;
7104 lifetime = T->getObjCARCImplicitLifetime();
7106 T = Context.getLifetimeQualifiedType(T, lifetime);
7109 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
7110 Context.getAdjustedParameterType(T),
7112 StorageClass, StorageClassAsWritten,
7115 // Parameters can not be abstract class types.
7116 // For record types, this is done by the AbstractClassUsageDiagnoser once
7117 // the class has been completely parsed.
7118 if (!CurContext->isRecord() &&
7119 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
7121 New->setInvalidDecl();
7123 // Parameter declarators cannot be interface types. All ObjC objects are
7124 // passed by reference.
7125 if (T->isObjCObjectType()) {
7127 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
7128 << FixItHint::CreateInsertion(NameLoc, "*");
7129 T = Context.getObjCObjectPointerType(T);
7133 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
7134 // duration shall not be qualified by an address-space qualifier."
7135 // Since all parameters have automatic store duration, they can not have
7136 // an address space.
7137 if (T.getAddressSpace() != 0) {
7138 Diag(NameLoc, diag::err_arg_with_address_space);
7139 New->setInvalidDecl();
7145 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
7146 SourceLocation LocAfterDecls) {
7147 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7149 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
7150 // for a K&R function.
7151 if (!FTI.hasPrototype) {
7152 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
7154 if (FTI.ArgInfo[i].Param == 0) {
7155 SmallString<256> Code;
7156 llvm::raw_svector_ostream(Code) << " int "
7157 << FTI.ArgInfo[i].Ident->getName()
7159 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
7160 << FTI.ArgInfo[i].Ident
7161 << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
7163 // Implicitly declare the argument as type 'int' for lack of a better
7165 AttributeFactory attrs;
7167 const char* PrevSpec; // unused
7168 unsigned DiagID; // unused
7169 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
7171 Declarator ParamD(DS, Declarator::KNRTypeListContext);
7172 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
7173 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
7179 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
7181 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
7182 assert(D.isFunctionDeclarator() && "Not a function declarator!");
7183 Scope *ParentScope = FnBodyScope->getParent();
7185 D.setFunctionDefinitionKind(FDK_Definition);
7186 Decl *DP = HandleDeclarator(ParentScope, D,
7187 MultiTemplateParamsArg(*this));
7188 return ActOnStartOfFunctionDef(FnBodyScope, DP);
7191 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
7192 // Don't warn about invalid declarations.
7193 if (FD->isInvalidDecl())
7196 // Or declarations that aren't global.
7197 if (!FD->isGlobal())
7200 // Don't warn about C++ member functions.
7201 if (isa<CXXMethodDecl>(FD))
7204 // Don't warn about 'main'.
7208 // Don't warn about inline functions.
7209 if (FD->isInlined())
7212 // Don't warn about function templates.
7213 if (FD->getDescribedFunctionTemplate())
7216 // Don't warn about function template specializations.
7217 if (FD->isFunctionTemplateSpecialization())
7220 bool MissingPrototype = true;
7221 for (const FunctionDecl *Prev = FD->getPreviousDecl();
7222 Prev; Prev = Prev->getPreviousDecl()) {
7223 // Ignore any declarations that occur in function or method
7224 // scope, because they aren't visible from the header.
7225 if (Prev->getDeclContext()->isFunctionOrMethod())
7228 MissingPrototype = !Prev->getType()->isFunctionProtoType();
7232 return MissingPrototype;
7235 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) {
7236 // Don't complain if we're in GNU89 mode and the previous definition
7237 // was an extern inline function.
7238 const FunctionDecl *Definition;
7239 if (FD->isDefined(Definition) &&
7240 !canRedefineFunction(Definition, getLangOpts())) {
7241 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
7242 Definition->getStorageClass() == SC_Extern)
7243 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
7244 << FD->getDeclName() << getLangOpts().CPlusPlus;
7246 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
7247 Diag(Definition->getLocation(), diag::note_previous_definition);
7251 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
7252 // Clear the last template instantiation error context.
7253 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
7257 FunctionDecl *FD = 0;
7259 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
7260 FD = FunTmpl->getTemplatedDecl();
7262 FD = cast<FunctionDecl>(D);
7264 // Enter a new function scope
7265 PushFunctionScope();
7267 // See if this is a redefinition.
7268 if (!FD->isLateTemplateParsed())
7269 CheckForFunctionRedefinition(FD);
7271 // Builtin functions cannot be defined.
7272 if (unsigned BuiltinID = FD->getBuiltinID()) {
7273 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
7274 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
7275 FD->setInvalidDecl();
7279 // The return type of a function definition must be complete
7280 // (C99 6.9.1p3, C++ [dcl.fct]p6).
7281 QualType ResultType = FD->getResultType();
7282 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
7283 !FD->isInvalidDecl() &&
7284 RequireCompleteType(FD->getLocation(), ResultType,
7285 diag::err_func_def_incomplete_result))
7286 FD->setInvalidDecl();
7288 // GNU warning -Wmissing-prototypes:
7289 // Warn if a global function is defined without a previous
7290 // prototype declaration. This warning is issued even if the
7291 // definition itself provides a prototype. The aim is to detect
7292 // global functions that fail to be declared in header files.
7293 if (ShouldWarnAboutMissingPrototype(FD))
7294 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
7297 PushDeclContext(FnBodyScope, FD);
7299 // Check the validity of our function parameters
7300 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
7301 /*CheckParameterNames=*/true);
7303 // Introduce our parameters into the function scope
7304 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
7305 ParmVarDecl *Param = FD->getParamDecl(p);
7306 Param->setOwningFunction(FD);
7308 // If this has an identifier, add it to the scope stack.
7309 if (Param->getIdentifier() && FnBodyScope) {
7310 CheckShadow(FnBodyScope, Param);
7312 PushOnScopeChains(Param, FnBodyScope);
7316 // If we had any tags defined in the function prototype,
7317 // introduce them into the function scope.
7319 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(),
7320 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) {
7323 // Some of these decls (like enums) may have been pinned to the translation unit
7324 // for lack of a real context earlier. If so, remove from the translation unit
7325 // and reattach to the current context.
7326 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
7327 // Is the decl actually in the context?
7328 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
7329 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
7331 Context.getTranslationUnitDecl()->removeDecl(D);
7335 // Either way, reassign the lexical decl context to our FunctionDecl.
7336 D->setLexicalDeclContext(CurContext);
7339 // If the decl has a non-null name, make accessible in the current scope.
7340 if (!D->getName().empty())
7341 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
7343 // Similarly, dive into enums and fish their constants out, making them
7344 // accessible in this scope.
7345 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
7346 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
7347 EE = ED->enumerator_end(); EI != EE; ++EI)
7348 PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
7353 // Checking attributes of current function definition
7354 // dllimport attribute.
7355 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
7356 if (DA && (!FD->getAttr<DLLExportAttr>())) {
7357 // dllimport attribute cannot be directly applied to definition.
7358 // Microsoft accepts dllimport for functions defined within class scope.
7359 if (!DA->isInherited() &&
7360 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
7361 Diag(FD->getLocation(),
7362 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
7364 FD->setInvalidDecl();
7368 // Visual C++ appears to not think this is an issue, so only issue
7369 // a warning when Microsoft extensions are disabled.
7370 if (!LangOpts.MicrosoftExt) {
7371 // If a symbol previously declared dllimport is later defined, the
7372 // attribute is ignored in subsequent references, and a warning is
7374 Diag(FD->getLocation(),
7375 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
7376 << FD->getName() << "dllimport";
7382 /// \brief Given the set of return statements within a function body,
7383 /// compute the variables that are subject to the named return value
7386 /// Each of the variables that is subject to the named return value
7387 /// optimization will be marked as NRVO variables in the AST, and any
7388 /// return statement that has a marked NRVO variable as its NRVO candidate can
7389 /// use the named return value optimization.
7391 /// This function applies a very simplistic algorithm for NRVO: if every return
7392 /// statement in the function has the same NRVO candidate, that candidate is
7393 /// the NRVO variable.
7395 /// FIXME: Employ a smarter algorithm that accounts for multiple return
7396 /// statements and the lifetimes of the NRVO candidates. We should be able to
7397 /// find a maximal set of NRVO variables.
7398 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
7399 ReturnStmt **Returns = Scope->Returns.data();
7401 const VarDecl *NRVOCandidate = 0;
7402 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
7403 if (!Returns[I]->getNRVOCandidate())
7407 NRVOCandidate = Returns[I]->getNRVOCandidate();
7408 else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
7413 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
7416 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
7417 return ActOnFinishFunctionBody(D, move(BodyArg), false);
7420 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
7421 bool IsInstantiation) {
7422 FunctionDecl *FD = 0;
7423 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
7425 FD = FunTmpl->getTemplatedDecl();
7427 FD = dyn_cast_or_null<FunctionDecl>(dcl);
7429 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
7430 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
7435 // If the function implicitly returns zero (like 'main') or is naked,
7436 // don't complain about missing return statements.
7437 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
7438 WP.disableCheckFallThrough();
7440 // MSVC permits the use of pure specifier (=0) on function definition,
7441 // defined at class scope, warn about this non standard construct.
7442 if (getLangOpts().MicrosoftExt && FD->isPure())
7443 Diag(FD->getLocation(), diag::warn_pure_function_definition);
7445 if (!FD->isInvalidDecl()) {
7446 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
7447 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
7448 FD->getResultType(), FD);
7450 // If this is a constructor, we need a vtable.
7451 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
7452 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
7454 computeNRVO(Body, getCurFunction());
7457 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
7458 "Function parsing confused");
7459 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
7460 assert(MD == getCurMethodDecl() && "Method parsing confused");
7463 MD->setEndLoc(Body->getLocEnd());
7464 if (!MD->isInvalidDecl()) {
7465 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
7466 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
7467 MD->getResultType(), MD);
7470 computeNRVO(Body, getCurFunction());
7472 if (ObjCShouldCallSuperDealloc) {
7473 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc);
7474 ObjCShouldCallSuperDealloc = false;
7476 if (ObjCShouldCallSuperFinalize) {
7477 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize);
7478 ObjCShouldCallSuperFinalize = false;
7484 assert(!ObjCShouldCallSuperDealloc && "This should only be set for "
7485 "ObjC methods, which should have been handled in the block above.");
7486 assert(!ObjCShouldCallSuperFinalize && "This should only be set for "
7487 "ObjC methods, which should have been handled in the block above.");
7489 // Verify and clean out per-function state.
7491 // C++ constructors that have function-try-blocks can't have return
7492 // statements in the handlers of that block. (C++ [except.handle]p14)
7494 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
7495 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
7497 // Verify that gotos and switch cases don't jump into scopes illegally.
7498 if (getCurFunction()->NeedsScopeChecking() &&
7499 !dcl->isInvalidDecl() &&
7500 !hasAnyUnrecoverableErrorsInThisFunction())
7501 DiagnoseInvalidJumps(Body);
7503 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
7504 if (!Destructor->getParent()->isDependentType())
7505 CheckDestructor(Destructor);
7507 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7508 Destructor->getParent());
7511 // If any errors have occurred, clear out any temporaries that may have
7512 // been leftover. This ensures that these temporaries won't be picked up for
7513 // deletion in some later function.
7514 if (PP.getDiagnostics().hasErrorOccurred() ||
7515 PP.getDiagnostics().getSuppressAllDiagnostics()) {
7516 DiscardCleanupsInEvaluationContext();
7517 } else if (!isa<FunctionTemplateDecl>(dcl)) {
7518 // Since the body is valid, issue any analysis-based warnings that are
7523 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
7524 (!CheckConstexprFunctionDecl(FD) ||
7525 !CheckConstexprFunctionBody(FD, Body)))
7526 FD->setInvalidDecl();
7528 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
7529 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
7530 assert(MaybeODRUseExprs.empty() &&
7531 "Leftover expressions for odr-use checking");
7534 if (!IsInstantiation)
7537 PopFunctionScopeInfo(ActivePolicy, dcl);
7539 // If any errors have occurred, clear out any temporaries that may have
7540 // been leftover. This ensures that these temporaries won't be picked up for
7541 // deletion in some later function.
7542 if (getDiagnostics().hasErrorOccurred()) {
7543 DiscardCleanupsInEvaluationContext();
7550 /// When we finish delayed parsing of an attribute, we must attach it to the
7552 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
7553 ParsedAttributes &Attrs) {
7554 // Always attach attributes to the underlying decl.
7555 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7556 D = TD->getTemplatedDecl();
7557 ProcessDeclAttributeList(S, D, Attrs.getList());
7561 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
7562 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
7563 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
7564 IdentifierInfo &II, Scope *S) {
7565 // Before we produce a declaration for an implicitly defined
7566 // function, see whether there was a locally-scoped declaration of
7567 // this name as a function or variable. If so, use that
7568 // (non-visible) declaration, and complain about it.
7569 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
7570 = findLocallyScopedExternalDecl(&II);
7571 if (Pos != LocallyScopedExternalDecls.end()) {
7572 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
7573 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
7577 // Extension in C99. Legal in C90, but warn about it.
7579 if (II.getName().startswith("__builtin_"))
7580 diag_id = diag::warn_builtin_unknown;
7581 else if (getLangOpts().C99)
7582 diag_id = diag::ext_implicit_function_decl;
7584 diag_id = diag::warn_implicit_function_decl;
7585 Diag(Loc, diag_id) << &II;
7587 // Because typo correction is expensive, only do it if the implicit
7588 // function declaration is going to be treated as an error.
7589 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
7590 TypoCorrection Corrected;
7591 DeclFilterCCC<FunctionDecl> Validator;
7592 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
7593 LookupOrdinaryName, S, 0, Validator))) {
7594 std::string CorrectedStr = Corrected.getAsString(getLangOpts());
7595 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts());
7596 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>();
7598 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr
7599 << FixItHint::CreateReplacement(Loc, CorrectedStr);
7601 if (Func->getLocation().isValid()
7602 && !II.getName().startswith("__builtin_"))
7603 Diag(Func->getLocation(), diag::note_previous_decl)
7604 << CorrectedQuotedStr;
7608 // Set a Declarator for the implicit definition: int foo();
7610 AttributeFactory attrFactory;
7611 DeclSpec DS(attrFactory);
7613 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
7614 (void)Error; // Silence warning.
7615 assert(!Error && "Error setting up implicit decl!");
7616 Declarator D(DS, Declarator::BlockContext);
7617 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
7618 0, 0, true, SourceLocation(),
7619 SourceLocation(), SourceLocation(),
7621 EST_None, SourceLocation(),
7622 0, 0, 0, 0, Loc, Loc, D),
7625 D.SetIdentifier(&II, Loc);
7627 // Insert this function into translation-unit scope.
7629 DeclContext *PrevDC = CurContext;
7630 CurContext = Context.getTranslationUnitDecl();
7632 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
7635 CurContext = PrevDC;
7637 AddKnownFunctionAttributes(FD);
7642 /// \brief Adds any function attributes that we know a priori based on
7643 /// the declaration of this function.
7645 /// These attributes can apply both to implicitly-declared builtins
7646 /// (like __builtin___printf_chk) or to library-declared functions
7647 /// like NSLog or printf.
7649 /// We need to check for duplicate attributes both here and where user-written
7650 /// attributes are applied to declarations.
7651 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
7652 if (FD->isInvalidDecl())
7655 // If this is a built-in function, map its builtin attributes to
7656 // actual attributes.
7657 if (unsigned BuiltinID = FD->getBuiltinID()) {
7658 // Handle printf-formatting attributes.
7661 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
7662 if (!FD->getAttr<FormatAttr>()) {
7663 const char *fmt = "printf";
7664 unsigned int NumParams = FD->getNumParams();
7665 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
7666 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
7668 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7670 HasVAListArg ? 0 : FormatIdx+2));
7673 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
7675 if (!FD->getAttr<FormatAttr>())
7676 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7677 "scanf", FormatIdx+1,
7678 HasVAListArg ? 0 : FormatIdx+2));
7681 // Mark const if we don't care about errno and that is the only
7682 // thing preventing the function from being const. This allows
7683 // IRgen to use LLVM intrinsics for such functions.
7684 if (!getLangOpts().MathErrno &&
7685 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
7686 if (!FD->getAttr<ConstAttr>())
7687 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7690 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
7691 !FD->getAttr<ReturnsTwiceAttr>())
7692 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
7693 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
7694 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
7695 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
7696 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
7699 IdentifierInfo *Name = FD->getIdentifier();
7702 if ((!getLangOpts().CPlusPlus &&
7703 FD->getDeclContext()->isTranslationUnit()) ||
7704 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
7705 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
7706 LinkageSpecDecl::lang_c)) {
7707 // Okay: this could be a libc/libm/Objective-C function we know
7712 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
7713 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
7714 // target-specific builtins, perhaps?
7715 if (!FD->getAttr<FormatAttr>())
7716 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
7718 Name->isStr("vasprintf") ? 0 : 3));
7722 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
7723 TypeSourceInfo *TInfo) {
7724 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
7725 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
7728 assert(D.isInvalidType() && "no declarator info for valid type");
7729 TInfo = Context.getTrivialTypeSourceInfo(T);
7732 // Scope manipulation handled by caller.
7733 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
7735 D.getIdentifierLoc(),
7739 // Bail out immediately if we have an invalid declaration.
7740 if (D.isInvalidType()) {
7741 NewTD->setInvalidDecl();
7745 if (D.getDeclSpec().isModulePrivateSpecified()) {
7746 if (CurContext->isFunctionOrMethod())
7747 Diag(NewTD->getLocation(), diag::err_module_private_local)
7748 << 2 << NewTD->getDeclName()
7749 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7750 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7752 NewTD->setModulePrivate();
7755 // C++ [dcl.typedef]p8:
7756 // If the typedef declaration defines an unnamed class (or
7757 // enum), the first typedef-name declared by the declaration
7758 // to be that class type (or enum type) is used to denote the
7759 // class type (or enum type) for linkage purposes only.
7760 // We need to check whether the type was declared in the declaration.
7761 switch (D.getDeclSpec().getTypeSpecType()) {
7766 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
7768 // Do nothing if the tag is not anonymous or already has an
7769 // associated typedef (from an earlier typedef in this decl group).
7770 if (tagFromDeclSpec->getIdentifier()) break;
7771 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
7773 // A well-formed anonymous tag must always be a TUK_Definition.
7774 assert(tagFromDeclSpec->isThisDeclarationADefinition());
7776 // The type must match the tag exactly; no qualifiers allowed.
7777 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
7780 // Otherwise, set this is the anon-decl typedef for the tag.
7781 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
7793 /// \brief Check that this is a valid underlying type for an enum declaration.
7794 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
7795 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
7796 QualType T = TI->getType();
7798 if (T->isDependentType() || T->isIntegralType(Context))
7801 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
7805 /// Check whether this is a valid redeclaration of a previous enumeration.
7806 /// \return true if the redeclaration was invalid.
7807 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
7808 QualType EnumUnderlyingTy,
7809 const EnumDecl *Prev) {
7810 bool IsFixed = !EnumUnderlyingTy.isNull();
7812 if (IsScoped != Prev->isScoped()) {
7813 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
7814 << Prev->isScoped();
7815 Diag(Prev->getLocation(), diag::note_previous_use);
7819 if (IsFixed && Prev->isFixed()) {
7820 if (!EnumUnderlyingTy->isDependentType() &&
7821 !Prev->getIntegerType()->isDependentType() &&
7822 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
7823 Prev->getIntegerType())) {
7824 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
7825 << EnumUnderlyingTy << Prev->getIntegerType();
7826 Diag(Prev->getLocation(), diag::note_previous_use);
7829 } else if (IsFixed != Prev->isFixed()) {
7830 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
7832 Diag(Prev->getLocation(), diag::note_previous_use);
7839 /// \brief Determine whether a tag with a given kind is acceptable
7840 /// as a redeclaration of the given tag declaration.
7842 /// \returns true if the new tag kind is acceptable, false otherwise.
7843 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
7844 TagTypeKind NewTag, bool isDefinition,
7845 SourceLocation NewTagLoc,
7846 const IdentifierInfo &Name) {
7847 // C++ [dcl.type.elab]p3:
7848 // The class-key or enum keyword present in the
7849 // elaborated-type-specifier shall agree in kind with the
7850 // declaration to which the name in the elaborated-type-specifier
7851 // refers. This rule also applies to the form of
7852 // elaborated-type-specifier that declares a class-name or
7853 // friend class since it can be construed as referring to the
7854 // definition of the class. Thus, in any
7855 // elaborated-type-specifier, the enum keyword shall be used to
7856 // refer to an enumeration (7.2), the union class-key shall be
7857 // used to refer to a union (clause 9), and either the class or
7858 // struct class-key shall be used to refer to a class (clause 9)
7859 // declared using the class or struct class-key.
7860 TagTypeKind OldTag = Previous->getTagKind();
7861 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct))
7862 if (OldTag == NewTag)
7865 if ((OldTag == TTK_Struct || OldTag == TTK_Class) &&
7866 (NewTag == TTK_Struct || NewTag == TTK_Class)) {
7867 // Warn about the struct/class tag mismatch.
7868 bool isTemplate = false;
7869 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
7870 isTemplate = Record->getDescribedClassTemplate();
7872 if (!ActiveTemplateInstantiations.empty()) {
7873 // In a template instantiation, do not offer fix-its for tag mismatches
7874 // since they usually mess up the template instead of fixing the problem.
7875 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7876 << (NewTag == TTK_Class) << isTemplate << &Name;
7881 // On definitions, check previous tags and issue a fix-it for each
7882 // one that doesn't match the current tag.
7883 if (Previous->getDefinition()) {
7884 // Don't suggest fix-its for redefinitions.
7888 bool previousMismatch = false;
7889 for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
7890 E(Previous->redecls_end()); I != E; ++I) {
7891 if (I->getTagKind() != NewTag) {
7892 if (!previousMismatch) {
7893 previousMismatch = true;
7894 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
7895 << (NewTag == TTK_Class) << isTemplate << &Name;
7897 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
7898 << (NewTag == TTK_Class)
7899 << FixItHint::CreateReplacement(I->getInnerLocStart(),
7900 NewTag == TTK_Class?
7901 "class" : "struct");
7907 // Check for a previous definition. If current tag and definition
7908 // are same type, do nothing. If no definition, but disagree with
7909 // with previous tag type, give a warning, but no fix-it.
7910 const TagDecl *Redecl = Previous->getDefinition() ?
7911 Previous->getDefinition() : Previous;
7912 if (Redecl->getTagKind() == NewTag) {
7916 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
7917 << (NewTag == TTK_Class)
7918 << isTemplate << &Name;
7919 Diag(Redecl->getLocation(), diag::note_previous_use);
7921 // If there is a previous defintion, suggest a fix-it.
7922 if (Previous->getDefinition()) {
7923 Diag(NewTagLoc, diag::note_struct_class_suggestion)
7924 << (Redecl->getTagKind() == TTK_Class)
7925 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
7926 Redecl->getTagKind() == TTK_Class? "class" : "struct");
7934 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
7935 /// former case, Name will be non-null. In the later case, Name will be null.
7936 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
7937 /// reference/declaration/definition of a tag.
7938 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7939 SourceLocation KWLoc, CXXScopeSpec &SS,
7940 IdentifierInfo *Name, SourceLocation NameLoc,
7941 AttributeList *Attr, AccessSpecifier AS,
7942 SourceLocation ModulePrivateLoc,
7943 MultiTemplateParamsArg TemplateParameterLists,
7944 bool &OwnedDecl, bool &IsDependent,
7945 SourceLocation ScopedEnumKWLoc,
7946 bool ScopedEnumUsesClassTag,
7947 TypeResult UnderlyingType) {
7948 // If this is not a definition, it must have a name.
7949 IdentifierInfo *OrigName = Name;
7950 assert((Name != 0 || TUK == TUK_Definition) &&
7951 "Nameless record must be a definition!");
7952 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
7955 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7956 bool ScopedEnum = ScopedEnumKWLoc.isValid();
7958 // FIXME: Check explicit specializations more carefully.
7959 bool isExplicitSpecialization = false;
7960 bool Invalid = false;
7962 // We only need to do this matching if we have template parameters
7963 // or a scope specifier, which also conveniently avoids this work
7964 // for non-C++ cases.
7965 if (TemplateParameterLists.size() > 0 ||
7966 (SS.isNotEmpty() && TUK != TUK_Reference)) {
7967 if (TemplateParameterList *TemplateParams
7968 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS,
7969 TemplateParameterLists.get(),
7970 TemplateParameterLists.size(),
7972 isExplicitSpecialization,
7974 if (TemplateParams->size() > 0) {
7975 // This is a declaration or definition of a class template (which may
7976 // be a member of another template).
7982 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
7983 SS, Name, NameLoc, Attr,
7986 TemplateParameterLists.size() - 1,
7987 (TemplateParameterList**) TemplateParameterLists.release());
7988 return Result.get();
7990 // The "template<>" header is extraneous.
7991 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7992 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7993 isExplicitSpecialization = true;
7998 // Figure out the underlying type if this a enum declaration. We need to do
7999 // this early, because it's needed to detect if this is an incompatible
8001 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
8003 if (Kind == TTK_Enum) {
8004 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
8005 // No underlying type explicitly specified, or we failed to parse the
8006 // type, default to int.
8007 EnumUnderlying = Context.IntTy.getTypePtr();
8008 else if (UnderlyingType.get()) {
8009 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
8010 // integral type; any cv-qualification is ignored.
8011 TypeSourceInfo *TI = 0;
8012 GetTypeFromParser(UnderlyingType.get(), &TI);
8013 EnumUnderlying = TI;
8015 if (CheckEnumUnderlyingType(TI))
8016 // Recover by falling back to int.
8017 EnumUnderlying = Context.IntTy.getTypePtr();
8019 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
8020 UPPC_FixedUnderlyingType))
8021 EnumUnderlying = Context.IntTy.getTypePtr();
8023 } else if (getLangOpts().MicrosoftMode)
8024 // Microsoft enums are always of int type.
8025 EnumUnderlying = Context.IntTy.getTypePtr();
8028 DeclContext *SearchDC = CurContext;
8029 DeclContext *DC = CurContext;
8030 bool isStdBadAlloc = false;
8032 RedeclarationKind Redecl = ForRedeclaration;
8033 if (TUK == TUK_Friend || TUK == TUK_Reference)
8034 Redecl = NotForRedeclaration;
8036 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
8038 if (Name && SS.isNotEmpty()) {
8039 // We have a nested-name tag ('struct foo::bar').
8041 // Check for invalid 'foo::'.
8042 if (SS.isInvalid()) {
8047 // If this is a friend or a reference to a class in a dependent
8048 // context, don't try to make a decl for it.
8049 if (TUK == TUK_Friend || TUK == TUK_Reference) {
8050 DC = computeDeclContext(SS, false);
8056 DC = computeDeclContext(SS, true);
8058 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
8064 if (RequireCompleteDeclContext(SS, DC))
8068 // Look-up name inside 'foo::'.
8069 LookupQualifiedName(Previous, DC);
8071 if (Previous.isAmbiguous())
8074 if (Previous.empty()) {
8075 // Name lookup did not find anything. However, if the
8076 // nested-name-specifier refers to the current instantiation,
8077 // and that current instantiation has any dependent base
8078 // classes, we might find something at instantiation time: treat
8079 // this as a dependent elaborated-type-specifier.
8080 // But this only makes any sense for reference-like lookups.
8081 if (Previous.wasNotFoundInCurrentInstantiation() &&
8082 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8087 // A tag 'foo::bar' must already exist.
8088 Diag(NameLoc, diag::err_not_tag_in_scope)
8089 << Kind << Name << DC << SS.getRange();
8095 // If this is a named struct, check to see if there was a previous forward
8096 // declaration or definition.
8097 // FIXME: We're looking into outer scopes here, even when we
8098 // shouldn't be. Doing so can result in ambiguities that we
8099 // shouldn't be diagnosing.
8100 LookupName(Previous, S);
8102 if (Previous.isAmbiguous() &&
8103 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
8104 LookupResult::Filter F = Previous.makeFilter();
8105 while (F.hasNext()) {
8106 NamedDecl *ND = F.next();
8107 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
8113 // Note: there used to be some attempt at recovery here.
8114 if (Previous.isAmbiguous())
8117 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
8118 // FIXME: This makes sure that we ignore the contexts associated
8119 // with C structs, unions, and enums when looking for a matching
8120 // tag declaration or definition. See the similar lookup tweak
8121 // in Sema::LookupName; is there a better way to deal with this?
8122 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
8123 SearchDC = SearchDC->getParent();
8125 } else if (S->isFunctionPrototypeScope()) {
8126 // If this is an enum declaration in function prototype scope, set its
8127 // initial context to the translation unit.
8128 // FIXME: [citation needed]
8129 SearchDC = Context.getTranslationUnitDecl();
8132 if (Previous.isSingleResult() &&
8133 Previous.getFoundDecl()->isTemplateParameter()) {
8134 // Maybe we will complain about the shadowed template parameter.
8135 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
8136 // Just pretend that we didn't see the previous declaration.
8140 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
8141 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
8142 // This is a declaration of or a reference to "std::bad_alloc".
8143 isStdBadAlloc = true;
8145 if (Previous.empty() && StdBadAlloc) {
8146 // std::bad_alloc has been implicitly declared (but made invisible to
8147 // name lookup). Fill in this implicit declaration as the previous
8148 // declaration, so that the declarations get chained appropriately.
8149 Previous.addDecl(getStdBadAlloc());
8153 // If we didn't find a previous declaration, and this is a reference
8154 // (or friend reference), move to the correct scope. In C++, we
8155 // also need to do a redeclaration lookup there, just in case
8156 // there's a shadow friend decl.
8157 if (Name && Previous.empty() &&
8158 (TUK == TUK_Reference || TUK == TUK_Friend)) {
8159 if (Invalid) goto CreateNewDecl;
8160 assert(SS.isEmpty());
8162 if (TUK == TUK_Reference) {
8163 // C++ [basic.scope.pdecl]p5:
8164 // -- for an elaborated-type-specifier of the form
8166 // class-key identifier
8168 // if the elaborated-type-specifier is used in the
8169 // decl-specifier-seq or parameter-declaration-clause of a
8170 // function defined in namespace scope, the identifier is
8171 // declared as a class-name in the namespace that contains
8172 // the declaration; otherwise, except as a friend
8173 // declaration, the identifier is declared in the smallest
8174 // non-class, non-function-prototype scope that contains the
8177 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
8178 // C structs and unions.
8180 // It is an error in C++ to declare (rather than define) an enum
8181 // type, including via an elaborated type specifier. We'll
8182 // diagnose that later; for now, declare the enum in the same
8183 // scope as we would have picked for any other tag type.
8185 // GNU C also supports this behavior as part of its incomplete
8186 // enum types extension, while GNU C++ does not.
8188 // Find the context where we'll be declaring the tag.
8189 // FIXME: We would like to maintain the current DeclContext as the
8191 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
8192 SearchDC = SearchDC->getParent();
8194 // Find the scope where we'll be declaring the tag.
8195 while (S->isClassScope() ||
8196 (getLangOpts().CPlusPlus &&
8197 S->isFunctionPrototypeScope()) ||
8198 ((S->getFlags() & Scope::DeclScope) == 0) ||
8200 ((DeclContext *)S->getEntity())->isTransparentContext()))
8203 assert(TUK == TUK_Friend);
8204 // C++ [namespace.memdef]p3:
8205 // If a friend declaration in a non-local class first declares a
8206 // class or function, the friend class or function is a member of
8207 // the innermost enclosing namespace.
8208 SearchDC = SearchDC->getEnclosingNamespaceContext();
8211 // In C++, we need to do a redeclaration lookup to properly
8212 // diagnose some problems.
8213 if (getLangOpts().CPlusPlus) {
8214 Previous.setRedeclarationKind(ForRedeclaration);
8215 LookupQualifiedName(Previous, SearchDC);
8219 if (!Previous.empty()) {
8220 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
8222 // It's okay to have a tag decl in the same scope as a typedef
8223 // which hides a tag decl in the same scope. Finding this
8224 // insanity with a redeclaration lookup can only actually happen
8227 // This is also okay for elaborated-type-specifiers, which is
8228 // technically forbidden by the current standard but which is
8229 // okay according to the likely resolution of an open issue;
8230 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
8231 if (getLangOpts().CPlusPlus) {
8232 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8233 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
8234 TagDecl *Tag = TT->getDecl();
8235 if (Tag->getDeclName() == Name &&
8236 Tag->getDeclContext()->getRedeclContext()
8237 ->Equals(TD->getDeclContext()->getRedeclContext())) {
8240 Previous.addDecl(Tag);
8241 Previous.resolveKind();
8247 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
8248 // If this is a use of a previous tag, or if the tag is already declared
8249 // in the same scope (so that the definition/declaration completes or
8250 // rementions the tag), reuse the decl.
8251 if (TUK == TUK_Reference || TUK == TUK_Friend ||
8252 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
8253 // Make sure that this wasn't declared as an enum and now used as a
8254 // struct or something similar.
8255 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
8256 TUK == TUK_Definition, KWLoc,
8259 = (PrevTagDecl->getTagKind() != TTK_Enum &&
8262 Diag(KWLoc, diag::err_use_with_wrong_tag)
8264 << FixItHint::CreateReplacement(SourceRange(KWLoc),
8265 PrevTagDecl->getKindName());
8267 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
8268 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
8271 Kind = PrevTagDecl->getTagKind();
8273 // Recover by making this an anonymous redefinition.
8280 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
8281 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
8283 // If this is an elaborated-type-specifier for a scoped enumeration,
8284 // the 'class' keyword is not necessary and not permitted.
8285 if (TUK == TUK_Reference || TUK == TUK_Friend) {
8287 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
8288 << PrevEnum->isScoped()
8289 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
8293 QualType EnumUnderlyingTy;
8294 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8295 EnumUnderlyingTy = TI->getType();
8296 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
8297 EnumUnderlyingTy = QualType(T, 0);
8299 // All conflicts with previous declarations are recovered by
8300 // returning the previous declaration, unless this is a definition,
8301 // in which case we want the caller to bail out.
8302 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
8303 ScopedEnum, EnumUnderlyingTy, PrevEnum))
8304 return TUK == TUK_Declaration ? PrevTagDecl : 0;
8308 // If this is a use, just return the declaration we found.
8310 // FIXME: In the future, return a variant or some other clue
8311 // for the consumer of this Decl to know it doesn't own it.
8312 // For our current ASTs this shouldn't be a problem, but will
8313 // need to be changed with DeclGroups.
8314 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
8315 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
8318 // Diagnose attempts to redefine a tag.
8319 if (TUK == TUK_Definition) {
8320 if (TagDecl *Def = PrevTagDecl->getDefinition()) {
8321 // If we're defining a specialization and the previous definition
8322 // is from an implicit instantiation, don't emit an error
8323 // here; we'll catch this in the general case below.
8324 bool IsExplicitSpecializationAfterInstantiation = false;
8325 if (isExplicitSpecialization) {
8326 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
8327 IsExplicitSpecializationAfterInstantiation =
8328 RD->getTemplateSpecializationKind() !=
8329 TSK_ExplicitSpecialization;
8330 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
8331 IsExplicitSpecializationAfterInstantiation =
8332 ED->getTemplateSpecializationKind() !=
8333 TSK_ExplicitSpecialization;
8336 if (!IsExplicitSpecializationAfterInstantiation) {
8337 // A redeclaration in function prototype scope in C isn't
8338 // visible elsewhere, so merely issue a warning.
8339 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
8340 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
8342 Diag(NameLoc, diag::err_redefinition) << Name;
8343 Diag(Def->getLocation(), diag::note_previous_definition);
8344 // If this is a redefinition, recover by making this
8345 // struct be anonymous, which will make any later
8346 // references get the previous definition.
8352 // If the type is currently being defined, complain
8353 // about a nested redefinition.
8355 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
8356 if (Tag->isBeingDefined()) {
8357 Diag(NameLoc, diag::err_nested_redefinition) << Name;
8358 Diag(PrevTagDecl->getLocation(),
8359 diag::note_previous_definition);
8366 // Okay, this is definition of a previously declared or referenced
8367 // tag PrevDecl. We're going to create a new Decl for it.
8370 // If we get here we have (another) forward declaration or we
8371 // have a definition. Just create a new decl.
8374 // If we get here, this is a definition of a new tag type in a nested
8375 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
8376 // new decl/type. We set PrevDecl to NULL so that the entities
8377 // have distinct types.
8380 // If we get here, we're going to create a new Decl. If PrevDecl
8381 // is non-NULL, it's a definition of the tag declared by
8382 // PrevDecl. If it's NULL, we have a new definition.
8385 // Otherwise, PrevDecl is not a tag, but was found with tag
8386 // lookup. This is only actually possible in C++, where a few
8387 // things like templates still live in the tag namespace.
8389 // Use a better diagnostic if an elaborated-type-specifier
8390 // found the wrong kind of type on the first
8391 // (non-redeclaration) lookup.
8392 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
8393 !Previous.isForRedeclaration()) {
8395 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8396 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8397 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8398 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
8399 Diag(PrevDecl->getLocation(), diag::note_declared_at);
8402 // Otherwise, only diagnose if the declaration is in scope.
8403 } else if (!isDeclInScope(PrevDecl, SearchDC, S,
8404 isExplicitSpecialization)) {
8407 // Diagnose implicit declarations introduced by elaborated types.
8408 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
8410 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
8411 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
8412 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
8413 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
8414 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8417 // Otherwise it's a declaration. Call out a particularly common
8419 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
8421 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
8422 Diag(NameLoc, diag::err_tag_definition_of_typedef)
8423 << Name << Kind << TND->getUnderlyingType();
8424 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
8427 // Otherwise, diagnose.
8429 // The tag name clashes with something else in the target scope,
8430 // issue an error and recover by making this tag be anonymous.
8431 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
8432 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8437 // The existing declaration isn't relevant to us; we're in a
8438 // new scope, so clear out the previous declaration.
8445 TagDecl *PrevDecl = 0;
8446 if (Previous.isSingleResult())
8447 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
8449 // If there is an identifier, use the location of the identifier as the
8450 // location of the decl, otherwise use the location of the struct/union
8452 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
8454 // Otherwise, create a new declaration. If there is a previous
8455 // declaration of the same entity, the two will be linked via
8459 bool IsForwardReference = false;
8460 if (Kind == TTK_Enum) {
8461 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8462 // enum X { A, B, C } D; D should chain to X.
8463 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
8464 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
8465 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
8466 // If this is an undefined enum, warn.
8467 if (TUK != TUK_Definition && !Invalid) {
8469 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) {
8470 // C++0x: 7.2p2: opaque-enum-declaration.
8471 // Conflicts are diagnosed above. Do nothing.
8473 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
8474 Diag(Loc, diag::ext_forward_ref_enum_def)
8476 Diag(Def->getLocation(), diag::note_previous_definition);
8478 unsigned DiagID = diag::ext_forward_ref_enum;
8479 if (getLangOpts().MicrosoftMode)
8480 DiagID = diag::ext_ms_forward_ref_enum;
8481 else if (getLangOpts().CPlusPlus)
8482 DiagID = diag::err_forward_ref_enum;
8485 // If this is a forward-declared reference to an enumeration, make a
8486 // note of it; we won't actually be introducing the declaration into
8487 // the declaration context.
8488 if (TUK == TUK_Reference)
8489 IsForwardReference = true;
8493 if (EnumUnderlying) {
8494 EnumDecl *ED = cast<EnumDecl>(New);
8495 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
8496 ED->setIntegerTypeSourceInfo(TI);
8498 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
8499 ED->setPromotionType(ED->getIntegerType());
8503 // struct/union/class
8505 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
8506 // struct X { int A; } D; D should chain to X.
8507 if (getLangOpts().CPlusPlus) {
8508 // FIXME: Look for a way to use RecordDecl for simple structs.
8509 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8510 cast_or_null<CXXRecordDecl>(PrevDecl));
8512 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
8513 StdBadAlloc = cast<CXXRecordDecl>(New);
8515 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
8516 cast_or_null<RecordDecl>(PrevDecl));
8519 // Maybe add qualifier info.
8520 if (SS.isNotEmpty()) {
8522 // If this is either a declaration or a definition, check the
8523 // nested-name-specifier against the current context. We don't do this
8524 // for explicit specializations, because they have similar checking
8525 // (with more specific diagnostics) in the call to
8526 // CheckMemberSpecialization, below.
8527 if (!isExplicitSpecialization &&
8528 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
8529 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
8532 New->setQualifierInfo(SS.getWithLocInContext(Context));
8533 if (TemplateParameterLists.size() > 0) {
8534 New->setTemplateParameterListsInfo(Context,
8535 TemplateParameterLists.size(),
8536 (TemplateParameterList**) TemplateParameterLists.release());
8543 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
8544 // Add alignment attributes if necessary; these attributes are checked when
8545 // the ASTContext lays out the structure.
8547 // It is important for implementing the correct semantics that this
8548 // happen here (in act on tag decl). The #pragma pack stack is
8549 // maintained as a result of parser callbacks which can occur at
8550 // many points during the parsing of a struct declaration (because
8551 // the #pragma tokens are effectively skipped over during the
8552 // parsing of the struct).
8553 AddAlignmentAttributesForRecord(RD);
8555 AddMsStructLayoutForRecord(RD);
8558 if (ModulePrivateLoc.isValid()) {
8559 if (isExplicitSpecialization)
8560 Diag(New->getLocation(), diag::err_module_private_specialization)
8562 << FixItHint::CreateRemoval(ModulePrivateLoc);
8563 // __module_private__ does not apply to local classes. However, we only
8564 // diagnose this as an error when the declaration specifiers are
8565 // freestanding. Here, we just ignore the __module_private__.
8566 else if (!SearchDC->isFunctionOrMethod())
8567 New->setModulePrivate();
8570 // If this is a specialization of a member class (of a class template),
8571 // check the specialization.
8572 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
8576 New->setInvalidDecl();
8579 ProcessDeclAttributeList(S, New, Attr);
8581 // If we're declaring or defining a tag in function prototype scope
8582 // in C, note that this type can only be used within the function.
8583 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
8584 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
8586 // Set the lexical context. If the tag has a C++ scope specifier, the
8587 // lexical context will be different from the semantic context.
8588 New->setLexicalDeclContext(CurContext);
8590 // Mark this as a friend decl if applicable.
8591 // In Microsoft mode, a friend declaration also acts as a forward
8592 // declaration so we always pass true to setObjectOfFriendDecl to make
8593 // the tag name visible.
8594 if (TUK == TUK_Friend)
8595 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() ||
8596 getLangOpts().MicrosoftExt);
8598 // Set the access specifier.
8599 if (!Invalid && SearchDC->isRecord())
8600 SetMemberAccessSpecifier(New, PrevDecl, AS);
8602 if (TUK == TUK_Definition)
8603 New->startDefinition();
8605 // If this has an identifier, add it to the scope stack.
8606 if (TUK == TUK_Friend) {
8607 // We might be replacing an existing declaration in the lookup tables;
8608 // if so, borrow its access specifier.
8610 New->setAccess(PrevDecl->getAccess());
8612 DeclContext *DC = New->getDeclContext()->getRedeclContext();
8613 DC->makeDeclVisibleInContext(New);
8614 if (Name) // can be null along some error paths
8615 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8616 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
8618 S = getNonFieldDeclScope(S);
8619 PushOnScopeChains(New, S, !IsForwardReference);
8620 if (IsForwardReference)
8621 SearchDC->makeDeclVisibleInContext(New);
8624 CurContext->addDecl(New);
8627 // If this is the C FILE type, notify the AST context.
8628 if (IdentifierInfo *II = New->getIdentifier())
8629 if (!New->isInvalidDecl() &&
8630 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
8632 Context.setFILEDecl(New);
8634 // If we were in function prototype scope (and not in C++ mode), add this
8635 // tag to the list of decls to inject into the function definition scope.
8636 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
8637 InFunctionDeclarator && Name)
8638 DeclsInPrototypeScope.push_back(New);
8644 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
8645 AdjustDeclIfTemplate(TagD);
8646 TagDecl *Tag = cast<TagDecl>(TagD);
8648 // Enter the tag context.
8649 PushDeclContext(S, Tag);
8652 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
8653 assert(isa<ObjCContainerDecl>(IDecl) &&
8654 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
8655 DeclContext *OCD = cast<DeclContext>(IDecl);
8656 assert(getContainingDC(OCD) == CurContext &&
8657 "The next DeclContext should be lexically contained in the current one.");
8662 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
8663 SourceLocation FinalLoc,
8664 SourceLocation LBraceLoc) {
8665 AdjustDeclIfTemplate(TagD);
8666 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
8668 FieldCollector->StartClass();
8670 if (!Record->getIdentifier())
8673 if (FinalLoc.isValid())
8674 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context));
8677 // [...] The class-name is also inserted into the scope of the
8678 // class itself; this is known as the injected-class-name. For
8679 // purposes of access checking, the injected-class-name is treated
8680 // as if it were a public member name.
8681 CXXRecordDecl *InjectedClassName
8682 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
8683 Record->getLocStart(), Record->getLocation(),
8684 Record->getIdentifier(),
8686 /*DelayTypeCreation=*/true);
8687 Context.getTypeDeclType(InjectedClassName, Record);
8688 InjectedClassName->setImplicit();
8689 InjectedClassName->setAccess(AS_public);
8690 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
8691 InjectedClassName->setDescribedClassTemplate(Template);
8692 PushOnScopeChains(InjectedClassName, S);
8693 assert(InjectedClassName->isInjectedClassName() &&
8694 "Broken injected-class-name");
8697 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
8698 SourceLocation RBraceLoc) {
8699 AdjustDeclIfTemplate(TagD);
8700 TagDecl *Tag = cast<TagDecl>(TagD);
8701 Tag->setRBraceLoc(RBraceLoc);
8703 // Make sure we "complete" the definition even it is invalid.
8704 if (Tag->isBeingDefined()) {
8705 assert(Tag->isInvalidDecl() && "We should already have completed it");
8706 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8707 RD->completeDefinition();
8710 if (isa<CXXRecordDecl>(Tag))
8711 FieldCollector->FinishClass();
8713 // Exit this scope of this tag's definition.
8716 // Notify the consumer that we've defined a tag.
8717 Consumer.HandleTagDeclDefinition(Tag);
8720 void Sema::ActOnObjCContainerFinishDefinition() {
8721 // Exit this scope of this interface definition.
8725 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
8726 assert(DC == CurContext && "Mismatch of container contexts");
8727 OriginalLexicalContext = DC;
8728 ActOnObjCContainerFinishDefinition();
8731 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
8732 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
8733 OriginalLexicalContext = 0;
8736 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
8737 AdjustDeclIfTemplate(TagD);
8738 TagDecl *Tag = cast<TagDecl>(TagD);
8739 Tag->setInvalidDecl();
8741 // Make sure we "complete" the definition even it is invalid.
8742 if (Tag->isBeingDefined()) {
8743 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
8744 RD->completeDefinition();
8747 // We're undoing ActOnTagStartDefinition here, not
8748 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
8749 // the FieldCollector.
8754 // Note that FieldName may be null for anonymous bitfields.
8755 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
8756 IdentifierInfo *FieldName,
8757 QualType FieldTy, Expr *BitWidth,
8759 // Default to true; that shouldn't confuse checks for emptiness
8763 // C99 6.7.2.1p4 - verify the field type.
8764 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
8765 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
8766 // Handle incomplete types with specific error.
8767 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
8770 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
8771 << FieldName << FieldTy << BitWidth->getSourceRange();
8772 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
8773 << FieldTy << BitWidth->getSourceRange();
8774 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
8775 UPPC_BitFieldWidth))
8778 // If the bit-width is type- or value-dependent, don't try to check
8780 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
8781 return Owned(BitWidth);
8784 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
8785 if (ICE.isInvalid())
8787 BitWidth = ICE.take();
8789 if (Value != 0 && ZeroWidth)
8792 // Zero-width bitfield is ok for anonymous field.
8793 if (Value == 0 && FieldName)
8794 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
8796 if (Value.isSigned() && Value.isNegative()) {
8798 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
8799 << FieldName << Value.toString(10);
8800 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
8801 << Value.toString(10);
8804 if (!FieldTy->isDependentType()) {
8805 uint64_t TypeSize = Context.getTypeSize(FieldTy);
8806 if (Value.getZExtValue() > TypeSize) {
8807 if (!getLangOpts().CPlusPlus) {
8809 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
8810 << FieldName << (unsigned)Value.getZExtValue()
8811 << (unsigned)TypeSize;
8813 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
8814 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8818 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
8819 << FieldName << (unsigned)Value.getZExtValue()
8820 << (unsigned)TypeSize;
8822 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
8823 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
8827 return Owned(BitWidth);
8830 /// ActOnField - Each field of a C struct/union is passed into this in order
8831 /// to create a FieldDecl object for it.
8832 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
8833 Declarator &D, Expr *BitfieldWidth) {
8834 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
8835 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
8836 /*HasInit=*/false, AS_public);
8840 /// HandleField - Analyze a field of a C struct or a C++ data member.
8842 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
8843 SourceLocation DeclStart,
8844 Declarator &D, Expr *BitWidth, bool HasInit,
8845 AccessSpecifier AS) {
8846 IdentifierInfo *II = D.getIdentifier();
8847 SourceLocation Loc = DeclStart;
8848 if (II) Loc = D.getIdentifierLoc();
8850 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8851 QualType T = TInfo->getType();
8852 if (getLangOpts().CPlusPlus) {
8853 CheckExtraCXXDefaultArguments(D);
8855 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8856 UPPC_DataMemberType)) {
8859 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
8863 DiagnoseFunctionSpecifiers(D);
8865 if (D.getDeclSpec().isThreadSpecified())
8866 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
8867 if (D.getDeclSpec().isConstexprSpecified())
8868 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
8871 // Check to see if this name was declared as a member previously
8872 NamedDecl *PrevDecl = 0;
8873 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
8874 LookupName(Previous, S);
8875 switch (Previous.getResultKind()) {
8876 case LookupResult::Found:
8877 case LookupResult::FoundUnresolvedValue:
8878 PrevDecl = Previous.getAsSingle<NamedDecl>();
8881 case LookupResult::FoundOverloaded:
8882 PrevDecl = Previous.getRepresentativeDecl();
8885 case LookupResult::NotFound:
8886 case LookupResult::NotFoundInCurrentInstantiation:
8887 case LookupResult::Ambiguous:
8890 Previous.suppressDiagnostics();
8892 if (PrevDecl && PrevDecl->isTemplateParameter()) {
8893 // Maybe we will complain about the shadowed template parameter.
8894 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8895 // Just pretend that we didn't see the previous declaration.
8899 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
8903 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
8904 SourceLocation TSSL = D.getLocStart();
8906 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit,
8907 TSSL, AS, PrevDecl, &D);
8909 if (NewFD->isInvalidDecl())
8910 Record->setInvalidDecl();
8912 if (D.getDeclSpec().isModulePrivateSpecified())
8913 NewFD->setModulePrivate();
8915 if (NewFD->isInvalidDecl() && PrevDecl) {
8916 // Don't introduce NewFD into scope; there's already something
8917 // with the same name in the same scope.
8919 PushOnScopeChains(NewFD, S);
8921 Record->addDecl(NewFD);
8926 /// \brief Build a new FieldDecl and check its well-formedness.
8928 /// This routine builds a new FieldDecl given the fields name, type,
8929 /// record, etc. \p PrevDecl should refer to any previous declaration
8930 /// with the same name and in the same scope as the field to be
8933 /// \returns a new FieldDecl.
8935 /// \todo The Declarator argument is a hack. It will be removed once
8936 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
8937 TypeSourceInfo *TInfo,
8938 RecordDecl *Record, SourceLocation Loc,
8939 bool Mutable, Expr *BitWidth, bool HasInit,
8940 SourceLocation TSSL,
8941 AccessSpecifier AS, NamedDecl *PrevDecl,
8943 IdentifierInfo *II = Name.getAsIdentifierInfo();
8944 bool InvalidDecl = false;
8945 if (D) InvalidDecl = D->isInvalidType();
8947 // If we receive a broken type, recover by assuming 'int' and
8948 // marking this declaration as invalid.
8954 QualType EltTy = Context.getBaseElementType(T);
8955 if (!EltTy->isDependentType()) {
8956 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
8957 // Fields of incomplete type force their record to be invalid.
8958 Record->setInvalidDecl();
8962 EltTy->isIncompleteType(&Def);
8963 if (Def && Def->isInvalidDecl()) {
8964 Record->setInvalidDecl();
8970 // C99 6.7.2.1p8: A member of a structure or union may have any type other
8971 // than a variably modified type.
8972 if (!InvalidDecl && T->isVariablyModifiedType()) {
8973 bool SizeIsNegative;
8974 llvm::APSInt Oversized;
8975 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
8978 if (!FixedTy.isNull()) {
8979 Diag(Loc, diag::warn_illegal_constant_array_size);
8983 Diag(Loc, diag::err_typecheck_negative_array_size);
8984 else if (Oversized.getBoolValue())
8985 Diag(Loc, diag::err_array_too_large)
8986 << Oversized.toString(10);
8988 Diag(Loc, diag::err_typecheck_field_variable_size);
8993 // Fields can not have abstract class types
8994 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
8995 diag::err_abstract_type_in_decl,
8999 bool ZeroWidth = false;
9000 // If this is declared as a bit-field, check the bit-field.
9001 if (!InvalidDecl && BitWidth) {
9002 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take();
9010 // Check that 'mutable' is consistent with the type of the declaration.
9011 if (!InvalidDecl && Mutable) {
9012 unsigned DiagID = 0;
9013 if (T->isReferenceType())
9014 DiagID = diag::err_mutable_reference;
9015 else if (T.isConstQualified())
9016 DiagID = diag::err_mutable_const;
9019 SourceLocation ErrLoc = Loc;
9020 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
9021 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
9022 Diag(ErrLoc, DiagID);
9028 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
9029 BitWidth, Mutable, HasInit);
9031 NewFD->setInvalidDecl();
9033 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
9034 Diag(Loc, diag::err_duplicate_member) << II;
9035 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9036 NewFD->setInvalidDecl();
9039 if (!InvalidDecl && getLangOpts().CPlusPlus) {
9040 if (Record->isUnion()) {
9041 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9042 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9043 if (RDecl->getDefinition()) {
9044 // C++ [class.union]p1: An object of a class with a non-trivial
9045 // constructor, a non-trivial copy constructor, a non-trivial
9046 // destructor, or a non-trivial copy assignment operator
9047 // cannot be a member of a union, nor can an array of such
9049 if (CheckNontrivialField(NewFD))
9050 NewFD->setInvalidDecl();
9054 // C++ [class.union]p1: If a union contains a member of reference type,
9055 // the program is ill-formed.
9056 if (EltTy->isReferenceType()) {
9057 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type)
9058 << NewFD->getDeclName() << EltTy;
9059 NewFD->setInvalidDecl();
9064 // FIXME: We need to pass in the attributes given an AST
9065 // representation, not a parser representation.
9067 // FIXME: What to pass instead of TUScope?
9068 ProcessDeclAttributes(TUScope, NewFD, *D);
9070 // In auto-retain/release, infer strong retension for fields of
9072 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
9073 NewFD->setInvalidDecl();
9075 if (T.isObjCGCWeak())
9076 Diag(Loc, diag::warn_attribute_weak_on_field);
9078 NewFD->setAccess(AS);
9082 bool Sema::CheckNontrivialField(FieldDecl *FD) {
9084 assert(getLangOpts().CPlusPlus && "valid check only for C++");
9086 if (FD->isInvalidDecl())
9089 QualType EltTy = Context.getBaseElementType(FD->getType());
9090 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
9091 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
9092 if (RDecl->getDefinition()) {
9093 // We check for copy constructors before constructors
9094 // because otherwise we'll never get complaints about
9095 // copy constructors.
9097 CXXSpecialMember member = CXXInvalid;
9098 if (!RDecl->hasTrivialCopyConstructor())
9099 member = CXXCopyConstructor;
9100 else if (!RDecl->hasTrivialDefaultConstructor())
9101 member = CXXDefaultConstructor;
9102 else if (!RDecl->hasTrivialCopyAssignment())
9103 member = CXXCopyAssignment;
9104 else if (!RDecl->hasTrivialDestructor())
9105 member = CXXDestructor;
9107 if (member != CXXInvalid) {
9108 if (!getLangOpts().CPlusPlus0x &&
9109 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
9110 // Objective-C++ ARC: it is an error to have a non-trivial field of
9111 // a union. However, system headers in Objective-C programs
9112 // occasionally have Objective-C lifetime objects within unions,
9113 // and rather than cause the program to fail, we make those
9114 // members unavailable.
9115 SourceLocation Loc = FD->getLocation();
9116 if (getSourceManager().isInSystemHeader(Loc)) {
9117 if (!FD->hasAttr<UnavailableAttr>())
9118 FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
9119 "this system field has retaining ownership"));
9124 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ?
9125 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
9126 diag::err_illegal_union_or_anon_struct_member)
9127 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
9128 DiagnoseNontrivial(RT, member);
9129 return !getLangOpts().CPlusPlus0x;
9137 /// If the given constructor is user-provided, produce a diagnostic explaining
9138 /// that it makes the class non-trivial.
9139 static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT,
9140 CXXConstructorDecl *CD,
9141 Sema::CXXSpecialMember CSM) {
9142 if (!CD->isUserProvided())
9145 SourceLocation CtorLoc = CD->getLocation();
9146 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM;
9150 /// DiagnoseNontrivial - Given that a class has a non-trivial
9151 /// special member, figure out why.
9152 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
9154 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
9156 // Check whether the member was user-declared.
9161 case CXXDefaultConstructor:
9162 if (RD->hasUserDeclaredConstructor()) {
9163 typedef CXXRecordDecl::ctor_iterator ctor_iter;
9164 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI)
9165 if (DiagnoseNontrivialUserProvidedCtor(*this, QT, *CI, member))
9168 // No user-provided constructors; look for constructor templates.
9169 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9171 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end());
9173 CXXConstructorDecl *CD =
9174 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl());
9175 if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member))
9181 case CXXCopyConstructor:
9182 if (RD->hasUserDeclaredCopyConstructor()) {
9183 SourceLocation CtorLoc =
9184 RD->getCopyConstructor(0)->getLocation();
9185 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9190 case CXXMoveConstructor:
9191 if (RD->hasUserDeclaredMoveConstructor()) {
9192 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation();
9193 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9198 case CXXCopyAssignment:
9199 if (RD->hasUserDeclaredCopyAssignment()) {
9200 // FIXME: this should use the location of the copy
9201 // assignment, not the type.
9202 SourceLocation TyLoc = RD->getLocStart();
9203 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
9208 case CXXMoveAssignment:
9209 if (RD->hasUserDeclaredMoveAssignment()) {
9210 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation();
9211 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member;
9217 if (RD->hasUserDeclaredDestructor()) {
9218 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation();
9219 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
9225 typedef CXXRecordDecl::base_class_iterator base_iter;
9227 // Virtual bases and members inhibit trivial copying/construction,
9228 // but not trivial destruction.
9229 if (member != CXXDestructor) {
9230 // Check for virtual bases. vbases includes indirect virtual bases,
9231 // so we just iterate through the direct bases.
9232 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
9233 if (bi->isVirtual()) {
9234 SourceLocation BaseLoc = bi->getLocStart();
9235 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
9239 // Check for virtual methods.
9240 typedef CXXRecordDecl::method_iterator meth_iter;
9241 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
9243 if (mi->isVirtual()) {
9244 SourceLocation MLoc = mi->getLocStart();
9245 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
9251 bool (CXXRecordDecl::*hasTrivial)() const;
9253 case CXXDefaultConstructor:
9254 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break;
9255 case CXXCopyConstructor:
9256 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
9257 case CXXCopyAssignment:
9258 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
9260 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
9262 llvm_unreachable("unexpected special member");
9265 // Check for nontrivial bases (and recurse).
9266 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
9267 const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
9268 assert(BaseRT && "Don't know how to handle dependent bases");
9269 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
9270 if (!(BaseRecTy->*hasTrivial)()) {
9271 SourceLocation BaseLoc = bi->getLocStart();
9272 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
9273 DiagnoseNontrivial(BaseRT, member);
9278 // Check for nontrivial members (and recurse).
9279 typedef RecordDecl::field_iterator field_iter;
9280 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
9282 QualType EltTy = Context.getBaseElementType((*fi)->getType());
9283 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
9284 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
9286 if (!(EltRD->*hasTrivial)()) {
9287 SourceLocation FLoc = (*fi)->getLocation();
9288 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
9289 DiagnoseNontrivial(EltRT, member);
9294 if (EltTy->isObjCLifetimeType()) {
9295 switch (EltTy.getObjCLifetime()) {
9296 case Qualifiers::OCL_None:
9297 case Qualifiers::OCL_ExplicitNone:
9300 case Qualifiers::OCL_Autoreleasing:
9301 case Qualifiers::OCL_Weak:
9302 case Qualifiers::OCL_Strong:
9303 Diag((*fi)->getLocation(), diag::note_nontrivial_objc_ownership)
9304 << QT << EltTy.getObjCLifetime();
9310 llvm_unreachable("found no explanation for non-trivial member");
9313 /// TranslateIvarVisibility - Translate visibility from a token ID to an
9315 static ObjCIvarDecl::AccessControl
9316 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
9317 switch (ivarVisibility) {
9318 default: llvm_unreachable("Unknown visitibility kind");
9319 case tok::objc_private: return ObjCIvarDecl::Private;
9320 case tok::objc_public: return ObjCIvarDecl::Public;
9321 case tok::objc_protected: return ObjCIvarDecl::Protected;
9322 case tok::objc_package: return ObjCIvarDecl::Package;
9326 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
9327 /// in order to create an IvarDecl object for it.
9328 Decl *Sema::ActOnIvar(Scope *S,
9329 SourceLocation DeclStart,
9330 Declarator &D, Expr *BitfieldWidth,
9331 tok::ObjCKeywordKind Visibility) {
9333 IdentifierInfo *II = D.getIdentifier();
9334 Expr *BitWidth = (Expr*)BitfieldWidth;
9335 SourceLocation Loc = DeclStart;
9336 if (II) Loc = D.getIdentifierLoc();
9338 // FIXME: Unnamed fields can be handled in various different ways, for
9339 // example, unnamed unions inject all members into the struct namespace!
9341 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9342 QualType T = TInfo->getType();
9345 // 6.7.2.1p3, 6.7.2.1p4
9346 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take();
9355 if (T->isReferenceType()) {
9356 Diag(Loc, diag::err_ivar_reference_type);
9359 // C99 6.7.2.1p8: A member of a structure or union may have any type other
9360 // than a variably modified type.
9361 else if (T->isVariablyModifiedType()) {
9362 Diag(Loc, diag::err_typecheck_ivar_variable_size);
9366 // Get the visibility (access control) for this ivar.
9367 ObjCIvarDecl::AccessControl ac =
9368 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
9369 : ObjCIvarDecl::None;
9370 // Must set ivar's DeclContext to its enclosing interface.
9371 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
9372 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
9374 ObjCContainerDecl *EnclosingContext;
9375 if (ObjCImplementationDecl *IMPDecl =
9376 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9377 if (!LangOpts.ObjCNonFragileABI2) {
9378 // Case of ivar declared in an implementation. Context is that of its class.
9379 EnclosingContext = IMPDecl->getClassInterface();
9380 assert(EnclosingContext && "Implementation has no class interface!");
9383 EnclosingContext = EnclosingDecl;
9385 if (ObjCCategoryDecl *CDecl =
9386 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9387 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
9388 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
9392 EnclosingContext = EnclosingDecl;
9395 // Construct the decl.
9396 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
9397 DeclStart, Loc, II, T,
9398 TInfo, ac, (Expr *)BitfieldWidth);
9401 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
9403 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
9404 && !isa<TagDecl>(PrevDecl)) {
9405 Diag(Loc, diag::err_duplicate_member) << II;
9406 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9407 NewID->setInvalidDecl();
9411 // Process attributes attached to the ivar.
9412 ProcessDeclAttributes(S, NewID, D);
9414 if (D.isInvalidType())
9415 NewID->setInvalidDecl();
9417 // In ARC, infer 'retaining' for ivars of retainable type.
9418 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
9419 NewID->setInvalidDecl();
9421 if (D.getDeclSpec().isModulePrivateSpecified())
9422 NewID->setModulePrivate();
9425 // FIXME: When interfaces are DeclContexts, we'll need to add
9426 // these to the interface.
9428 IdResolver.AddDecl(NewID);
9434 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
9435 /// class and class extensions. For every class @interface and class
9436 /// extension @interface, if the last ivar is a bitfield of any type,
9437 /// then add an implicit `char :0` ivar to the end of that interface.
9438 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
9439 SmallVectorImpl<Decl *> &AllIvarDecls) {
9440 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty())
9443 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
9444 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
9446 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
9448 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
9450 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
9451 if (!CD->IsClassExtension())
9454 // No need to add this to end of @implementation.
9458 // All conditions are met. Add a new bitfield to the tail end of ivars.
9459 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
9460 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
9462 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
9463 DeclLoc, DeclLoc, 0,
9465 Context.getTrivialTypeSourceInfo(Context.CharTy,
9467 ObjCIvarDecl::Private, BW,
9469 AllIvarDecls.push_back(Ivar);
9472 void Sema::ActOnFields(Scope* S,
9473 SourceLocation RecLoc, Decl *EnclosingDecl,
9474 llvm::ArrayRef<Decl *> Fields,
9475 SourceLocation LBrac, SourceLocation RBrac,
9476 AttributeList *Attr) {
9477 assert(EnclosingDecl && "missing record or interface decl");
9479 // If the decl this is being inserted into is invalid, then it may be a
9480 // redeclaration or some other bogus case. Don't try to add fields to it.
9481 if (EnclosingDecl->isInvalidDecl())
9484 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
9486 // Start counting up the number of named members; make sure to include
9487 // members of anonymous structs and unions in the total.
9488 unsigned NumNamedMembers = 0;
9490 for (RecordDecl::decl_iterator i = Record->decls_begin(),
9491 e = Record->decls_end(); i != e; i++) {
9492 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
9493 if (IFD->getDeclName())
9498 // Verify that all the fields are okay.
9499 SmallVector<FieldDecl*, 32> RecFields;
9501 bool ARCErrReported = false;
9502 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
9504 FieldDecl *FD = cast<FieldDecl>(*i);
9506 // Get the type for the field.
9507 const Type *FDTy = FD->getType().getTypePtr();
9509 if (!FD->isAnonymousStructOrUnion()) {
9510 // Remember all fields written by the user.
9511 RecFields.push_back(FD);
9514 // If the field is already invalid for some reason, don't emit more
9515 // diagnostics about it.
9516 if (FD->isInvalidDecl()) {
9517 EnclosingDecl->setInvalidDecl();
9522 // A structure or union shall not contain a member with
9523 // incomplete or function type (hence, a structure shall not
9524 // contain an instance of itself, but may contain a pointer to
9525 // an instance of itself), except that the last member of a
9526 // structure with more than one named member may have incomplete
9527 // array type; such a structure (and any union containing,
9528 // possibly recursively, a member that is such a structure)
9529 // shall not be a member of a structure or an element of an
9531 if (FDTy->isFunctionType()) {
9532 // Field declared as a function.
9533 Diag(FD->getLocation(), diag::err_field_declared_as_function)
9534 << FD->getDeclName();
9535 FD->setInvalidDecl();
9536 EnclosingDecl->setInvalidDecl();
9538 } else if (FDTy->isIncompleteArrayType() && Record &&
9539 ((i + 1 == Fields.end() && !Record->isUnion()) ||
9540 ((getLangOpts().MicrosoftExt ||
9541 getLangOpts().CPlusPlus) &&
9542 (i + 1 == Fields.end() || Record->isUnion())))) {
9543 // Flexible array member.
9544 // Microsoft and g++ is more permissive regarding flexible array.
9545 // It will accept flexible array in union and also
9546 // as the sole element of a struct/class.
9547 if (getLangOpts().MicrosoftExt) {
9548 if (Record->isUnion())
9549 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms)
9550 << FD->getDeclName();
9551 else if (Fields.size() == 1)
9552 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms)
9553 << FD->getDeclName() << Record->getTagKind();
9554 } else if (getLangOpts().CPlusPlus) {
9555 if (Record->isUnion())
9556 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9557 << FD->getDeclName();
9558 else if (Fields.size() == 1)
9559 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu)
9560 << FD->getDeclName() << Record->getTagKind();
9561 } else if (!getLangOpts().C99) {
9562 if (Record->isUnion())
9563 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu)
9564 << FD->getDeclName();
9566 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
9567 << FD->getDeclName() << Record->getTagKind();
9568 } else if (NumNamedMembers < 1) {
9569 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
9570 << FD->getDeclName();
9571 FD->setInvalidDecl();
9572 EnclosingDecl->setInvalidDecl();
9575 if (!FD->getType()->isDependentType() &&
9576 !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
9577 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
9578 << FD->getDeclName() << FD->getType();
9579 FD->setInvalidDecl();
9580 EnclosingDecl->setInvalidDecl();
9583 // Okay, we have a legal flexible array member at the end of the struct.
9585 Record->setHasFlexibleArrayMember(true);
9586 } else if (!FDTy->isDependentType() &&
9587 RequireCompleteType(FD->getLocation(), FD->getType(),
9588 diag::err_field_incomplete)) {
9590 FD->setInvalidDecl();
9591 EnclosingDecl->setInvalidDecl();
9593 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
9594 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
9595 // If this is a member of a union, then entire union becomes "flexible".
9596 if (Record && Record->isUnion()) {
9597 Record->setHasFlexibleArrayMember(true);
9599 // If this is a struct/class and this is not the last element, reject
9600 // it. Note that GCC supports variable sized arrays in the middle of
9602 if (i + 1 != Fields.end())
9603 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
9604 << FD->getDeclName() << FD->getType();
9606 // We support flexible arrays at the end of structs in
9607 // other structs as an extension.
9608 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
9609 << FD->getDeclName();
9611 Record->setHasFlexibleArrayMember(true);
9615 if (Record && FDTTy->getDecl()->hasObjectMember())
9616 Record->setHasObjectMember(true);
9617 } else if (FDTy->isObjCObjectType()) {
9618 /// A field cannot be an Objective-c object
9619 Diag(FD->getLocation(), diag::err_statically_allocated_object)
9620 << FixItHint::CreateInsertion(FD->getLocation(), "*");
9621 QualType T = Context.getObjCObjectPointerType(FD->getType());
9624 else if (!getLangOpts().CPlusPlus) {
9625 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) {
9626 // It's an error in ARC if a field has lifetime.
9627 // We don't want to report this in a system header, though,
9628 // so we just make the field unavailable.
9629 // FIXME: that's really not sufficient; we need to make the type
9630 // itself invalid to, say, initialize or copy.
9631 QualType T = FD->getType();
9632 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
9633 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
9634 SourceLocation loc = FD->getLocation();
9635 if (getSourceManager().isInSystemHeader(loc)) {
9636 if (!FD->hasAttr<UnavailableAttr>()) {
9637 FD->addAttr(new (Context) UnavailableAttr(loc, Context,
9638 "this system field has retaining ownership"));
9641 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct)
9642 << T->isBlockPointerType();
9644 ARCErrReported = true;
9647 else if (getLangOpts().ObjC1 &&
9648 getLangOpts().getGC() != LangOptions::NonGC &&
9649 Record && !Record->hasObjectMember()) {
9650 if (FD->getType()->isObjCObjectPointerType() ||
9651 FD->getType().isObjCGCStrong())
9652 Record->setHasObjectMember(true);
9653 else if (Context.getAsArrayType(FD->getType())) {
9654 QualType BaseType = Context.getBaseElementType(FD->getType());
9655 if (BaseType->isRecordType() &&
9656 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
9657 Record->setHasObjectMember(true);
9658 else if (BaseType->isObjCObjectPointerType() ||
9659 BaseType.isObjCGCStrong())
9660 Record->setHasObjectMember(true);
9664 // Keep track of the number of named members.
9665 if (FD->getIdentifier())
9669 // Okay, we successfully defined 'Record'.
9671 bool Completed = false;
9672 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
9673 if (!CXXRecord->isInvalidDecl()) {
9674 // Set access bits correctly on the directly-declared conversions.
9675 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions();
9676 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end();
9678 Convs->setAccess(I, (*I)->getAccess());
9680 if (!CXXRecord->isDependentType()) {
9681 // Objective-C Automatic Reference Counting:
9682 // If a class has a non-static data member of Objective-C pointer
9683 // type (or array thereof), it is a non-POD type and its
9684 // default constructor (if any), copy constructor, copy assignment
9685 // operator, and destructor are non-trivial.
9687 // This rule is also handled by CXXRecordDecl::completeDefinition().
9688 // However, here we check whether this particular class is only
9689 // non-POD because of the presence of an Objective-C pointer member.
9690 // If so, objects of this type cannot be shared between code compiled
9691 // with instant objects and code compiled with manual retain/release.
9692 if (getLangOpts().ObjCAutoRefCount &&
9693 CXXRecord->hasObjectMember() &&
9694 CXXRecord->getLinkage() == ExternalLinkage) {
9695 if (CXXRecord->isPOD()) {
9696 Diag(CXXRecord->getLocation(),
9697 diag::warn_arc_non_pod_class_with_object_member)
9700 // FIXME: Fix-Its would be nice here, but finding a good location
9701 // for them is going to be tricky.
9702 if (CXXRecord->hasTrivialCopyConstructor())
9703 Diag(CXXRecord->getLocation(),
9704 diag::warn_arc_trivial_member_function_with_object_member)
9706 if (CXXRecord->hasTrivialCopyAssignment())
9707 Diag(CXXRecord->getLocation(),
9708 diag::warn_arc_trivial_member_function_with_object_member)
9710 if (CXXRecord->hasTrivialDestructor())
9711 Diag(CXXRecord->getLocation(),
9712 diag::warn_arc_trivial_member_function_with_object_member)
9717 // Adjust user-defined destructor exception spec.
9718 if (getLangOpts().CPlusPlus0x &&
9719 CXXRecord->hasUserDeclaredDestructor())
9720 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor());
9722 // Add any implicitly-declared members to this class.
9723 AddImplicitlyDeclaredMembersToClass(CXXRecord);
9725 // If we have virtual base classes, we may end up finding multiple
9726 // final overriders for a given virtual function. Check for this
9728 if (CXXRecord->getNumVBases()) {
9729 CXXFinalOverriderMap FinalOverriders;
9730 CXXRecord->getFinalOverriders(FinalOverriders);
9732 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
9733 MEnd = FinalOverriders.end();
9735 for (OverridingMethods::iterator SO = M->second.begin(),
9736 SOEnd = M->second.end();
9737 SO != SOEnd; ++SO) {
9738 assert(SO->second.size() > 0 &&
9739 "Virtual function without overridding functions?");
9740 if (SO->second.size() == 1)
9743 // C++ [class.virtual]p2:
9744 // In a derived class, if a virtual member function of a base
9745 // class subobject has more than one final overrider the
9746 // program is ill-formed.
9747 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
9748 << (NamedDecl *)M->first << Record;
9749 Diag(M->first->getLocation(),
9750 diag::note_overridden_virtual_function);
9751 for (OverridingMethods::overriding_iterator
9752 OM = SO->second.begin(),
9753 OMEnd = SO->second.end();
9755 Diag(OM->Method->getLocation(), diag::note_final_overrider)
9756 << (NamedDecl *)M->first << OM->Method->getParent();
9758 Record->setInvalidDecl();
9761 CXXRecord->completeDefinition(&FinalOverriders);
9769 Record->completeDefinition();
9771 // Now that the record is complete, do any delayed exception spec checks
9773 while (!DelayedDestructorExceptionSpecChecks.empty()) {
9774 const CXXDestructorDecl *Dtor =
9775 DelayedDestructorExceptionSpecChecks.back().first;
9776 if (Dtor->getParent() != Record)
9779 assert(!Dtor->getParent()->isDependentType() &&
9780 "Should not ever add destructors of templates into the list.");
9781 CheckOverridingFunctionExceptionSpec(Dtor,
9782 DelayedDestructorExceptionSpecChecks.back().second);
9783 DelayedDestructorExceptionSpecChecks.pop_back();
9787 ObjCIvarDecl **ClsFields =
9788 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
9789 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
9790 ID->setEndOfDefinitionLoc(RBrac);
9791 // Add ivar's to class's DeclContext.
9792 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9793 ClsFields[i]->setLexicalDeclContext(ID);
9794 ID->addDecl(ClsFields[i]);
9796 // Must enforce the rule that ivars in the base classes may not be
9798 if (ID->getSuperClass())
9799 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
9800 } else if (ObjCImplementationDecl *IMPDecl =
9801 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
9802 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
9803 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
9804 // Ivar declared in @implementation never belongs to the implementation.
9805 // Only it is in implementation's lexical context.
9806 ClsFields[I]->setLexicalDeclContext(IMPDecl);
9807 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
9808 IMPDecl->setIvarLBraceLoc(LBrac);
9809 IMPDecl->setIvarRBraceLoc(RBrac);
9810 } else if (ObjCCategoryDecl *CDecl =
9811 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
9812 // case of ivars in class extension; all other cases have been
9813 // reported as errors elsewhere.
9814 // FIXME. Class extension does not have a LocEnd field.
9815 // CDecl->setLocEnd(RBrac);
9816 // Add ivar's to class extension's DeclContext.
9817 // Diagnose redeclaration of private ivars.
9818 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
9819 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
9821 if (const ObjCIvarDecl *ClsIvar =
9822 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9823 Diag(ClsFields[i]->getLocation(),
9824 diag::err_duplicate_ivar_declaration);
9825 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
9828 for (const ObjCCategoryDecl *ClsExtDecl =
9829 IDecl->getFirstClassExtension();
9830 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
9831 if (const ObjCIvarDecl *ClsExtIvar =
9832 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
9833 Diag(ClsFields[i]->getLocation(),
9834 diag::err_duplicate_ivar_declaration);
9835 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
9840 ClsFields[i]->setLexicalDeclContext(CDecl);
9841 CDecl->addDecl(ClsFields[i]);
9843 CDecl->setIvarLBraceLoc(LBrac);
9844 CDecl->setIvarRBraceLoc(RBrac);
9849 ProcessDeclAttributeList(S, Record, Attr);
9851 // If there's a #pragma GCC visibility in scope, and this isn't a subclass,
9852 // set the visibility of this record.
9853 if (Record && !Record->getDeclContext()->isRecord())
9854 AddPushedVisibilityAttribute(Record);
9857 /// \brief Determine whether the given integral value is representable within
9858 /// the given type T.
9859 static bool isRepresentableIntegerValue(ASTContext &Context,
9860 llvm::APSInt &Value,
9862 assert(T->isIntegralType(Context) && "Integral type required!");
9863 unsigned BitWidth = Context.getIntWidth(T);
9865 if (Value.isUnsigned() || Value.isNonNegative()) {
9866 if (T->isSignedIntegerOrEnumerationType())
9868 return Value.getActiveBits() <= BitWidth;
9870 return Value.getMinSignedBits() <= BitWidth;
9873 // \brief Given an integral type, return the next larger integral type
9874 // (or a NULL type of no such type exists).
9875 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
9876 // FIXME: Int128/UInt128 support, which also needs to be introduced into
9877 // enum checking below.
9878 assert(T->isIntegralType(Context) && "Integral type required!");
9879 const unsigned NumTypes = 4;
9880 QualType SignedIntegralTypes[NumTypes] = {
9881 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
9883 QualType UnsignedIntegralTypes[NumTypes] = {
9884 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
9885 Context.UnsignedLongLongTy
9888 unsigned BitWidth = Context.getTypeSize(T);
9889 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
9890 : UnsignedIntegralTypes;
9891 for (unsigned I = 0; I != NumTypes; ++I)
9892 if (Context.getTypeSize(Types[I]) > BitWidth)
9898 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
9899 EnumConstantDecl *LastEnumConst,
9900 SourceLocation IdLoc,
9903 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
9904 llvm::APSInt EnumVal(IntWidth);
9907 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
9911 Val = DefaultLvalueConversion(Val).take();
9914 if (Enum->isDependentType() || Val->isTypeDependent())
9915 EltTy = Context.DependentTy;
9917 SourceLocation ExpLoc;
9918 if (getLangOpts().CPlusPlus0x && Enum->isFixed() &&
9919 !getLangOpts().MicrosoftMode) {
9920 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
9921 // constant-expression in the enumerator-definition shall be a converted
9922 // constant expression of the underlying type.
9923 EltTy = Enum->getIntegerType();
9924 ExprResult Converted =
9925 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
9927 if (Converted.isInvalid())
9930 Val = Converted.take();
9931 } else if (!Val->isValueDependent() &&
9932 !(Val = VerifyIntegerConstantExpression(Val,
9933 &EnumVal).take())) {
9934 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
9936 if (Enum->isFixed()) {
9937 EltTy = Enum->getIntegerType();
9939 // In Obj-C and Microsoft mode, require the enumeration value to be
9940 // representable in the underlying type of the enumeration. In C++11,
9941 // we perform a non-narrowing conversion as part of converted constant
9942 // expression checking.
9943 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
9944 if (getLangOpts().MicrosoftMode) {
9945 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
9946 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9948 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
9950 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
9951 } else if (getLangOpts().CPlusPlus) {
9952 // C++11 [dcl.enum]p5:
9953 // If the underlying type is not fixed, the type of each enumerator
9954 // is the type of its initializing value:
9955 // - If an initializer is specified for an enumerator, the
9956 // initializing value has the same type as the expression.
9957 EltTy = Val->getType();
9960 // The expression that defines the value of an enumeration constant
9961 // shall be an integer constant expression that has a value
9962 // representable as an int.
9964 // Complain if the value is not representable in an int.
9965 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
9966 Diag(IdLoc, diag::ext_enum_value_not_int)
9967 << EnumVal.toString(10) << Val->getSourceRange()
9968 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
9969 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
9970 // Force the type of the expression to 'int'.
9971 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
9973 EltTy = Val->getType();
9980 if (Enum->isDependentType())
9981 EltTy = Context.DependentTy;
9982 else if (!LastEnumConst) {
9983 // C++0x [dcl.enum]p5:
9984 // If the underlying type is not fixed, the type of each enumerator
9985 // is the type of its initializing value:
9986 // - If no initializer is specified for the first enumerator, the
9987 // initializing value has an unspecified integral type.
9989 // GCC uses 'int' for its unspecified integral type, as does
9991 if (Enum->isFixed()) {
9992 EltTy = Enum->getIntegerType();
9995 EltTy = Context.IntTy;
9998 // Assign the last value + 1.
9999 EnumVal = LastEnumConst->getInitVal();
10001 EltTy = LastEnumConst->getType();
10003 // Check for overflow on increment.
10004 if (EnumVal < LastEnumConst->getInitVal()) {
10005 // C++0x [dcl.enum]p5:
10006 // If the underlying type is not fixed, the type of each enumerator
10007 // is the type of its initializing value:
10009 // - Otherwise the type of the initializing value is the same as
10010 // the type of the initializing value of the preceding enumerator
10011 // unless the incremented value is not representable in that type,
10012 // in which case the type is an unspecified integral type
10013 // sufficient to contain the incremented value. If no such type
10014 // exists, the program is ill-formed.
10015 QualType T = getNextLargerIntegralType(Context, EltTy);
10016 if (T.isNull() || Enum->isFixed()) {
10017 // There is no integral type larger enough to represent this
10018 // value. Complain, then allow the value to wrap around.
10019 EnumVal = LastEnumConst->getInitVal();
10020 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
10022 if (Enum->isFixed())
10023 // When the underlying type is fixed, this is ill-formed.
10024 Diag(IdLoc, diag::err_enumerator_wrapped)
10025 << EnumVal.toString(10)
10028 Diag(IdLoc, diag::warn_enumerator_too_large)
10029 << EnumVal.toString(10);
10034 // Retrieve the last enumerator's value, extent that type to the
10035 // type that is supposed to be large enough to represent the incremented
10036 // value, then increment.
10037 EnumVal = LastEnumConst->getInitVal();
10038 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10039 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
10042 // If we're not in C++, diagnose the overflow of enumerator values,
10043 // which in C99 means that the enumerator value is not representable in
10044 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
10045 // permits enumerator values that are representable in some larger
10047 if (!getLangOpts().CPlusPlus && !T.isNull())
10048 Diag(IdLoc, diag::warn_enum_value_overflow);
10049 } else if (!getLangOpts().CPlusPlus &&
10050 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
10051 // Enforce C99 6.7.2.2p2 even when we compute the next value.
10052 Diag(IdLoc, diag::ext_enum_value_not_int)
10053 << EnumVal.toString(10) << 1;
10058 if (!EltTy->isDependentType()) {
10059 // Make the enumerator value match the signedness and size of the
10060 // enumerator's type.
10061 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
10062 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
10065 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
10070 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
10071 SourceLocation IdLoc, IdentifierInfo *Id,
10072 AttributeList *Attr,
10073 SourceLocation EqualLoc, Expr *Val) {
10074 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
10075 EnumConstantDecl *LastEnumConst =
10076 cast_or_null<EnumConstantDecl>(lastEnumConst);
10078 // The scope passed in may not be a decl scope. Zip up the scope tree until
10079 // we find one that is.
10080 S = getNonFieldDeclScope(S);
10082 // Verify that there isn't already something declared with this name in this
10084 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
10086 if (PrevDecl && PrevDecl->isTemplateParameter()) {
10087 // Maybe we will complain about the shadowed template parameter.
10088 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
10089 // Just pretend that we didn't see the previous declaration.
10094 // When in C++, we may get a TagDecl with the same name; in this case the
10095 // enum constant will 'hide' the tag.
10096 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
10097 "Received TagDecl when not in C++!");
10098 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
10099 if (isa<EnumConstantDecl>(PrevDecl))
10100 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
10102 Diag(IdLoc, diag::err_redefinition) << Id;
10103 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10108 // C++ [class.mem]p13:
10109 // If T is the name of a class, then each of the following shall have a
10110 // name different from T:
10111 // - every enumerator of every member of class T that is an enumerated
10113 if (CXXRecordDecl *Record
10114 = dyn_cast<CXXRecordDecl>(
10115 TheEnumDecl->getDeclContext()->getRedeclContext()))
10116 if (Record->getIdentifier() && Record->getIdentifier() == Id)
10117 Diag(IdLoc, diag::err_member_name_of_class) << Id;
10119 EnumConstantDecl *New =
10120 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
10123 // Process attributes.
10124 if (Attr) ProcessDeclAttributeList(S, New, Attr);
10126 // Register this decl in the current scope stack.
10127 New->setAccess(TheEnumDecl->getAccess());
10128 PushOnScopeChains(New, S);
10134 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
10135 SourceLocation RBraceLoc, Decl *EnumDeclX,
10136 Decl **Elements, unsigned NumElements,
10137 Scope *S, AttributeList *Attr) {
10138 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
10139 QualType EnumType = Context.getTypeDeclType(Enum);
10142 ProcessDeclAttributeList(S, Enum, Attr);
10144 if (Enum->isDependentType()) {
10145 for (unsigned i = 0; i != NumElements; ++i) {
10146 EnumConstantDecl *ECD =
10147 cast_or_null<EnumConstantDecl>(Elements[i]);
10148 if (!ECD) continue;
10150 ECD->setType(EnumType);
10153 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
10157 // TODO: If the result value doesn't fit in an int, it must be a long or long
10158 // long value. ISO C does not support this, but GCC does as an extension,
10160 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
10161 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
10162 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
10164 // Verify that all the values are okay, compute the size of the values, and
10165 // reverse the list.
10166 unsigned NumNegativeBits = 0;
10167 unsigned NumPositiveBits = 0;
10169 // Keep track of whether all elements have type int.
10170 bool AllElementsInt = true;
10172 for (unsigned i = 0; i != NumElements; ++i) {
10173 EnumConstantDecl *ECD =
10174 cast_or_null<EnumConstantDecl>(Elements[i]);
10175 if (!ECD) continue; // Already issued a diagnostic.
10177 const llvm::APSInt &InitVal = ECD->getInitVal();
10179 // Keep track of the size of positive and negative values.
10180 if (InitVal.isUnsigned() || InitVal.isNonNegative())
10181 NumPositiveBits = std::max(NumPositiveBits,
10182 (unsigned)InitVal.getActiveBits());
10184 NumNegativeBits = std::max(NumNegativeBits,
10185 (unsigned)InitVal.getMinSignedBits());
10187 // Keep track of whether every enum element has type int (very commmon).
10188 if (AllElementsInt)
10189 AllElementsInt = ECD->getType() == Context.IntTy;
10192 // Figure out the type that should be used for this enum.
10194 unsigned BestWidth;
10196 // C++0x N3000 [conv.prom]p3:
10197 // An rvalue of an unscoped enumeration type whose underlying
10198 // type is not fixed can be converted to an rvalue of the first
10199 // of the following types that can represent all the values of
10200 // the enumeration: int, unsigned int, long int, unsigned long
10201 // int, long long int, or unsigned long long int.
10203 // An identifier declared as an enumeration constant has type int.
10204 // The C99 rule is modified by a gcc extension
10205 QualType BestPromotionType;
10207 bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
10208 // -fshort-enums is the equivalent to specifying the packed attribute on all
10209 // enum definitions.
10210 if (LangOpts.ShortEnums)
10213 if (Enum->isFixed()) {
10214 BestType = Enum->getIntegerType();
10215 if (BestType->isPromotableIntegerType())
10216 BestPromotionType = Context.getPromotedIntegerType(BestType);
10218 BestPromotionType = BestType;
10219 // We don't need to set BestWidth, because BestType is going to be the type
10220 // of the enumerators, but we do anyway because otherwise some compilers
10221 // warn that it might be used uninitialized.
10222 BestWidth = CharWidth;
10224 else if (NumNegativeBits) {
10225 // If there is a negative value, figure out the smallest integer type (of
10226 // int/long/longlong) that fits.
10227 // If it's packed, check also if it fits a char or a short.
10228 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
10229 BestType = Context.SignedCharTy;
10230 BestWidth = CharWidth;
10231 } else if (Packed && NumNegativeBits <= ShortWidth &&
10232 NumPositiveBits < ShortWidth) {
10233 BestType = Context.ShortTy;
10234 BestWidth = ShortWidth;
10235 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
10236 BestType = Context.IntTy;
10237 BestWidth = IntWidth;
10239 BestWidth = Context.getTargetInfo().getLongWidth();
10241 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
10242 BestType = Context.LongTy;
10244 BestWidth = Context.getTargetInfo().getLongLongWidth();
10246 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
10247 Diag(Enum->getLocation(), diag::warn_enum_too_large);
10248 BestType = Context.LongLongTy;
10251 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
10253 // If there is no negative value, figure out the smallest type that fits
10254 // all of the enumerator values.
10255 // If it's packed, check also if it fits a char or a short.
10256 if (Packed && NumPositiveBits <= CharWidth) {
10257 BestType = Context.UnsignedCharTy;
10258 BestPromotionType = Context.IntTy;
10259 BestWidth = CharWidth;
10260 } else if (Packed && NumPositiveBits <= ShortWidth) {
10261 BestType = Context.UnsignedShortTy;
10262 BestPromotionType = Context.IntTy;
10263 BestWidth = ShortWidth;
10264 } else if (NumPositiveBits <= IntWidth) {
10265 BestType = Context.UnsignedIntTy;
10266 BestWidth = IntWidth;
10268 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10269 ? Context.UnsignedIntTy : Context.IntTy;
10270 } else if (NumPositiveBits <=
10271 (BestWidth = Context.getTargetInfo().getLongWidth())) {
10272 BestType = Context.UnsignedLongTy;
10274 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10275 ? Context.UnsignedLongTy : Context.LongTy;
10277 BestWidth = Context.getTargetInfo().getLongLongWidth();
10278 assert(NumPositiveBits <= BestWidth &&
10279 "How could an initializer get larger than ULL?");
10280 BestType = Context.UnsignedLongLongTy;
10282 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
10283 ? Context.UnsignedLongLongTy : Context.LongLongTy;
10287 // Loop over all of the enumerator constants, changing their types to match
10288 // the type of the enum if needed.
10289 for (unsigned i = 0; i != NumElements; ++i) {
10290 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
10291 if (!ECD) continue; // Already issued a diagnostic.
10293 // Standard C says the enumerators have int type, but we allow, as an
10294 // extension, the enumerators to be larger than int size. If each
10295 // enumerator value fits in an int, type it as an int, otherwise type it the
10296 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
10297 // that X has type 'int', not 'unsigned'.
10299 // Determine whether the value fits into an int.
10300 llvm::APSInt InitVal = ECD->getInitVal();
10302 // If it fits into an integer type, force it. Otherwise force it to match
10303 // the enum decl type.
10307 if (!getLangOpts().CPlusPlus &&
10308 !Enum->isFixed() &&
10309 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
10310 NewTy = Context.IntTy;
10311 NewWidth = IntWidth;
10313 } else if (ECD->getType() == BestType) {
10314 // Already the right type!
10315 if (getLangOpts().CPlusPlus)
10316 // C++ [dcl.enum]p4: Following the closing brace of an
10317 // enum-specifier, each enumerator has the type of its
10319 ECD->setType(EnumType);
10323 NewWidth = BestWidth;
10324 NewSign = BestType->isSignedIntegerOrEnumerationType();
10327 // Adjust the APSInt value.
10328 InitVal = InitVal.extOrTrunc(NewWidth);
10329 InitVal.setIsSigned(NewSign);
10330 ECD->setInitVal(InitVal);
10332 // Adjust the Expr initializer and type.
10333 if (ECD->getInitExpr() &&
10334 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
10335 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
10337 ECD->getInitExpr(),
10340 if (getLangOpts().CPlusPlus)
10341 // C++ [dcl.enum]p4: Following the closing brace of an
10342 // enum-specifier, each enumerator has the type of its
10344 ECD->setType(EnumType);
10346 ECD->setType(NewTy);
10349 Enum->completeDefinition(BestType, BestPromotionType,
10350 NumPositiveBits, NumNegativeBits);
10352 // If we're declaring a function, ensure this decl isn't forgotten about -
10353 // it needs to go into the function scope.
10354 if (InFunctionDeclarator)
10355 DeclsInPrototypeScope.push_back(Enum);
10359 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
10360 SourceLocation StartLoc,
10361 SourceLocation EndLoc) {
10362 StringLiteral *AsmString = cast<StringLiteral>(expr);
10364 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
10365 AsmString, StartLoc,
10367 CurContext->addDecl(New);
10371 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
10372 SourceLocation ImportLoc,
10373 ModuleIdPath Path) {
10374 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
10375 Module::AllVisible,
10376 /*IsIncludeDirective=*/false);
10380 llvm::SmallVector<SourceLocation, 2> IdentifierLocs;
10381 Module *ModCheck = Mod;
10382 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
10383 // If we've run out of module parents, just drop the remaining identifiers.
10384 // We need the length to be consistent.
10387 ModCheck = ModCheck->Parent;
10389 IdentifierLocs.push_back(Path[I].second);
10392 ImportDecl *Import = ImportDecl::Create(Context,
10393 Context.getTranslationUnitDecl(),
10394 AtLoc.isValid()? AtLoc : ImportLoc,
10395 Mod, IdentifierLocs);
10396 Context.getTranslationUnitDecl()->addDecl(Import);
10400 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
10401 IdentifierInfo* AliasName,
10402 SourceLocation PragmaLoc,
10403 SourceLocation NameLoc,
10404 SourceLocation AliasNameLoc) {
10405 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
10406 LookupOrdinaryName);
10407 AsmLabelAttr *Attr =
10408 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
10411 PrevDecl->addAttr(Attr);
10413 (void)ExtnameUndeclaredIdentifiers.insert(
10414 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
10417 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
10418 SourceLocation PragmaLoc,
10419 SourceLocation NameLoc) {
10420 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
10423 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
10425 (void)WeakUndeclaredIdentifiers.insert(
10426 std::pair<IdentifierInfo*,WeakInfo>
10427 (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
10431 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
10432 IdentifierInfo* AliasName,
10433 SourceLocation PragmaLoc,
10434 SourceLocation NameLoc,
10435 SourceLocation AliasNameLoc) {
10436 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
10437 LookupOrdinaryName);
10438 WeakInfo W = WeakInfo(Name, NameLoc);
10441 if (!PrevDecl->hasAttr<AliasAttr>())
10442 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
10443 DeclApplyPragmaWeak(TUScope, ND, W);
10445 (void)WeakUndeclaredIdentifiers.insert(
10446 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
10450 Decl *Sema::getObjCDeclContext() const {
10451 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
10454 AvailabilityResult Sema::getCurContextAvailability() const {
10455 const Decl *D = cast<Decl>(getCurLexicalContext());
10456 // A category implicitly has the availability of the interface.
10457 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
10458 D = CatD->getClassInterface();
10460 return D->getAvailability();