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 "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
51 using namespace clang;
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68 bool AllowTemplates=false)
69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70 AllowClassTemplates(AllowTemplates) {
71 WantExpressionKeywords = false;
72 WantCXXNamedCasts = false;
73 WantRemainingKeywords = false;
76 bool ValidateCandidate(const TypoCorrection &candidate) override {
77 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80 return (IsType || AllowedTemplate) &&
81 (AllowInvalidDecl || !ND->isInvalidDecl());
83 return !WantClassName && candidate.isKeyword();
87 bool AllowInvalidDecl;
89 bool AllowClassTemplates;
92 } // end anonymous namespace
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
97 // FIXME: Take into account the current language when deciding whether a
98 // token kind is a valid type specifier
101 case tok::kw___int64:
102 case tok::kw___int128:
104 case tok::kw_unsigned:
111 case tok::kw___float128:
112 case tok::kw_wchar_t:
114 case tok::kw___underlying_type:
115 case tok::kw___auto_type:
118 case tok::annot_typename:
119 case tok::kw_char16_t:
120 case tok::kw_char32_t:
122 case tok::annot_decltype:
123 case tok::kw_decltype:
124 return getLangOpts().CPlusPlus;
134 enum class UnqualifiedTypeNameLookupResult {
139 } // end anonymous namespace
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147 SourceLocation NameLoc,
148 const CXXRecordDecl *RD) {
149 if (!RD->hasDefinition())
150 return UnqualifiedTypeNameLookupResult::NotFound;
151 // Look for type decls in base classes.
152 UnqualifiedTypeNameLookupResult FoundTypeDecl =
153 UnqualifiedTypeNameLookupResult::NotFound;
154 for (const auto &Base : RD->bases()) {
155 const CXXRecordDecl *BaseRD = nullptr;
156 if (auto *BaseTT = Base.getType()->getAs<TagType>())
157 BaseRD = BaseTT->getAsCXXRecordDecl();
158 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159 // Look for type decls in dependent base classes that have known primary
161 if (!TST || !TST->isDependentType())
163 auto *TD = TST->getTemplateName().getAsTemplateDecl();
166 auto *BasePrimaryTemplate =
167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
168 if (!BasePrimaryTemplate)
170 BaseRD = BasePrimaryTemplate;
173 for (NamedDecl *ND : BaseRD->lookup(&II)) {
174 if (!isa<TypeDecl>(ND))
175 return UnqualifiedTypeNameLookupResult::FoundNonType;
176 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
178 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
179 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
180 case UnqualifiedTypeNameLookupResult::FoundNonType:
181 return UnqualifiedTypeNameLookupResult::FoundNonType;
182 case UnqualifiedTypeNameLookupResult::FoundType:
183 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
185 case UnqualifiedTypeNameLookupResult::NotFound:
192 return FoundTypeDecl;
195 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
196 const IdentifierInfo &II,
197 SourceLocation NameLoc) {
198 // Lookup in the parent class template context, if any.
199 const CXXRecordDecl *RD = nullptr;
200 UnqualifiedTypeNameLookupResult FoundTypeDecl =
201 UnqualifiedTypeNameLookupResult::NotFound;
202 for (DeclContext *DC = S.CurContext;
203 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
204 DC = DC->getParent()) {
205 // Look for type decls in dependent base classes that have known primary
207 RD = dyn_cast<CXXRecordDecl>(DC);
208 if (RD && RD->getDescribedClassTemplate())
209 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
211 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
214 // We found some types in dependent base classes. Recover as if the user
215 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
216 // lookup during template instantiation.
217 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
219 ASTContext &Context = S.Context;
220 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
221 cast<Type>(Context.getRecordType(RD)));
222 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
225 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
227 TypeLocBuilder Builder;
228 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
229 DepTL.setNameLoc(NameLoc);
230 DepTL.setElaboratedKeywordLoc(SourceLocation());
231 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
232 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
235 /// \brief If the identifier refers to a type name within this scope,
236 /// return the declaration of that type.
238 /// This routine performs ordinary name lookup of the identifier II
239 /// within the given scope, with optional C++ scope specifier SS, to
240 /// determine whether the name refers to a type. If so, returns an
241 /// opaque pointer (actually a QualType) corresponding to that
242 /// type. Otherwise, returns NULL.
243 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
244 Scope *S, CXXScopeSpec *SS,
245 bool isClassName, bool HasTrailingDot,
246 ParsedType ObjectTypePtr,
247 bool IsCtorOrDtorName,
248 bool WantNontrivialTypeSourceInfo,
249 IdentifierInfo **CorrectedII) {
250 // Determine where we will perform name lookup.
251 DeclContext *LookupCtx = nullptr;
253 QualType ObjectType = ObjectTypePtr.get();
254 if (ObjectType->isRecordType())
255 LookupCtx = computeDeclContext(ObjectType);
256 } else if (SS && SS->isNotEmpty()) {
257 LookupCtx = computeDeclContext(*SS, false);
260 if (isDependentScopeSpecifier(*SS)) {
262 // A qualified-id that refers to a type and in which the
263 // nested-name-specifier depends on a template-parameter (14.6.2)
264 // shall be prefixed by the keyword typename to indicate that the
265 // qualified-id denotes a type, forming an
266 // elaborated-type-specifier (7.1.5.3).
268 // We therefore do not perform any name lookup if the result would
269 // refer to a member of an unknown specialization.
270 if (!isClassName && !IsCtorOrDtorName)
273 // We know from the grammar that this name refers to a type,
274 // so build a dependent node to describe the type.
275 if (WantNontrivialTypeSourceInfo)
276 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
278 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
279 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
281 return ParsedType::make(T);
287 if (!LookupCtx->isDependentContext() &&
288 RequireCompleteDeclContext(*SS, LookupCtx))
292 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
293 // lookup for class-names.
294 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
296 LookupResult Result(*this, &II, NameLoc, Kind);
298 // Perform "qualified" name lookup into the declaration context we
299 // computed, which is either the type of the base of a member access
300 // expression or the declaration context associated with a prior
301 // nested-name-specifier.
302 LookupQualifiedName(Result, LookupCtx);
304 if (ObjectTypePtr && Result.empty()) {
305 // C++ [basic.lookup.classref]p3:
306 // If the unqualified-id is ~type-name, the type-name is looked up
307 // in the context of the entire postfix-expression. If the type T of
308 // the object expression is of a class type C, the type-name is also
309 // looked up in the scope of class C. At least one of the lookups shall
310 // find a name that refers to (possibly cv-qualified) T.
311 LookupName(Result, S);
314 // Perform unqualified name lookup.
315 LookupName(Result, S);
317 // For unqualified lookup in a class template in MSVC mode, look into
318 // dependent base classes where the primary class template is known.
319 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
320 if (ParsedType TypeInBase =
321 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
326 NamedDecl *IIDecl = nullptr;
327 switch (Result.getResultKind()) {
328 case LookupResult::NotFound:
329 case LookupResult::NotFoundInCurrentInstantiation:
331 TypoCorrection Correction = CorrectTypo(
332 Result.getLookupNameInfo(), Kind, S, SS,
333 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
335 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
337 bool MemberOfUnknownSpecialization;
338 UnqualifiedId TemplateName;
339 TemplateName.setIdentifier(NewII, NameLoc);
340 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
341 CXXScopeSpec NewSS, *NewSSPtr = SS;
343 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
346 if (Correction && (NNS || NewII != &II) &&
347 // Ignore a correction to a template type as the to-be-corrected
348 // identifier is not a template (typo correction for template names
349 // is handled elsewhere).
350 !(getLangOpts().CPlusPlus && NewSSPtr &&
351 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
352 Template, MemberOfUnknownSpecialization))) {
353 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
354 isClassName, HasTrailingDot, ObjectTypePtr,
356 WantNontrivialTypeSourceInfo);
358 diagnoseTypo(Correction,
359 PDiag(diag::err_unknown_type_or_class_name_suggest)
360 << Result.getLookupName() << isClassName);
362 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
363 *CorrectedII = NewII;
368 // If typo correction failed or was not performed, fall through
369 case LookupResult::FoundOverloaded:
370 case LookupResult::FoundUnresolvedValue:
371 Result.suppressDiagnostics();
374 case LookupResult::Ambiguous:
375 // Recover from type-hiding ambiguities by hiding the type. We'll
376 // do the lookup again when looking for an object, and we can
377 // diagnose the error then. If we don't do this, then the error
378 // about hiding the type will be immediately followed by an error
379 // that only makes sense if the identifier was treated like a type.
380 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
381 Result.suppressDiagnostics();
385 // Look to see if we have a type anywhere in the list of results.
386 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
387 Res != ResEnd; ++Res) {
388 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
390 (*Res)->getLocation().getRawEncoding() <
391 IIDecl->getLocation().getRawEncoding())
397 // None of the entities we found is a type, so there is no way
398 // to even assume that the result is a type. In this case, don't
399 // complain about the ambiguity. The parser will either try to
400 // perform this lookup again (e.g., as an object name), which
401 // will produce the ambiguity, or will complain that it expected
403 Result.suppressDiagnostics();
407 // We found a type within the ambiguous lookup; diagnose the
408 // ambiguity and then return that type. This might be the right
409 // answer, or it might not be, but it suppresses any attempt to
410 // perform the name lookup again.
413 case LookupResult::Found:
414 IIDecl = Result.getFoundDecl();
418 assert(IIDecl && "Didn't find decl");
421 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
422 DiagnoseUseOfDecl(IIDecl, NameLoc);
424 T = Context.getTypeDeclType(TD);
425 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
427 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
428 // constructor or destructor name (in such a case, the scope specifier
429 // will be attached to the enclosing Expr or Decl node).
430 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
431 if (WantNontrivialTypeSourceInfo) {
432 // Construct a type with type-source information.
433 TypeLocBuilder Builder;
434 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
436 T = getElaboratedType(ETK_None, *SS, T);
437 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
438 ElabTL.setElaboratedKeywordLoc(SourceLocation());
439 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
440 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
442 T = getElaboratedType(ETK_None, *SS, T);
445 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
446 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
448 T = Context.getObjCInterfaceType(IDecl);
452 // If it's not plausibly a type, suppress diagnostics.
453 Result.suppressDiagnostics();
456 return ParsedType::make(T);
459 // Builds a fake NNS for the given decl context.
460 static NestedNameSpecifier *
461 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
462 for (;; DC = DC->getLookupParent()) {
463 DC = DC->getPrimaryContext();
464 auto *ND = dyn_cast<NamespaceDecl>(DC);
465 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
466 return NestedNameSpecifier::Create(Context, nullptr, ND);
467 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
468 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
469 RD->getTypeForDecl());
470 else if (isa<TranslationUnitDecl>(DC))
471 return NestedNameSpecifier::GlobalSpecifier(Context);
473 llvm_unreachable("something isn't in TU scope?");
476 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
477 SourceLocation NameLoc) {
478 // Accepting an undeclared identifier as a default argument for a template
479 // type parameter is a Microsoft extension.
480 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
482 // Build a fake DependentNameType that will perform lookup into CurContext at
483 // instantiation time. The name specifier isn't dependent, so template
484 // instantiation won't transform it. It will retry the lookup, however.
485 NestedNameSpecifier *NNS =
486 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
487 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
489 // Build type location information. We synthesized the qualifier, so we have
490 // to build a fake NestedNameSpecifierLoc.
491 NestedNameSpecifierLocBuilder NNSLocBuilder;
492 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
493 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
495 TypeLocBuilder Builder;
496 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
497 DepTL.setNameLoc(NameLoc);
498 DepTL.setElaboratedKeywordLoc(SourceLocation());
499 DepTL.setQualifierLoc(QualifierLoc);
500 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
503 /// isTagName() - This method is called *for error recovery purposes only*
504 /// to determine if the specified name is a valid tag name ("struct foo"). If
505 /// so, this returns the TST for the tag corresponding to it (TST_enum,
506 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
507 /// cases in C where the user forgot to specify the tag.
508 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
509 // Do a tag name lookup in this scope.
510 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
511 LookupName(R, S, false);
512 R.suppressDiagnostics();
513 if (R.getResultKind() == LookupResult::Found)
514 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
515 switch (TD->getTagKind()) {
516 case TTK_Struct: return DeclSpec::TST_struct;
517 case TTK_Interface: return DeclSpec::TST_interface;
518 case TTK_Union: return DeclSpec::TST_union;
519 case TTK_Class: return DeclSpec::TST_class;
520 case TTK_Enum: return DeclSpec::TST_enum;
524 return DeclSpec::TST_unspecified;
527 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
528 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
529 /// then downgrade the missing typename error to a warning.
530 /// This is needed for MSVC compatibility; Example:
532 /// template<class T> class A {
534 /// typedef int TYPE;
536 /// template<class T> class B : public A<T> {
538 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
541 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
542 if (CurContext->isRecord()) {
543 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
546 const Type *Ty = SS->getScopeRep()->getAsType();
548 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
549 for (const auto &Base : RD->bases())
550 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
552 return S->isFunctionPrototypeScope();
554 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
557 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
558 SourceLocation IILoc,
561 ParsedType &SuggestedType,
562 bool AllowClassTemplates) {
563 // We don't have anything to suggest (yet).
564 SuggestedType = nullptr;
566 // There may have been a typo in the name of the type. Look up typo
567 // results, in case we have something that we can suggest.
568 if (TypoCorrection Corrected =
569 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
570 llvm::make_unique<TypeNameValidatorCCC>(
571 false, false, AllowClassTemplates),
572 CTK_ErrorRecovery)) {
573 if (Corrected.isKeyword()) {
574 // We corrected to a keyword.
575 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
576 II = Corrected.getCorrectionAsIdentifierInfo();
578 // We found a similarly-named type or interface; suggest that.
579 if (!SS || !SS->isSet()) {
580 diagnoseTypo(Corrected,
581 PDiag(diag::err_unknown_typename_suggest) << II);
582 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
583 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
584 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
585 II->getName().equals(CorrectedStr);
586 diagnoseTypo(Corrected,
587 PDiag(diag::err_unknown_nested_typename_suggest)
588 << II << DC << DroppedSpecifier << SS->getRange());
590 llvm_unreachable("could not have corrected a typo here");
594 if (Corrected.getCorrectionSpecifier())
595 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
598 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
599 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
600 /*IsCtorOrDtorName=*/false,
601 /*NonTrivialTypeSourceInfo=*/true);
606 if (getLangOpts().CPlusPlus) {
607 // See if II is a class template that the user forgot to pass arguments to.
609 Name.setIdentifier(II, IILoc);
610 CXXScopeSpec EmptySS;
611 TemplateTy TemplateResult;
612 bool MemberOfUnknownSpecialization;
613 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
614 Name, nullptr, true, TemplateResult,
615 MemberOfUnknownSpecialization) == TNK_Type_template) {
616 TemplateName TplName = TemplateResult.get();
617 Diag(IILoc, diag::err_template_missing_args) << TplName;
618 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
619 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
620 << TplDecl->getTemplateParameters()->getSourceRange();
626 // FIXME: Should we move the logic that tries to recover from a missing tag
627 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
629 if (!SS || (!SS->isSet() && !SS->isInvalid()))
630 Diag(IILoc, diag::err_unknown_typename) << II;
631 else if (DeclContext *DC = computeDeclContext(*SS, false))
632 Diag(IILoc, diag::err_typename_nested_not_found)
633 << II << DC << SS->getRange();
634 else if (isDependentScopeSpecifier(*SS)) {
635 unsigned DiagID = diag::err_typename_missing;
636 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
637 DiagID = diag::ext_typename_missing;
639 Diag(SS->getRange().getBegin(), DiagID)
640 << SS->getScopeRep() << II->getName()
641 << SourceRange(SS->getRange().getBegin(), IILoc)
642 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
643 SuggestedType = ActOnTypenameType(S, SourceLocation(),
644 *SS, *II, IILoc).get();
646 assert(SS && SS->isInvalid() &&
647 "Invalid scope specifier has already been diagnosed");
651 /// \brief Determine whether the given result set contains either a type name
653 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
654 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
655 NextToken.is(tok::less);
657 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
658 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
661 if (CheckTemplate && isa<TemplateDecl>(*I))
668 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
669 Scope *S, CXXScopeSpec &SS,
670 IdentifierInfo *&Name,
671 SourceLocation NameLoc) {
672 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
673 SemaRef.LookupParsedName(R, S, &SS);
674 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
675 StringRef FixItTagName;
676 switch (Tag->getTagKind()) {
678 FixItTagName = "class ";
682 FixItTagName = "enum ";
686 FixItTagName = "struct ";
690 FixItTagName = "__interface ";
694 FixItTagName = "union ";
698 StringRef TagName = FixItTagName.drop_back();
699 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
700 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
701 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
703 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
705 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
708 // Replace lookup results with just the tag decl.
709 Result.clear(Sema::LookupTagName);
710 SemaRef.LookupParsedName(Result, S, &SS);
717 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
718 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
719 QualType T, SourceLocation NameLoc) {
720 ASTContext &Context = S.Context;
722 TypeLocBuilder Builder;
723 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
725 T = S.getElaboratedType(ETK_None, SS, T);
726 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
727 ElabTL.setElaboratedKeywordLoc(SourceLocation());
728 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
729 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
732 Sema::NameClassification
733 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
734 SourceLocation NameLoc, const Token &NextToken,
735 bool IsAddressOfOperand,
736 std::unique_ptr<CorrectionCandidateCallback> CCC) {
737 DeclarationNameInfo NameInfo(Name, NameLoc);
738 ObjCMethodDecl *CurMethod = getCurMethodDecl();
740 if (NextToken.is(tok::coloncolon)) {
741 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
742 QualType(), false, SS, nullptr, false);
745 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
746 LookupParsedName(Result, S, &SS, !CurMethod);
748 // For unqualified lookup in a class template in MSVC mode, look into
749 // dependent base classes where the primary class template is known.
750 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
751 if (ParsedType TypeInBase =
752 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
756 // Perform lookup for Objective-C instance variables (including automatically
757 // synthesized instance variables), if we're in an Objective-C method.
758 // FIXME: This lookup really, really needs to be folded in to the normal
759 // unqualified lookup mechanism.
760 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
761 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
762 if (E.get() || E.isInvalid())
766 bool SecondTry = false;
767 bool IsFilteredTemplateName = false;
770 switch (Result.getResultKind()) {
771 case LookupResult::NotFound:
772 // If an unqualified-id is followed by a '(', then we have a function
774 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
775 // In C++, this is an ADL-only call.
777 if (getLangOpts().CPlusPlus)
778 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
781 // If the expression that precedes the parenthesized argument list in a
782 // function call consists solely of an identifier, and if no
783 // declaration is visible for this identifier, the identifier is
784 // implicitly declared exactly as if, in the innermost block containing
785 // the function call, the declaration
787 // extern int identifier ();
791 // We also allow this in C99 as an extension.
792 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
794 Result.resolveKind();
795 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
799 // In C, we first see whether there is a tag type by the same name, in
800 // which case it's likely that the user just forgot to write "enum",
801 // "struct", or "union".
802 if (!getLangOpts().CPlusPlus && !SecondTry &&
803 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
807 // Perform typo correction to determine if there is another name that is
808 // close to this name.
809 if (!SecondTry && CCC) {
811 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
812 Result.getLookupKind(), S,
814 CTK_ErrorRecovery)) {
815 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
816 unsigned QualifiedDiag = diag::err_no_member_suggest;
818 NamedDecl *FirstDecl = Corrected.getFoundDecl();
819 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
820 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
821 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
822 UnqualifiedDiag = diag::err_no_template_suggest;
823 QualifiedDiag = diag::err_no_member_template_suggest;
824 } else if (UnderlyingFirstDecl &&
825 (isa<TypeDecl>(UnderlyingFirstDecl) ||
826 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
827 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
828 UnqualifiedDiag = diag::err_unknown_typename_suggest;
829 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
833 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
834 } else {// FIXME: is this even reachable? Test it.
835 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
836 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
837 Name->getName().equals(CorrectedStr);
838 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
839 << Name << computeDeclContext(SS, false)
840 << DroppedSpecifier << SS.getRange());
843 // Update the name, so that the caller has the new name.
844 Name = Corrected.getCorrectionAsIdentifierInfo();
846 // Typo correction corrected to a keyword.
847 if (Corrected.isKeyword())
850 // Also update the LookupResult...
851 // FIXME: This should probably go away at some point
853 Result.setLookupName(Corrected.getCorrection());
855 Result.addDecl(FirstDecl);
857 // If we found an Objective-C instance variable, let
858 // LookupInObjCMethod build the appropriate expression to
859 // reference the ivar.
860 // FIXME: This is a gross hack.
861 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
863 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
871 // We failed to correct; just fall through and let the parser deal with it.
872 Result.suppressDiagnostics();
873 return NameClassification::Unknown();
875 case LookupResult::NotFoundInCurrentInstantiation: {
876 // We performed name lookup into the current instantiation, and there were
877 // dependent bases, so we treat this result the same way as any other
878 // dependent nested-name-specifier.
881 // A name used in a template declaration or definition and that is
882 // dependent on a template-parameter is assumed not to name a type
883 // unless the applicable name lookup finds a type name or the name is
884 // qualified by the keyword typename.
886 // FIXME: If the next token is '<', we might want to ask the parser to
887 // perform some heroics to see if we actually have a
888 // template-argument-list, which would indicate a missing 'template'
890 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
891 NameInfo, IsAddressOfOperand,
892 /*TemplateArgs=*/nullptr);
895 case LookupResult::Found:
896 case LookupResult::FoundOverloaded:
897 case LookupResult::FoundUnresolvedValue:
900 case LookupResult::Ambiguous:
901 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
902 hasAnyAcceptableTemplateNames(Result)) {
903 // C++ [temp.local]p3:
904 // A lookup that finds an injected-class-name (10.2) can result in an
905 // ambiguity in certain cases (for example, if it is found in more than
906 // one base class). If all of the injected-class-names that are found
907 // refer to specializations of the same class template, and if the name
908 // is followed by a template-argument-list, the reference refers to the
909 // class template itself and not a specialization thereof, and is not
912 // This filtering can make an ambiguous result into an unambiguous one,
913 // so try again after filtering out template names.
914 FilterAcceptableTemplateNames(Result);
915 if (!Result.isAmbiguous()) {
916 IsFilteredTemplateName = true;
921 // Diagnose the ambiguity and return an error.
922 return NameClassification::Error();
925 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
926 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
927 // C++ [temp.names]p3:
928 // After name lookup (3.4) finds that a name is a template-name or that
929 // an operator-function-id or a literal- operator-id refers to a set of
930 // overloaded functions any member of which is a function template if
931 // this is followed by a <, the < is always taken as the delimiter of a
932 // template-argument-list and never as the less-than operator.
933 if (!IsFilteredTemplateName)
934 FilterAcceptableTemplateNames(Result);
936 if (!Result.empty()) {
937 bool IsFunctionTemplate;
939 TemplateName Template;
940 if (Result.end() - Result.begin() > 1) {
941 IsFunctionTemplate = true;
942 Template = Context.getOverloadedTemplateName(Result.begin(),
946 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
947 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
948 IsVarTemplate = isa<VarTemplateDecl>(TD);
950 if (SS.isSet() && !SS.isInvalid())
951 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
952 /*TemplateKeyword=*/false,
955 Template = TemplateName(TD);
958 if (IsFunctionTemplate) {
959 // Function templates always go through overload resolution, at which
960 // point we'll perform the various checks (e.g., accessibility) we need
961 // to based on which function we selected.
962 Result.suppressDiagnostics();
964 return NameClassification::FunctionTemplate(Template);
967 return IsVarTemplate ? NameClassification::VarTemplate(Template)
968 : NameClassification::TypeTemplate(Template);
972 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
973 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
974 DiagnoseUseOfDecl(Type, NameLoc);
975 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
976 QualType T = Context.getTypeDeclType(Type);
978 return buildNestedType(*this, SS, T, NameLoc);
979 return ParsedType::make(T);
982 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
984 // FIXME: It's unfortunate that we don't have a Type node for handling this.
985 if (ObjCCompatibleAliasDecl *Alias =
986 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
987 Class = Alias->getClassInterface();
991 DiagnoseUseOfDecl(Class, NameLoc);
993 if (NextToken.is(tok::period)) {
994 // Interface. <something> is parsed as a property reference expression.
995 // Just return "unknown" as a fall-through for now.
996 Result.suppressDiagnostics();
997 return NameClassification::Unknown();
1000 QualType T = Context.getObjCInterfaceType(Class);
1001 return ParsedType::make(T);
1004 // We can have a type template here if we're classifying a template argument.
1005 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1006 return NameClassification::TypeTemplate(
1007 TemplateName(cast<TemplateDecl>(FirstDecl)));
1009 // Check for a tag type hidden by a non-type decl in a few cases where it
1010 // seems likely a type is wanted instead of the non-type that was found.
1011 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1012 if ((NextToken.is(tok::identifier) ||
1014 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1015 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1016 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1017 DiagnoseUseOfDecl(Type, NameLoc);
1018 QualType T = Context.getTypeDeclType(Type);
1019 if (SS.isNotEmpty())
1020 return buildNestedType(*this, SS, T, NameLoc);
1021 return ParsedType::make(T);
1024 if (FirstDecl->isCXXClassMember())
1025 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1028 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1029 return BuildDeclarationNameExpr(SS, Result, ADL);
1032 // Determines the context to return to after temporarily entering a
1033 // context. This depends in an unnecessarily complicated way on the
1034 // exact ordering of callbacks from the parser.
1035 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1037 // Functions defined inline within classes aren't parsed until we've
1038 // finished parsing the top-level class, so the top-level class is
1039 // the context we'll need to return to.
1040 // A Lambda call operator whose parent is a class must not be treated
1041 // as an inline member function. A Lambda can be used legally
1042 // either as an in-class member initializer or a default argument. These
1043 // are parsed once the class has been marked complete and so the containing
1044 // context would be the nested class (when the lambda is defined in one);
1045 // If the class is not complete, then the lambda is being used in an
1046 // ill-formed fashion (such as to specify the width of a bit-field, or
1047 // in an array-bound) - in which case we still want to return the
1048 // lexically containing DC (which could be a nested class).
1049 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1050 DC = DC->getLexicalParent();
1052 // A function not defined within a class will always return to its
1054 if (!isa<CXXRecordDecl>(DC))
1057 // A C++ inline method/friend is parsed *after* the topmost class
1058 // it was declared in is fully parsed ("complete"); the topmost
1059 // class is the context we need to return to.
1060 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1063 // Return the declaration context of the topmost class the inline method is
1068 return DC->getLexicalParent();
1071 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1072 assert(getContainingDC(DC) == CurContext &&
1073 "The next DeclContext should be lexically contained in the current one.");
1078 void Sema::PopDeclContext() {
1079 assert(CurContext && "DeclContext imbalance!");
1081 CurContext = getContainingDC(CurContext);
1082 assert(CurContext && "Popped translation unit!");
1085 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1087 // Unlike PushDeclContext, the context to which we return is not necessarily
1088 // the containing DC of TD, because the new context will be some pre-existing
1089 // TagDecl definition instead of a fresh one.
1090 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1091 CurContext = cast<TagDecl>(D)->getDefinition();
1092 assert(CurContext && "skipping definition of undefined tag");
1093 // Start lookups from the parent of the current context; we don't want to look
1094 // into the pre-existing complete definition.
1095 S->setEntity(CurContext->getLookupParent());
1099 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1100 CurContext = static_cast<decltype(CurContext)>(Context);
1103 /// EnterDeclaratorContext - Used when we must lookup names in the context
1104 /// of a declarator's nested name specifier.
1106 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1107 // C++0x [basic.lookup.unqual]p13:
1108 // A name used in the definition of a static data member of class
1109 // X (after the qualified-id of the static member) is looked up as
1110 // if the name was used in a member function of X.
1111 // C++0x [basic.lookup.unqual]p14:
1112 // If a variable member of a namespace is defined outside of the
1113 // scope of its namespace then any name used in the definition of
1114 // the variable member (after the declarator-id) is looked up as
1115 // if the definition of the variable member occurred in its
1117 // Both of these imply that we should push a scope whose context
1118 // is the semantic context of the declaration. We can't use
1119 // PushDeclContext here because that context is not necessarily
1120 // lexically contained in the current context. Fortunately,
1121 // the containing scope should have the appropriate information.
1123 assert(!S->getEntity() && "scope already has entity");
1126 Scope *Ancestor = S->getParent();
1127 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1128 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1135 void Sema::ExitDeclaratorContext(Scope *S) {
1136 assert(S->getEntity() == CurContext && "Context imbalance!");
1138 // Switch back to the lexical context. The safety of this is
1139 // enforced by an assert in EnterDeclaratorContext.
1140 Scope *Ancestor = S->getParent();
1141 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1142 CurContext = Ancestor->getEntity();
1144 // We don't need to do anything with the scope, which is going to
1148 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1149 // We assume that the caller has already called
1150 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1151 FunctionDecl *FD = D->getAsFunction();
1155 // Same implementation as PushDeclContext, but enters the context
1156 // from the lexical parent, rather than the top-level class.
1157 assert(CurContext == FD->getLexicalParent() &&
1158 "The next DeclContext should be lexically contained in the current one.");
1160 S->setEntity(CurContext);
1162 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1163 ParmVarDecl *Param = FD->getParamDecl(P);
1164 // If the parameter has an identifier, then add it to the scope
1165 if (Param->getIdentifier()) {
1167 IdResolver.AddDecl(Param);
1172 void Sema::ActOnExitFunctionContext() {
1173 // Same implementation as PopDeclContext, but returns to the lexical parent,
1174 // rather than the top-level class.
1175 assert(CurContext && "DeclContext imbalance!");
1176 CurContext = CurContext->getLexicalParent();
1177 assert(CurContext && "Popped translation unit!");
1180 /// \brief Determine whether we allow overloading of the function
1181 /// PrevDecl with another declaration.
1183 /// This routine determines whether overloading is possible, not
1184 /// whether some new function is actually an overload. It will return
1185 /// true in C++ (where we can always provide overloads) or, as an
1186 /// extension, in C when the previous function is already an
1187 /// overloaded function declaration or has the "overloadable"
1189 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1190 ASTContext &Context) {
1191 if (Context.getLangOpts().CPlusPlus)
1194 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1197 return (Previous.getResultKind() == LookupResult::Found
1198 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1201 /// Add this decl to the scope shadowed decl chains.
1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1203 // Move up the scope chain until we find the nearest enclosing
1204 // non-transparent context. The declaration will be introduced into this
1206 while (S->getEntity() && S->getEntity()->isTransparentContext())
1209 // Add scoped declarations into their context, so that they can be
1210 // found later. Declarations without a context won't be inserted
1211 // into any context.
1213 CurContext->addDecl(D);
1215 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1216 // are function-local declarations.
1217 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1218 !D->getDeclContext()->getRedeclContext()->Equals(
1219 D->getLexicalDeclContext()->getRedeclContext()) &&
1220 !D->getLexicalDeclContext()->isFunctionOrMethod())
1223 // Template instantiations should also not be pushed into scope.
1224 if (isa<FunctionDecl>(D) &&
1225 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1228 // If this replaces anything in the current scope,
1229 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1230 IEnd = IdResolver.end();
1231 for (; I != IEnd; ++I) {
1232 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1234 IdResolver.RemoveDecl(*I);
1236 // Should only need to replace one decl.
1243 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1244 // Implicitly-generated labels may end up getting generated in an order that
1245 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1246 // the label at the appropriate place in the identifier chain.
1247 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1248 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1249 if (IDC == CurContext) {
1250 if (!S->isDeclScope(*I))
1252 } else if (IDC->Encloses(CurContext))
1256 IdResolver.InsertDeclAfter(I, D);
1258 IdResolver.AddDecl(D);
1262 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1263 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1264 TUScope->AddDecl(D);
1267 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1268 bool AllowInlineNamespace) {
1269 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1272 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1273 DeclContext *TargetDC = DC->getPrimaryContext();
1275 if (DeclContext *ScopeDC = S->getEntity())
1276 if (ScopeDC->getPrimaryContext() == TargetDC)
1278 } while ((S = S->getParent()));
1283 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1287 /// Filters out lookup results that don't fall within the given scope
1288 /// as determined by isDeclInScope.
1289 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1290 bool ConsiderLinkage,
1291 bool AllowInlineNamespace) {
1292 LookupResult::Filter F = R.makeFilter();
1293 while (F.hasNext()) {
1294 NamedDecl *D = F.next();
1296 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1299 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1308 static bool isUsingDecl(NamedDecl *D) {
1309 return isa<UsingShadowDecl>(D) ||
1310 isa<UnresolvedUsingTypenameDecl>(D) ||
1311 isa<UnresolvedUsingValueDecl>(D);
1314 /// Removes using shadow declarations from the lookup results.
1315 static void RemoveUsingDecls(LookupResult &R) {
1316 LookupResult::Filter F = R.makeFilter();
1318 if (isUsingDecl(F.next()))
1324 /// \brief Check for this common pattern:
1327 /// S(const S&); // DO NOT IMPLEMENT
1328 /// void operator=(const S&); // DO NOT IMPLEMENT
1331 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1332 // FIXME: Should check for private access too but access is set after we get
1334 if (D->doesThisDeclarationHaveABody())
1337 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1338 return CD->isCopyConstructor();
1339 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1340 return Method->isCopyAssignmentOperator();
1344 // We need this to handle
1347 // void *foo() { return 0; }
1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1351 // for example. If 'A', foo will have external linkage. If we have '*A',
1352 // foo will have no linkage. Since we can't know until we get to the end
1353 // of the typedef, this function finds out if D might have non-external linkage.
1354 // Callers should verify at the end of the TU if it D has external linkage or
1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1357 const DeclContext *DC = D->getDeclContext();
1358 while (!DC->isTranslationUnit()) {
1359 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1360 if (!RD->hasNameForLinkage())
1363 DC = DC->getParent();
1366 return !D->isExternallyVisible();
1369 // FIXME: This needs to be refactored; some other isInMainFile users want
1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1372 if (S.TUKind != TU_Complete)
1374 return S.SourceMgr.isInMainFile(Loc);
1377 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1380 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1383 // Ignore all entities declared within templates, and out-of-line definitions
1384 // of members of class templates.
1385 if (D->getDeclContext()->isDependentContext() ||
1386 D->getLexicalDeclContext()->isDependentContext())
1389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1390 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1394 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1397 // 'static inline' functions are defined in headers; don't warn.
1398 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1402 if (FD->doesThisDeclarationHaveABody() &&
1403 Context.DeclMustBeEmitted(FD))
1405 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1406 // Constants and utility variables are defined in headers with internal
1407 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1409 if (!isMainFileLoc(*this, VD->getLocation()))
1412 if (Context.DeclMustBeEmitted(VD))
1415 if (VD->isStaticDataMember() &&
1416 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1422 // Only warn for unused decls internal to the translation unit.
1423 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1424 // for inline functions defined in the main source file, for instance.
1425 return mightHaveNonExternalLinkage(D);
1428 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1432 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1433 const FunctionDecl *First = FD->getFirstDecl();
1434 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1435 return; // First should already be in the vector.
1438 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1439 const VarDecl *First = VD->getFirstDecl();
1440 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1441 return; // First should already be in the vector.
1444 if (ShouldWarnIfUnusedFileScopedDecl(D))
1445 UnusedFileScopedDecls.push_back(D);
1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1449 if (D->isInvalidDecl())
1452 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1453 D->hasAttr<ObjCPreciseLifetimeAttr>())
1456 if (isa<LabelDecl>(D))
1459 // Except for labels, we only care about unused decls that are local to
1461 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1462 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1463 // For dependent types, the diagnostic is deferred.
1465 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1466 if (!WithinFunction)
1469 if (isa<TypedefNameDecl>(D))
1472 // White-list anything that isn't a local variable.
1473 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1476 // Types of valid local variables should be complete, so this should succeed.
1477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1479 // White-list anything with an __attribute__((unused)) type.
1480 QualType Ty = VD->getType();
1482 // Only look at the outermost level of typedef.
1483 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1484 if (TT->getDecl()->hasAttr<UnusedAttr>())
1488 // If we failed to complete the type for some reason, or if the type is
1489 // dependent, don't diagnose the variable.
1490 if (Ty->isIncompleteType() || Ty->isDependentType())
1493 if (const TagType *TT = Ty->getAs<TagType>()) {
1494 const TagDecl *Tag = TT->getDecl();
1495 if (Tag->hasAttr<UnusedAttr>())
1498 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1499 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1502 if (const Expr *Init = VD->getInit()) {
1503 if (const ExprWithCleanups *Cleanups =
1504 dyn_cast<ExprWithCleanups>(Init))
1505 Init = Cleanups->getSubExpr();
1506 const CXXConstructExpr *Construct =
1507 dyn_cast<CXXConstructExpr>(Init);
1508 if (Construct && !Construct->isElidable()) {
1509 CXXConstructorDecl *CD = Construct->getConstructor();
1510 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1517 // TODO: __attribute__((unused)) templates?
1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1525 if (isa<LabelDecl>(D)) {
1526 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1527 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1528 if (AfterColon.isInvalid())
1530 Hint = FixItHint::CreateRemoval(CharSourceRange::
1531 getCharRange(D->getLocStart(), AfterColon));
1535 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1536 if (D->getTypeForDecl()->isDependentType())
1539 for (auto *TmpD : D->decls()) {
1540 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1541 DiagnoseUnusedDecl(T);
1542 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1543 DiagnoseUnusedNestedTypedefs(R);
1547 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1548 /// unless they are marked attr(unused).
1549 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1550 if (!ShouldDiagnoseUnusedDecl(D))
1553 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1554 // typedefs can be referenced later on, so the diagnostics are emitted
1555 // at end-of-translation-unit.
1556 UnusedLocalTypedefNameCandidates.insert(TD);
1561 GenerateFixForUnusedDecl(D, Context, Hint);
1564 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1565 DiagID = diag::warn_unused_exception_param;
1566 else if (isa<LabelDecl>(D))
1567 DiagID = diag::warn_unused_label;
1569 DiagID = diag::warn_unused_variable;
1571 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1574 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1575 // Verify that we have no forward references left. If so, there was a goto
1576 // or address of a label taken, but no definition of it. Label fwd
1577 // definitions are indicated with a null substmt which is also not a resolved
1578 // MS inline assembly label name.
1579 bool Diagnose = false;
1580 if (L->isMSAsmLabel())
1581 Diagnose = !L->isResolvedMSAsmLabel();
1583 Diagnose = L->getStmt() == nullptr;
1585 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1588 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1589 S->mergeNRVOIntoParent();
1591 if (S->decl_empty()) return;
1592 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1593 "Scope shouldn't contain decls!");
1595 for (auto *TmpD : S->decls()) {
1596 assert(TmpD && "This decl didn't get pushed??");
1598 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1599 NamedDecl *D = cast<NamedDecl>(TmpD);
1601 if (!D->getDeclName()) continue;
1603 // Diagnose unused variables in this scope.
1604 if (!S->hasUnrecoverableErrorOccurred()) {
1605 DiagnoseUnusedDecl(D);
1606 if (const auto *RD = dyn_cast<RecordDecl>(D))
1607 DiagnoseUnusedNestedTypedefs(RD);
1610 // If this was a forward reference to a label, verify it was defined.
1611 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1612 CheckPoppedLabel(LD, *this);
1614 // Remove this name from our lexical scope, and warn on it if we haven't
1616 IdResolver.RemoveDecl(D);
1617 auto ShadowI = ShadowingDecls.find(D);
1618 if (ShadowI != ShadowingDecls.end()) {
1619 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1620 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1621 << D << FD << FD->getParent();
1622 Diag(FD->getLocation(), diag::note_previous_declaration);
1624 ShadowingDecls.erase(ShadowI);
1629 /// \brief Look for an Objective-C class in the translation unit.
1631 /// \param Id The name of the Objective-C class we're looking for. If
1632 /// typo-correction fixes this name, the Id will be updated
1633 /// to the fixed name.
1635 /// \param IdLoc The location of the name in the translation unit.
1637 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1638 /// if there is no class with the given name.
1640 /// \returns The declaration of the named Objective-C class, or NULL if the
1641 /// class could not be found.
1642 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1643 SourceLocation IdLoc,
1644 bool DoTypoCorrection) {
1645 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1646 // creation from this context.
1647 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1649 if (!IDecl && DoTypoCorrection) {
1650 // Perform typo correction at the given location, but only if we
1651 // find an Objective-C class name.
1652 if (TypoCorrection C = CorrectTypo(
1653 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1654 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1655 CTK_ErrorRecovery)) {
1656 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1657 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1658 Id = IDecl->getIdentifier();
1661 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1662 // This routine must always return a class definition, if any.
1663 if (Def && Def->getDefinition())
1664 Def = Def->getDefinition();
1668 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1669 /// from S, where a non-field would be declared. This routine copes
1670 /// with the difference between C and C++ scoping rules in structs and
1671 /// unions. For example, the following code is well-formed in C but
1672 /// ill-formed in C++:
1678 /// void test_S6() {
1683 /// For the declaration of BAR, this routine will return a different
1684 /// scope. The scope S will be the scope of the unnamed enumeration
1685 /// within S6. In C++, this routine will return the scope associated
1686 /// with S6, because the enumeration's scope is a transparent
1687 /// context but structures can contain non-field names. In C, this
1688 /// routine will return the translation unit scope, since the
1689 /// enumeration's scope is a transparent context and structures cannot
1690 /// contain non-field names.
1691 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1692 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1693 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1694 (S->isClassScope() && !getLangOpts().CPlusPlus))
1699 /// \brief Looks up the declaration of "struct objc_super" and
1700 /// saves it for later use in building builtin declaration of
1701 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1702 /// pre-existing declaration exists no action takes place.
1703 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1704 IdentifierInfo *II) {
1705 if (!II->isStr("objc_msgSendSuper"))
1707 ASTContext &Context = ThisSema.Context;
1709 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1710 SourceLocation(), Sema::LookupTagName);
1711 ThisSema.LookupName(Result, S);
1712 if (Result.getResultKind() == LookupResult::Found)
1713 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1714 Context.setObjCSuperType(Context.getTagDeclType(TD));
1717 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1719 case ASTContext::GE_None:
1721 case ASTContext::GE_Missing_stdio:
1723 case ASTContext::GE_Missing_setjmp:
1725 case ASTContext::GE_Missing_ucontext:
1726 return "ucontext.h";
1728 llvm_unreachable("unhandled error kind");
1731 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1732 /// file scope. lazily create a decl for it. ForRedeclaration is true
1733 /// if we're creating this built-in in anticipation of redeclaring the
1735 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1736 Scope *S, bool ForRedeclaration,
1737 SourceLocation Loc) {
1738 LookupPredefedObjCSuperType(*this, S, II);
1740 ASTContext::GetBuiltinTypeError Error;
1741 QualType R = Context.GetBuiltinType(ID, Error);
1743 if (ForRedeclaration)
1744 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1745 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1749 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1750 Diag(Loc, diag::ext_implicit_lib_function_decl)
1751 << Context.BuiltinInfo.getName(ID) << R;
1752 if (Context.BuiltinInfo.getHeaderName(ID) &&
1753 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1754 Diag(Loc, diag::note_include_header_or_declare)
1755 << Context.BuiltinInfo.getHeaderName(ID)
1756 << Context.BuiltinInfo.getName(ID);
1762 DeclContext *Parent = Context.getTranslationUnitDecl();
1763 if (getLangOpts().CPlusPlus) {
1764 LinkageSpecDecl *CLinkageDecl =
1765 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1766 LinkageSpecDecl::lang_c, false);
1767 CLinkageDecl->setImplicit();
1768 Parent->addDecl(CLinkageDecl);
1769 Parent = CLinkageDecl;
1772 FunctionDecl *New = FunctionDecl::Create(Context,
1774 Loc, Loc, II, R, /*TInfo=*/nullptr,
1777 R->isFunctionProtoType());
1780 // Create Decl objects for each parameter, adding them to the
1782 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1783 SmallVector<ParmVarDecl*, 16> Params;
1784 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1786 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1787 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1789 parm->setScopeInfo(0, i);
1790 Params.push_back(parm);
1792 New->setParams(Params);
1795 AddKnownFunctionAttributes(New);
1796 RegisterLocallyScopedExternCDecl(New, S);
1798 // TUScope is the translation-unit scope to insert this function into.
1799 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1800 // relate Scopes to DeclContexts, and probably eliminate CurContext
1801 // entirely, but we're not there yet.
1802 DeclContext *SavedContext = CurContext;
1803 CurContext = Parent;
1804 PushOnScopeChains(New, TUScope);
1805 CurContext = SavedContext;
1809 /// Typedef declarations don't have linkage, but they still denote the same
1810 /// entity if their types are the same.
1811 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1813 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1814 TypedefNameDecl *Decl,
1815 LookupResult &Previous) {
1816 // This is only interesting when modules are enabled.
1817 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1820 // Empty sets are uninteresting.
1821 if (Previous.empty())
1824 LookupResult::Filter Filter = Previous.makeFilter();
1825 while (Filter.hasNext()) {
1826 NamedDecl *Old = Filter.next();
1828 // Non-hidden declarations are never ignored.
1829 if (S.isVisible(Old))
1832 // Declarations of the same entity are not ignored, even if they have
1833 // different linkages.
1834 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1835 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1836 Decl->getUnderlyingType()))
1839 // If both declarations give a tag declaration a typedef name for linkage
1840 // purposes, then they declare the same entity.
1841 if (S.getLangOpts().CPlusPlus &&
1842 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1843 Decl->getAnonDeclWithTypedefName())
1853 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1855 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1856 OldType = OldTypedef->getUnderlyingType();
1858 OldType = Context.getTypeDeclType(Old);
1859 QualType NewType = New->getUnderlyingType();
1861 if (NewType->isVariablyModifiedType()) {
1862 // Must not redefine a typedef with a variably-modified type.
1863 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1864 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1866 if (Old->getLocation().isValid())
1867 Diag(Old->getLocation(), diag::note_previous_definition);
1868 New->setInvalidDecl();
1872 if (OldType != NewType &&
1873 !OldType->isDependentType() &&
1874 !NewType->isDependentType() &&
1875 !Context.hasSameType(OldType, NewType)) {
1876 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1877 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1878 << Kind << NewType << OldType;
1879 if (Old->getLocation().isValid())
1880 Diag(Old->getLocation(), diag::note_previous_definition);
1881 New->setInvalidDecl();
1887 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1888 /// same name and scope as a previous declaration 'Old'. Figure out
1889 /// how to resolve this situation, merging decls or emitting
1890 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1892 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1893 LookupResult &OldDecls) {
1894 // If the new decl is known invalid already, don't bother doing any
1896 if (New->isInvalidDecl()) return;
1898 // Allow multiple definitions for ObjC built-in typedefs.
1899 // FIXME: Verify the underlying types are equivalent!
1900 if (getLangOpts().ObjC1) {
1901 const IdentifierInfo *TypeID = New->getIdentifier();
1902 switch (TypeID->getLength()) {
1906 if (!TypeID->isStr("id"))
1908 QualType T = New->getUnderlyingType();
1909 if (!T->isPointerType())
1911 if (!T->isVoidPointerType()) {
1912 QualType PT = T->getAs<PointerType>()->getPointeeType();
1913 if (!PT->isStructureType())
1916 Context.setObjCIdRedefinitionType(T);
1917 // Install the built-in type for 'id', ignoring the current definition.
1918 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1922 if (!TypeID->isStr("Class"))
1924 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1925 // Install the built-in type for 'Class', ignoring the current definition.
1926 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1929 if (!TypeID->isStr("SEL"))
1931 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1932 // Install the built-in type for 'SEL', ignoring the current definition.
1933 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1936 // Fall through - the typedef name was not a builtin type.
1939 // Verify the old decl was also a type.
1940 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1942 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1943 << New->getDeclName();
1945 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1946 if (OldD->getLocation().isValid())
1947 Diag(OldD->getLocation(), diag::note_previous_definition);
1949 return New->setInvalidDecl();
1952 // If the old declaration is invalid, just give up here.
1953 if (Old->isInvalidDecl())
1954 return New->setInvalidDecl();
1956 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1957 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1958 auto *NewTag = New->getAnonDeclWithTypedefName();
1959 NamedDecl *Hidden = nullptr;
1960 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1961 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1962 !hasVisibleDefinition(OldTag, &Hidden)) {
1963 // There is a definition of this tag, but it is not visible. Use it
1964 // instead of our tag.
1965 New->setTypeForDecl(OldTD->getTypeForDecl());
1966 if (OldTD->isModed())
1967 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1968 OldTD->getUnderlyingType());
1970 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1972 // Make the old tag definition visible.
1973 makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1975 // If this was an unscoped enumeration, yank all of its enumerators
1976 // out of the scope.
1977 if (isa<EnumDecl>(NewTag)) {
1978 Scope *EnumScope = getNonFieldDeclScope(S);
1979 for (auto *D : NewTag->decls()) {
1980 auto *ED = cast<EnumConstantDecl>(D);
1981 assert(EnumScope->isDeclScope(ED));
1982 EnumScope->RemoveDecl(ED);
1983 IdResolver.RemoveDecl(ED);
1984 ED->getLexicalDeclContext()->removeDecl(ED);
1990 // If the typedef types are not identical, reject them in all languages and
1991 // with any extensions enabled.
1992 if (isIncompatibleTypedef(Old, New))
1995 // The types match. Link up the redeclaration chain and merge attributes if
1996 // the old declaration was a typedef.
1997 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1998 New->setPreviousDecl(Typedef);
1999 mergeDeclAttributes(New, Old);
2002 if (getLangOpts().MicrosoftExt)
2005 if (getLangOpts().CPlusPlus) {
2006 // C++ [dcl.typedef]p2:
2007 // In a given non-class scope, a typedef specifier can be used to
2008 // redefine the name of any type declared in that scope to refer
2009 // to the type to which it already refers.
2010 if (!isa<CXXRecordDecl>(CurContext))
2013 // C++0x [dcl.typedef]p4:
2014 // In a given class scope, a typedef specifier can be used to redefine
2015 // any class-name declared in that scope that is not also a typedef-name
2016 // to refer to the type to which it already refers.
2018 // This wording came in via DR424, which was a correction to the
2019 // wording in DR56, which accidentally banned code like:
2022 // typedef struct A { } A;
2025 // in the C++03 standard. We implement the C++0x semantics, which
2026 // allow the above but disallow
2033 // since that was the intent of DR56.
2034 if (!isa<TypedefNameDecl>(Old))
2037 Diag(New->getLocation(), diag::err_redefinition)
2038 << New->getDeclName();
2039 Diag(Old->getLocation(), diag::note_previous_definition);
2040 return New->setInvalidDecl();
2043 // Modules always permit redefinition of typedefs, as does C11.
2044 if (getLangOpts().Modules || getLangOpts().C11)
2047 // If we have a redefinition of a typedef in C, emit a warning. This warning
2048 // is normally mapped to an error, but can be controlled with
2049 // -Wtypedef-redefinition. If either the original or the redefinition is
2050 // in a system header, don't emit this for compatibility with GCC.
2051 if (getDiagnostics().getSuppressSystemWarnings() &&
2052 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2053 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2056 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2057 << New->getDeclName();
2058 Diag(Old->getLocation(), diag::note_previous_definition);
2061 /// DeclhasAttr - returns true if decl Declaration already has the target
2063 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2064 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2065 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2066 for (const auto *i : D->attrs())
2067 if (i->getKind() == A->getKind()) {
2069 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2073 // FIXME: Don't hardcode this check
2074 if (OA && isa<OwnershipAttr>(i))
2075 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2082 static bool isAttributeTargetADefinition(Decl *D) {
2083 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2084 return VD->isThisDeclarationADefinition();
2085 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2086 return TD->isCompleteDefinition() || TD->isBeingDefined();
2090 /// Merge alignment attributes from \p Old to \p New, taking into account the
2091 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2093 /// \return \c true if any attributes were added to \p New.
2094 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2095 // Look for alignas attributes on Old, and pick out whichever attribute
2096 // specifies the strictest alignment requirement.
2097 AlignedAttr *OldAlignasAttr = nullptr;
2098 AlignedAttr *OldStrictestAlignAttr = nullptr;
2099 unsigned OldAlign = 0;
2100 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2101 // FIXME: We have no way of representing inherited dependent alignments
2103 // template<int A, int B> struct alignas(A) X;
2104 // template<int A, int B> struct alignas(B) X {};
2105 // For now, we just ignore any alignas attributes which are not on the
2106 // definition in such a case.
2107 if (I->isAlignmentDependent())
2113 unsigned Align = I->getAlignment(S.Context);
2114 if (Align > OldAlign) {
2116 OldStrictestAlignAttr = I;
2120 // Look for alignas attributes on New.
2121 AlignedAttr *NewAlignasAttr = nullptr;
2122 unsigned NewAlign = 0;
2123 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2124 if (I->isAlignmentDependent())
2130 unsigned Align = I->getAlignment(S.Context);
2131 if (Align > NewAlign)
2135 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2136 // Both declarations have 'alignas' attributes. We require them to match.
2137 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2138 // fall short. (If two declarations both have alignas, they must both match
2139 // every definition, and so must match each other if there is a definition.)
2141 // If either declaration only contains 'alignas(0)' specifiers, then it
2142 // specifies the natural alignment for the type.
2143 if (OldAlign == 0 || NewAlign == 0) {
2145 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2148 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2151 OldAlign = S.Context.getTypeAlign(Ty);
2153 NewAlign = S.Context.getTypeAlign(Ty);
2156 if (OldAlign != NewAlign) {
2157 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2158 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2159 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2160 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2164 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2165 // C++11 [dcl.align]p6:
2166 // if any declaration of an entity has an alignment-specifier,
2167 // every defining declaration of that entity shall specify an
2168 // equivalent alignment.
2170 // If the definition of an object does not have an alignment
2171 // specifier, any other declaration of that object shall also
2172 // have no alignment specifier.
2173 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2175 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2179 bool AnyAdded = false;
2181 // Ensure we have an attribute representing the strictest alignment.
2182 if (OldAlign > NewAlign) {
2183 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2184 Clone->setInherited(true);
2185 New->addAttr(Clone);
2189 // Ensure we have an alignas attribute if the old declaration had one.
2190 if (OldAlignasAttr && !NewAlignasAttr &&
2191 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2192 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2193 Clone->setInherited(true);
2194 New->addAttr(Clone);
2201 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2202 const InheritableAttr *Attr,
2203 Sema::AvailabilityMergeKind AMK) {
2204 InheritableAttr *NewAttr = nullptr;
2205 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2206 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2207 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2208 AA->isImplicit(), AA->getIntroduced(),
2209 AA->getDeprecated(),
2210 AA->getObsoleted(), AA->getUnavailable(),
2211 AA->getMessage(), AA->getStrict(),
2212 AA->getReplacement(), AMK,
2213 AttrSpellingListIndex);
2214 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2215 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2216 AttrSpellingListIndex);
2217 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2218 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2219 AttrSpellingListIndex);
2220 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2221 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2222 AttrSpellingListIndex);
2223 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2224 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2225 AttrSpellingListIndex);
2226 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2227 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2228 FA->getFormatIdx(), FA->getFirstArg(),
2229 AttrSpellingListIndex);
2230 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2231 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2232 AttrSpellingListIndex);
2233 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2234 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2235 AttrSpellingListIndex,
2236 IA->getSemanticSpelling());
2237 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2238 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2239 &S.Context.Idents.get(AA->getSpelling()),
2240 AttrSpellingListIndex);
2241 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2242 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2243 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2244 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2245 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2246 NewAttr = S.mergeInternalLinkageAttr(
2247 D, InternalLinkageA->getRange(),
2248 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2249 AttrSpellingListIndex);
2250 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2251 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2252 &S.Context.Idents.get(CommonA->getSpelling()),
2253 AttrSpellingListIndex);
2254 else if (isa<AlignedAttr>(Attr))
2255 // AlignedAttrs are handled separately, because we need to handle all
2256 // such attributes on a declaration at the same time.
2258 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2259 (AMK == Sema::AMK_Override ||
2260 AMK == Sema::AMK_ProtocolImplementation))
2262 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2263 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2266 NewAttr->setInherited(true);
2267 D->addAttr(NewAttr);
2268 if (isa<MSInheritanceAttr>(NewAttr))
2269 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2276 static const Decl *getDefinition(const Decl *D) {
2277 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2278 return TD->getDefinition();
2279 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2280 const VarDecl *Def = VD->getDefinition();
2283 return VD->getActingDefinition();
2285 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2286 const FunctionDecl* Def;
2287 if (FD->isDefined(Def))
2293 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2294 for (const auto *Attribute : D->attrs())
2295 if (Attribute->getKind() == Kind)
2300 /// checkNewAttributesAfterDef - If we already have a definition, check that
2301 /// there are no new attributes in this declaration.
2302 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2303 if (!New->hasAttrs())
2306 const Decl *Def = getDefinition(Old);
2307 if (!Def || Def == New)
2310 AttrVec &NewAttributes = New->getAttrs();
2311 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2312 const Attr *NewAttribute = NewAttributes[I];
2314 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2315 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2316 Sema::SkipBodyInfo SkipBody;
2317 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2319 // If we're skipping this definition, drop the "alias" attribute.
2320 if (SkipBody.ShouldSkip) {
2321 NewAttributes.erase(NewAttributes.begin() + I);
2326 VarDecl *VD = cast<VarDecl>(New);
2327 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2328 VarDecl::TentativeDefinition
2329 ? diag::err_alias_after_tentative
2330 : diag::err_redefinition;
2331 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2332 S.Diag(Def->getLocation(), diag::note_previous_definition);
2333 VD->setInvalidDecl();
2339 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2340 // Tentative definitions are only interesting for the alias check above.
2341 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2347 if (hasAttribute(Def, NewAttribute->getKind())) {
2349 continue; // regular attr merging will take care of validating this.
2352 if (isa<C11NoReturnAttr>(NewAttribute)) {
2353 // C's _Noreturn is allowed to be added to a function after it is defined.
2356 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2357 if (AA->isAlignas()) {
2358 // C++11 [dcl.align]p6:
2359 // if any declaration of an entity has an alignment-specifier,
2360 // every defining declaration of that entity shall specify an
2361 // equivalent alignment.
2363 // If the definition of an object does not have an alignment
2364 // specifier, any other declaration of that object shall also
2365 // have no alignment specifier.
2366 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2368 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2370 NewAttributes.erase(NewAttributes.begin() + I);
2376 S.Diag(NewAttribute->getLocation(),
2377 diag::warn_attribute_precede_definition);
2378 S.Diag(Def->getLocation(), diag::note_previous_definition);
2379 NewAttributes.erase(NewAttributes.begin() + I);
2384 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2385 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2386 AvailabilityMergeKind AMK) {
2387 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2388 UsedAttr *NewAttr = OldAttr->clone(Context);
2389 NewAttr->setInherited(true);
2390 New->addAttr(NewAttr);
2393 if (!Old->hasAttrs() && !New->hasAttrs())
2396 // Attributes declared post-definition are currently ignored.
2397 checkNewAttributesAfterDef(*this, New, Old);
2399 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2400 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2401 if (OldA->getLabel() != NewA->getLabel()) {
2402 // This redeclaration changes __asm__ label.
2403 Diag(New->getLocation(), diag::err_different_asm_label);
2404 Diag(OldA->getLocation(), diag::note_previous_declaration);
2406 } else if (Old->isUsed()) {
2407 // This redeclaration adds an __asm__ label to a declaration that has
2408 // already been ODR-used.
2409 Diag(New->getLocation(), diag::err_late_asm_label_name)
2410 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2414 // Re-declaration cannot add abi_tag's.
2415 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2416 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2417 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2418 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2419 NewTag) == OldAbiTagAttr->tags_end()) {
2420 Diag(NewAbiTagAttr->getLocation(),
2421 diag::err_new_abi_tag_on_redeclaration)
2423 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2427 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2428 Diag(Old->getLocation(), diag::note_previous_declaration);
2432 if (!Old->hasAttrs())
2435 bool foundAny = New->hasAttrs();
2437 // Ensure that any moving of objects within the allocated map is done before
2439 if (!foundAny) New->setAttrs(AttrVec());
2441 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2442 // Ignore deprecated/unavailable/availability attributes if requested.
2443 AvailabilityMergeKind LocalAMK = AMK_None;
2444 if (isa<DeprecatedAttr>(I) ||
2445 isa<UnavailableAttr>(I) ||
2446 isa<AvailabilityAttr>(I)) {
2451 case AMK_Redeclaration:
2453 case AMK_ProtocolImplementation:
2460 if (isa<UsedAttr>(I))
2463 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2467 if (mergeAlignedAttrs(*this, New, Old))
2470 if (!foundAny) New->dropAttrs();
2473 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2475 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2476 const ParmVarDecl *oldDecl,
2478 // C++11 [dcl.attr.depend]p2:
2479 // The first declaration of a function shall specify the
2480 // carries_dependency attribute for its declarator-id if any declaration
2481 // of the function specifies the carries_dependency attribute.
2482 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2483 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2484 S.Diag(CDA->getLocation(),
2485 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2486 // Find the first declaration of the parameter.
2487 // FIXME: Should we build redeclaration chains for function parameters?
2488 const FunctionDecl *FirstFD =
2489 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2490 const ParmVarDecl *FirstVD =
2491 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2492 S.Diag(FirstVD->getLocation(),
2493 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2496 if (!oldDecl->hasAttrs())
2499 bool foundAny = newDecl->hasAttrs();
2501 // Ensure that any moving of objects within the allocated map is
2502 // done before we process them.
2503 if (!foundAny) newDecl->setAttrs(AttrVec());
2505 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2506 if (!DeclHasAttr(newDecl, I)) {
2507 InheritableAttr *newAttr =
2508 cast<InheritableParamAttr>(I->clone(S.Context));
2509 newAttr->setInherited(true);
2510 newDecl->addAttr(newAttr);
2515 if (!foundAny) newDecl->dropAttrs();
2518 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2519 const ParmVarDecl *OldParam,
2521 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2522 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2523 if (*Oldnullability != *Newnullability) {
2524 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2525 << DiagNullabilityKind(
2527 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2529 << DiagNullabilityKind(
2531 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2533 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2536 QualType NewT = NewParam->getType();
2537 NewT = S.Context.getAttributedType(
2538 AttributedType::getNullabilityAttrKind(*Oldnullability),
2540 NewParam->setType(NewT);
2547 /// Used in MergeFunctionDecl to keep track of function parameters in
2549 struct GNUCompatibleParamWarning {
2550 ParmVarDecl *OldParm;
2551 ParmVarDecl *NewParm;
2552 QualType PromotedType;
2555 } // end anonymous namespace
2557 /// getSpecialMember - get the special member enum for a method.
2558 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2559 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2560 if (Ctor->isDefaultConstructor())
2561 return Sema::CXXDefaultConstructor;
2563 if (Ctor->isCopyConstructor())
2564 return Sema::CXXCopyConstructor;
2566 if (Ctor->isMoveConstructor())
2567 return Sema::CXXMoveConstructor;
2568 } else if (isa<CXXDestructorDecl>(MD)) {
2569 return Sema::CXXDestructor;
2570 } else if (MD->isCopyAssignmentOperator()) {
2571 return Sema::CXXCopyAssignment;
2572 } else if (MD->isMoveAssignmentOperator()) {
2573 return Sema::CXXMoveAssignment;
2576 return Sema::CXXInvalid;
2579 // Determine whether the previous declaration was a definition, implicit
2580 // declaration, or a declaration.
2581 template <typename T>
2582 static std::pair<diag::kind, SourceLocation>
2583 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2584 diag::kind PrevDiag;
2585 SourceLocation OldLocation = Old->getLocation();
2586 if (Old->isThisDeclarationADefinition())
2587 PrevDiag = diag::note_previous_definition;
2588 else if (Old->isImplicit()) {
2589 PrevDiag = diag::note_previous_implicit_declaration;
2590 if (OldLocation.isInvalid())
2591 OldLocation = New->getLocation();
2593 PrevDiag = diag::note_previous_declaration;
2594 return std::make_pair(PrevDiag, OldLocation);
2597 /// canRedefineFunction - checks if a function can be redefined. Currently,
2598 /// only extern inline functions can be redefined, and even then only in
2600 static bool canRedefineFunction(const FunctionDecl *FD,
2601 const LangOptions& LangOpts) {
2602 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2603 !LangOpts.CPlusPlus &&
2604 FD->isInlineSpecified() &&
2605 FD->getStorageClass() == SC_Extern);
2608 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2609 const AttributedType *AT = T->getAs<AttributedType>();
2610 while (AT && !AT->isCallingConv())
2611 AT = AT->getModifiedType()->getAs<AttributedType>();
2615 template <typename T>
2616 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2617 const DeclContext *DC = Old->getDeclContext();
2621 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2622 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2624 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2629 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2630 static bool isExternC(VarTemplateDecl *) { return false; }
2632 /// \brief Check whether a redeclaration of an entity introduced by a
2633 /// using-declaration is valid, given that we know it's not an overload
2634 /// (nor a hidden tag declaration).
2635 template<typename ExpectedDecl>
2636 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2637 ExpectedDecl *New) {
2638 // C++11 [basic.scope.declarative]p4:
2639 // Given a set of declarations in a single declarative region, each of
2640 // which specifies the same unqualified name,
2641 // -- they shall all refer to the same entity, or all refer to functions
2642 // and function templates; or
2643 // -- exactly one declaration shall declare a class name or enumeration
2644 // name that is not a typedef name and the other declarations shall all
2645 // refer to the same variable or enumerator, or all refer to functions
2646 // and function templates; in this case the class name or enumeration
2647 // name is hidden (3.3.10).
2649 // C++11 [namespace.udecl]p14:
2650 // If a function declaration in namespace scope or block scope has the
2651 // same name and the same parameter-type-list as a function introduced
2652 // by a using-declaration, and the declarations do not declare the same
2653 // function, the program is ill-formed.
2655 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2657 !Old->getDeclContext()->getRedeclContext()->Equals(
2658 New->getDeclContext()->getRedeclContext()) &&
2659 !(isExternC(Old) && isExternC(New)))
2663 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2664 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2665 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2671 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2672 const FunctionDecl *B) {
2673 assert(A->getNumParams() == B->getNumParams());
2675 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2676 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2677 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2680 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2683 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2686 /// MergeFunctionDecl - We just parsed a function 'New' from
2687 /// declarator D which has the same name and scope as a previous
2688 /// declaration 'Old'. Figure out how to resolve this situation,
2689 /// merging decls or emitting diagnostics as appropriate.
2691 /// In C++, New and Old must be declarations that are not
2692 /// overloaded. Use IsOverload to determine whether New and Old are
2693 /// overloaded, and to select the Old declaration that New should be
2696 /// Returns true if there was an error, false otherwise.
2697 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2698 Scope *S, bool MergeTypeWithOld) {
2699 // Verify the old decl was also a function.
2700 FunctionDecl *Old = OldD->getAsFunction();
2702 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2703 if (New->getFriendObjectKind()) {
2704 Diag(New->getLocation(), diag::err_using_decl_friend);
2705 Diag(Shadow->getTargetDecl()->getLocation(),
2706 diag::note_using_decl_target);
2707 Diag(Shadow->getUsingDecl()->getLocation(),
2708 diag::note_using_decl) << 0;
2712 // Check whether the two declarations might declare the same function.
2713 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2715 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2717 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2718 << New->getDeclName();
2719 Diag(OldD->getLocation(), diag::note_previous_definition);
2724 // If the old declaration is invalid, just give up here.
2725 if (Old->isInvalidDecl())
2728 diag::kind PrevDiag;
2729 SourceLocation OldLocation;
2730 std::tie(PrevDiag, OldLocation) =
2731 getNoteDiagForInvalidRedeclaration(Old, New);
2733 // Don't complain about this if we're in GNU89 mode and the old function
2734 // is an extern inline function.
2735 // Don't complain about specializations. They are not supposed to have
2737 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2738 New->getStorageClass() == SC_Static &&
2739 Old->hasExternalFormalLinkage() &&
2740 !New->getTemplateSpecializationInfo() &&
2741 !canRedefineFunction(Old, getLangOpts())) {
2742 if (getLangOpts().MicrosoftExt) {
2743 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2744 Diag(OldLocation, PrevDiag);
2746 Diag(New->getLocation(), diag::err_static_non_static) << New;
2747 Diag(OldLocation, PrevDiag);
2752 if (New->hasAttr<InternalLinkageAttr>() &&
2753 !Old->hasAttr<InternalLinkageAttr>()) {
2754 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2755 << New->getDeclName();
2756 Diag(Old->getLocation(), diag::note_previous_definition);
2757 New->dropAttr<InternalLinkageAttr>();
2760 // If a function is first declared with a calling convention, but is later
2761 // declared or defined without one, all following decls assume the calling
2762 // convention of the first.
2764 // It's OK if a function is first declared without a calling convention,
2765 // but is later declared or defined with the default calling convention.
2767 // To test if either decl has an explicit calling convention, we look for
2768 // AttributedType sugar nodes on the type as written. If they are missing or
2769 // were canonicalized away, we assume the calling convention was implicit.
2771 // Note also that we DO NOT return at this point, because we still have
2772 // other tests to run.
2773 QualType OldQType = Context.getCanonicalType(Old->getType());
2774 QualType NewQType = Context.getCanonicalType(New->getType());
2775 const FunctionType *OldType = cast<FunctionType>(OldQType);
2776 const FunctionType *NewType = cast<FunctionType>(NewQType);
2777 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2778 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2779 bool RequiresAdjustment = false;
2781 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2782 FunctionDecl *First = Old->getFirstDecl();
2783 const FunctionType *FT =
2784 First->getType().getCanonicalType()->castAs<FunctionType>();
2785 FunctionType::ExtInfo FI = FT->getExtInfo();
2786 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2787 if (!NewCCExplicit) {
2788 // Inherit the CC from the previous declaration if it was specified
2789 // there but not here.
2790 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2791 RequiresAdjustment = true;
2793 // Calling conventions aren't compatible, so complain.
2794 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2795 Diag(New->getLocation(), diag::err_cconv_change)
2796 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2798 << (!FirstCCExplicit ? "" :
2799 FunctionType::getNameForCallConv(FI.getCC()));
2801 // Put the note on the first decl, since it is the one that matters.
2802 Diag(First->getLocation(), diag::note_previous_declaration);
2807 // FIXME: diagnose the other way around?
2808 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2809 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2810 RequiresAdjustment = true;
2813 // Merge regparm attribute.
2814 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2815 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2816 if (NewTypeInfo.getHasRegParm()) {
2817 Diag(New->getLocation(), diag::err_regparm_mismatch)
2818 << NewType->getRegParmType()
2819 << OldType->getRegParmType();
2820 Diag(OldLocation, diag::note_previous_declaration);
2824 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2825 RequiresAdjustment = true;
2828 // Merge ns_returns_retained attribute.
2829 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2830 if (NewTypeInfo.getProducesResult()) {
2831 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2832 Diag(OldLocation, diag::note_previous_declaration);
2836 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2837 RequiresAdjustment = true;
2840 if (RequiresAdjustment) {
2841 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2842 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2843 New->setType(QualType(AdjustedType, 0));
2844 NewQType = Context.getCanonicalType(New->getType());
2845 NewType = cast<FunctionType>(NewQType);
2848 // If this redeclaration makes the function inline, we may need to add it to
2849 // UndefinedButUsed.
2850 if (!Old->isInlined() && New->isInlined() &&
2851 !New->hasAttr<GNUInlineAttr>() &&
2852 !getLangOpts().GNUInline &&
2853 Old->isUsed(false) &&
2854 !Old->isDefined() && !New->isThisDeclarationADefinition())
2855 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2858 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2860 if (New->hasAttr<GNUInlineAttr>() &&
2861 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2862 UndefinedButUsed.erase(Old->getCanonicalDecl());
2865 // If pass_object_size params don't match up perfectly, this isn't a valid
2867 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2868 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2869 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2870 << New->getDeclName();
2871 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2875 if (getLangOpts().CPlusPlus) {
2877 // Certain function declarations cannot be overloaded:
2878 // -- Function declarations that differ only in the return type
2879 // cannot be overloaded.
2881 // Go back to the type source info to compare the declared return types,
2882 // per C++1y [dcl.type.auto]p13:
2883 // Redeclarations or specializations of a function or function template
2884 // with a declared return type that uses a placeholder type shall also
2885 // use that placeholder, not a deduced type.
2886 QualType OldDeclaredReturnType =
2887 (Old->getTypeSourceInfo()
2888 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2889 : OldType)->getReturnType();
2890 QualType NewDeclaredReturnType =
2891 (New->getTypeSourceInfo()
2892 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2893 : NewType)->getReturnType();
2895 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2896 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2897 New->isLocalExternDecl())) {
2898 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2899 OldDeclaredReturnType->isObjCObjectPointerType())
2900 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2901 if (ResQT.isNull()) {
2902 if (New->isCXXClassMember() && New->isOutOfLine())
2903 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2904 << New << New->getReturnTypeSourceRange();
2906 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2907 << New->getReturnTypeSourceRange();
2908 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2909 << Old->getReturnTypeSourceRange();
2916 QualType OldReturnType = OldType->getReturnType();
2917 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2918 if (OldReturnType != NewReturnType) {
2919 // If this function has a deduced return type and has already been
2920 // defined, copy the deduced value from the old declaration.
2921 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2922 if (OldAT && OldAT->isDeduced()) {
2924 SubstAutoType(New->getType(),
2925 OldAT->isDependentType() ? Context.DependentTy
2926 : OldAT->getDeducedType()));
2927 NewQType = Context.getCanonicalType(
2928 SubstAutoType(NewQType,
2929 OldAT->isDependentType() ? Context.DependentTy
2930 : OldAT->getDeducedType()));
2934 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2935 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2936 if (OldMethod && NewMethod) {
2937 // Preserve triviality.
2938 NewMethod->setTrivial(OldMethod->isTrivial());
2940 // MSVC allows explicit template specialization at class scope:
2941 // 2 CXXMethodDecls referring to the same function will be injected.
2942 // We don't want a redeclaration error.
2943 bool IsClassScopeExplicitSpecialization =
2944 OldMethod->isFunctionTemplateSpecialization() &&
2945 NewMethod->isFunctionTemplateSpecialization();
2946 bool isFriend = NewMethod->getFriendObjectKind();
2948 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2949 !IsClassScopeExplicitSpecialization) {
2950 // -- Member function declarations with the same name and the
2951 // same parameter types cannot be overloaded if any of them
2952 // is a static member function declaration.
2953 if (OldMethod->isStatic() != NewMethod->isStatic()) {
2954 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2955 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2959 // C++ [class.mem]p1:
2960 // [...] A member shall not be declared twice in the
2961 // member-specification, except that a nested class or member
2962 // class template can be declared and then later defined.
2963 if (ActiveTemplateInstantiations.empty()) {
2965 if (isa<CXXConstructorDecl>(OldMethod))
2966 NewDiag = diag::err_constructor_redeclared;
2967 else if (isa<CXXDestructorDecl>(NewMethod))
2968 NewDiag = diag::err_destructor_redeclared;
2969 else if (isa<CXXConversionDecl>(NewMethod))
2970 NewDiag = diag::err_conv_function_redeclared;
2972 NewDiag = diag::err_member_redeclared;
2974 Diag(New->getLocation(), NewDiag);
2976 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2977 << New << New->getType();
2979 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2982 // Complain if this is an explicit declaration of a special
2983 // member that was initially declared implicitly.
2985 // As an exception, it's okay to befriend such methods in order
2986 // to permit the implicit constructor/destructor/operator calls.
2987 } else if (OldMethod->isImplicit()) {
2989 NewMethod->setImplicit();
2991 Diag(NewMethod->getLocation(),
2992 diag::err_definition_of_implicitly_declared_member)
2993 << New << getSpecialMember(OldMethod);
2996 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2997 Diag(NewMethod->getLocation(),
2998 diag::err_definition_of_explicitly_defaulted_member)
2999 << getSpecialMember(OldMethod);
3004 // C++11 [dcl.attr.noreturn]p1:
3005 // The first declaration of a function shall specify the noreturn
3006 // attribute if any declaration of that function specifies the noreturn
3008 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3009 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3010 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3011 Diag(Old->getFirstDecl()->getLocation(),
3012 diag::note_noreturn_missing_first_decl);
3015 // C++11 [dcl.attr.depend]p2:
3016 // The first declaration of a function shall specify the
3017 // carries_dependency attribute for its declarator-id if any declaration
3018 // of the function specifies the carries_dependency attribute.
3019 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3020 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3021 Diag(CDA->getLocation(),
3022 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3023 Diag(Old->getFirstDecl()->getLocation(),
3024 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3028 // All declarations for a function shall agree exactly in both the
3029 // return type and the parameter-type-list.
3030 // We also want to respect all the extended bits except noreturn.
3032 // noreturn should now match unless the old type info didn't have it.
3033 QualType OldQTypeForComparison = OldQType;
3034 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3035 assert(OldQType == QualType(OldType, 0));
3036 const FunctionType *OldTypeForComparison
3037 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3038 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3039 assert(OldQTypeForComparison.isCanonical());
3042 if (haveIncompatibleLanguageLinkages(Old, New)) {
3043 // As a special case, retain the language linkage from previous
3044 // declarations of a friend function as an extension.
3046 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3047 // and is useful because there's otherwise no way to specify language
3048 // linkage within class scope.
3050 // Check cautiously as the friend object kind isn't yet complete.
3051 if (New->getFriendObjectKind() != Decl::FOK_None) {
3052 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3053 Diag(OldLocation, PrevDiag);
3055 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3056 Diag(OldLocation, PrevDiag);
3061 if (OldQTypeForComparison == NewQType)
3062 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3064 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3065 New->isLocalExternDecl()) {
3066 // It's OK if we couldn't merge types for a local function declaraton
3067 // if either the old or new type is dependent. We'll merge the types
3068 // when we instantiate the function.
3072 // Fall through for conflicting redeclarations and redefinitions.
3075 // C: Function types need to be compatible, not identical. This handles
3076 // duplicate function decls like "void f(int); void f(enum X);" properly.
3077 if (!getLangOpts().CPlusPlus &&
3078 Context.typesAreCompatible(OldQType, NewQType)) {
3079 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3080 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3081 const FunctionProtoType *OldProto = nullptr;
3082 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3083 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3084 // The old declaration provided a function prototype, but the
3085 // new declaration does not. Merge in the prototype.
3086 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3087 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3089 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3090 OldProto->getExtProtoInfo());
3091 New->setType(NewQType);
3092 New->setHasInheritedPrototype();
3094 // Synthesize parameters with the same types.
3095 SmallVector<ParmVarDecl*, 16> Params;
3096 for (const auto &ParamType : OldProto->param_types()) {
3097 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3098 SourceLocation(), nullptr,
3099 ParamType, /*TInfo=*/nullptr,
3101 Param->setScopeInfo(0, Params.size());
3102 Param->setImplicit();
3103 Params.push_back(Param);
3106 New->setParams(Params);
3109 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3112 // GNU C permits a K&R definition to follow a prototype declaration
3113 // if the declared types of the parameters in the K&R definition
3114 // match the types in the prototype declaration, even when the
3115 // promoted types of the parameters from the K&R definition differ
3116 // from the types in the prototype. GCC then keeps the types from
3119 // If a variadic prototype is followed by a non-variadic K&R definition,
3120 // the K&R definition becomes variadic. This is sort of an edge case, but
3121 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3123 if (!getLangOpts().CPlusPlus &&
3124 Old->hasPrototype() && !New->hasPrototype() &&
3125 New->getType()->getAs<FunctionProtoType>() &&
3126 Old->getNumParams() == New->getNumParams()) {
3127 SmallVector<QualType, 16> ArgTypes;
3128 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3129 const FunctionProtoType *OldProto
3130 = Old->getType()->getAs<FunctionProtoType>();
3131 const FunctionProtoType *NewProto
3132 = New->getType()->getAs<FunctionProtoType>();
3134 // Determine whether this is the GNU C extension.
3135 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3136 NewProto->getReturnType());
3137 bool LooseCompatible = !MergedReturn.isNull();
3138 for (unsigned Idx = 0, End = Old->getNumParams();
3139 LooseCompatible && Idx != End; ++Idx) {
3140 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3141 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3142 if (Context.typesAreCompatible(OldParm->getType(),
3143 NewProto->getParamType(Idx))) {
3144 ArgTypes.push_back(NewParm->getType());
3145 } else if (Context.typesAreCompatible(OldParm->getType(),
3147 /*CompareUnqualified=*/true)) {
3148 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3149 NewProto->getParamType(Idx) };
3150 Warnings.push_back(Warn);
3151 ArgTypes.push_back(NewParm->getType());
3153 LooseCompatible = false;
3156 if (LooseCompatible) {
3157 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3158 Diag(Warnings[Warn].NewParm->getLocation(),
3159 diag::ext_param_promoted_not_compatible_with_prototype)
3160 << Warnings[Warn].PromotedType
3161 << Warnings[Warn].OldParm->getType();
3162 if (Warnings[Warn].OldParm->getLocation().isValid())
3163 Diag(Warnings[Warn].OldParm->getLocation(),
3164 diag::note_previous_declaration);
3167 if (MergeTypeWithOld)
3168 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3169 OldProto->getExtProtoInfo()));
3170 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3173 // Fall through to diagnose conflicting types.
3176 // A function that has already been declared has been redeclared or
3177 // defined with a different type; show an appropriate diagnostic.
3179 // If the previous declaration was an implicitly-generated builtin
3180 // declaration, then at the very least we should use a specialized note.
3182 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3183 // If it's actually a library-defined builtin function like 'malloc'
3184 // or 'printf', just warn about the incompatible redeclaration.
3185 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3186 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3187 Diag(OldLocation, diag::note_previous_builtin_declaration)
3188 << Old << Old->getType();
3190 // If this is a global redeclaration, just forget hereafter
3191 // about the "builtin-ness" of the function.
3193 // Doing this for local extern declarations is problematic. If
3194 // the builtin declaration remains visible, a second invalid
3195 // local declaration will produce a hard error; if it doesn't
3196 // remain visible, a single bogus local redeclaration (which is
3197 // actually only a warning) could break all the downstream code.
3198 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3199 New->getIdentifier()->revertBuiltin();
3204 PrevDiag = diag::note_previous_builtin_declaration;
3207 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3208 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3212 /// \brief Completes the merge of two function declarations that are
3213 /// known to be compatible.
3215 /// This routine handles the merging of attributes and other
3216 /// properties of function declarations from the old declaration to
3217 /// the new declaration, once we know that New is in fact a
3218 /// redeclaration of Old.
3221 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3222 Scope *S, bool MergeTypeWithOld) {
3223 // Merge the attributes
3224 mergeDeclAttributes(New, Old);
3226 // Merge "pure" flag.
3230 // Merge "used" flag.
3231 if (Old->getMostRecentDecl()->isUsed(false))
3234 // Merge attributes from the parameters. These can mismatch with K&R
3236 if (New->getNumParams() == Old->getNumParams())
3237 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3238 ParmVarDecl *NewParam = New->getParamDecl(i);
3239 ParmVarDecl *OldParam = Old->getParamDecl(i);
3240 mergeParamDeclAttributes(NewParam, OldParam, *this);
3241 mergeParamDeclTypes(NewParam, OldParam, *this);
3244 if (getLangOpts().CPlusPlus)
3245 return MergeCXXFunctionDecl(New, Old, S);
3247 // Merge the function types so the we get the composite types for the return
3248 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3250 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3251 if (!Merged.isNull() && MergeTypeWithOld)
3252 New->setType(Merged);
3257 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3258 ObjCMethodDecl *oldMethod) {
3259 // Merge the attributes, including deprecated/unavailable
3260 AvailabilityMergeKind MergeKind =
3261 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3262 ? AMK_ProtocolImplementation
3263 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3266 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3268 // Merge attributes from the parameters.
3269 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3270 oe = oldMethod->param_end();
3271 for (ObjCMethodDecl::param_iterator
3272 ni = newMethod->param_begin(), ne = newMethod->param_end();
3273 ni != ne && oi != oe; ++ni, ++oi)
3274 mergeParamDeclAttributes(*ni, *oi, *this);
3276 CheckObjCMethodOverride(newMethod, oldMethod);
3279 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3280 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3282 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3283 ? diag::err_redefinition_different_type
3284 : diag::err_redeclaration_different_type)
3285 << New->getDeclName() << New->getType() << Old->getType();
3287 diag::kind PrevDiag;
3288 SourceLocation OldLocation;
3289 std::tie(PrevDiag, OldLocation)
3290 = getNoteDiagForInvalidRedeclaration(Old, New);
3291 S.Diag(OldLocation, PrevDiag);
3292 New->setInvalidDecl();
3295 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3296 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3297 /// emitting diagnostics as appropriate.
3299 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3300 /// to here in AddInitializerToDecl. We can't check them before the initializer
3302 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3303 bool MergeTypeWithOld) {
3304 if (New->isInvalidDecl() || Old->isInvalidDecl())
3308 if (getLangOpts().CPlusPlus) {
3309 if (New->getType()->isUndeducedType()) {
3310 // We don't know what the new type is until the initializer is attached.
3312 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3313 // These could still be something that needs exception specs checked.
3314 return MergeVarDeclExceptionSpecs(New, Old);
3316 // C++ [basic.link]p10:
3317 // [...] the types specified by all declarations referring to a given
3318 // object or function shall be identical, except that declarations for an
3319 // array object can specify array types that differ by the presence or
3320 // absence of a major array bound (8.3.4).
3321 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3322 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3323 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3325 // We are merging a variable declaration New into Old. If it has an array
3326 // bound, and that bound differs from Old's bound, we should diagnose the
3328 if (!NewArray->isIncompleteArrayType()) {
3329 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3330 PrevVD = PrevVD->getPreviousDecl()) {
3331 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3332 if (PrevVDTy->isIncompleteArrayType())
3335 if (!Context.hasSameType(NewArray, PrevVDTy))
3336 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3340 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3341 if (Context.hasSameType(OldArray->getElementType(),
3342 NewArray->getElementType()))
3343 MergedT = New->getType();
3345 // FIXME: Check visibility. New is hidden but has a complete type. If New
3346 // has no array bound, it should not inherit one from Old, if Old is not
3348 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3349 if (Context.hasSameType(OldArray->getElementType(),
3350 NewArray->getElementType()))
3351 MergedT = Old->getType();
3354 else if (New->getType()->isObjCObjectPointerType() &&
3355 Old->getType()->isObjCObjectPointerType()) {
3356 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3361 // All declarations that refer to the same object or function shall have
3363 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3365 if (MergedT.isNull()) {
3366 // It's OK if we couldn't merge types if either type is dependent, for a
3367 // block-scope variable. In other cases (static data members of class
3368 // templates, variable templates, ...), we require the types to be
3370 // FIXME: The C++ standard doesn't say anything about this.
3371 if ((New->getType()->isDependentType() ||
3372 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3373 // If the old type was dependent, we can't merge with it, so the new type
3374 // becomes dependent for now. We'll reproduce the original type when we
3375 // instantiate the TypeSourceInfo for the variable.
3376 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3377 New->setType(Context.DependentTy);
3380 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3383 // Don't actually update the type on the new declaration if the old
3384 // declaration was an extern declaration in a different scope.
3385 if (MergeTypeWithOld)
3386 New->setType(MergedT);
3389 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3390 LookupResult &Previous) {
3392 // For an identifier with internal or external linkage declared
3393 // in a scope in which a prior declaration of that identifier is
3394 // visible, if the prior declaration specifies internal or
3395 // external linkage, the type of the identifier at the later
3396 // declaration becomes the composite type.
3398 // If the variable isn't visible, we do not merge with its type.
3399 if (Previous.isShadowed())
3402 if (S.getLangOpts().CPlusPlus) {
3403 // C++11 [dcl.array]p3:
3404 // If there is a preceding declaration of the entity in the same
3405 // scope in which the bound was specified, an omitted array bound
3406 // is taken to be the same as in that earlier declaration.
3407 return NewVD->isPreviousDeclInSameBlockScope() ||
3408 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3409 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3411 // If the old declaration was function-local, don't merge with its
3412 // type unless we're in the same function.
3413 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3414 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3418 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3419 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3420 /// situation, merging decls or emitting diagnostics as appropriate.
3422 /// Tentative definition rules (C99 6.9.2p2) are checked by
3423 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3424 /// definitions here, since the initializer hasn't been attached.
3426 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3427 // If the new decl is already invalid, don't do any other checking.
3428 if (New->isInvalidDecl())
3431 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3434 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3436 // Verify the old decl was also a variable or variable template.
3437 VarDecl *Old = nullptr;
3438 VarTemplateDecl *OldTemplate = nullptr;
3439 if (Previous.isSingleResult()) {
3441 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3442 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3445 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3446 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3447 return New->setInvalidDecl();
3449 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3452 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3453 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3454 return New->setInvalidDecl();
3458 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3459 << New->getDeclName();
3460 Diag(Previous.getRepresentativeDecl()->getLocation(),
3461 diag::note_previous_definition);
3462 return New->setInvalidDecl();
3465 // Ensure the template parameters are compatible.
3467 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3468 OldTemplate->getTemplateParameters(),
3469 /*Complain=*/true, TPL_TemplateMatch))
3470 return New->setInvalidDecl();
3472 // C++ [class.mem]p1:
3473 // A member shall not be declared twice in the member-specification [...]
3475 // Here, we need only consider static data members.
3476 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3477 Diag(New->getLocation(), diag::err_duplicate_member)
3478 << New->getIdentifier();
3479 Diag(Old->getLocation(), diag::note_previous_declaration);
3480 New->setInvalidDecl();
3483 mergeDeclAttributes(New, Old);
3484 // Warn if an already-declared variable is made a weak_import in a subsequent
3486 if (New->hasAttr<WeakImportAttr>() &&
3487 Old->getStorageClass() == SC_None &&
3488 !Old->hasAttr<WeakImportAttr>()) {
3489 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3490 Diag(Old->getLocation(), diag::note_previous_definition);
3491 // Remove weak_import attribute on new declaration.
3492 New->dropAttr<WeakImportAttr>();
3495 if (New->hasAttr<InternalLinkageAttr>() &&
3496 !Old->hasAttr<InternalLinkageAttr>()) {
3497 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3498 << New->getDeclName();
3499 Diag(Old->getLocation(), diag::note_previous_definition);
3500 New->dropAttr<InternalLinkageAttr>();
3504 VarDecl *MostRecent = Old->getMostRecentDecl();
3505 if (MostRecent != Old) {
3506 MergeVarDeclTypes(New, MostRecent,
3507 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3508 if (New->isInvalidDecl())
3512 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3513 if (New->isInvalidDecl())
3516 diag::kind PrevDiag;
3517 SourceLocation OldLocation;
3518 std::tie(PrevDiag, OldLocation) =
3519 getNoteDiagForInvalidRedeclaration(Old, New);
3521 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3522 if (New->getStorageClass() == SC_Static &&
3523 !New->isStaticDataMember() &&
3524 Old->hasExternalFormalLinkage()) {
3525 if (getLangOpts().MicrosoftExt) {
3526 Diag(New->getLocation(), diag::ext_static_non_static)
3527 << New->getDeclName();
3528 Diag(OldLocation, PrevDiag);
3530 Diag(New->getLocation(), diag::err_static_non_static)
3531 << New->getDeclName();
3532 Diag(OldLocation, PrevDiag);
3533 return New->setInvalidDecl();
3537 // For an identifier declared with the storage-class specifier
3538 // extern in a scope in which a prior declaration of that
3539 // identifier is visible,23) if the prior declaration specifies
3540 // internal or external linkage, the linkage of the identifier at
3541 // the later declaration is the same as the linkage specified at
3542 // the prior declaration. If no prior declaration is visible, or
3543 // if the prior declaration specifies no linkage, then the
3544 // identifier has external linkage.
3545 if (New->hasExternalStorage() && Old->hasLinkage())
3547 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3548 !New->isStaticDataMember() &&
3549 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3550 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3551 Diag(OldLocation, PrevDiag);
3552 return New->setInvalidDecl();
3555 // Check if extern is followed by non-extern and vice-versa.
3556 if (New->hasExternalStorage() &&
3557 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3558 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3559 Diag(OldLocation, PrevDiag);
3560 return New->setInvalidDecl();
3562 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3563 !New->hasExternalStorage()) {
3564 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3565 Diag(OldLocation, PrevDiag);
3566 return New->setInvalidDecl();
3569 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3571 // FIXME: The test for external storage here seems wrong? We still
3572 // need to check for mismatches.
3573 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3574 // Don't complain about out-of-line definitions of static members.
3575 !(Old->getLexicalDeclContext()->isRecord() &&
3576 !New->getLexicalDeclContext()->isRecord())) {
3577 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3578 Diag(OldLocation, PrevDiag);
3579 return New->setInvalidDecl();
3582 if (New->getTLSKind() != Old->getTLSKind()) {
3583 if (!Old->getTLSKind()) {
3584 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3585 Diag(OldLocation, PrevDiag);
3586 } else if (!New->getTLSKind()) {
3587 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3588 Diag(OldLocation, PrevDiag);
3590 // Do not allow redeclaration to change the variable between requiring
3591 // static and dynamic initialization.
3592 // FIXME: GCC allows this, but uses the TLS keyword on the first
3593 // declaration to determine the kind. Do we need to be compatible here?
3594 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3595 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3596 Diag(OldLocation, PrevDiag);
3600 // C++ doesn't have tentative definitions, so go right ahead and check here.
3602 if (getLangOpts().CPlusPlus &&
3603 New->isThisDeclarationADefinition() == VarDecl::Definition &&
3604 (Def = Old->getDefinition())) {
3605 NamedDecl *Hidden = nullptr;
3606 if (!hasVisibleDefinition(Def, &Hidden) &&
3607 (New->getFormalLinkage() == InternalLinkage ||
3608 New->getDescribedVarTemplate() ||
3609 New->getNumTemplateParameterLists() ||
3610 New->getDeclContext()->isDependentContext())) {
3611 // The previous definition is hidden, and multiple definitions are
3612 // permitted (in separate TUs). Form another definition of it.
3614 Diag(New->getLocation(), diag::err_redefinition) << New;
3615 Diag(Def->getLocation(), diag::note_previous_definition);
3616 New->setInvalidDecl();
3621 if (haveIncompatibleLanguageLinkages(Old, New)) {
3622 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3623 Diag(OldLocation, PrevDiag);
3624 New->setInvalidDecl();
3628 // Merge "used" flag.
3629 if (Old->getMostRecentDecl()->isUsed(false))
3632 // Keep a chain of previous declarations.
3633 New->setPreviousDecl(Old);
3635 NewTemplate->setPreviousDecl(OldTemplate);
3637 // Inherit access appropriately.
3638 New->setAccess(Old->getAccess());
3640 NewTemplate->setAccess(New->getAccess());
3643 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3644 /// no declarator (e.g. "struct foo;") is parsed.
3646 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3647 RecordDecl *&AnonRecord) {
3648 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3652 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3653 // disambiguate entities defined in different scopes.
3654 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3656 // We will pick our mangling number depending on which version of MSVC is being
3658 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3659 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3660 ? S->getMSCurManglingNumber()
3661 : S->getMSLastManglingNumber();
3664 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3665 if (!Context.getLangOpts().CPlusPlus)
3668 if (isa<CXXRecordDecl>(Tag->getParent())) {
3669 // If this tag is the direct child of a class, number it if
3671 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3673 MangleNumberingContext &MCtx =
3674 Context.getManglingNumberContext(Tag->getParent());
3675 Context.setManglingNumber(
3676 Tag, MCtx.getManglingNumber(
3677 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3681 // If this tag isn't a direct child of a class, number it if it is local.
3682 Decl *ManglingContextDecl;
3683 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3684 Tag->getDeclContext(), ManglingContextDecl)) {
3685 Context.setManglingNumber(
3686 Tag, MCtx->getManglingNumber(
3687 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3691 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3692 TypedefNameDecl *NewTD) {
3693 if (TagFromDeclSpec->isInvalidDecl())
3696 // Do nothing if the tag already has a name for linkage purposes.
3697 if (TagFromDeclSpec->hasNameForLinkage())
3700 // A well-formed anonymous tag must always be a TUK_Definition.
3701 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3703 // The type must match the tag exactly; no qualifiers allowed.
3704 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3705 Context.getTagDeclType(TagFromDeclSpec))) {
3706 if (getLangOpts().CPlusPlus)
3707 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3711 // If we've already computed linkage for the anonymous tag, then
3712 // adding a typedef name for the anonymous decl can change that
3713 // linkage, which might be a serious problem. Diagnose this as
3714 // unsupported and ignore the typedef name. TODO: we should
3715 // pursue this as a language defect and establish a formal rule
3716 // for how to handle it.
3717 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3718 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3720 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3721 tagLoc = getLocForEndOfToken(tagLoc);
3723 llvm::SmallString<40> textToInsert;
3724 textToInsert += ' ';
3725 textToInsert += NewTD->getIdentifier()->getName();
3726 Diag(tagLoc, diag::note_typedef_changes_linkage)
3727 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3731 // Otherwise, set this is the anon-decl typedef for the tag.
3732 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3735 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3737 case DeclSpec::TST_class:
3739 case DeclSpec::TST_struct:
3741 case DeclSpec::TST_interface:
3743 case DeclSpec::TST_union:
3745 case DeclSpec::TST_enum:
3748 llvm_unreachable("unexpected type specifier");
3752 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3753 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3754 /// parameters to cope with template friend declarations.
3756 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3757 MultiTemplateParamsArg TemplateParams,
3758 bool IsExplicitInstantiation,
3759 RecordDecl *&AnonRecord) {
3760 Decl *TagD = nullptr;
3761 TagDecl *Tag = nullptr;
3762 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3763 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3764 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3765 DS.getTypeSpecType() == DeclSpec::TST_union ||
3766 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3767 TagD = DS.getRepAsDecl();
3769 if (!TagD) // We probably had an error
3772 // Note that the above type specs guarantee that the
3773 // type rep is a Decl, whereas in many of the others
3775 if (isa<TagDecl>(TagD))
3776 Tag = cast<TagDecl>(TagD);
3777 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3778 Tag = CTD->getTemplatedDecl();
3782 handleTagNumbering(Tag, S);
3783 Tag->setFreeStanding();
3784 if (Tag->isInvalidDecl())
3788 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3789 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3790 // or incomplete types shall not be restrict-qualified."
3791 if (TypeQuals & DeclSpec::TQ_restrict)
3792 Diag(DS.getRestrictSpecLoc(),
3793 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3794 << DS.getSourceRange();
3797 if (DS.isConstexprSpecified()) {
3798 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3799 // and definitions of functions and variables.
3801 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3802 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3804 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3805 // Don't emit warnings after this error.
3809 if (DS.isConceptSpecified()) {
3810 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3811 // either a function concept and its definition or a variable concept and
3813 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3817 DiagnoseFunctionSpecifiers(DS);
3819 if (DS.isFriendSpecified()) {
3820 // If we're dealing with a decl but not a TagDecl, assume that
3821 // whatever routines created it handled the friendship aspect.
3824 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3827 const CXXScopeSpec &SS = DS.getTypeSpecScope();
3828 bool IsExplicitSpecialization =
3829 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3830 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3831 !IsExplicitInstantiation && !IsExplicitSpecialization &&
3832 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3833 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3834 // nested-name-specifier unless it is an explicit instantiation
3835 // or an explicit specialization.
3837 // FIXME: We allow class template partial specializations here too, per the
3838 // obvious intent of DR1819.
3840 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3841 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3842 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3846 // Track whether this decl-specifier declares anything.
3847 bool DeclaresAnything = true;
3849 // Handle anonymous struct definitions.
3850 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3851 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3852 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3853 if (getLangOpts().CPlusPlus ||
3854 Record->getDeclContext()->isRecord()) {
3855 // If CurContext is a DeclContext that can contain statements,
3856 // RecursiveASTVisitor won't visit the decls that
3857 // BuildAnonymousStructOrUnion() will put into CurContext.
3858 // Also store them here so that they can be part of the
3859 // DeclStmt that gets created in this case.
3860 // FIXME: Also return the IndirectFieldDecls created by
3861 // BuildAnonymousStructOr union, for the same reason?
3862 if (CurContext->isFunctionOrMethod())
3863 AnonRecord = Record;
3864 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3865 Context.getPrintingPolicy());
3868 DeclaresAnything = false;
3873 // A struct-declaration that does not declare an anonymous structure or
3874 // anonymous union shall contain a struct-declarator-list.
3876 // This rule also existed in C89 and C99; the grammar for struct-declaration
3877 // did not permit a struct-declaration without a struct-declarator-list.
3878 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3879 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3880 // Check for Microsoft C extension: anonymous struct/union member.
3881 // Handle 2 kinds of anonymous struct/union:
3885 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3886 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3887 if ((Tag && Tag->getDeclName()) ||
3888 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3889 RecordDecl *Record = nullptr;
3891 Record = dyn_cast<RecordDecl>(Tag);
3892 else if (const RecordType *RT =
3893 DS.getRepAsType().get()->getAsStructureType())
3894 Record = RT->getDecl();
3895 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3896 Record = UT->getDecl();
3898 if (Record && getLangOpts().MicrosoftExt) {
3899 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3900 << Record->isUnion() << DS.getSourceRange();
3901 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3904 DeclaresAnything = false;
3908 // Skip all the checks below if we have a type error.
3909 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3910 (TagD && TagD->isInvalidDecl()))
3913 if (getLangOpts().CPlusPlus &&
3914 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3915 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3916 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3917 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3918 DeclaresAnything = false;
3920 if (!DS.isMissingDeclaratorOk()) {
3921 // Customize diagnostic for a typedef missing a name.
3922 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3923 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3924 << DS.getSourceRange();
3926 DeclaresAnything = false;
3929 if (DS.isModulePrivateSpecified() &&
3930 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3931 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3932 << Tag->getTagKind()
3933 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3935 ActOnDocumentableDecl(TagD);
3938 // A declaration [...] shall declare at least a declarator [...], a tag,
3939 // or the members of an enumeration.
3941 // [If there are no declarators], and except for the declaration of an
3942 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3943 // names into the program, or shall redeclare a name introduced by a
3944 // previous declaration.
3945 if (!DeclaresAnything) {
3946 // In C, we allow this as a (popular) extension / bug. Don't bother
3947 // producing further diagnostics for redundant qualifiers after this.
3948 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3953 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3954 // init-declarator-list of the declaration shall not be empty.
3955 // C++ [dcl.fct.spec]p1:
3956 // If a cv-qualifier appears in a decl-specifier-seq, the
3957 // init-declarator-list of the declaration shall not be empty.
3959 // Spurious qualifiers here appear to be valid in C.
3960 unsigned DiagID = diag::warn_standalone_specifier;
3961 if (getLangOpts().CPlusPlus)
3962 DiagID = diag::ext_standalone_specifier;
3964 // Note that a linkage-specification sets a storage class, but
3965 // 'extern "C" struct foo;' is actually valid and not theoretically
3967 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3968 if (SCS == DeclSpec::SCS_mutable)
3969 // Since mutable is not a viable storage class specifier in C, there is
3970 // no reason to treat it as an extension. Instead, diagnose as an error.
3971 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3972 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3973 Diag(DS.getStorageClassSpecLoc(), DiagID)
3974 << DeclSpec::getSpecifierName(SCS);
3977 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3978 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3979 << DeclSpec::getSpecifierName(TSCS);
3980 if (DS.getTypeQualifiers()) {
3981 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3982 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3983 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3984 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3985 // Restrict is covered above.
3986 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3987 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3990 // Warn about ignored type attributes, for example:
3991 // __attribute__((aligned)) struct A;
3992 // Attributes should be placed after tag to apply to type declaration.
3993 if (!DS.getAttributes().empty()) {
3994 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3995 if (TypeSpecType == DeclSpec::TST_class ||
3996 TypeSpecType == DeclSpec::TST_struct ||
3997 TypeSpecType == DeclSpec::TST_interface ||
3998 TypeSpecType == DeclSpec::TST_union ||
3999 TypeSpecType == DeclSpec::TST_enum) {
4000 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4001 attrs = attrs->getNext())
4002 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4003 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4010 /// We are trying to inject an anonymous member into the given scope;
4011 /// check if there's an existing declaration that can't be overloaded.
4013 /// \return true if this is a forbidden redeclaration
4014 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4017 DeclarationName Name,
4018 SourceLocation NameLoc,
4020 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4021 Sema::ForRedeclaration);
4022 if (!SemaRef.LookupName(R, S)) return false;
4024 // Pick a representative declaration.
4025 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4026 assert(PrevDecl && "Expected a non-null Decl");
4028 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4031 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4033 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4038 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4039 /// anonymous struct or union AnonRecord into the owning context Owner
4040 /// and scope S. This routine will be invoked just after we realize
4041 /// that an unnamed union or struct is actually an anonymous union or
4048 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4049 /// // f into the surrounding scope.x
4052 /// This routine is recursive, injecting the names of nested anonymous
4053 /// structs/unions into the owning context and scope as well.
4055 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4056 RecordDecl *AnonRecord, AccessSpecifier AS,
4057 SmallVectorImpl<NamedDecl *> &Chaining) {
4058 bool Invalid = false;
4060 // Look every FieldDecl and IndirectFieldDecl with a name.
4061 for (auto *D : AnonRecord->decls()) {
4062 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4063 cast<NamedDecl>(D)->getDeclName()) {
4064 ValueDecl *VD = cast<ValueDecl>(D);
4065 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4067 AnonRecord->isUnion())) {
4068 // C++ [class.union]p2:
4069 // The names of the members of an anonymous union shall be
4070 // distinct from the names of any other entity in the
4071 // scope in which the anonymous union is declared.
4074 // C++ [class.union]p2:
4075 // For the purpose of name lookup, after the anonymous union
4076 // definition, the members of the anonymous union are
4077 // considered to have been defined in the scope in which the
4078 // anonymous union is declared.
4079 unsigned OldChainingSize = Chaining.size();
4080 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4081 Chaining.append(IF->chain_begin(), IF->chain_end());
4083 Chaining.push_back(VD);
4085 assert(Chaining.size() >= 2);
4086 NamedDecl **NamedChain =
4087 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4088 for (unsigned i = 0; i < Chaining.size(); i++)
4089 NamedChain[i] = Chaining[i];
4091 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4092 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4093 VD->getType(), NamedChain, Chaining.size());
4095 for (const auto *Attr : VD->attrs())
4096 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4098 IndirectField->setAccess(AS);
4099 IndirectField->setImplicit();
4100 SemaRef.PushOnScopeChains(IndirectField, S);
4102 // That includes picking up the appropriate access specifier.
4103 if (AS != AS_none) IndirectField->setAccess(AS);
4105 Chaining.resize(OldChainingSize);
4113 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4114 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4115 /// illegal input values are mapped to SC_None.
4117 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4118 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4119 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4120 "Parser allowed 'typedef' as storage class VarDecl.");
4121 switch (StorageClassSpec) {
4122 case DeclSpec::SCS_unspecified: return SC_None;
4123 case DeclSpec::SCS_extern:
4124 if (DS.isExternInLinkageSpec())
4127 case DeclSpec::SCS_static: return SC_Static;
4128 case DeclSpec::SCS_auto: return SC_Auto;
4129 case DeclSpec::SCS_register: return SC_Register;
4130 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4131 // Illegal SCSs map to None: error reporting is up to the caller.
4132 case DeclSpec::SCS_mutable: // Fall through.
4133 case DeclSpec::SCS_typedef: return SC_None;
4135 llvm_unreachable("unknown storage class specifier");
4138 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4139 assert(Record->hasInClassInitializer());
4141 for (const auto *I : Record->decls()) {
4142 const auto *FD = dyn_cast<FieldDecl>(I);
4143 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4144 FD = IFD->getAnonField();
4145 if (FD && FD->hasInClassInitializer())
4146 return FD->getLocation();
4149 llvm_unreachable("couldn't find in-class initializer");
4152 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4153 SourceLocation DefaultInitLoc) {
4154 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4157 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4158 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4161 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4162 CXXRecordDecl *AnonUnion) {
4163 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4166 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4169 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4170 /// anonymous structure or union. Anonymous unions are a C++ feature
4171 /// (C++ [class.union]) and a C11 feature; anonymous structures
4172 /// are a C11 feature and GNU C++ extension.
4173 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4176 const PrintingPolicy &Policy) {
4177 DeclContext *Owner = Record->getDeclContext();
4179 // Diagnose whether this anonymous struct/union is an extension.
4180 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4181 Diag(Record->getLocation(), diag::ext_anonymous_union);
4182 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4183 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4184 else if (!Record->isUnion() && !getLangOpts().C11)
4185 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4187 // C and C++ require different kinds of checks for anonymous
4189 bool Invalid = false;
4190 if (getLangOpts().CPlusPlus) {
4191 const char *PrevSpec = nullptr;
4193 if (Record->isUnion()) {
4194 // C++ [class.union]p6:
4195 // Anonymous unions declared in a named namespace or in the
4196 // global namespace shall be declared static.
4197 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4198 (isa<TranslationUnitDecl>(Owner) ||
4199 (isa<NamespaceDecl>(Owner) &&
4200 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4201 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4202 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4204 // Recover by adding 'static'.
4205 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4206 PrevSpec, DiagID, Policy);
4208 // C++ [class.union]p6:
4209 // A storage class is not allowed in a declaration of an
4210 // anonymous union in a class scope.
4211 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4212 isa<RecordDecl>(Owner)) {
4213 Diag(DS.getStorageClassSpecLoc(),
4214 diag::err_anonymous_union_with_storage_spec)
4215 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4217 // Recover by removing the storage specifier.
4218 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4220 PrevSpec, DiagID, Context.getPrintingPolicy());
4224 // Ignore const/volatile/restrict qualifiers.
4225 if (DS.getTypeQualifiers()) {
4226 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4227 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4228 << Record->isUnion() << "const"
4229 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4230 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4231 Diag(DS.getVolatileSpecLoc(),
4232 diag::ext_anonymous_struct_union_qualified)
4233 << Record->isUnion() << "volatile"
4234 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4235 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4236 Diag(DS.getRestrictSpecLoc(),
4237 diag::ext_anonymous_struct_union_qualified)
4238 << Record->isUnion() << "restrict"
4239 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4240 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4241 Diag(DS.getAtomicSpecLoc(),
4242 diag::ext_anonymous_struct_union_qualified)
4243 << Record->isUnion() << "_Atomic"
4244 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4246 DS.ClearTypeQualifiers();
4249 // C++ [class.union]p2:
4250 // The member-specification of an anonymous union shall only
4251 // define non-static data members. [Note: nested types and
4252 // functions cannot be declared within an anonymous union. ]
4253 for (auto *Mem : Record->decls()) {
4254 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4255 // C++ [class.union]p3:
4256 // An anonymous union shall not have private or protected
4257 // members (clause 11).
4258 assert(FD->getAccess() != AS_none);
4259 if (FD->getAccess() != AS_public) {
4260 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4261 << Record->isUnion() << (FD->getAccess() == AS_protected);
4265 // C++ [class.union]p1
4266 // An object of a class with a non-trivial constructor, a non-trivial
4267 // copy constructor, a non-trivial destructor, or a non-trivial copy
4268 // assignment operator cannot be a member of a union, nor can an
4269 // array of such objects.
4270 if (CheckNontrivialField(FD))
4272 } else if (Mem->isImplicit()) {
4273 // Any implicit members are fine.
4274 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4275 // This is a type that showed up in an
4276 // elaborated-type-specifier inside the anonymous struct or
4277 // union, but which actually declares a type outside of the
4278 // anonymous struct or union. It's okay.
4279 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4280 if (!MemRecord->isAnonymousStructOrUnion() &&
4281 MemRecord->getDeclName()) {
4282 // Visual C++ allows type definition in anonymous struct or union.
4283 if (getLangOpts().MicrosoftExt)
4284 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4285 << Record->isUnion();
4287 // This is a nested type declaration.
4288 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4289 << Record->isUnion();
4293 // This is an anonymous type definition within another anonymous type.
4294 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4295 // not part of standard C++.
4296 Diag(MemRecord->getLocation(),
4297 diag::ext_anonymous_record_with_anonymous_type)
4298 << Record->isUnion();
4300 } else if (isa<AccessSpecDecl>(Mem)) {
4301 // Any access specifier is fine.
4302 } else if (isa<StaticAssertDecl>(Mem)) {
4303 // In C++1z, static_assert declarations are also fine.
4305 // We have something that isn't a non-static data
4306 // member. Complain about it.
4307 unsigned DK = diag::err_anonymous_record_bad_member;
4308 if (isa<TypeDecl>(Mem))
4309 DK = diag::err_anonymous_record_with_type;
4310 else if (isa<FunctionDecl>(Mem))
4311 DK = diag::err_anonymous_record_with_function;
4312 else if (isa<VarDecl>(Mem))
4313 DK = diag::err_anonymous_record_with_static;
4315 // Visual C++ allows type definition in anonymous struct or union.
4316 if (getLangOpts().MicrosoftExt &&
4317 DK == diag::err_anonymous_record_with_type)
4318 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4319 << Record->isUnion();
4321 Diag(Mem->getLocation(), DK) << Record->isUnion();
4327 // C++11 [class.union]p8 (DR1460):
4328 // At most one variant member of a union may have a
4329 // brace-or-equal-initializer.
4330 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4332 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4333 cast<CXXRecordDecl>(Record));
4336 if (!Record->isUnion() && !Owner->isRecord()) {
4337 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4338 << getLangOpts().CPlusPlus;
4342 // Mock up a declarator.
4343 Declarator Dc(DS, Declarator::MemberContext);
4344 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4345 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4347 // Create a declaration for this anonymous struct/union.
4348 NamedDecl *Anon = nullptr;
4349 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4350 Anon = FieldDecl::Create(Context, OwningClass,
4352 Record->getLocation(),
4353 /*IdentifierInfo=*/nullptr,
4354 Context.getTypeDeclType(Record),
4356 /*BitWidth=*/nullptr, /*Mutable=*/false,
4357 /*InitStyle=*/ICIS_NoInit);
4358 Anon->setAccess(AS);
4359 if (getLangOpts().CPlusPlus)
4360 FieldCollector->Add(cast<FieldDecl>(Anon));
4362 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4363 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4364 if (SCSpec == DeclSpec::SCS_mutable) {
4365 // mutable can only appear on non-static class members, so it's always
4367 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4372 Anon = VarDecl::Create(Context, Owner,
4374 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4375 Context.getTypeDeclType(Record),
4378 // Default-initialize the implicit variable. This initialization will be
4379 // trivial in almost all cases, except if a union member has an in-class
4381 // union { int n = 0; };
4382 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4384 Anon->setImplicit();
4386 // Mark this as an anonymous struct/union type.
4387 Record->setAnonymousStructOrUnion(true);
4389 // Add the anonymous struct/union object to the current
4390 // context. We'll be referencing this object when we refer to one of
4392 Owner->addDecl(Anon);
4394 // Inject the members of the anonymous struct/union into the owning
4395 // context and into the identifier resolver chain for name lookup
4397 SmallVector<NamedDecl*, 2> Chain;
4398 Chain.push_back(Anon);
4400 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4403 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4404 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4405 Decl *ManglingContextDecl;
4406 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4407 NewVD->getDeclContext(), ManglingContextDecl)) {
4408 Context.setManglingNumber(
4409 NewVD, MCtx->getManglingNumber(
4410 NewVD, getMSManglingNumber(getLangOpts(), S)));
4411 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4417 Anon->setInvalidDecl();
4422 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4423 /// Microsoft C anonymous structure.
4424 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4427 /// struct A { int a; };
4428 /// struct B { struct A; int b; };
4435 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4436 RecordDecl *Record) {
4437 assert(Record && "expected a record!");
4439 // Mock up a declarator.
4440 Declarator Dc(DS, Declarator::TypeNameContext);
4441 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4442 assert(TInfo && "couldn't build declarator info for anonymous struct");
4444 auto *ParentDecl = cast<RecordDecl>(CurContext);
4445 QualType RecTy = Context.getTypeDeclType(Record);
4447 // Create a declaration for this anonymous struct.
4448 NamedDecl *Anon = FieldDecl::Create(Context,
4452 /*IdentifierInfo=*/nullptr,
4455 /*BitWidth=*/nullptr, /*Mutable=*/false,
4456 /*InitStyle=*/ICIS_NoInit);
4457 Anon->setImplicit();
4459 // Add the anonymous struct object to the current context.
4460 CurContext->addDecl(Anon);
4462 // Inject the members of the anonymous struct into the current
4463 // context and into the identifier resolver chain for name lookup
4465 SmallVector<NamedDecl*, 2> Chain;
4466 Chain.push_back(Anon);
4468 RecordDecl *RecordDef = Record->getDefinition();
4469 if (RequireCompleteType(Anon->getLocation(), RecTy,
4470 diag::err_field_incomplete) ||
4471 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4473 Anon->setInvalidDecl();
4474 ParentDecl->setInvalidDecl();
4480 /// GetNameForDeclarator - Determine the full declaration name for the
4481 /// given Declarator.
4482 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4483 return GetNameFromUnqualifiedId(D.getName());
4486 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4488 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4489 DeclarationNameInfo NameInfo;
4490 NameInfo.setLoc(Name.StartLocation);
4492 switch (Name.getKind()) {
4494 case UnqualifiedId::IK_ImplicitSelfParam:
4495 case UnqualifiedId::IK_Identifier:
4496 NameInfo.setName(Name.Identifier);
4497 NameInfo.setLoc(Name.StartLocation);
4500 case UnqualifiedId::IK_OperatorFunctionId:
4501 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4502 Name.OperatorFunctionId.Operator));
4503 NameInfo.setLoc(Name.StartLocation);
4504 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4505 = Name.OperatorFunctionId.SymbolLocations[0];
4506 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4507 = Name.EndLocation.getRawEncoding();
4510 case UnqualifiedId::IK_LiteralOperatorId:
4511 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4513 NameInfo.setLoc(Name.StartLocation);
4514 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4517 case UnqualifiedId::IK_ConversionFunctionId: {
4518 TypeSourceInfo *TInfo;
4519 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4521 return DeclarationNameInfo();
4522 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4523 Context.getCanonicalType(Ty)));
4524 NameInfo.setLoc(Name.StartLocation);
4525 NameInfo.setNamedTypeInfo(TInfo);
4529 case UnqualifiedId::IK_ConstructorName: {
4530 TypeSourceInfo *TInfo;
4531 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4533 return DeclarationNameInfo();
4534 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4535 Context.getCanonicalType(Ty)));
4536 NameInfo.setLoc(Name.StartLocation);
4537 NameInfo.setNamedTypeInfo(TInfo);
4541 case UnqualifiedId::IK_ConstructorTemplateId: {
4542 // In well-formed code, we can only have a constructor
4543 // template-id that refers to the current context, so go there
4544 // to find the actual type being constructed.
4545 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4546 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4547 return DeclarationNameInfo();
4549 // Determine the type of the class being constructed.
4550 QualType CurClassType = Context.getTypeDeclType(CurClass);
4552 // FIXME: Check two things: that the template-id names the same type as
4553 // CurClassType, and that the template-id does not occur when the name
4556 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4557 Context.getCanonicalType(CurClassType)));
4558 NameInfo.setLoc(Name.StartLocation);
4559 // FIXME: should we retrieve TypeSourceInfo?
4560 NameInfo.setNamedTypeInfo(nullptr);
4564 case UnqualifiedId::IK_DestructorName: {
4565 TypeSourceInfo *TInfo;
4566 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4568 return DeclarationNameInfo();
4569 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4570 Context.getCanonicalType(Ty)));
4571 NameInfo.setLoc(Name.StartLocation);
4572 NameInfo.setNamedTypeInfo(TInfo);
4576 case UnqualifiedId::IK_TemplateId: {
4577 TemplateName TName = Name.TemplateId->Template.get();
4578 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4579 return Context.getNameForTemplate(TName, TNameLoc);
4582 } // switch (Name.getKind())
4584 llvm_unreachable("Unknown name kind");
4587 static QualType getCoreType(QualType Ty) {
4589 if (Ty->isPointerType() || Ty->isReferenceType())
4590 Ty = Ty->getPointeeType();
4591 else if (Ty->isArrayType())
4592 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4594 return Ty.withoutLocalFastQualifiers();
4598 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4599 /// and Definition have "nearly" matching parameters. This heuristic is
4600 /// used to improve diagnostics in the case where an out-of-line function
4601 /// definition doesn't match any declaration within the class or namespace.
4602 /// Also sets Params to the list of indices to the parameters that differ
4603 /// between the declaration and the definition. If hasSimilarParameters
4604 /// returns true and Params is empty, then all of the parameters match.
4605 static bool hasSimilarParameters(ASTContext &Context,
4606 FunctionDecl *Declaration,
4607 FunctionDecl *Definition,
4608 SmallVectorImpl<unsigned> &Params) {
4610 if (Declaration->param_size() != Definition->param_size())
4612 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4613 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4614 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4616 // The parameter types are identical
4617 if (Context.hasSameType(DefParamTy, DeclParamTy))
4620 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4621 QualType DefParamBaseTy = getCoreType(DefParamTy);
4622 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4623 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4625 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4626 (DeclTyName && DeclTyName == DefTyName))
4627 Params.push_back(Idx);
4628 else // The two parameters aren't even close
4635 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4636 /// declarator needs to be rebuilt in the current instantiation.
4637 /// Any bits of declarator which appear before the name are valid for
4638 /// consideration here. That's specifically the type in the decl spec
4639 /// and the base type in any member-pointer chunks.
4640 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4641 DeclarationName Name) {
4642 // The types we specifically need to rebuild are:
4643 // - typenames, typeofs, and decltypes
4644 // - types which will become injected class names
4645 // Of course, we also need to rebuild any type referencing such a
4646 // type. It's safest to just say "dependent", but we call out a
4649 DeclSpec &DS = D.getMutableDeclSpec();
4650 switch (DS.getTypeSpecType()) {
4651 case DeclSpec::TST_typename:
4652 case DeclSpec::TST_typeofType:
4653 case DeclSpec::TST_underlyingType:
4654 case DeclSpec::TST_atomic: {
4655 // Grab the type from the parser.
4656 TypeSourceInfo *TSI = nullptr;
4657 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4658 if (T.isNull() || !T->isDependentType()) break;
4660 // Make sure there's a type source info. This isn't really much
4661 // of a waste; most dependent types should have type source info
4662 // attached already.
4664 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4666 // Rebuild the type in the current instantiation.
4667 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4668 if (!TSI) return true;
4670 // Store the new type back in the decl spec.
4671 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4672 DS.UpdateTypeRep(LocType);
4676 case DeclSpec::TST_decltype:
4677 case DeclSpec::TST_typeofExpr: {
4678 Expr *E = DS.getRepAsExpr();
4679 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4680 if (Result.isInvalid()) return true;
4681 DS.UpdateExprRep(Result.get());
4686 // Nothing to do for these decl specs.
4690 // It doesn't matter what order we do this in.
4691 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4692 DeclaratorChunk &Chunk = D.getTypeObject(I);
4694 // The only type information in the declarator which can come
4695 // before the declaration name is the base type of a member
4697 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4700 // Rebuild the scope specifier in-place.
4701 CXXScopeSpec &SS = Chunk.Mem.Scope();
4702 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4709 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4710 D.setFunctionDefinitionKind(FDK_Declaration);
4711 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4713 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4714 Dcl && Dcl->getDeclContext()->isFileContext())
4715 Dcl->setTopLevelDeclInObjCContainer();
4720 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4721 /// If T is the name of a class, then each of the following shall have a
4722 /// name different from T:
4723 /// - every static data member of class T;
4724 /// - every member function of class T
4725 /// - every member of class T that is itself a type;
4726 /// \returns true if the declaration name violates these rules.
4727 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4728 DeclarationNameInfo NameInfo) {
4729 DeclarationName Name = NameInfo.getName();
4731 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4732 while (Record && Record->isAnonymousStructOrUnion())
4733 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4734 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4735 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4742 /// \brief Diagnose a declaration whose declarator-id has the given
4743 /// nested-name-specifier.
4745 /// \param SS The nested-name-specifier of the declarator-id.
4747 /// \param DC The declaration context to which the nested-name-specifier
4750 /// \param Name The name of the entity being declared.
4752 /// \param Loc The location of the name of the entity being declared.
4754 /// \returns true if we cannot safely recover from this error, false otherwise.
4755 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4756 DeclarationName Name,
4757 SourceLocation Loc) {
4758 DeclContext *Cur = CurContext;
4759 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4760 Cur = Cur->getParent();
4762 // If the user provided a superfluous scope specifier that refers back to the
4763 // class in which the entity is already declared, diagnose and ignore it.
4769 // Note, it was once ill-formed to give redundant qualification in all
4770 // contexts, but that rule was removed by DR482.
4771 if (Cur->Equals(DC)) {
4772 if (Cur->isRecord()) {
4773 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4774 : diag::err_member_extra_qualification)
4775 << Name << FixItHint::CreateRemoval(SS.getRange());
4778 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4783 // Check whether the qualifying scope encloses the scope of the original
4785 if (!Cur->Encloses(DC)) {
4786 if (Cur->isRecord())
4787 Diag(Loc, diag::err_member_qualification)
4788 << Name << SS.getRange();
4789 else if (isa<TranslationUnitDecl>(DC))
4790 Diag(Loc, diag::err_invalid_declarator_global_scope)
4791 << Name << SS.getRange();
4792 else if (isa<FunctionDecl>(Cur))
4793 Diag(Loc, diag::err_invalid_declarator_in_function)
4794 << Name << SS.getRange();
4795 else if (isa<BlockDecl>(Cur))
4796 Diag(Loc, diag::err_invalid_declarator_in_block)
4797 << Name << SS.getRange();
4799 Diag(Loc, diag::err_invalid_declarator_scope)
4800 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4805 if (Cur->isRecord()) {
4806 // Cannot qualify members within a class.
4807 Diag(Loc, diag::err_member_qualification)
4808 << Name << SS.getRange();
4811 // C++ constructors and destructors with incorrect scopes can break
4812 // our AST invariants by having the wrong underlying types. If
4813 // that's the case, then drop this declaration entirely.
4814 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4815 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4816 !Context.hasSameType(Name.getCXXNameType(),
4817 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4823 // C++11 [dcl.meaning]p1:
4824 // [...] "The nested-name-specifier of the qualified declarator-id shall
4825 // not begin with a decltype-specifer"
4826 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4827 while (SpecLoc.getPrefix())
4828 SpecLoc = SpecLoc.getPrefix();
4829 if (dyn_cast_or_null<DecltypeType>(
4830 SpecLoc.getNestedNameSpecifier()->getAsType()))
4831 Diag(Loc, diag::err_decltype_in_declarator)
4832 << SpecLoc.getTypeLoc().getSourceRange();
4837 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4838 MultiTemplateParamsArg TemplateParamLists) {
4839 // TODO: consider using NameInfo for diagnostic.
4840 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4841 DeclarationName Name = NameInfo.getName();
4843 // All of these full declarators require an identifier. If it doesn't have
4844 // one, the ParsedFreeStandingDeclSpec action should be used.
4846 if (!D.isInvalidType()) // Reject this if we think it is valid.
4847 Diag(D.getDeclSpec().getLocStart(),
4848 diag::err_declarator_need_ident)
4849 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4851 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4854 // The scope passed in may not be a decl scope. Zip up the scope tree until
4855 // we find one that is.
4856 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4857 (S->getFlags() & Scope::TemplateParamScope) != 0)
4860 DeclContext *DC = CurContext;
4861 if (D.getCXXScopeSpec().isInvalid())
4863 else if (D.getCXXScopeSpec().isSet()) {
4864 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4865 UPPC_DeclarationQualifier))
4868 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4869 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4870 if (!DC || isa<EnumDecl>(DC)) {
4871 // If we could not compute the declaration context, it's because the
4872 // declaration context is dependent but does not refer to a class,
4873 // class template, or class template partial specialization. Complain
4874 // and return early, to avoid the coming semantic disaster.
4875 Diag(D.getIdentifierLoc(),
4876 diag::err_template_qualified_declarator_no_match)
4877 << D.getCXXScopeSpec().getScopeRep()
4878 << D.getCXXScopeSpec().getRange();
4881 bool IsDependentContext = DC->isDependentContext();
4883 if (!IsDependentContext &&
4884 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4887 // If a class is incomplete, do not parse entities inside it.
4888 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4889 Diag(D.getIdentifierLoc(),
4890 diag::err_member_def_undefined_record)
4891 << Name << DC << D.getCXXScopeSpec().getRange();
4894 if (!D.getDeclSpec().isFriendSpecified()) {
4895 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4896 Name, D.getIdentifierLoc())) {
4904 // Check whether we need to rebuild the type of the given
4905 // declaration in the current instantiation.
4906 if (EnteringContext && IsDependentContext &&
4907 TemplateParamLists.size() != 0) {
4908 ContextRAII SavedContext(*this, DC);
4909 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4914 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4915 QualType R = TInfo->getType();
4917 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4918 // If this is a typedef, we'll end up spewing multiple diagnostics.
4919 // Just return early; it's safer. If this is a function, let the
4920 // "constructor cannot have a return type" diagnostic handle it.
4921 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4924 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4925 UPPC_DeclarationType))
4928 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4931 // See if this is a redefinition of a variable in the same scope.
4932 if (!D.getCXXScopeSpec().isSet()) {
4933 bool IsLinkageLookup = false;
4934 bool CreateBuiltins = false;
4936 // If the declaration we're planning to build will be a function
4937 // or object with linkage, then look for another declaration with
4938 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4940 // If the declaration we're planning to build will be declared with
4941 // external linkage in the translation unit, create any builtin with
4943 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4945 else if (CurContext->isFunctionOrMethod() &&
4946 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4947 R->isFunctionType())) {
4948 IsLinkageLookup = true;
4950 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4951 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4952 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4953 CreateBuiltins = true;
4955 if (IsLinkageLookup)
4956 Previous.clear(LookupRedeclarationWithLinkage);
4958 LookupName(Previous, S, CreateBuiltins);
4959 } else { // Something like "int foo::x;"
4960 LookupQualifiedName(Previous, DC);
4962 // C++ [dcl.meaning]p1:
4963 // When the declarator-id is qualified, the declaration shall refer to a
4964 // previously declared member of the class or namespace to which the
4965 // qualifier refers (or, in the case of a namespace, of an element of the
4966 // inline namespace set of that namespace (7.3.1)) or to a specialization
4969 // Note that we already checked the context above, and that we do not have
4970 // enough information to make sure that Previous contains the declaration
4971 // we want to match. For example, given:
4978 // void X::f(int) { } // ill-formed
4980 // In this case, Previous will point to the overload set
4981 // containing the two f's declared in X, but neither of them
4984 // C++ [dcl.meaning]p1:
4985 // [...] the member shall not merely have been introduced by a
4986 // using-declaration in the scope of the class or namespace nominated by
4987 // the nested-name-specifier of the declarator-id.
4988 RemoveUsingDecls(Previous);
4991 if (Previous.isSingleResult() &&
4992 Previous.getFoundDecl()->isTemplateParameter()) {
4993 // Maybe we will complain about the shadowed template parameter.
4994 if (!D.isInvalidType())
4995 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4996 Previous.getFoundDecl());
4998 // Just pretend that we didn't see the previous declaration.
5002 // In C++, the previous declaration we find might be a tag type
5003 // (class or enum). In this case, the new declaration will hide the
5004 // tag type. Note that this does does not apply if we're declaring a
5005 // typedef (C++ [dcl.typedef]p4).
5006 if (Previous.isSingleTagDecl() &&
5007 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5010 // Check that there are no default arguments other than in the parameters
5011 // of a function declaration (C++ only).
5012 if (getLangOpts().CPlusPlus)
5013 CheckExtraCXXDefaultArguments(D);
5015 if (D.getDeclSpec().isConceptSpecified()) {
5016 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5017 // applied only to the definition of a function template or variable
5018 // template, declared in namespace scope
5019 if (!TemplateParamLists.size()) {
5020 Diag(D.getDeclSpec().getConceptSpecLoc(),
5021 diag:: err_concept_wrong_decl_kind);
5025 if (!DC->getRedeclContext()->isFileContext()) {
5026 Diag(D.getIdentifierLoc(),
5027 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5034 bool AddToScope = true;
5035 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5036 if (TemplateParamLists.size()) {
5037 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5041 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5042 } else if (R->isFunctionType()) {
5043 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5047 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5054 // If this has an identifier and is not an invalid redeclaration or
5055 // function template specialization, add it to the scope stack.
5056 if (New->getDeclName() && AddToScope &&
5057 !(D.isRedeclaration() && New->isInvalidDecl())) {
5058 // Only make a locally-scoped extern declaration visible if it is the first
5059 // declaration of this entity. Qualified lookup for such an entity should
5060 // only find this declaration if there is no visible declaration of it.
5061 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5062 PushOnScopeChains(New, S, AddToContext);
5064 CurContext->addHiddenDecl(New);
5067 if (isInOpenMPDeclareTargetContext())
5068 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5073 /// Helper method to turn variable array types into constant array
5074 /// types in certain situations which would otherwise be errors (for
5075 /// GCC compatibility).
5076 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5077 ASTContext &Context,
5078 bool &SizeIsNegative,
5079 llvm::APSInt &Oversized) {
5080 // This method tries to turn a variable array into a constant
5081 // array even when the size isn't an ICE. This is necessary
5082 // for compatibility with code that depends on gcc's buggy
5083 // constant expression folding, like struct {char x[(int)(char*)2];}
5084 SizeIsNegative = false;
5087 if (T->isDependentType())
5090 QualifierCollector Qs;
5091 const Type *Ty = Qs.strip(T);
5093 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5094 QualType Pointee = PTy->getPointeeType();
5095 QualType FixedType =
5096 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5098 if (FixedType.isNull()) return FixedType;
5099 FixedType = Context.getPointerType(FixedType);
5100 return Qs.apply(Context, FixedType);
5102 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5103 QualType Inner = PTy->getInnerType();
5104 QualType FixedType =
5105 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5107 if (FixedType.isNull()) return FixedType;
5108 FixedType = Context.getParenType(FixedType);
5109 return Qs.apply(Context, FixedType);
5112 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5115 // FIXME: We should probably handle this case
5116 if (VLATy->getElementType()->isVariablyModifiedType())
5120 if (!VLATy->getSizeExpr() ||
5121 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5124 // Check whether the array size is negative.
5125 if (Res.isSigned() && Res.isNegative()) {
5126 SizeIsNegative = true;
5130 // Check whether the array is too large to be addressed.
5131 unsigned ActiveSizeBits
5132 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5134 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5139 return Context.getConstantArrayType(VLATy->getElementType(),
5140 Res, ArrayType::Normal, 0);
5144 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5145 SrcTL = SrcTL.getUnqualifiedLoc();
5146 DstTL = DstTL.getUnqualifiedLoc();
5147 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5148 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5149 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5150 DstPTL.getPointeeLoc());
5151 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5154 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5155 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5156 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5157 DstPTL.getInnerLoc());
5158 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5159 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5162 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5163 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5164 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5165 TypeLoc DstElemTL = DstATL.getElementLoc();
5166 DstElemTL.initializeFullCopy(SrcElemTL);
5167 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5168 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5169 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5172 /// Helper method to turn variable array types into constant array
5173 /// types in certain situations which would otherwise be errors (for
5174 /// GCC compatibility).
5175 static TypeSourceInfo*
5176 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5177 ASTContext &Context,
5178 bool &SizeIsNegative,
5179 llvm::APSInt &Oversized) {
5181 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5182 SizeIsNegative, Oversized);
5183 if (FixedTy.isNull())
5185 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5186 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5187 FixedTInfo->getTypeLoc());
5191 /// \brief Register the given locally-scoped extern "C" declaration so
5192 /// that it can be found later for redeclarations. We include any extern "C"
5193 /// declaration that is not visible in the translation unit here, not just
5194 /// function-scope declarations.
5196 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5197 if (!getLangOpts().CPlusPlus &&
5198 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5199 // Don't need to track declarations in the TU in C.
5202 // Note that we have a locally-scoped external with this name.
5203 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5206 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5207 // FIXME: We can have multiple results via __attribute__((overloadable)).
5208 auto Result = Context.getExternCContextDecl()->lookup(Name);
5209 return Result.empty() ? nullptr : *Result.begin();
5212 /// \brief Diagnose function specifiers on a declaration of an identifier that
5213 /// does not identify a function.
5214 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5215 // FIXME: We should probably indicate the identifier in question to avoid
5216 // confusion for constructs like "inline int a(), b;"
5217 if (DS.isInlineSpecified())
5218 Diag(DS.getInlineSpecLoc(),
5219 diag::err_inline_non_function);
5221 if (DS.isVirtualSpecified())
5222 Diag(DS.getVirtualSpecLoc(),
5223 diag::err_virtual_non_function);
5225 if (DS.isExplicitSpecified())
5226 Diag(DS.getExplicitSpecLoc(),
5227 diag::err_explicit_non_function);
5229 if (DS.isNoreturnSpecified())
5230 Diag(DS.getNoreturnSpecLoc(),
5231 diag::err_noreturn_non_function);
5235 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5236 TypeSourceInfo *TInfo, LookupResult &Previous) {
5237 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5238 if (D.getCXXScopeSpec().isSet()) {
5239 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5240 << D.getCXXScopeSpec().getRange();
5242 // Pretend we didn't see the scope specifier.
5247 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5249 if (D.getDeclSpec().isConstexprSpecified())
5250 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5252 if (D.getDeclSpec().isConceptSpecified())
5253 Diag(D.getDeclSpec().getConceptSpecLoc(),
5254 diag::err_concept_wrong_decl_kind);
5256 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5257 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5258 << D.getName().getSourceRange();
5262 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5263 if (!NewTD) return nullptr;
5265 // Handle attributes prior to checking for duplicates in MergeVarDecl
5266 ProcessDeclAttributes(S, NewTD, D);
5268 CheckTypedefForVariablyModifiedType(S, NewTD);
5270 bool Redeclaration = D.isRedeclaration();
5271 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5272 D.setRedeclaration(Redeclaration);
5277 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5278 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5279 // then it shall have block scope.
5280 // Note that variably modified types must be fixed before merging the decl so
5281 // that redeclarations will match.
5282 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5283 QualType T = TInfo->getType();
5284 if (T->isVariablyModifiedType()) {
5285 getCurFunction()->setHasBranchProtectedScope();
5287 if (S->getFnParent() == nullptr) {
5288 bool SizeIsNegative;
5289 llvm::APSInt Oversized;
5290 TypeSourceInfo *FixedTInfo =
5291 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5295 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5296 NewTD->setTypeSourceInfo(FixedTInfo);
5299 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5300 else if (T->isVariableArrayType())
5301 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5302 else if (Oversized.getBoolValue())
5303 Diag(NewTD->getLocation(), diag::err_array_too_large)
5304 << Oversized.toString(10);
5306 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5307 NewTD->setInvalidDecl();
5313 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5314 /// declares a typedef-name, either using the 'typedef' type specifier or via
5315 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5317 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5318 LookupResult &Previous, bool &Redeclaration) {
5319 // Merge the decl with the existing one if appropriate. If the decl is
5320 // in an outer scope, it isn't the same thing.
5321 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5322 /*AllowInlineNamespace*/false);
5323 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5324 if (!Previous.empty()) {
5325 Redeclaration = true;
5326 MergeTypedefNameDecl(S, NewTD, Previous);
5329 // If this is the C FILE type, notify the AST context.
5330 if (IdentifierInfo *II = NewTD->getIdentifier())
5331 if (!NewTD->isInvalidDecl() &&
5332 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5333 if (II->isStr("FILE"))
5334 Context.setFILEDecl(NewTD);
5335 else if (II->isStr("jmp_buf"))
5336 Context.setjmp_bufDecl(NewTD);
5337 else if (II->isStr("sigjmp_buf"))
5338 Context.setsigjmp_bufDecl(NewTD);
5339 else if (II->isStr("ucontext_t"))
5340 Context.setucontext_tDecl(NewTD);
5346 /// \brief Determines whether the given declaration is an out-of-scope
5347 /// previous declaration.
5349 /// This routine should be invoked when name lookup has found a
5350 /// previous declaration (PrevDecl) that is not in the scope where a
5351 /// new declaration by the same name is being introduced. If the new
5352 /// declaration occurs in a local scope, previous declarations with
5353 /// linkage may still be considered previous declarations (C99
5354 /// 6.2.2p4-5, C++ [basic.link]p6).
5356 /// \param PrevDecl the previous declaration found by name
5359 /// \param DC the context in which the new declaration is being
5362 /// \returns true if PrevDecl is an out-of-scope previous declaration
5363 /// for a new delcaration with the same name.
5365 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5366 ASTContext &Context) {
5370 if (!PrevDecl->hasLinkage())
5373 if (Context.getLangOpts().CPlusPlus) {
5374 // C++ [basic.link]p6:
5375 // If there is a visible declaration of an entity with linkage
5376 // having the same name and type, ignoring entities declared
5377 // outside the innermost enclosing namespace scope, the block
5378 // scope declaration declares that same entity and receives the
5379 // linkage of the previous declaration.
5380 DeclContext *OuterContext = DC->getRedeclContext();
5381 if (!OuterContext->isFunctionOrMethod())
5382 // This rule only applies to block-scope declarations.
5385 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5386 if (PrevOuterContext->isRecord())
5387 // We found a member function: ignore it.
5390 // Find the innermost enclosing namespace for the new and
5391 // previous declarations.
5392 OuterContext = OuterContext->getEnclosingNamespaceContext();
5393 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5395 // The previous declaration is in a different namespace, so it
5396 // isn't the same function.
5397 if (!OuterContext->Equals(PrevOuterContext))
5404 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5405 CXXScopeSpec &SS = D.getCXXScopeSpec();
5406 if (!SS.isSet()) return;
5407 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5410 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5411 QualType type = decl->getType();
5412 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5413 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5414 // Various kinds of declaration aren't allowed to be __autoreleasing.
5415 unsigned kind = -1U;
5416 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5417 if (var->hasAttr<BlocksAttr>())
5418 kind = 0; // __block
5419 else if (!var->hasLocalStorage())
5421 } else if (isa<ObjCIvarDecl>(decl)) {
5423 } else if (isa<FieldDecl>(decl)) {
5428 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5431 } else if (lifetime == Qualifiers::OCL_None) {
5432 // Try to infer lifetime.
5433 if (!type->isObjCLifetimeType())
5436 lifetime = type->getObjCARCImplicitLifetime();
5437 type = Context.getLifetimeQualifiedType(type, lifetime);
5438 decl->setType(type);
5441 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5442 // Thread-local variables cannot have lifetime.
5443 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5444 var->getTLSKind()) {
5445 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5454 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5455 // Ensure that an auto decl is deduced otherwise the checks below might cache
5456 // the wrong linkage.
5457 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5459 // 'weak' only applies to declarations with external linkage.
5460 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5461 if (!ND.isExternallyVisible()) {
5462 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5463 ND.dropAttr<WeakAttr>();
5466 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5467 if (ND.isExternallyVisible()) {
5468 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5469 ND.dropAttr<WeakRefAttr>();
5470 ND.dropAttr<AliasAttr>();
5474 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5475 if (VD->hasInit()) {
5476 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5477 assert(VD->isThisDeclarationADefinition() &&
5478 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5479 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5480 VD->dropAttr<AliasAttr>();
5485 // 'selectany' only applies to externally visible variable declarations.
5486 // It does not apply to functions.
5487 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5488 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5489 S.Diag(Attr->getLocation(),
5490 diag::err_attribute_selectany_non_extern_data);
5491 ND.dropAttr<SelectAnyAttr>();
5495 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5496 // dll attributes require external linkage. Static locals may have external
5497 // linkage but still cannot be explicitly imported or exported.
5498 auto *VD = dyn_cast<VarDecl>(&ND);
5499 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5500 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5502 ND.setInvalidDecl();
5506 // Virtual functions cannot be marked as 'notail'.
5507 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5508 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5509 if (MD->isVirtual()) {
5510 S.Diag(ND.getLocation(),
5511 diag::err_invalid_attribute_on_virtual_function)
5513 ND.dropAttr<NotTailCalledAttr>();
5517 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5519 bool IsSpecialization) {
5520 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5521 OldDecl = OldTD->getTemplatedDecl();
5522 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5523 NewDecl = NewTD->getTemplatedDecl();
5525 if (!OldDecl || !NewDecl)
5528 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5529 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5530 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5531 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5533 // dllimport and dllexport are inheritable attributes so we have to exclude
5534 // inherited attribute instances.
5535 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5536 (NewExportAttr && !NewExportAttr->isInherited());
5538 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5539 // the only exception being explicit specializations.
5540 // Implicitly generated declarations are also excluded for now because there
5541 // is no other way to switch these to use dllimport or dllexport.
5542 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5544 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5545 // Allow with a warning for free functions and global variables.
5546 bool JustWarn = false;
5547 if (!OldDecl->isCXXClassMember()) {
5548 auto *VD = dyn_cast<VarDecl>(OldDecl);
5549 if (VD && !VD->getDescribedVarTemplate())
5551 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5552 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5556 // We cannot change a declaration that's been used because IR has already
5557 // been emitted. Dllimported functions will still work though (modulo
5558 // address equality) as they can use the thunk.
5559 if (OldDecl->isUsed())
5560 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5563 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5564 : diag::err_attribute_dll_redeclaration;
5565 S.Diag(NewDecl->getLocation(), DiagID)
5567 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5568 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5570 NewDecl->setInvalidDecl();
5575 // A redeclaration is not allowed to drop a dllimport attribute, the only
5576 // exceptions being inline function definitions, local extern declarations,
5577 // and qualified friend declarations.
5578 // NB: MSVC converts such a declaration to dllexport.
5579 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5580 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5581 // Ignore static data because out-of-line definitions are diagnosed
5583 IsStaticDataMember = VD->isStaticDataMember();
5584 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5585 IsInline = FD->isInlined();
5586 IsQualifiedFriend = FD->getQualifier() &&
5587 FD->getFriendObjectKind() == Decl::FOK_Declared;
5590 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5591 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5592 S.Diag(NewDecl->getLocation(),
5593 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5594 << NewDecl << OldImportAttr;
5595 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5596 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5597 OldDecl->dropAttr<DLLImportAttr>();
5598 NewDecl->dropAttr<DLLImportAttr>();
5599 } else if (IsInline && OldImportAttr &&
5600 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5601 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5602 OldDecl->dropAttr<DLLImportAttr>();
5603 NewDecl->dropAttr<DLLImportAttr>();
5604 S.Diag(NewDecl->getLocation(),
5605 diag::warn_dllimport_dropped_from_inline_function)
5606 << NewDecl << OldImportAttr;
5610 /// Given that we are within the definition of the given function,
5611 /// will that definition behave like C99's 'inline', where the
5612 /// definition is discarded except for optimization purposes?
5613 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5614 // Try to avoid calling GetGVALinkageForFunction.
5616 // All cases of this require the 'inline' keyword.
5617 if (!FD->isInlined()) return false;
5619 // This is only possible in C++ with the gnu_inline attribute.
5620 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5623 // Okay, go ahead and call the relatively-more-expensive function.
5626 // AST quite reasonably asserts that it's working on a function
5627 // definition. We don't really have a way to tell it that we're
5628 // currently defining the function, so just lie to it in +Asserts
5629 // builds. This is an awful hack.
5634 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5643 /// Determine whether a variable is extern "C" prior to attaching
5644 /// an initializer. We can't just call isExternC() here, because that
5645 /// will also compute and cache whether the declaration is externally
5646 /// visible, which might change when we attach the initializer.
5648 /// This can only be used if the declaration is known to not be a
5649 /// redeclaration of an internal linkage declaration.
5655 /// Attaching the initializer here makes this declaration not externally
5656 /// visible, because its type has internal linkage.
5658 /// FIXME: This is a hack.
5659 template<typename T>
5660 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5661 if (S.getLangOpts().CPlusPlus) {
5662 // In C++, the overloadable attribute negates the effects of extern "C".
5663 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5666 // So do CUDA's host/device attributes.
5667 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5668 D->template hasAttr<CUDAHostAttr>()))
5671 return D->isExternC();
5674 static bool shouldConsiderLinkage(const VarDecl *VD) {
5675 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5676 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5677 return VD->hasExternalStorage();
5678 if (DC->isFileContext())
5682 llvm_unreachable("Unexpected context");
5685 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5686 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5687 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5688 isa<OMPDeclareReductionDecl>(DC))
5692 llvm_unreachable("Unexpected context");
5695 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5696 AttributeList::Kind Kind) {
5697 for (const AttributeList *L = AttrList; L; L = L->getNext())
5698 if (L->getKind() == Kind)
5703 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5704 AttributeList::Kind Kind) {
5705 // Check decl attributes on the DeclSpec.
5706 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5709 // Walk the declarator structure, checking decl attributes that were in a type
5710 // position to the decl itself.
5711 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5712 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5716 // Finally, check attributes on the decl itself.
5717 return hasParsedAttr(S, PD.getAttributes(), Kind);
5720 /// Adjust the \c DeclContext for a function or variable that might be a
5721 /// function-local external declaration.
5722 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5723 if (!DC->isFunctionOrMethod())
5726 // If this is a local extern function or variable declared within a function
5727 // template, don't add it into the enclosing namespace scope until it is
5728 // instantiated; it might have a dependent type right now.
5729 if (DC->isDependentContext())
5732 // C++11 [basic.link]p7:
5733 // When a block scope declaration of an entity with linkage is not found to
5734 // refer to some other declaration, then that entity is a member of the
5735 // innermost enclosing namespace.
5737 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5738 // semantically-enclosing namespace, not a lexically-enclosing one.
5739 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5740 DC = DC->getParent();
5744 /// \brief Returns true if given declaration has external C language linkage.
5745 static bool isDeclExternC(const Decl *D) {
5746 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5747 return FD->isExternC();
5748 if (const auto *VD = dyn_cast<VarDecl>(D))
5749 return VD->isExternC();
5751 llvm_unreachable("Unknown type of decl!");
5755 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5756 TypeSourceInfo *TInfo, LookupResult &Previous,
5757 MultiTemplateParamsArg TemplateParamLists,
5759 QualType R = TInfo->getType();
5760 DeclarationName Name = GetNameForDeclarator(D).getName();
5762 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5763 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5765 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5766 Diag(D.getIdentifierLoc(),
5767 diag::err_opencl_type_can_only_be_used_as_function_parameter)
5773 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5774 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5776 // dllimport globals without explicit storage class are treated as extern. We
5777 // have to change the storage class this early to get the right DeclContext.
5778 if (SC == SC_None && !DC->isRecord() &&
5779 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5780 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5783 DeclContext *OriginalDC = DC;
5784 bool IsLocalExternDecl = SC == SC_Extern &&
5785 adjustContextForLocalExternDecl(DC);
5787 if (getLangOpts().OpenCL) {
5788 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5790 while (NR->isPointerType()) {
5791 if (NR->isFunctionPointerType()) {
5792 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5796 NR = NR->getPointeeType();
5799 if (!getOpenCLOptions().cl_khr_fp16) {
5800 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5801 // half array type (unless the cl_khr_fp16 extension is enabled).
5802 if (Context.getBaseElementType(R)->isHalfType()) {
5803 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5809 if (SCSpec == DeclSpec::SCS_mutable) {
5810 // mutable can only appear on non-static class members, so it's always
5812 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5817 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5818 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5819 D.getDeclSpec().getStorageClassSpecLoc())) {
5820 // In C++11, the 'register' storage class specifier is deprecated.
5821 // Suppress the warning in system macros, it's used in macros in some
5822 // popular C system headers, such as in glibc's htonl() macro.
5823 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5824 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5825 : diag::warn_deprecated_register)
5826 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5829 IdentifierInfo *II = Name.getAsIdentifierInfo();
5831 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5836 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5838 if (!DC->isRecord() && S->getFnParent() == nullptr) {
5839 // C99 6.9p2: The storage-class specifiers auto and register shall not
5840 // appear in the declaration specifiers in an external declaration.
5841 // Global Register+Asm is a GNU extension we support.
5842 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5843 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5848 if (getLangOpts().OpenCL) {
5849 // OpenCL v1.2 s6.9.b p4:
5850 // The sampler type cannot be used with the __local and __global address
5851 // space qualifiers.
5852 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5853 R.getAddressSpace() == LangAS::opencl_global)) {
5854 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5857 // OpenCL 1.2 spec, p6.9 r:
5858 // The event type cannot be used to declare a program scope variable.
5859 // The event type cannot be used with the __local, __constant and __global
5860 // address space qualifiers.
5861 if (R->isEventT()) {
5862 if (S->getParent() == nullptr) {
5863 Diag(D.getLocStart(), diag::err_event_t_global_var);
5867 if (R.getAddressSpace()) {
5868 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5874 bool IsExplicitSpecialization = false;
5875 bool IsVariableTemplateSpecialization = false;
5876 bool IsPartialSpecialization = false;
5877 bool IsVariableTemplate = false;
5878 VarDecl *NewVD = nullptr;
5879 VarTemplateDecl *NewTemplate = nullptr;
5880 TemplateParameterList *TemplateParams = nullptr;
5881 if (!getLangOpts().CPlusPlus) {
5882 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5883 D.getIdentifierLoc(), II,
5886 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5887 ParsingInitForAutoVars.insert(NewVD);
5889 if (D.isInvalidType())
5890 NewVD->setInvalidDecl();
5892 bool Invalid = false;
5894 if (DC->isRecord() && !CurContext->isRecord()) {
5895 // This is an out-of-line definition of a static data member.
5900 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5901 diag::err_static_out_of_line)
5902 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5907 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5908 // to names of variables declared in a block or to function parameters.
5909 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5912 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5913 diag::err_storage_class_for_static_member)
5914 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5916 case SC_PrivateExtern:
5917 llvm_unreachable("C storage class in c++!");
5921 if (SC == SC_Static && CurContext->isRecord()) {
5922 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5923 if (RD->isLocalClass())
5924 Diag(D.getIdentifierLoc(),
5925 diag::err_static_data_member_not_allowed_in_local_class)
5926 << Name << RD->getDeclName();
5928 // C++98 [class.union]p1: If a union contains a static data member,
5929 // the program is ill-formed. C++11 drops this restriction.
5931 Diag(D.getIdentifierLoc(),
5932 getLangOpts().CPlusPlus11
5933 ? diag::warn_cxx98_compat_static_data_member_in_union
5934 : diag::ext_static_data_member_in_union) << Name;
5935 // We conservatively disallow static data members in anonymous structs.
5936 else if (!RD->getDeclName())
5937 Diag(D.getIdentifierLoc(),
5938 diag::err_static_data_member_not_allowed_in_anon_struct)
5939 << Name << RD->isUnion();
5943 // Match up the template parameter lists with the scope specifier, then
5944 // determine whether we have a template or a template specialization.
5945 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5946 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5947 D.getCXXScopeSpec(),
5948 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5949 ? D.getName().TemplateId
5952 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5954 if (TemplateParams) {
5955 if (!TemplateParams->size() &&
5956 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5957 // There is an extraneous 'template<>' for this variable. Complain
5958 // about it, but allow the declaration of the variable.
5959 Diag(TemplateParams->getTemplateLoc(),
5960 diag::err_template_variable_noparams)
5962 << SourceRange(TemplateParams->getTemplateLoc(),
5963 TemplateParams->getRAngleLoc());
5964 TemplateParams = nullptr;
5966 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5967 // This is an explicit specialization or a partial specialization.
5968 // FIXME: Check that we can declare a specialization here.
5969 IsVariableTemplateSpecialization = true;
5970 IsPartialSpecialization = TemplateParams->size() > 0;
5971 } else { // if (TemplateParams->size() > 0)
5972 // This is a template declaration.
5973 IsVariableTemplate = true;
5975 // Check that we can declare a template here.
5976 if (CheckTemplateDeclScope(S, TemplateParams))
5979 // Only C++1y supports variable templates (N3651).
5980 Diag(D.getIdentifierLoc(),
5981 getLangOpts().CPlusPlus14
5982 ? diag::warn_cxx11_compat_variable_template
5983 : diag::ext_variable_template);
5988 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5989 "should have a 'template<>' for this decl");
5992 if (IsVariableTemplateSpecialization) {
5993 SourceLocation TemplateKWLoc =
5994 TemplateParamLists.size() > 0
5995 ? TemplateParamLists[0]->getTemplateLoc()
5997 DeclResult Res = ActOnVarTemplateSpecialization(
5998 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5999 IsPartialSpecialization);
6000 if (Res.isInvalid())
6002 NewVD = cast<VarDecl>(Res.get());
6005 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6006 D.getIdentifierLoc(), II, R, TInfo, SC);
6008 // If this is supposed to be a variable template, create it as such.
6009 if (IsVariableTemplate) {
6011 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6012 TemplateParams, NewVD);
6013 NewVD->setDescribedVarTemplate(NewTemplate);
6016 // If this decl has an auto type in need of deduction, make a note of the
6017 // Decl so we can diagnose uses of it in its own initializer.
6018 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6019 ParsingInitForAutoVars.insert(NewVD);
6021 if (D.isInvalidType() || Invalid) {
6022 NewVD->setInvalidDecl();
6024 NewTemplate->setInvalidDecl();
6027 SetNestedNameSpecifier(NewVD, D);
6029 // If we have any template parameter lists that don't directly belong to
6030 // the variable (matching the scope specifier), store them.
6031 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6032 if (TemplateParamLists.size() > VDTemplateParamLists)
6033 NewVD->setTemplateParameterListsInfo(
6034 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6036 if (D.getDeclSpec().isConstexprSpecified())
6037 NewVD->setConstexpr(true);
6039 if (D.getDeclSpec().isConceptSpecified()) {
6040 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6043 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6044 // be declared with the thread_local, inline, friend, or constexpr
6045 // specifiers, [...]
6046 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6047 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6048 diag::err_concept_decl_invalid_specifiers)
6050 NewVD->setInvalidDecl(true);
6053 if (D.getDeclSpec().isConstexprSpecified()) {
6054 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6055 diag::err_concept_decl_invalid_specifiers)
6057 NewVD->setInvalidDecl(true);
6060 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6061 // applied only to the definition of a function template or variable
6062 // template, declared in namespace scope.
6063 if (IsVariableTemplateSpecialization) {
6064 Diag(D.getDeclSpec().getConceptSpecLoc(),
6065 diag::err_concept_specified_specialization)
6066 << (IsPartialSpecialization ? 2 : 1);
6069 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6070 // following restrictions:
6071 // - The declared type shall have the type bool.
6072 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6073 !NewVD->isInvalidDecl()) {
6074 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6075 NewVD->setInvalidDecl(true);
6080 // Set the lexical context. If the declarator has a C++ scope specifier, the
6081 // lexical context will be different from the semantic context.
6082 NewVD->setLexicalDeclContext(CurContext);
6084 NewTemplate->setLexicalDeclContext(CurContext);
6086 if (IsLocalExternDecl)
6087 NewVD->setLocalExternDecl();
6089 bool EmitTLSUnsupportedError = false;
6090 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6091 // C++11 [dcl.stc]p4:
6092 // When thread_local is applied to a variable of block scope the
6093 // storage-class-specifier static is implied if it does not appear
6095 // Core issue: 'static' is not implied if the variable is declared
6097 if (NewVD->hasLocalStorage() &&
6098 (SCSpec != DeclSpec::SCS_unspecified ||
6099 TSCS != DeclSpec::TSCS_thread_local ||
6100 !DC->isFunctionOrMethod()))
6101 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6102 diag::err_thread_non_global)
6103 << DeclSpec::getSpecifierName(TSCS);
6104 else if (!Context.getTargetInfo().isTLSSupported()) {
6105 if (getLangOpts().CUDA) {
6106 // Postpone error emission until we've collected attributes required to
6107 // figure out whether it's a host or device variable and whether the
6108 // error should be ignored.
6109 EmitTLSUnsupportedError = true;
6110 // We still need to mark the variable as TLS so it shows up in AST with
6111 // proper storage class for other tools to use even if we're not going
6112 // to emit any code for it.
6113 NewVD->setTSCSpec(TSCS);
6115 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6116 diag::err_thread_unsupported);
6118 NewVD->setTSCSpec(TSCS);
6122 // An inline definition of a function with external linkage shall
6123 // not contain a definition of a modifiable object with static or
6124 // thread storage duration...
6125 // We only apply this when the function is required to be defined
6126 // elsewhere, i.e. when the function is not 'extern inline'. Note
6127 // that a local variable with thread storage duration still has to
6128 // be marked 'static'. Also note that it's possible to get these
6129 // semantics in C++ using __attribute__((gnu_inline)).
6130 if (SC == SC_Static && S->getFnParent() != nullptr &&
6131 !NewVD->getType().isConstQualified()) {
6132 FunctionDecl *CurFD = getCurFunctionDecl();
6133 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6134 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6135 diag::warn_static_local_in_extern_inline);
6136 MaybeSuggestAddingStaticToDecl(CurFD);
6140 if (D.getDeclSpec().isModulePrivateSpecified()) {
6141 if (IsVariableTemplateSpecialization)
6142 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6143 << (IsPartialSpecialization ? 1 : 0)
6144 << FixItHint::CreateRemoval(
6145 D.getDeclSpec().getModulePrivateSpecLoc());
6146 else if (IsExplicitSpecialization)
6147 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6149 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6150 else if (NewVD->hasLocalStorage())
6151 Diag(NewVD->getLocation(), diag::err_module_private_local)
6152 << 0 << NewVD->getDeclName()
6153 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6154 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6156 NewVD->setModulePrivate();
6158 NewTemplate->setModulePrivate();
6162 // Handle attributes prior to checking for duplicates in MergeVarDecl
6163 ProcessDeclAttributes(S, NewVD, D);
6165 if (getLangOpts().CUDA) {
6166 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6167 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6168 diag::err_thread_unsupported);
6169 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6170 // storage [duration]."
6171 if (SC == SC_None && S->getFnParent() != nullptr &&
6172 (NewVD->hasAttr<CUDASharedAttr>() ||
6173 NewVD->hasAttr<CUDAConstantAttr>())) {
6174 NewVD->setStorageClass(SC_Static);
6178 // Ensure that dllimport globals without explicit storage class are treated as
6179 // extern. The storage class is set above using parsed attributes. Now we can
6180 // check the VarDecl itself.
6181 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6182 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6183 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6185 // In auto-retain/release, infer strong retension for variables of
6187 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6188 NewVD->setInvalidDecl();
6190 // Handle GNU asm-label extension (encoded as an attribute).
6191 if (Expr *E = (Expr*)D.getAsmLabel()) {
6192 // The parser guarantees this is a string.
6193 StringLiteral *SE = cast<StringLiteral>(E);
6194 StringRef Label = SE->getString();
6195 if (S->getFnParent() != nullptr) {
6199 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6202 // Local Named register
6203 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6204 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6205 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6209 case SC_PrivateExtern:
6212 } else if (SC == SC_Register) {
6213 // Global Named register
6214 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6215 const auto &TI = Context.getTargetInfo();
6216 bool HasSizeMismatch;
6218 if (!TI.isValidGCCRegisterName(Label))
6219 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6220 else if (!TI.validateGlobalRegisterVariable(Label,
6221 Context.getTypeSize(R),
6223 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6224 else if (HasSizeMismatch)
6225 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6228 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6229 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6230 NewVD->setInvalidDecl(true);
6234 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6235 Context, Label, 0));
6236 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6237 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6238 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6239 if (I != ExtnameUndeclaredIdentifiers.end()) {
6240 if (isDeclExternC(NewVD)) {
6241 NewVD->addAttr(I->second);
6242 ExtnameUndeclaredIdentifiers.erase(I);
6244 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6245 << /*Variable*/1 << NewVD;
6249 // Diagnose shadowed variables before filtering for scope.
6250 if (D.getCXXScopeSpec().isEmpty())
6251 CheckShadow(S, NewVD, Previous);
6253 // Don't consider existing declarations that are in a different
6254 // scope and are out-of-semantic-context declarations (if the new
6255 // declaration has linkage).
6256 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6257 D.getCXXScopeSpec().isNotEmpty() ||
6258 IsExplicitSpecialization ||
6259 IsVariableTemplateSpecialization);
6261 // Check whether the previous declaration is in the same block scope. This
6262 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6263 if (getLangOpts().CPlusPlus &&
6264 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6265 NewVD->setPreviousDeclInSameBlockScope(
6266 Previous.isSingleResult() && !Previous.isShadowed() &&
6267 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6269 if (!getLangOpts().CPlusPlus) {
6270 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6272 // If this is an explicit specialization of a static data member, check it.
6273 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6274 CheckMemberSpecialization(NewVD, Previous))
6275 NewVD->setInvalidDecl();
6277 // Merge the decl with the existing one if appropriate.
6278 if (!Previous.empty()) {
6279 if (Previous.isSingleResult() &&
6280 isa<FieldDecl>(Previous.getFoundDecl()) &&
6281 D.getCXXScopeSpec().isSet()) {
6282 // The user tried to define a non-static data member
6283 // out-of-line (C++ [dcl.meaning]p1).
6284 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6285 << D.getCXXScopeSpec().getRange();
6287 NewVD->setInvalidDecl();
6289 } else if (D.getCXXScopeSpec().isSet()) {
6290 // No previous declaration in the qualifying scope.
6291 Diag(D.getIdentifierLoc(), diag::err_no_member)
6292 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6293 << D.getCXXScopeSpec().getRange();
6294 NewVD->setInvalidDecl();
6297 if (!IsVariableTemplateSpecialization)
6298 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6300 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6301 // an explicit specialization (14.8.3) or a partial specialization of a
6302 // concept definition.
6303 if (IsVariableTemplateSpecialization &&
6304 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6305 Previous.isSingleResult()) {
6306 NamedDecl *PreviousDecl = Previous.getFoundDecl();
6307 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6308 if (VarTmpl->isConcept()) {
6309 Diag(NewVD->getLocation(), diag::err_concept_specialized)
6311 << (IsPartialSpecialization ? 2 /*partially specialized*/
6312 : 1 /*explicitly specialized*/);
6313 Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6314 NewVD->setInvalidDecl();
6320 VarTemplateDecl *PrevVarTemplate =
6321 NewVD->getPreviousDecl()
6322 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6325 // Check the template parameter list of this declaration, possibly
6326 // merging in the template parameter list from the previous variable
6327 // template declaration.
6328 if (CheckTemplateParameterList(
6330 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6332 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6333 DC->isDependentContext())
6334 ? TPC_ClassTemplateMember
6336 NewVD->setInvalidDecl();
6338 // If we are providing an explicit specialization of a static variable
6339 // template, make a note of that.
6340 if (PrevVarTemplate &&
6341 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6342 PrevVarTemplate->setMemberSpecialization();
6346 ProcessPragmaWeak(S, NewVD);
6348 // If this is the first declaration of an extern C variable, update
6349 // the map of such variables.
6350 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6351 isIncompleteDeclExternC(*this, NewVD))
6352 RegisterLocallyScopedExternCDecl(NewVD, S);
6354 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6355 Decl *ManglingContextDecl;
6356 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6357 NewVD->getDeclContext(), ManglingContextDecl)) {
6358 Context.setManglingNumber(
6359 NewVD, MCtx->getManglingNumber(
6360 NewVD, getMSManglingNumber(getLangOpts(), S)));
6361 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6365 // Special handling of variable named 'main'.
6366 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6367 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6368 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6370 // C++ [basic.start.main]p3
6371 // A program that declares a variable main at global scope is ill-formed.
6372 if (getLangOpts().CPlusPlus)
6373 Diag(D.getLocStart(), diag::err_main_global_variable);
6375 // In C, and external-linkage variable named main results in undefined
6377 else if (NewVD->hasExternalFormalLinkage())
6378 Diag(D.getLocStart(), diag::warn_main_redefined);
6381 if (D.isRedeclaration() && !Previous.empty()) {
6382 checkDLLAttributeRedeclaration(
6383 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6384 IsExplicitSpecialization);
6388 if (NewVD->isInvalidDecl())
6389 NewTemplate->setInvalidDecl();
6390 ActOnDocumentableDecl(NewTemplate);
6397 /// Enum describing the %select options in diag::warn_decl_shadow.
6398 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6400 /// Determine what kind of declaration we're shadowing.
6401 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6402 const DeclContext *OldDC) {
6403 if (isa<RecordDecl>(OldDC))
6404 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6405 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6408 /// \brief Diagnose variable or built-in function shadowing. Implements
6411 /// This method is called whenever a VarDecl is added to a "useful"
6414 /// \param S the scope in which the shadowing name is being declared
6415 /// \param R the lookup of the name
6417 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6418 // Return if warning is ignored.
6419 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6422 // Don't diagnose declarations at file scope.
6423 if (D->hasGlobalStorage())
6426 DeclContext *NewDC = D->getDeclContext();
6428 // Only diagnose if we're shadowing an unambiguous field or variable.
6429 if (R.getResultKind() != LookupResult::Found)
6432 NamedDecl* ShadowedDecl = R.getFoundDecl();
6433 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6436 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6437 // Fields are not shadowed by variables in C++ static methods.
6438 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6442 // Fields shadowed by constructor parameters are a special case. Usually
6443 // the constructor initializes the field with the parameter.
6444 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6445 // Remember that this was shadowed so we can either warn about its
6446 // modification or its existence depending on warning settings.
6447 D = D->getCanonicalDecl();
6448 ShadowingDecls.insert({D, FD});
6453 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6454 if (shadowedVar->isExternC()) {
6455 // For shadowing external vars, make sure that we point to the global
6456 // declaration, not a locally scoped extern declaration.
6457 for (auto I : shadowedVar->redecls())
6458 if (I->isFileVarDecl()) {
6464 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6466 // Only warn about certain kinds of shadowing for class members.
6467 if (NewDC && NewDC->isRecord()) {
6468 // In particular, don't warn about shadowing non-class members.
6469 if (!OldDC->isRecord())
6472 // TODO: should we warn about static data members shadowing
6473 // static data members from base classes?
6475 // TODO: don't diagnose for inaccessible shadowed members.
6476 // This is hard to do perfectly because we might friend the
6477 // shadowing context, but that's just a false negative.
6481 DeclarationName Name = R.getLookupName();
6483 // Emit warning and note.
6484 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6486 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6487 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6488 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6491 /// \brief Check -Wshadow without the advantage of a previous lookup.
6492 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6493 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6496 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6497 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6499 CheckShadow(S, D, R);
6502 /// Check if 'E', which is an expression that is about to be modified, refers
6503 /// to a constructor parameter that shadows a field.
6504 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6505 // Quickly ignore expressions that can't be shadowing ctor parameters.
6506 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6508 E = E->IgnoreParenImpCasts();
6509 auto *DRE = dyn_cast<DeclRefExpr>(E);
6512 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6513 auto I = ShadowingDecls.find(D);
6514 if (I == ShadowingDecls.end())
6516 const NamedDecl *ShadowedDecl = I->second;
6517 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6518 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6519 Diag(D->getLocation(), diag::note_var_declared_here) << D;
6520 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6522 // Avoid issuing multiple warnings about the same decl.
6523 ShadowingDecls.erase(I);
6526 /// Check for conflict between this global or extern "C" declaration and
6527 /// previous global or extern "C" declarations. This is only used in C++.
6528 template<typename T>
6529 static bool checkGlobalOrExternCConflict(
6530 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6531 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6532 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6534 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6535 // The common case: this global doesn't conflict with any extern "C"
6541 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6542 // Both the old and new declarations have C language linkage. This is a
6545 Previous.addDecl(Prev);
6549 // This is a global, non-extern "C" declaration, and there is a previous
6550 // non-global extern "C" declaration. Diagnose if this is a variable
6552 if (!isa<VarDecl>(ND))
6555 // The declaration is extern "C". Check for any declaration in the
6556 // translation unit which might conflict.
6558 // We have already performed the lookup into the translation unit.
6560 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6562 if (isa<VarDecl>(*I)) {
6568 DeclContext::lookup_result R =
6569 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6570 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6572 if (isa<VarDecl>(*I)) {
6576 // FIXME: If we have any other entity with this name in global scope,
6577 // the declaration is ill-formed, but that is a defect: it breaks the
6578 // 'stat' hack, for instance. Only variables can have mangled name
6579 // clashes with extern "C" declarations, so only they deserve a
6588 // Use the first declaration's location to ensure we point at something which
6589 // is lexically inside an extern "C" linkage-spec.
6590 assert(Prev && "should have found a previous declaration to diagnose");
6591 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6592 Prev = FD->getFirstDecl();
6594 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6596 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6598 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6603 /// Apply special rules for handling extern "C" declarations. Returns \c true
6604 /// if we have found that this is a redeclaration of some prior entity.
6606 /// Per C++ [dcl.link]p6:
6607 /// Two declarations [for a function or variable] with C language linkage
6608 /// with the same name that appear in different scopes refer to the same
6609 /// [entity]. An entity with C language linkage shall not be declared with
6610 /// the same name as an entity in global scope.
6611 template<typename T>
6612 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6613 LookupResult &Previous) {
6614 if (!S.getLangOpts().CPlusPlus) {
6615 // In C, when declaring a global variable, look for a corresponding 'extern'
6616 // variable declared in function scope. We don't need this in C++, because
6617 // we find local extern decls in the surrounding file-scope DeclContext.
6618 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6619 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6621 Previous.addDecl(Prev);
6628 // A declaration in the translation unit can conflict with an extern "C"
6630 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6631 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6633 // An extern "C" declaration can conflict with a declaration in the
6634 // translation unit or can be a redeclaration of an extern "C" declaration
6635 // in another scope.
6636 if (isIncompleteDeclExternC(S,ND))
6637 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6639 // Neither global nor extern "C": nothing to do.
6643 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6644 // If the decl is already known invalid, don't check it.
6645 if (NewVD->isInvalidDecl())
6648 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6649 QualType T = TInfo->getType();
6651 // Defer checking an 'auto' type until its initializer is attached.
6652 if (T->isUndeducedType())
6655 if (NewVD->hasAttrs())
6656 CheckAlignasUnderalignment(NewVD);
6658 if (T->isObjCObjectType()) {
6659 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6660 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6661 T = Context.getObjCObjectPointerType(T);
6665 // Emit an error if an address space was applied to decl with local storage.
6666 // This includes arrays of objects with address space qualifiers, but not
6667 // automatic variables that point to other address spaces.
6668 // ISO/IEC TR 18037 S5.1.2
6669 if (!getLangOpts().OpenCL
6670 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6671 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6672 NewVD->setInvalidDecl();
6676 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6678 if (getLangOpts().OpenCLVersion == 120 &&
6679 !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6680 NewVD->isStaticLocal()) {
6681 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6682 NewVD->setInvalidDecl();
6686 if (getLangOpts().OpenCL) {
6687 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6688 if (NewVD->hasAttr<BlocksAttr>()) {
6689 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6693 if (T->isBlockPointerType()) {
6694 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6695 // can't use 'extern' storage class.
6696 if (!T.isConstQualified()) {
6697 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6699 NewVD->setInvalidDecl();
6702 if (NewVD->hasExternalStorage()) {
6703 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6704 NewVD->setInvalidDecl();
6707 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6708 // TODO: this check is not enough as it doesn't diagnose the typedef
6709 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6710 const FunctionProtoType *FTy =
6711 BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6712 if (FTy && FTy->isVariadic()) {
6713 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6714 << T << NewVD->getSourceRange();
6715 NewVD->setInvalidDecl();
6719 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6720 // __constant address space.
6721 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6722 // variables inside a function can also be declared in the global
6724 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6725 NewVD->hasExternalStorage()) {
6726 if (!T->isSamplerT() &&
6727 !(T.getAddressSpace() == LangAS::opencl_constant ||
6728 (T.getAddressSpace() == LangAS::opencl_global &&
6729 getLangOpts().OpenCLVersion == 200))) {
6730 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6731 if (getLangOpts().OpenCLVersion == 200)
6732 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6733 << Scope << "global or constant";
6735 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6736 << Scope << "constant";
6737 NewVD->setInvalidDecl();
6741 if (T.getAddressSpace() == LangAS::opencl_global) {
6742 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6743 << 1 /*is any function*/ << "global";
6744 NewVD->setInvalidDecl();
6747 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6749 if (T.getAddressSpace() == LangAS::opencl_constant ||
6750 T.getAddressSpace() == LangAS::opencl_local) {
6751 FunctionDecl *FD = getCurFunctionDecl();
6752 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6753 if (T.getAddressSpace() == LangAS::opencl_constant)
6754 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6755 << 0 /*non-kernel only*/ << "constant";
6757 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6758 << 0 /*non-kernel only*/ << "local";
6759 NewVD->setInvalidDecl();
6766 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6767 && !NewVD->hasAttr<BlocksAttr>()) {
6768 if (getLangOpts().getGC() != LangOptions::NonGC)
6769 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6771 assert(!getLangOpts().ObjCAutoRefCount);
6772 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6776 bool isVM = T->isVariablyModifiedType();
6777 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6778 NewVD->hasAttr<BlocksAttr>())
6779 getCurFunction()->setHasBranchProtectedScope();
6781 if ((isVM && NewVD->hasLinkage()) ||
6782 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6783 bool SizeIsNegative;
6784 llvm::APSInt Oversized;
6785 TypeSourceInfo *FixedTInfo =
6786 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6787 SizeIsNegative, Oversized);
6788 if (!FixedTInfo && T->isVariableArrayType()) {
6789 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6790 // FIXME: This won't give the correct result for
6792 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6794 if (NewVD->isFileVarDecl())
6795 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6797 else if (NewVD->isStaticLocal())
6798 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6801 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6803 NewVD->setInvalidDecl();
6808 if (NewVD->isFileVarDecl())
6809 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6811 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6812 NewVD->setInvalidDecl();
6816 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6817 NewVD->setType(FixedTInfo->getType());
6818 NewVD->setTypeSourceInfo(FixedTInfo);
6821 if (T->isVoidType()) {
6822 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6823 // of objects and functions.
6824 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6825 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6827 NewVD->setInvalidDecl();
6832 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6833 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6834 NewVD->setInvalidDecl();
6838 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6839 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6840 NewVD->setInvalidDecl();
6844 if (NewVD->isConstexpr() && !T->isDependentType() &&
6845 RequireLiteralType(NewVD->getLocation(), T,
6846 diag::err_constexpr_var_non_literal)) {
6847 NewVD->setInvalidDecl();
6852 /// \brief Perform semantic checking on a newly-created variable
6855 /// This routine performs all of the type-checking required for a
6856 /// variable declaration once it has been built. It is used both to
6857 /// check variables after they have been parsed and their declarators
6858 /// have been translated into a declaration, and to check variables
6859 /// that have been instantiated from a template.
6861 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6863 /// Returns true if the variable declaration is a redeclaration.
6864 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6865 CheckVariableDeclarationType(NewVD);
6867 // If the decl is already known invalid, don't check it.
6868 if (NewVD->isInvalidDecl())
6871 // If we did not find anything by this name, look for a non-visible
6872 // extern "C" declaration with the same name.
6873 if (Previous.empty() &&
6874 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6875 Previous.setShadowed();
6877 if (!Previous.empty()) {
6878 MergeVarDecl(NewVD, Previous);
6885 struct FindOverriddenMethod {
6887 CXXMethodDecl *Method;
6889 /// Member lookup function that determines whether a given C++
6890 /// method overrides a method in a base class, to be used with
6891 /// CXXRecordDecl::lookupInBases().
6892 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6893 RecordDecl *BaseRecord =
6894 Specifier->getType()->getAs<RecordType>()->getDecl();
6896 DeclarationName Name = Method->getDeclName();
6898 // FIXME: Do we care about other names here too?
6899 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6900 // We really want to find the base class destructor here.
6901 QualType T = S->Context.getTypeDeclType(BaseRecord);
6902 CanQualType CT = S->Context.getCanonicalType(T);
6904 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6907 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6908 Path.Decls = Path.Decls.slice(1)) {
6909 NamedDecl *D = Path.Decls.front();
6910 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6911 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6920 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6921 } // end anonymous namespace
6923 /// \brief Report an error regarding overriding, along with any relevant
6924 /// overriden methods.
6926 /// \param DiagID the primary error to report.
6927 /// \param MD the overriding method.
6928 /// \param OEK which overrides to include as notes.
6929 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6930 OverrideErrorKind OEK = OEK_All) {
6931 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6932 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6933 E = MD->end_overridden_methods();
6935 // This check (& the OEK parameter) could be replaced by a predicate, but
6936 // without lambdas that would be overkill. This is still nicer than writing
6937 // out the diag loop 3 times.
6938 if ((OEK == OEK_All) ||
6939 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6940 (OEK == OEK_Deleted && (*I)->isDeleted()))
6941 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6945 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6946 /// and if so, check that it's a valid override and remember it.
6947 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6948 // Look for methods in base classes that this method might override.
6950 FindOverriddenMethod FOM;
6953 bool hasDeletedOverridenMethods = false;
6954 bool hasNonDeletedOverridenMethods = false;
6955 bool AddedAny = false;
6956 if (DC->lookupInBases(FOM, Paths)) {
6957 for (auto *I : Paths.found_decls()) {
6958 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6959 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6960 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6961 !CheckOverridingFunctionAttributes(MD, OldMD) &&
6962 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6963 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6964 hasDeletedOverridenMethods |= OldMD->isDeleted();
6965 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6972 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6973 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6975 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6976 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6983 // Struct for holding all of the extra arguments needed by
6984 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6985 struct ActOnFDArgs {
6988 MultiTemplateParamsArg TemplateParamLists;
6991 } // end anonymous namespace
6995 // Callback to only accept typo corrections that have a non-zero edit distance.
6996 // Also only accept corrections that have the same parent decl.
6997 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6999 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7000 CXXRecordDecl *Parent)
7001 : Context(Context), OriginalFD(TypoFD),
7002 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7004 bool ValidateCandidate(const TypoCorrection &candidate) override {
7005 if (candidate.getEditDistance() == 0)
7008 SmallVector<unsigned, 1> MismatchedParams;
7009 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7010 CDeclEnd = candidate.end();
7011 CDecl != CDeclEnd; ++CDecl) {
7012 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7014 if (FD && !FD->hasBody() &&
7015 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7016 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7017 CXXRecordDecl *Parent = MD->getParent();
7018 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7020 } else if (!ExpectedParent) {
7030 ASTContext &Context;
7031 FunctionDecl *OriginalFD;
7032 CXXRecordDecl *ExpectedParent;
7035 } // end anonymous namespace
7037 /// \brief Generate diagnostics for an invalid function redeclaration.
7039 /// This routine handles generating the diagnostic messages for an invalid
7040 /// function redeclaration, including finding possible similar declarations
7041 /// or performing typo correction if there are no previous declarations with
7044 /// Returns a NamedDecl iff typo correction was performed and substituting in
7045 /// the new declaration name does not cause new errors.
7046 static NamedDecl *DiagnoseInvalidRedeclaration(
7047 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7048 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7049 DeclarationName Name = NewFD->getDeclName();
7050 DeclContext *NewDC = NewFD->getDeclContext();
7051 SmallVector<unsigned, 1> MismatchedParams;
7052 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7053 TypoCorrection Correction;
7054 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7055 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7056 : diag::err_member_decl_does_not_match;
7057 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7058 IsLocalFriend ? Sema::LookupLocalFriendName
7059 : Sema::LookupOrdinaryName,
7060 Sema::ForRedeclaration);
7062 NewFD->setInvalidDecl();
7064 SemaRef.LookupName(Prev, S);
7066 SemaRef.LookupQualifiedName(Prev, NewDC);
7067 assert(!Prev.isAmbiguous() &&
7068 "Cannot have an ambiguity in previous-declaration lookup");
7069 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7070 if (!Prev.empty()) {
7071 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7072 Func != FuncEnd; ++Func) {
7073 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7075 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7076 // Add 1 to the index so that 0 can mean the mismatch didn't
7077 // involve a parameter
7079 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7080 NearMatches.push_back(std::make_pair(FD, ParamNum));
7083 // If the qualified name lookup yielded nothing, try typo correction
7084 } else if ((Correction = SemaRef.CorrectTypo(
7085 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7086 &ExtraArgs.D.getCXXScopeSpec(),
7087 llvm::make_unique<DifferentNameValidatorCCC>(
7088 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7089 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7090 // Set up everything for the call to ActOnFunctionDeclarator
7091 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7092 ExtraArgs.D.getIdentifierLoc());
7094 Previous.setLookupName(Correction.getCorrection());
7095 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7096 CDeclEnd = Correction.end();
7097 CDecl != CDeclEnd; ++CDecl) {
7098 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7099 if (FD && !FD->hasBody() &&
7100 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7101 Previous.addDecl(FD);
7104 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7107 // Retry building the function declaration with the new previous
7108 // declarations, and with errors suppressed.
7111 Sema::SFINAETrap Trap(SemaRef);
7113 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7114 // pieces need to verify the typo-corrected C++ declaration and hopefully
7115 // eliminate the need for the parameter pack ExtraArgs.
7116 Result = SemaRef.ActOnFunctionDeclarator(
7117 ExtraArgs.S, ExtraArgs.D,
7118 Correction.getCorrectionDecl()->getDeclContext(),
7119 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7120 ExtraArgs.AddToScope);
7122 if (Trap.hasErrorOccurred())
7127 // Determine which correction we picked.
7128 Decl *Canonical = Result->getCanonicalDecl();
7129 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7131 if ((*I)->getCanonicalDecl() == Canonical)
7132 Correction.setCorrectionDecl(*I);
7134 SemaRef.diagnoseTypo(
7136 SemaRef.PDiag(IsLocalFriend
7137 ? diag::err_no_matching_local_friend_suggest
7138 : diag::err_member_decl_does_not_match_suggest)
7139 << Name << NewDC << IsDefinition);
7143 // Pretend the typo correction never occurred
7144 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7145 ExtraArgs.D.getIdentifierLoc());
7146 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7148 Previous.setLookupName(Name);
7151 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7152 << Name << NewDC << IsDefinition << NewFD->getLocation();
7154 bool NewFDisConst = false;
7155 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7156 NewFDisConst = NewMD->isConst();
7158 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7159 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7160 NearMatch != NearMatchEnd; ++NearMatch) {
7161 FunctionDecl *FD = NearMatch->first;
7162 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7163 bool FDisConst = MD && MD->isConst();
7164 bool IsMember = MD || !IsLocalFriend;
7166 // FIXME: These notes are poorly worded for the local friend case.
7167 if (unsigned Idx = NearMatch->second) {
7168 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7169 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7170 if (Loc.isInvalid()) Loc = FD->getLocation();
7171 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7172 : diag::note_local_decl_close_param_match)
7173 << Idx << FDParam->getType()
7174 << NewFD->getParamDecl(Idx - 1)->getType();
7175 } else if (FDisConst != NewFDisConst) {
7176 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7177 << NewFDisConst << FD->getSourceRange().getEnd();
7179 SemaRef.Diag(FD->getLocation(),
7180 IsMember ? diag::note_member_def_close_match
7181 : diag::note_local_decl_close_match);
7186 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7187 switch (D.getDeclSpec().getStorageClassSpec()) {
7188 default: llvm_unreachable("Unknown storage class!");
7189 case DeclSpec::SCS_auto:
7190 case DeclSpec::SCS_register:
7191 case DeclSpec::SCS_mutable:
7192 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7193 diag::err_typecheck_sclass_func);
7196 case DeclSpec::SCS_unspecified: break;
7197 case DeclSpec::SCS_extern:
7198 if (D.getDeclSpec().isExternInLinkageSpec())
7201 case DeclSpec::SCS_static: {
7202 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7204 // The declaration of an identifier for a function that has
7205 // block scope shall have no explicit storage-class specifier
7206 // other than extern
7207 // See also (C++ [dcl.stc]p4).
7208 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7209 diag::err_static_block_func);
7214 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7217 // No explicit storage class has already been returned
7221 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7222 DeclContext *DC, QualType &R,
7223 TypeSourceInfo *TInfo,
7225 bool &IsVirtualOkay) {
7226 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7227 DeclarationName Name = NameInfo.getName();
7229 FunctionDecl *NewFD = nullptr;
7230 bool isInline = D.getDeclSpec().isInlineSpecified();
7232 if (!SemaRef.getLangOpts().CPlusPlus) {
7233 // Determine whether the function was written with a
7234 // prototype. This true when:
7235 // - there is a prototype in the declarator, or
7236 // - the type R of the function is some kind of typedef or other reference
7237 // to a type name (which eventually refers to a function type).
7239 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7240 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7242 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7243 D.getLocStart(), NameInfo, R,
7244 TInfo, SC, isInline,
7245 HasPrototype, false);
7246 if (D.isInvalidType())
7247 NewFD->setInvalidDecl();
7252 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7253 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7255 // Check that the return type is not an abstract class type.
7256 // For record types, this is done by the AbstractClassUsageDiagnoser once
7257 // the class has been completely parsed.
7258 if (!DC->isRecord() &&
7259 SemaRef.RequireNonAbstractType(
7260 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7261 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7264 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7265 // This is a C++ constructor declaration.
7266 assert(DC->isRecord() &&
7267 "Constructors can only be declared in a member context");
7269 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7270 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7271 D.getLocStart(), NameInfo,
7272 R, TInfo, isExplicit, isInline,
7273 /*isImplicitlyDeclared=*/false,
7276 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7277 // This is a C++ destructor declaration.
7278 if (DC->isRecord()) {
7279 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7280 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7281 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7282 SemaRef.Context, Record,
7284 NameInfo, R, TInfo, isInline,
7285 /*isImplicitlyDeclared=*/false);
7287 // If the class is complete, then we now create the implicit exception
7288 // specification. If the class is incomplete or dependent, we can't do
7290 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7291 Record->getDefinition() && !Record->isBeingDefined() &&
7292 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7293 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7296 IsVirtualOkay = true;
7300 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7303 // Create a FunctionDecl to satisfy the function definition parsing
7305 return FunctionDecl::Create(SemaRef.Context, DC,
7307 D.getIdentifierLoc(), Name, R, TInfo,
7309 /*hasPrototype=*/true, isConstexpr);
7312 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7313 if (!DC->isRecord()) {
7314 SemaRef.Diag(D.getIdentifierLoc(),
7315 diag::err_conv_function_not_member);
7319 SemaRef.CheckConversionDeclarator(D, R, SC);
7320 IsVirtualOkay = true;
7321 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7322 D.getLocStart(), NameInfo,
7323 R, TInfo, isInline, isExplicit,
7324 isConstexpr, SourceLocation());
7326 } else if (DC->isRecord()) {
7327 // If the name of the function is the same as the name of the record,
7328 // then this must be an invalid constructor that has a return type.
7329 // (The parser checks for a return type and makes the declarator a
7330 // constructor if it has no return type).
7331 if (Name.getAsIdentifierInfo() &&
7332 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7333 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7334 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7335 << SourceRange(D.getIdentifierLoc());
7339 // This is a C++ method declaration.
7340 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7341 cast<CXXRecordDecl>(DC),
7342 D.getLocStart(), NameInfo, R,
7343 TInfo, SC, isInline,
7344 isConstexpr, SourceLocation());
7345 IsVirtualOkay = !Ret->isStatic();
7349 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7350 if (!isFriend && SemaRef.CurContext->isRecord())
7353 // Determine whether the function was written with a
7354 // prototype. This true when:
7355 // - we're in C++ (where every function has a prototype),
7356 return FunctionDecl::Create(SemaRef.Context, DC,
7358 NameInfo, R, TInfo, SC, isInline,
7359 true/*HasPrototype*/, isConstexpr);
7363 enum OpenCLParamType {
7367 PrivatePtrKernelParam,
7372 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7373 if (PT->isPointerType()) {
7374 QualType PointeeType = PT->getPointeeType();
7375 if (PointeeType->isPointerType())
7376 return PtrPtrKernelParam;
7377 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7381 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7382 // be used as builtin types.
7384 if (PT->isImageType())
7385 return PtrKernelParam;
7387 if (PT->isBooleanType())
7388 return InvalidKernelParam;
7391 return InvalidKernelParam;
7393 if (PT->isHalfType())
7394 return InvalidKernelParam;
7396 if (PT->isRecordType())
7397 return RecordKernelParam;
7399 return ValidKernelParam;
7402 static void checkIsValidOpenCLKernelParameter(
7406 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7407 QualType PT = Param->getType();
7409 // Cache the valid types we encounter to avoid rechecking structs that are
7411 if (ValidTypes.count(PT.getTypePtr()))
7414 switch (getOpenCLKernelParameterType(PT)) {
7415 case PtrPtrKernelParam:
7416 // OpenCL v1.2 s6.9.a:
7417 // A kernel function argument cannot be declared as a
7418 // pointer to a pointer type.
7419 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7423 case PrivatePtrKernelParam:
7424 // OpenCL v1.2 s6.9.a:
7425 // A kernel function argument cannot be declared as a
7426 // pointer to the private address space.
7427 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7431 // OpenCL v1.2 s6.9.k:
7432 // Arguments to kernel functions in a program cannot be declared with the
7433 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7434 // uintptr_t or a struct and/or union that contain fields declared to be
7435 // one of these built-in scalar types.
7437 case InvalidKernelParam:
7438 // OpenCL v1.2 s6.8 n:
7439 // A kernel function argument cannot be declared
7441 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7445 case PtrKernelParam:
7446 case ValidKernelParam:
7447 ValidTypes.insert(PT.getTypePtr());
7450 case RecordKernelParam:
7454 // Track nested structs we will inspect
7455 SmallVector<const Decl *, 4> VisitStack;
7457 // Track where we are in the nested structs. Items will migrate from
7458 // VisitStack to HistoryStack as we do the DFS for bad field.
7459 SmallVector<const FieldDecl *, 4> HistoryStack;
7460 HistoryStack.push_back(nullptr);
7462 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7463 VisitStack.push_back(PD);
7465 assert(VisitStack.back() && "First decl null?");
7468 const Decl *Next = VisitStack.pop_back_val();
7470 assert(!HistoryStack.empty());
7471 // Found a marker, we have gone up a level
7472 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7473 ValidTypes.insert(Hist->getType().getTypePtr());
7478 // Adds everything except the original parameter declaration (which is not a
7479 // field itself) to the history stack.
7480 const RecordDecl *RD;
7481 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7482 HistoryStack.push_back(Field);
7483 RD = Field->getType()->castAs<RecordType>()->getDecl();
7485 RD = cast<RecordDecl>(Next);
7488 // Add a null marker so we know when we've gone back up a level
7489 VisitStack.push_back(nullptr);
7491 for (const auto *FD : RD->fields()) {
7492 QualType QT = FD->getType();
7494 if (ValidTypes.count(QT.getTypePtr()))
7497 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7498 if (ParamType == ValidKernelParam)
7501 if (ParamType == RecordKernelParam) {
7502 VisitStack.push_back(FD);
7506 // OpenCL v1.2 s6.9.p:
7507 // Arguments to kernel functions that are declared to be a struct or union
7508 // do not allow OpenCL objects to be passed as elements of the struct or
7510 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7511 ParamType == PrivatePtrKernelParam) {
7512 S.Diag(Param->getLocation(),
7513 diag::err_record_with_pointers_kernel_param)
7514 << PT->isUnionType()
7517 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7520 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7521 << PD->getDeclName();
7523 // We have an error, now let's go back up through history and show where
7524 // the offending field came from
7525 for (ArrayRef<const FieldDecl *>::const_iterator
7526 I = HistoryStack.begin() + 1,
7527 E = HistoryStack.end();
7529 const FieldDecl *OuterField = *I;
7530 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7531 << OuterField->getType();
7534 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7535 << QT->isPointerType()
7540 } while (!VisitStack.empty());
7544 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7545 TypeSourceInfo *TInfo, LookupResult &Previous,
7546 MultiTemplateParamsArg TemplateParamLists,
7548 QualType R = TInfo->getType();
7550 assert(R.getTypePtr()->isFunctionType());
7552 // TODO: consider using NameInfo for diagnostic.
7553 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7554 DeclarationName Name = NameInfo.getName();
7555 StorageClass SC = getFunctionStorageClass(*this, D);
7557 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7558 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7559 diag::err_invalid_thread)
7560 << DeclSpec::getSpecifierName(TSCS);
7562 if (D.isFirstDeclarationOfMember())
7563 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7564 D.getIdentifierLoc());
7566 bool isFriend = false;
7567 FunctionTemplateDecl *FunctionTemplate = nullptr;
7568 bool isExplicitSpecialization = false;
7569 bool isFunctionTemplateSpecialization = false;
7571 bool isDependentClassScopeExplicitSpecialization = false;
7572 bool HasExplicitTemplateArgs = false;
7573 TemplateArgumentListInfo TemplateArgs;
7575 bool isVirtualOkay = false;
7577 DeclContext *OriginalDC = DC;
7578 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7580 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7582 if (!NewFD) return nullptr;
7584 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7585 NewFD->setTopLevelDeclInObjCContainer();
7587 // Set the lexical context. If this is a function-scope declaration, or has a
7588 // C++ scope specifier, or is the object of a friend declaration, the lexical
7589 // context will be different from the semantic context.
7590 NewFD->setLexicalDeclContext(CurContext);
7592 if (IsLocalExternDecl)
7593 NewFD->setLocalExternDecl();
7595 if (getLangOpts().CPlusPlus) {
7596 bool isInline = D.getDeclSpec().isInlineSpecified();
7597 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7598 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7599 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7600 bool isConcept = D.getDeclSpec().isConceptSpecified();
7601 isFriend = D.getDeclSpec().isFriendSpecified();
7602 if (isFriend && !isInline && D.isFunctionDefinition()) {
7603 // C++ [class.friend]p5
7604 // A function can be defined in a friend declaration of a
7605 // class . . . . Such a function is implicitly inline.
7606 NewFD->setImplicitlyInline();
7609 // If this is a method defined in an __interface, and is not a constructor
7610 // or an overloaded operator, then set the pure flag (isVirtual will already
7612 if (const CXXRecordDecl *Parent =
7613 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7614 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7615 NewFD->setPure(true);
7617 // C++ [class.union]p2
7618 // A union can have member functions, but not virtual functions.
7619 if (isVirtual && Parent->isUnion())
7620 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7623 SetNestedNameSpecifier(NewFD, D);
7624 isExplicitSpecialization = false;
7625 isFunctionTemplateSpecialization = false;
7626 if (D.isInvalidType())
7627 NewFD->setInvalidDecl();
7629 // Match up the template parameter lists with the scope specifier, then
7630 // determine whether we have a template or a template specialization.
7631 bool Invalid = false;
7632 if (TemplateParameterList *TemplateParams =
7633 MatchTemplateParametersToScopeSpecifier(
7634 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7635 D.getCXXScopeSpec(),
7636 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7637 ? D.getName().TemplateId
7639 TemplateParamLists, isFriend, isExplicitSpecialization,
7641 if (TemplateParams->size() > 0) {
7642 // This is a function template
7644 // Check that we can declare a template here.
7645 if (CheckTemplateDeclScope(S, TemplateParams))
7646 NewFD->setInvalidDecl();
7648 // A destructor cannot be a template.
7649 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7650 Diag(NewFD->getLocation(), diag::err_destructor_template);
7651 NewFD->setInvalidDecl();
7654 // If we're adding a template to a dependent context, we may need to
7655 // rebuilding some of the types used within the template parameter list,
7656 // now that we know what the current instantiation is.
7657 if (DC->isDependentContext()) {
7658 ContextRAII SavedContext(*this, DC);
7659 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7663 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7664 NewFD->getLocation(),
7665 Name, TemplateParams,
7667 FunctionTemplate->setLexicalDeclContext(CurContext);
7668 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7670 // For source fidelity, store the other template param lists.
7671 if (TemplateParamLists.size() > 1) {
7672 NewFD->setTemplateParameterListsInfo(Context,
7673 TemplateParamLists.drop_back(1));
7676 // This is a function template specialization.
7677 isFunctionTemplateSpecialization = true;
7678 // For source fidelity, store all the template param lists.
7679 if (TemplateParamLists.size() > 0)
7680 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7682 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7684 // We want to remove the "template<>", found here.
7685 SourceRange RemoveRange = TemplateParams->getSourceRange();
7687 // If we remove the template<> and the name is not a
7688 // template-id, we're actually silently creating a problem:
7689 // the friend declaration will refer to an untemplated decl,
7690 // and clearly the user wants a template specialization. So
7691 // we need to insert '<>' after the name.
7692 SourceLocation InsertLoc;
7693 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7694 InsertLoc = D.getName().getSourceRange().getEnd();
7695 InsertLoc = getLocForEndOfToken(InsertLoc);
7698 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7699 << Name << RemoveRange
7700 << FixItHint::CreateRemoval(RemoveRange)
7701 << FixItHint::CreateInsertion(InsertLoc, "<>");
7706 // All template param lists were matched against the scope specifier:
7707 // this is NOT (an explicit specialization of) a template.
7708 if (TemplateParamLists.size() > 0)
7709 // For source fidelity, store all the template param lists.
7710 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7714 NewFD->setInvalidDecl();
7715 if (FunctionTemplate)
7716 FunctionTemplate->setInvalidDecl();
7719 // C++ [dcl.fct.spec]p5:
7720 // The virtual specifier shall only be used in declarations of
7721 // nonstatic class member functions that appear within a
7722 // member-specification of a class declaration; see 10.3.
7724 if (isVirtual && !NewFD->isInvalidDecl()) {
7725 if (!isVirtualOkay) {
7726 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7727 diag::err_virtual_non_function);
7728 } else if (!CurContext->isRecord()) {
7729 // 'virtual' was specified outside of the class.
7730 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7731 diag::err_virtual_out_of_class)
7732 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7733 } else if (NewFD->getDescribedFunctionTemplate()) {
7734 // C++ [temp.mem]p3:
7735 // A member function template shall not be virtual.
7736 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7737 diag::err_virtual_member_function_template)
7738 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7740 // Okay: Add virtual to the method.
7741 NewFD->setVirtualAsWritten(true);
7744 if (getLangOpts().CPlusPlus14 &&
7745 NewFD->getReturnType()->isUndeducedType())
7746 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7749 if (getLangOpts().CPlusPlus14 &&
7750 (NewFD->isDependentContext() ||
7751 (isFriend && CurContext->isDependentContext())) &&
7752 NewFD->getReturnType()->isUndeducedType()) {
7753 // If the function template is referenced directly (for instance, as a
7754 // member of the current instantiation), pretend it has a dependent type.
7755 // This is not really justified by the standard, but is the only sane
7757 // FIXME: For a friend function, we have not marked the function as being
7758 // a friend yet, so 'isDependentContext' on the FD doesn't work.
7759 const FunctionProtoType *FPT =
7760 NewFD->getType()->castAs<FunctionProtoType>();
7762 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7763 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7764 FPT->getExtProtoInfo()));
7767 // C++ [dcl.fct.spec]p3:
7768 // The inline specifier shall not appear on a block scope function
7770 if (isInline && !NewFD->isInvalidDecl()) {
7771 if (CurContext->isFunctionOrMethod()) {
7772 // 'inline' is not allowed on block scope function declaration.
7773 Diag(D.getDeclSpec().getInlineSpecLoc(),
7774 diag::err_inline_declaration_block_scope) << Name
7775 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7779 // C++ [dcl.fct.spec]p6:
7780 // The explicit specifier shall be used only in the declaration of a
7781 // constructor or conversion function within its class definition;
7782 // see 12.3.1 and 12.3.2.
7783 if (isExplicit && !NewFD->isInvalidDecl()) {
7784 if (!CurContext->isRecord()) {
7785 // 'explicit' was specified outside of the class.
7786 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7787 diag::err_explicit_out_of_class)
7788 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7789 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7790 !isa<CXXConversionDecl>(NewFD)) {
7791 // 'explicit' was specified on a function that wasn't a constructor
7792 // or conversion function.
7793 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7794 diag::err_explicit_non_ctor_or_conv_function)
7795 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7800 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7801 // are implicitly inline.
7802 NewFD->setImplicitlyInline();
7804 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7805 // be either constructors or to return a literal type. Therefore,
7806 // destructors cannot be declared constexpr.
7807 if (isa<CXXDestructorDecl>(NewFD))
7808 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7812 // This is a function concept.
7813 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7816 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7817 // applied only to the definition of a function template [...]
7818 if (!D.isFunctionDefinition()) {
7819 Diag(D.getDeclSpec().getConceptSpecLoc(),
7820 diag::err_function_concept_not_defined);
7821 NewFD->setInvalidDecl();
7824 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7825 // have no exception-specification and is treated as if it were specified
7826 // with noexcept(true) (15.4). [...]
7827 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7828 if (FPT->hasExceptionSpec()) {
7830 if (D.isFunctionDeclarator())
7831 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7832 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7833 << FixItHint::CreateRemoval(Range);
7834 NewFD->setInvalidDecl();
7836 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7839 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7840 // following restrictions:
7841 // - The declared return type shall have the type bool.
7842 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7843 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7844 NewFD->setInvalidDecl();
7847 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7848 // following restrictions:
7849 // - The declaration's parameter list shall be equivalent to an empty
7851 if (FPT->getNumParams() > 0 || FPT->isVariadic())
7852 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7855 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7856 // implicity defined to be a constexpr declaration (implicitly inline)
7857 NewFD->setImplicitlyInline();
7859 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7860 // be declared with the thread_local, inline, friend, or constexpr
7861 // specifiers, [...]
7863 Diag(D.getDeclSpec().getInlineSpecLoc(),
7864 diag::err_concept_decl_invalid_specifiers)
7866 NewFD->setInvalidDecl(true);
7870 Diag(D.getDeclSpec().getFriendSpecLoc(),
7871 diag::err_concept_decl_invalid_specifiers)
7873 NewFD->setInvalidDecl(true);
7877 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7878 diag::err_concept_decl_invalid_specifiers)
7880 NewFD->setInvalidDecl(true);
7883 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7884 // applied only to the definition of a function template or variable
7885 // template, declared in namespace scope.
7886 if (isFunctionTemplateSpecialization) {
7887 Diag(D.getDeclSpec().getConceptSpecLoc(),
7888 diag::err_concept_specified_specialization) << 1;
7889 NewFD->setInvalidDecl(true);
7894 // If __module_private__ was specified, mark the function accordingly.
7895 if (D.getDeclSpec().isModulePrivateSpecified()) {
7896 if (isFunctionTemplateSpecialization) {
7897 SourceLocation ModulePrivateLoc
7898 = D.getDeclSpec().getModulePrivateSpecLoc();
7899 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7901 << FixItHint::CreateRemoval(ModulePrivateLoc);
7903 NewFD->setModulePrivate();
7904 if (FunctionTemplate)
7905 FunctionTemplate->setModulePrivate();
7910 if (FunctionTemplate) {
7911 FunctionTemplate->setObjectOfFriendDecl();
7912 FunctionTemplate->setAccess(AS_public);
7914 NewFD->setObjectOfFriendDecl();
7915 NewFD->setAccess(AS_public);
7918 // If a function is defined as defaulted or deleted, mark it as such now.
7919 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7920 // definition kind to FDK_Definition.
7921 switch (D.getFunctionDefinitionKind()) {
7922 case FDK_Declaration:
7923 case FDK_Definition:
7927 NewFD->setDefaulted();
7931 NewFD->setDeletedAsWritten();
7935 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7936 D.isFunctionDefinition()) {
7937 // C++ [class.mfct]p2:
7938 // A member function may be defined (8.4) in its class definition, in
7939 // which case it is an inline member function (7.1.2)
7940 NewFD->setImplicitlyInline();
7943 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7944 !CurContext->isRecord()) {
7945 // C++ [class.static]p1:
7946 // A data or function member of a class may be declared static
7947 // in a class definition, in which case it is a static member of
7950 // Complain about the 'static' specifier if it's on an out-of-line
7951 // member function definition.
7952 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7953 diag::err_static_out_of_line)
7954 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7957 // C++11 [except.spec]p15:
7958 // A deallocation function with no exception-specification is treated
7959 // as if it were specified with noexcept(true).
7960 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7961 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7962 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7963 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7964 NewFD->setType(Context.getFunctionType(
7965 FPT->getReturnType(), FPT->getParamTypes(),
7966 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7969 // Filter out previous declarations that don't match the scope.
7970 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7971 D.getCXXScopeSpec().isNotEmpty() ||
7972 isExplicitSpecialization ||
7973 isFunctionTemplateSpecialization);
7975 // Handle GNU asm-label extension (encoded as an attribute).
7976 if (Expr *E = (Expr*) D.getAsmLabel()) {
7977 // The parser guarantees this is a string.
7978 StringLiteral *SE = cast<StringLiteral>(E);
7979 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7980 SE->getString(), 0));
7981 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7982 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7983 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7984 if (I != ExtnameUndeclaredIdentifiers.end()) {
7985 if (isDeclExternC(NewFD)) {
7986 NewFD->addAttr(I->second);
7987 ExtnameUndeclaredIdentifiers.erase(I);
7989 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7990 << /*Variable*/0 << NewFD;
7994 // Copy the parameter declarations from the declarator D to the function
7995 // declaration NewFD, if they are available. First scavenge them into Params.
7996 SmallVector<ParmVarDecl*, 16> Params;
7997 if (D.isFunctionDeclarator()) {
7998 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8000 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8001 // function that takes no arguments, not a function that takes a
8002 // single void argument.
8003 // We let through "const void" here because Sema::GetTypeForDeclarator
8004 // already checks for that case.
8005 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8006 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8007 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8008 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8009 Param->setDeclContext(NewFD);
8010 Params.push_back(Param);
8012 if (Param->isInvalidDecl())
8013 NewFD->setInvalidDecl();
8016 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8017 // When we're declaring a function with a typedef, typeof, etc as in the
8018 // following example, we'll need to synthesize (unnamed)
8019 // parameters for use in the declaration.
8022 // typedef void fn(int);
8026 // Synthesize a parameter for each argument type.
8027 for (const auto &AI : FT->param_types()) {
8028 ParmVarDecl *Param =
8029 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8030 Param->setScopeInfo(0, Params.size());
8031 Params.push_back(Param);
8034 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8035 "Should not need args for typedef of non-prototype fn");
8038 // Finally, we know we have the right number of parameters, install them.
8039 NewFD->setParams(Params);
8041 // Find all anonymous symbols defined during the declaration of this function
8042 // and add to NewFD. This lets us track decls such 'enum Y' in:
8044 // void f(enum Y {AA} x) {}
8046 // which would otherwise incorrectly end up in the translation unit scope.
8047 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8048 DeclsInPrototypeScope.clear();
8050 if (D.getDeclSpec().isNoreturnSpecified())
8052 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8055 // Functions returning a variably modified type violate C99 6.7.5.2p2
8056 // because all functions have linkage.
8057 if (!NewFD->isInvalidDecl() &&
8058 NewFD->getReturnType()->isVariablyModifiedType()) {
8059 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8060 NewFD->setInvalidDecl();
8063 // Apply an implicit SectionAttr if #pragma code_seg is active.
8064 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8065 !NewFD->hasAttr<SectionAttr>()) {
8067 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8068 CodeSegStack.CurrentValue->getString(),
8069 CodeSegStack.CurrentPragmaLocation));
8070 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8071 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8072 ASTContext::PSF_Read,
8074 NewFD->dropAttr<SectionAttr>();
8077 // Handle attributes.
8078 ProcessDeclAttributes(S, NewFD, D);
8080 if (getLangOpts().CUDA)
8081 maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8083 if (getLangOpts().OpenCL) {
8084 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8085 // type declaration will generate a compilation error.
8086 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8087 if (AddressSpace == LangAS::opencl_local ||
8088 AddressSpace == LangAS::opencl_global ||
8089 AddressSpace == LangAS::opencl_constant) {
8090 Diag(NewFD->getLocation(),
8091 diag::err_opencl_return_value_with_address_space);
8092 NewFD->setInvalidDecl();
8096 if (!getLangOpts().CPlusPlus) {
8097 // Perform semantic checking on the function declaration.
8098 bool isExplicitSpecialization=false;
8099 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8100 CheckMain(NewFD, D.getDeclSpec());
8102 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8103 CheckMSVCRTEntryPoint(NewFD);
8105 if (!NewFD->isInvalidDecl())
8106 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8107 isExplicitSpecialization));
8108 else if (!Previous.empty())
8109 // Recover gracefully from an invalid redeclaration.
8110 D.setRedeclaration(true);
8111 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8112 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8113 "previous declaration set still overloaded");
8115 // Diagnose no-prototype function declarations with calling conventions that
8116 // don't support variadic calls. Only do this in C and do it after merging
8117 // possibly prototyped redeclarations.
8118 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8119 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8120 CallingConv CC = FT->getExtInfo().getCC();
8121 if (!supportsVariadicCall(CC)) {
8122 // Windows system headers sometimes accidentally use stdcall without
8123 // (void) parameters, so we relax this to a warning.
8125 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8126 Diag(NewFD->getLocation(), DiagID)
8127 << FunctionType::getNameForCallConv(CC);
8131 // C++11 [replacement.functions]p3:
8132 // The program's definitions shall not be specified as inline.
8134 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8136 // Suppress the diagnostic if the function is __attribute__((used)), since
8137 // that forces an external definition to be emitted.
8138 if (D.getDeclSpec().isInlineSpecified() &&
8139 NewFD->isReplaceableGlobalAllocationFunction() &&
8140 !NewFD->hasAttr<UsedAttr>())
8141 Diag(D.getDeclSpec().getInlineSpecLoc(),
8142 diag::ext_operator_new_delete_declared_inline)
8143 << NewFD->getDeclName();
8145 // If the declarator is a template-id, translate the parser's template
8146 // argument list into our AST format.
8147 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8148 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8149 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8150 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8151 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8152 TemplateId->NumArgs);
8153 translateTemplateArguments(TemplateArgsPtr,
8156 HasExplicitTemplateArgs = true;
8158 if (NewFD->isInvalidDecl()) {
8159 HasExplicitTemplateArgs = false;
8160 } else if (FunctionTemplate) {
8161 // Function template with explicit template arguments.
8162 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8163 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8165 HasExplicitTemplateArgs = false;
8167 assert((isFunctionTemplateSpecialization ||
8168 D.getDeclSpec().isFriendSpecified()) &&
8169 "should have a 'template<>' for this decl");
8170 // "friend void foo<>(int);" is an implicit specialization decl.
8171 isFunctionTemplateSpecialization = true;
8173 } else if (isFriend && isFunctionTemplateSpecialization) {
8174 // This combination is only possible in a recovery case; the user
8175 // wrote something like:
8176 // template <> friend void foo(int);
8177 // which we're recovering from as if the user had written:
8178 // friend void foo<>(int);
8179 // Go ahead and fake up a template id.
8180 HasExplicitTemplateArgs = true;
8181 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8182 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8185 // If it's a friend (and only if it's a friend), it's possible
8186 // that either the specialized function type or the specialized
8187 // template is dependent, and therefore matching will fail. In
8188 // this case, don't check the specialization yet.
8189 bool InstantiationDependent = false;
8190 if (isFunctionTemplateSpecialization && isFriend &&
8191 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8192 TemplateSpecializationType::anyDependentTemplateArguments(
8193 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8194 InstantiationDependent))) {
8195 assert(HasExplicitTemplateArgs &&
8196 "friend function specialization without template args");
8197 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8199 NewFD->setInvalidDecl();
8200 } else if (isFunctionTemplateSpecialization) {
8201 if (CurContext->isDependentContext() && CurContext->isRecord()
8203 isDependentClassScopeExplicitSpecialization = true;
8204 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8205 diag::ext_function_specialization_in_class :
8206 diag::err_function_specialization_in_class)
8207 << NewFD->getDeclName();
8208 } else if (CheckFunctionTemplateSpecialization(NewFD,
8209 (HasExplicitTemplateArgs ? &TemplateArgs
8212 NewFD->setInvalidDecl();
8215 // A storage-class-specifier shall not be specified in an explicit
8216 // specialization (14.7.3)
8217 FunctionTemplateSpecializationInfo *Info =
8218 NewFD->getTemplateSpecializationInfo();
8219 if (Info && SC != SC_None) {
8220 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8221 Diag(NewFD->getLocation(),
8222 diag::err_explicit_specialization_inconsistent_storage_class)
8224 << FixItHint::CreateRemoval(
8225 D.getDeclSpec().getStorageClassSpecLoc());
8228 Diag(NewFD->getLocation(),
8229 diag::ext_explicit_specialization_storage_class)
8230 << FixItHint::CreateRemoval(
8231 D.getDeclSpec().getStorageClassSpecLoc());
8233 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8234 if (CheckMemberSpecialization(NewFD, Previous))
8235 NewFD->setInvalidDecl();
8238 // Perform semantic checking on the function declaration.
8239 if (!isDependentClassScopeExplicitSpecialization) {
8240 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8241 CheckMain(NewFD, D.getDeclSpec());
8243 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8244 CheckMSVCRTEntryPoint(NewFD);
8246 if (!NewFD->isInvalidDecl())
8247 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8248 isExplicitSpecialization));
8249 else if (!Previous.empty())
8250 // Recover gracefully from an invalid redeclaration.
8251 D.setRedeclaration(true);
8254 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8255 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8256 "previous declaration set still overloaded");
8258 NamedDecl *PrincipalDecl = (FunctionTemplate
8259 ? cast<NamedDecl>(FunctionTemplate)
8262 if (isFriend && D.isRedeclaration()) {
8263 AccessSpecifier Access = AS_public;
8264 if (!NewFD->isInvalidDecl())
8265 Access = NewFD->getPreviousDecl()->getAccess();
8267 NewFD->setAccess(Access);
8268 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8271 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8272 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8273 PrincipalDecl->setNonMemberOperator();
8275 // If we have a function template, check the template parameter
8276 // list. This will check and merge default template arguments.
8277 if (FunctionTemplate) {
8278 FunctionTemplateDecl *PrevTemplate =
8279 FunctionTemplate->getPreviousDecl();
8280 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8281 PrevTemplate ? PrevTemplate->getTemplateParameters()
8283 D.getDeclSpec().isFriendSpecified()
8284 ? (D.isFunctionDefinition()
8285 ? TPC_FriendFunctionTemplateDefinition
8286 : TPC_FriendFunctionTemplate)
8287 : (D.getCXXScopeSpec().isSet() &&
8288 DC && DC->isRecord() &&
8289 DC->isDependentContext())
8290 ? TPC_ClassTemplateMember
8291 : TPC_FunctionTemplate);
8294 if (NewFD->isInvalidDecl()) {
8295 // Ignore all the rest of this.
8296 } else if (!D.isRedeclaration()) {
8297 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8299 // Fake up an access specifier if it's supposed to be a class member.
8300 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8301 NewFD->setAccess(AS_public);
8303 // Qualified decls generally require a previous declaration.
8304 if (D.getCXXScopeSpec().isSet()) {
8305 // ...with the major exception of templated-scope or
8306 // dependent-scope friend declarations.
8308 // TODO: we currently also suppress this check in dependent
8309 // contexts because (1) the parameter depth will be off when
8310 // matching friend templates and (2) we might actually be
8311 // selecting a friend based on a dependent factor. But there
8312 // are situations where these conditions don't apply and we
8313 // can actually do this check immediately.
8315 (TemplateParamLists.size() ||
8316 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8317 CurContext->isDependentContext())) {
8320 // The user tried to provide an out-of-line definition for a
8321 // function that is a member of a class or namespace, but there
8322 // was no such member function declared (C++ [class.mfct]p2,
8323 // C++ [namespace.memdef]p2). For example:
8329 // void X::f() { } // ill-formed
8331 // Complain about this problem, and attempt to suggest close
8332 // matches (e.g., those that differ only in cv-qualifiers and
8333 // whether the parameter types are references).
8335 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8336 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8337 AddToScope = ExtraArgs.AddToScope;
8342 // Unqualified local friend declarations are required to resolve
8344 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8345 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8346 *this, Previous, NewFD, ExtraArgs, true, S)) {
8347 AddToScope = ExtraArgs.AddToScope;
8351 } else if (!D.isFunctionDefinition() &&
8352 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8353 !isFriend && !isFunctionTemplateSpecialization &&
8354 !isExplicitSpecialization) {
8355 // An out-of-line member function declaration must also be a
8356 // definition (C++ [class.mfct]p2).
8357 // Note that this is not the case for explicit specializations of
8358 // function templates or member functions of class templates, per
8359 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8360 // extension for compatibility with old SWIG code which likes to
8362 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8363 << D.getCXXScopeSpec().getRange();
8367 ProcessPragmaWeak(S, NewFD);
8368 checkAttributesAfterMerging(*this, *NewFD);
8370 AddKnownFunctionAttributes(NewFD);
8372 if (NewFD->hasAttr<OverloadableAttr>() &&
8373 !NewFD->getType()->getAs<FunctionProtoType>()) {
8374 Diag(NewFD->getLocation(),
8375 diag::err_attribute_overloadable_no_prototype)
8378 // Turn this into a variadic function with no parameters.
8379 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8380 FunctionProtoType::ExtProtoInfo EPI(
8381 Context.getDefaultCallingConvention(true, false));
8382 EPI.Variadic = true;
8383 EPI.ExtInfo = FT->getExtInfo();
8385 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8389 // If there's a #pragma GCC visibility in scope, and this isn't a class
8390 // member, set the visibility of this function.
8391 if (!DC->isRecord() && NewFD->isExternallyVisible())
8392 AddPushedVisibilityAttribute(NewFD);
8394 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8395 // marking the function.
8396 AddCFAuditedAttribute(NewFD);
8398 // If this is a function definition, check if we have to apply optnone due to
8400 if(D.isFunctionDefinition())
8401 AddRangeBasedOptnone(NewFD);
8403 // If this is the first declaration of an extern C variable, update
8404 // the map of such variables.
8405 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8406 isIncompleteDeclExternC(*this, NewFD))
8407 RegisterLocallyScopedExternCDecl(NewFD, S);
8409 // Set this FunctionDecl's range up to the right paren.
8410 NewFD->setRangeEnd(D.getSourceRange().getEnd());
8412 if (D.isRedeclaration() && !Previous.empty()) {
8413 checkDLLAttributeRedeclaration(
8414 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8415 isExplicitSpecialization || isFunctionTemplateSpecialization);
8418 if (getLangOpts().CUDA) {
8419 IdentifierInfo *II = NewFD->getIdentifier();
8420 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8421 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8422 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8423 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8425 Context.setcudaConfigureCallDecl(NewFD);
8428 // Variadic functions, other than a *declaration* of printf, are not allowed
8429 // in device-side CUDA code, unless someone passed
8430 // -fcuda-allow-variadic-functions.
8431 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8432 (NewFD->hasAttr<CUDADeviceAttr>() ||
8433 NewFD->hasAttr<CUDAGlobalAttr>()) &&
8434 !(II && II->isStr("printf") && NewFD->isExternC() &&
8435 !D.isFunctionDefinition())) {
8436 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8440 if (getLangOpts().CPlusPlus) {
8441 if (FunctionTemplate) {
8442 if (NewFD->isInvalidDecl())
8443 FunctionTemplate->setInvalidDecl();
8444 return FunctionTemplate;
8448 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8449 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8450 if ((getLangOpts().OpenCLVersion >= 120)
8451 && (SC == SC_Static)) {
8452 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8456 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8457 if (!NewFD->getReturnType()->isVoidType()) {
8458 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8459 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8460 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8465 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8466 for (auto Param : NewFD->params())
8467 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8469 for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8470 PE = NewFD->param_end(); PI != PE; ++PI) {
8471 ParmVarDecl *Param = *PI;
8472 QualType PT = Param->getType();
8474 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8476 if (getLangOpts().OpenCLVersion >= 200) {
8477 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8478 QualType ElemTy = PipeTy->getElementType();
8479 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8480 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8487 MarkUnusedFileScopedDecl(NewFD);
8489 // Here we have an function template explicit specialization at class scope.
8490 // The actually specialization will be postponed to template instatiation
8491 // time via the ClassScopeFunctionSpecializationDecl node.
8492 if (isDependentClassScopeExplicitSpecialization) {
8493 ClassScopeFunctionSpecializationDecl *NewSpec =
8494 ClassScopeFunctionSpecializationDecl::Create(
8495 Context, CurContext, SourceLocation(),
8496 cast<CXXMethodDecl>(NewFD),
8497 HasExplicitTemplateArgs, TemplateArgs);
8498 CurContext->addDecl(NewSpec);
8505 /// \brief Perform semantic checking of a new function declaration.
8507 /// Performs semantic analysis of the new function declaration
8508 /// NewFD. This routine performs all semantic checking that does not
8509 /// require the actual declarator involved in the declaration, and is
8510 /// used both for the declaration of functions as they are parsed
8511 /// (called via ActOnDeclarator) and for the declaration of functions
8512 /// that have been instantiated via C++ template instantiation (called
8513 /// via InstantiateDecl).
8515 /// \param IsExplicitSpecialization whether this new function declaration is
8516 /// an explicit specialization of the previous declaration.
8518 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8520 /// \returns true if the function declaration is a redeclaration.
8521 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8522 LookupResult &Previous,
8523 bool IsExplicitSpecialization) {
8524 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8525 "Variably modified return types are not handled here");
8527 // Determine whether the type of this function should be merged with
8528 // a previous visible declaration. This never happens for functions in C++,
8529 // and always happens in C if the previous declaration was visible.
8530 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8531 !Previous.isShadowed();
8533 bool Redeclaration = false;
8534 NamedDecl *OldDecl = nullptr;
8536 // Merge or overload the declaration with an existing declaration of
8537 // the same name, if appropriate.
8538 if (!Previous.empty()) {
8539 // Determine whether NewFD is an overload of PrevDecl or
8540 // a declaration that requires merging. If it's an overload,
8541 // there's no more work to do here; we'll just add the new
8542 // function to the scope.
8543 if (!AllowOverloadingOfFunction(Previous, Context)) {
8544 NamedDecl *Candidate = Previous.getRepresentativeDecl();
8545 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8546 Redeclaration = true;
8547 OldDecl = Candidate;
8550 switch (CheckOverload(S, NewFD, Previous, OldDecl,
8551 /*NewIsUsingDecl*/ false)) {
8553 Redeclaration = true;
8556 case Ovl_NonFunction:
8557 Redeclaration = true;
8561 Redeclaration = false;
8565 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8566 // If a function name is overloadable in C, then every function
8567 // with that name must be marked "overloadable".
8568 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8569 << Redeclaration << NewFD;
8570 NamedDecl *OverloadedDecl = nullptr;
8572 OverloadedDecl = OldDecl;
8573 else if (!Previous.empty())
8574 OverloadedDecl = Previous.getRepresentativeDecl();
8576 Diag(OverloadedDecl->getLocation(),
8577 diag::note_attribute_overloadable_prev_overload);
8578 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8583 // Check for a previous extern "C" declaration with this name.
8584 if (!Redeclaration &&
8585 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8586 if (!Previous.empty()) {
8587 // This is an extern "C" declaration with the same name as a previous
8588 // declaration, and thus redeclares that entity...
8589 Redeclaration = true;
8590 OldDecl = Previous.getFoundDecl();
8591 MergeTypeWithPrevious = false;
8593 // ... except in the presence of __attribute__((overloadable)).
8594 if (OldDecl->hasAttr<OverloadableAttr>()) {
8595 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8596 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8597 << Redeclaration << NewFD;
8598 Diag(Previous.getFoundDecl()->getLocation(),
8599 diag::note_attribute_overloadable_prev_overload);
8600 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8602 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8603 Redeclaration = false;
8610 // C++11 [dcl.constexpr]p8:
8611 // A constexpr specifier for a non-static member function that is not
8612 // a constructor declares that member function to be const.
8614 // This needs to be delayed until we know whether this is an out-of-line
8615 // definition of a static member function.
8617 // This rule is not present in C++1y, so we produce a backwards
8618 // compatibility warning whenever it happens in C++11.
8619 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8620 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8621 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8622 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8623 CXXMethodDecl *OldMD = nullptr;
8625 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8626 if (!OldMD || !OldMD->isStatic()) {
8627 const FunctionProtoType *FPT =
8628 MD->getType()->castAs<FunctionProtoType>();
8629 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8630 EPI.TypeQuals |= Qualifiers::Const;
8631 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8632 FPT->getParamTypes(), EPI));
8634 // Warn that we did this, if we're not performing template instantiation.
8635 // In that case, we'll have warned already when the template was defined.
8636 if (ActiveTemplateInstantiations.empty()) {
8637 SourceLocation AddConstLoc;
8638 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8639 .IgnoreParens().getAs<FunctionTypeLoc>())
8640 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8642 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8643 << FixItHint::CreateInsertion(AddConstLoc, " const");
8648 if (Redeclaration) {
8649 // NewFD and OldDecl represent declarations that need to be
8651 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8652 NewFD->setInvalidDecl();
8653 return Redeclaration;
8657 Previous.addDecl(OldDecl);
8659 if (FunctionTemplateDecl *OldTemplateDecl
8660 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8661 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8662 FunctionTemplateDecl *NewTemplateDecl
8663 = NewFD->getDescribedFunctionTemplate();
8664 assert(NewTemplateDecl && "Template/non-template mismatch");
8665 if (CXXMethodDecl *Method
8666 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8667 Method->setAccess(OldTemplateDecl->getAccess());
8668 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8671 // If this is an explicit specialization of a member that is a function
8672 // template, mark it as a member specialization.
8673 if (IsExplicitSpecialization &&
8674 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8675 NewTemplateDecl->setMemberSpecialization();
8676 assert(OldTemplateDecl->isMemberSpecialization());
8677 // Explicit specializations of a member template do not inherit deleted
8678 // status from the parent member template that they are specializing.
8679 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8680 FunctionDecl *const OldTemplatedDecl =
8681 OldTemplateDecl->getTemplatedDecl();
8682 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8683 OldTemplatedDecl->setDeletedAsWritten(false);
8688 // This needs to happen first so that 'inline' propagates.
8689 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8691 if (isa<CXXMethodDecl>(NewFD))
8692 NewFD->setAccess(OldDecl->getAccess());
8696 // Semantic checking for this function declaration (in isolation).
8698 if (getLangOpts().CPlusPlus) {
8699 // C++-specific checks.
8700 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8701 CheckConstructor(Constructor);
8702 } else if (CXXDestructorDecl *Destructor =
8703 dyn_cast<CXXDestructorDecl>(NewFD)) {
8704 CXXRecordDecl *Record = Destructor->getParent();
8705 QualType ClassType = Context.getTypeDeclType(Record);
8707 // FIXME: Shouldn't we be able to perform this check even when the class
8708 // type is dependent? Both gcc and edg can handle that.
8709 if (!ClassType->isDependentType()) {
8710 DeclarationName Name
8711 = Context.DeclarationNames.getCXXDestructorName(
8712 Context.getCanonicalType(ClassType));
8713 if (NewFD->getDeclName() != Name) {
8714 Diag(NewFD->getLocation(), diag::err_destructor_name);
8715 NewFD->setInvalidDecl();
8716 return Redeclaration;
8719 } else if (CXXConversionDecl *Conversion
8720 = dyn_cast<CXXConversionDecl>(NewFD)) {
8721 ActOnConversionDeclarator(Conversion);
8724 // Find any virtual functions that this function overrides.
8725 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8726 if (!Method->isFunctionTemplateSpecialization() &&
8727 !Method->getDescribedFunctionTemplate() &&
8728 Method->isCanonicalDecl()) {
8729 if (AddOverriddenMethods(Method->getParent(), Method)) {
8730 // If the function was marked as "static", we have a problem.
8731 if (NewFD->getStorageClass() == SC_Static) {
8732 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8737 if (Method->isStatic())
8738 checkThisInStaticMemberFunctionType(Method);
8741 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8742 if (NewFD->isOverloadedOperator() &&
8743 CheckOverloadedOperatorDeclaration(NewFD)) {
8744 NewFD->setInvalidDecl();
8745 return Redeclaration;
8748 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8749 if (NewFD->getLiteralIdentifier() &&
8750 CheckLiteralOperatorDeclaration(NewFD)) {
8751 NewFD->setInvalidDecl();
8752 return Redeclaration;
8755 // In C++, check default arguments now that we have merged decls. Unless
8756 // the lexical context is the class, because in this case this is done
8757 // during delayed parsing anyway.
8758 if (!CurContext->isRecord())
8759 CheckCXXDefaultArguments(NewFD);
8761 // If this function declares a builtin function, check the type of this
8762 // declaration against the expected type for the builtin.
8763 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8764 ASTContext::GetBuiltinTypeError Error;
8765 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8766 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8767 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8768 // The type of this function differs from the type of the builtin,
8769 // so forget about the builtin entirely.
8770 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8774 // If this function is declared as being extern "C", then check to see if
8775 // the function returns a UDT (class, struct, or union type) that is not C
8776 // compatible, and if it does, warn the user.
8777 // But, issue any diagnostic on the first declaration only.
8778 if (Previous.empty() && NewFD->isExternC()) {
8779 QualType R = NewFD->getReturnType();
8780 if (R->isIncompleteType() && !R->isVoidType())
8781 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8783 else if (!R.isPODType(Context) && !R->isVoidType() &&
8784 !R->isObjCObjectPointerType())
8785 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8788 return Redeclaration;
8791 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8792 // C++11 [basic.start.main]p3:
8793 // A program that [...] declares main to be inline, static or
8794 // constexpr is ill-formed.
8795 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8796 // appear in a declaration of main.
8797 // static main is not an error under C99, but we should warn about it.
8798 // We accept _Noreturn main as an extension.
8799 if (FD->getStorageClass() == SC_Static)
8800 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8801 ? diag::err_static_main : diag::warn_static_main)
8802 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8803 if (FD->isInlineSpecified())
8804 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8805 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8806 if (DS.isNoreturnSpecified()) {
8807 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8808 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8809 Diag(NoreturnLoc, diag::ext_noreturn_main);
8810 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8811 << FixItHint::CreateRemoval(NoreturnRange);
8813 if (FD->isConstexpr()) {
8814 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8815 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8816 FD->setConstexpr(false);
8819 if (getLangOpts().OpenCL) {
8820 Diag(FD->getLocation(), diag::err_opencl_no_main)
8821 << FD->hasAttr<OpenCLKernelAttr>();
8822 FD->setInvalidDecl();
8826 QualType T = FD->getType();
8827 assert(T->isFunctionType() && "function decl is not of function type");
8828 const FunctionType* FT = T->castAs<FunctionType>();
8830 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8831 // In C with GNU extensions we allow main() to have non-integer return
8832 // type, but we should warn about the extension, and we disable the
8833 // implicit-return-zero rule.
8835 // GCC in C mode accepts qualified 'int'.
8836 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8837 FD->setHasImplicitReturnZero(true);
8839 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8840 SourceRange RTRange = FD->getReturnTypeSourceRange();
8841 if (RTRange.isValid())
8842 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8843 << FixItHint::CreateReplacement(RTRange, "int");
8846 // In C and C++, main magically returns 0 if you fall off the end;
8847 // set the flag which tells us that.
8848 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8850 // All the standards say that main() should return 'int'.
8851 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8852 FD->setHasImplicitReturnZero(true);
8854 // Otherwise, this is just a flat-out error.
8855 SourceRange RTRange = FD->getReturnTypeSourceRange();
8856 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8857 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8859 FD->setInvalidDecl(true);
8863 // Treat protoless main() as nullary.
8864 if (isa<FunctionNoProtoType>(FT)) return;
8866 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8867 unsigned nparams = FTP->getNumParams();
8868 assert(FD->getNumParams() == nparams);
8870 bool HasExtraParameters = (nparams > 3);
8872 if (FTP->isVariadic()) {
8873 Diag(FD->getLocation(), diag::ext_variadic_main);
8874 // FIXME: if we had information about the location of the ellipsis, we
8875 // could add a FixIt hint to remove it as a parameter.
8878 // Darwin passes an undocumented fourth argument of type char**. If
8879 // other platforms start sprouting these, the logic below will start
8881 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8882 HasExtraParameters = false;
8884 if (HasExtraParameters) {
8885 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8886 FD->setInvalidDecl(true);
8890 // FIXME: a lot of the following diagnostics would be improved
8891 // if we had some location information about types.
8894 Context.getPointerType(Context.getPointerType(Context.CharTy));
8895 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8897 for (unsigned i = 0; i < nparams; ++i) {
8898 QualType AT = FTP->getParamType(i);
8900 bool mismatch = true;
8902 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8904 else if (Expected[i] == CharPP) {
8905 // As an extension, the following forms are okay:
8907 // char const * const *
8910 QualifierCollector qs;
8911 const PointerType* PT;
8912 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8913 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8914 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8917 mismatch = !qs.empty();
8922 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8923 // TODO: suggest replacing given type with expected type
8924 FD->setInvalidDecl(true);
8928 if (nparams == 1 && !FD->isInvalidDecl()) {
8929 Diag(FD->getLocation(), diag::warn_main_one_arg);
8932 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8933 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8934 FD->setInvalidDecl();
8938 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8939 QualType T = FD->getType();
8940 assert(T->isFunctionType() && "function decl is not of function type");
8941 const FunctionType *FT = T->castAs<FunctionType>();
8943 // Set an implicit return of 'zero' if the function can return some integral,
8944 // enumeration, pointer or nullptr type.
8945 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8946 FT->getReturnType()->isAnyPointerType() ||
8947 FT->getReturnType()->isNullPtrType())
8948 // DllMain is exempt because a return value of zero means it failed.
8949 if (FD->getName() != "DllMain")
8950 FD->setHasImplicitReturnZero(true);
8952 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8953 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8954 FD->setInvalidDecl();
8958 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8959 // FIXME: Need strict checking. In C89, we need to check for
8960 // any assignment, increment, decrement, function-calls, or
8961 // commas outside of a sizeof. In C99, it's the same list,
8962 // except that the aforementioned are allowed in unevaluated
8963 // expressions. Everything else falls under the
8964 // "may accept other forms of constant expressions" exception.
8965 // (We never end up here for C++, so the constant expression
8966 // rules there don't matter.)
8967 const Expr *Culprit;
8968 if (Init->isConstantInitializer(Context, false, &Culprit))
8970 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8971 << Culprit->getSourceRange();
8976 // Visits an initialization expression to see if OrigDecl is evaluated in
8977 // its own initialization and throws a warning if it does.
8978 class SelfReferenceChecker
8979 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8984 bool isReferenceType;
8987 llvm::SmallVector<unsigned, 4> InitFieldIndex;
8990 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8992 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8993 S(S), OrigDecl(OrigDecl) {
8995 isRecordType = false;
8996 isReferenceType = false;
8998 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8999 isPODType = VD->getType().isPODType(S.Context);
9000 isRecordType = VD->getType()->isRecordType();
9001 isReferenceType = VD->getType()->isReferenceType();
9005 // For most expressions, just call the visitor. For initializer lists,
9006 // track the index of the field being initialized since fields are
9007 // initialized in order allowing use of previously initialized fields.
9008 void CheckExpr(Expr *E) {
9009 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9015 // Track and increment the index here.
9017 InitFieldIndex.push_back(0);
9018 for (auto Child : InitList->children()) {
9019 CheckExpr(cast<Expr>(Child));
9020 ++InitFieldIndex.back();
9022 InitFieldIndex.pop_back();
9025 // Returns true if MemberExpr is checked and no futher checking is needed.
9026 // Returns false if additional checking is required.
9027 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9028 llvm::SmallVector<FieldDecl*, 4> Fields;
9030 bool ReferenceField = false;
9032 // Get the field memebers used.
9033 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9034 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9037 Fields.push_back(FD);
9038 if (FD->getType()->isReferenceType())
9039 ReferenceField = true;
9040 Base = ME->getBase()->IgnoreParenImpCasts();
9043 // Keep checking only if the base Decl is the same.
9044 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9045 if (!DRE || DRE->getDecl() != OrigDecl)
9048 // A reference field can be bound to an unininitialized field.
9049 if (CheckReference && !ReferenceField)
9052 // Convert FieldDecls to their index number.
9053 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9054 for (const FieldDecl *I : llvm::reverse(Fields))
9055 UsedFieldIndex.push_back(I->getFieldIndex());
9057 // See if a warning is needed by checking the first difference in index
9058 // numbers. If field being used has index less than the field being
9059 // initialized, then the use is safe.
9060 for (auto UsedIter = UsedFieldIndex.begin(),
9061 UsedEnd = UsedFieldIndex.end(),
9062 OrigIter = InitFieldIndex.begin(),
9063 OrigEnd = InitFieldIndex.end();
9064 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9065 if (*UsedIter < *OrigIter)
9067 if (*UsedIter > *OrigIter)
9071 // TODO: Add a different warning which will print the field names.
9072 HandleDeclRefExpr(DRE);
9076 // For most expressions, the cast is directly above the DeclRefExpr.
9077 // For conditional operators, the cast can be outside the conditional
9078 // operator if both expressions are DeclRefExpr's.
9079 void HandleValue(Expr *E) {
9080 E = E->IgnoreParens();
9081 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9082 HandleDeclRefExpr(DRE);
9086 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9087 Visit(CO->getCond());
9088 HandleValue(CO->getTrueExpr());
9089 HandleValue(CO->getFalseExpr());
9093 if (BinaryConditionalOperator *BCO =
9094 dyn_cast<BinaryConditionalOperator>(E)) {
9095 Visit(BCO->getCond());
9096 HandleValue(BCO->getFalseExpr());
9100 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9101 HandleValue(OVE->getSourceExpr());
9105 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9106 if (BO->getOpcode() == BO_Comma) {
9107 Visit(BO->getLHS());
9108 HandleValue(BO->getRHS());
9113 if (isa<MemberExpr>(E)) {
9115 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9116 false /*CheckReference*/))
9120 Expr *Base = E->IgnoreParenImpCasts();
9121 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9122 // Check for static member variables and don't warn on them.
9123 if (!isa<FieldDecl>(ME->getMemberDecl()))
9125 Base = ME->getBase()->IgnoreParenImpCasts();
9127 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9128 HandleDeclRefExpr(DRE);
9135 // Reference types not handled in HandleValue are handled here since all
9136 // uses of references are bad, not just r-value uses.
9137 void VisitDeclRefExpr(DeclRefExpr *E) {
9138 if (isReferenceType)
9139 HandleDeclRefExpr(E);
9142 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9143 if (E->getCastKind() == CK_LValueToRValue) {
9144 HandleValue(E->getSubExpr());
9148 Inherited::VisitImplicitCastExpr(E);
9151 void VisitMemberExpr(MemberExpr *E) {
9153 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9157 // Don't warn on arrays since they can be treated as pointers.
9158 if (E->getType()->canDecayToPointerType()) return;
9160 // Warn when a non-static method call is followed by non-static member
9161 // field accesses, which is followed by a DeclRefExpr.
9162 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9163 bool Warn = (MD && !MD->isStatic());
9164 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9165 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9166 if (!isa<FieldDecl>(ME->getMemberDecl()))
9168 Base = ME->getBase()->IgnoreParenImpCasts();
9171 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9173 HandleDeclRefExpr(DRE);
9177 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9178 // Visit that expression.
9182 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9183 Expr *Callee = E->getCallee();
9185 if (isa<UnresolvedLookupExpr>(Callee))
9186 return Inherited::VisitCXXOperatorCallExpr(E);
9189 for (auto Arg: E->arguments())
9190 HandleValue(Arg->IgnoreParenImpCasts());
9193 void VisitUnaryOperator(UnaryOperator *E) {
9194 // For POD record types, addresses of its own members are well-defined.
9195 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9196 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9198 HandleValue(E->getSubExpr());
9202 if (E->isIncrementDecrementOp()) {
9203 HandleValue(E->getSubExpr());
9207 Inherited::VisitUnaryOperator(E);
9210 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9212 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9213 if (E->getConstructor()->isCopyConstructor()) {
9214 Expr *ArgExpr = E->getArg(0);
9215 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9216 if (ILE->getNumInits() == 1)
9217 ArgExpr = ILE->getInit(0);
9218 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9219 if (ICE->getCastKind() == CK_NoOp)
9220 ArgExpr = ICE->getSubExpr();
9221 HandleValue(ArgExpr);
9224 Inherited::VisitCXXConstructExpr(E);
9227 void VisitCallExpr(CallExpr *E) {
9228 // Treat std::move as a use.
9229 if (E->getNumArgs() == 1) {
9230 if (FunctionDecl *FD = E->getDirectCallee()) {
9231 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9232 FD->getIdentifier()->isStr("move")) {
9233 HandleValue(E->getArg(0));
9239 Inherited::VisitCallExpr(E);
9242 void VisitBinaryOperator(BinaryOperator *E) {
9243 if (E->isCompoundAssignmentOp()) {
9244 HandleValue(E->getLHS());
9249 Inherited::VisitBinaryOperator(E);
9252 // A custom visitor for BinaryConditionalOperator is needed because the
9253 // regular visitor would check the condition and true expression separately
9254 // but both point to the same place giving duplicate diagnostics.
9255 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9256 Visit(E->getCond());
9257 Visit(E->getFalseExpr());
9260 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9261 Decl* ReferenceDecl = DRE->getDecl();
9262 if (OrigDecl != ReferenceDecl) return;
9264 if (isReferenceType) {
9265 diag = diag::warn_uninit_self_reference_in_reference_init;
9266 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9267 diag = diag::warn_static_self_reference_in_init;
9268 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9269 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9270 DRE->getDecl()->getType()->isRecordType()) {
9271 diag = diag::warn_uninit_self_reference_in_init;
9273 // Local variables will be handled by the CFG analysis.
9277 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9279 << DRE->getNameInfo().getName()
9280 << OrigDecl->getLocation()
9281 << DRE->getSourceRange());
9285 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9286 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9288 // Parameters arguments are occassionially constructed with itself,
9289 // for instance, in recursive functions. Skip them.
9290 if (isa<ParmVarDecl>(OrigDecl))
9293 E = E->IgnoreParens();
9295 // Skip checking T a = a where T is not a record or reference type.
9296 // Doing so is a way to silence uninitialized warnings.
9297 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9298 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9299 if (ICE->getCastKind() == CK_LValueToRValue)
9300 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9301 if (DRE->getDecl() == OrigDecl)
9304 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9306 } // end anonymous namespace
9308 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9309 DeclarationName Name, QualType Type,
9310 TypeSourceInfo *TSI,
9311 SourceRange Range, bool DirectInit,
9313 bool IsInitCapture = !VDecl;
9314 assert((!VDecl || !VDecl->isInitCapture()) &&
9315 "init captures are expected to be deduced prior to initialization");
9317 ArrayRef<Expr *> DeduceInits = Init;
9319 if (auto *PL = dyn_cast<ParenListExpr>(Init))
9320 DeduceInits = PL->exprs();
9321 else if (auto *IL = dyn_cast<InitListExpr>(Init))
9322 DeduceInits = IL->inits();
9325 // Deduction only works if we have exactly one source expression.
9326 if (DeduceInits.empty()) {
9327 // It isn't possible to write this directly, but it is possible to
9328 // end up in this situation with "auto x(some_pack...);"
9329 Diag(Init->getLocStart(), IsInitCapture
9330 ? diag::err_init_capture_no_expression
9331 : diag::err_auto_var_init_no_expression)
9332 << Name << Type << Range;
9336 if (DeduceInits.size() > 1) {
9337 Diag(DeduceInits[1]->getLocStart(),
9338 IsInitCapture ? diag::err_init_capture_multiple_expressions
9339 : diag::err_auto_var_init_multiple_expressions)
9340 << Name << Type << Range;
9344 Expr *DeduceInit = DeduceInits[0];
9345 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9346 Diag(Init->getLocStart(), IsInitCapture
9347 ? diag::err_init_capture_paren_braces
9348 : diag::err_auto_var_init_paren_braces)
9349 << isa<InitListExpr>(Init) << Name << Type << Range;
9353 // Expressions default to 'id' when we're in a debugger.
9354 bool DefaultedAnyToId = false;
9355 if (getLangOpts().DebuggerCastResultToId &&
9356 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9357 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9358 if (Result.isInvalid()) {
9361 Init = Result.get();
9362 DefaultedAnyToId = true;
9365 QualType DeducedType;
9366 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9368 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9369 else if (isa<InitListExpr>(Init))
9370 Diag(Range.getBegin(),
9371 diag::err_init_capture_deduction_failure_from_init_list)
9373 << (DeduceInit->getType().isNull() ? TSI->getType()
9374 : DeduceInit->getType())
9375 << DeduceInit->getSourceRange();
9377 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9378 << Name << TSI->getType()
9379 << (DeduceInit->getType().isNull() ? TSI->getType()
9380 : DeduceInit->getType())
9381 << DeduceInit->getSourceRange();
9384 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9385 // 'id' instead of a specific object type prevents most of our usual
9387 // We only want to warn outside of template instantiations, though:
9388 // inside a template, the 'id' could have come from a parameter.
9389 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9390 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9391 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9392 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9398 /// AddInitializerToDecl - Adds the initializer Init to the
9399 /// declaration dcl. If DirectInit is true, this is C++ direct
9400 /// initialization rather than copy initialization.
9401 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9402 bool DirectInit, bool TypeMayContainAuto) {
9403 // If there is no declaration, there was an error parsing it. Just ignore
9405 if (!RealDecl || RealDecl->isInvalidDecl()) {
9406 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9411 // Pure-specifiers are handled in ActOnPureSpecifier.
9412 Diag(Method->getLocation(), diag::err_member_function_initialization)
9413 << Method->getDeclName() << Init->getSourceRange();
9414 Method->setInvalidDecl();
9418 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9420 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9421 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9422 RealDecl->setInvalidDecl();
9426 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9427 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9428 // Attempt typo correction early so that the type of the init expression can
9429 // be deduced based on the chosen correction if the original init contains a
9431 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9432 if (!Res.isUsable()) {
9433 RealDecl->setInvalidDecl();
9438 QualType DeducedType = deduceVarTypeFromInitializer(
9439 VDecl, VDecl->getDeclName(), VDecl->getType(),
9440 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9441 if (DeducedType.isNull()) {
9442 RealDecl->setInvalidDecl();
9446 VDecl->setType(DeducedType);
9447 assert(VDecl->isLinkageValid());
9449 // In ARC, infer lifetime.
9450 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9451 VDecl->setInvalidDecl();
9453 // If this is a redeclaration, check that the type we just deduced matches
9454 // the previously declared type.
9455 if (VarDecl *Old = VDecl->getPreviousDecl()) {
9456 // We never need to merge the type, because we cannot form an incomplete
9457 // array of auto, nor deduce such a type.
9458 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9461 // Check the deduced type is valid for a variable declaration.
9462 CheckVariableDeclarationType(VDecl);
9463 if (VDecl->isInvalidDecl())
9467 // dllimport cannot be used on variable definitions.
9468 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9469 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9470 VDecl->setInvalidDecl();
9474 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9475 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9476 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9477 VDecl->setInvalidDecl();
9481 if (!VDecl->getType()->isDependentType()) {
9482 // A definition must end up with a complete type, which means it must be
9483 // complete with the restriction that an array type might be completed by
9484 // the initializer; note that later code assumes this restriction.
9485 QualType BaseDeclType = VDecl->getType();
9486 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9487 BaseDeclType = Array->getElementType();
9488 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9489 diag::err_typecheck_decl_incomplete_type)) {
9490 RealDecl->setInvalidDecl();
9494 // The variable can not have an abstract class type.
9495 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9496 diag::err_abstract_type_in_decl,
9497 AbstractVariableType))
9498 VDecl->setInvalidDecl();
9502 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9503 NamedDecl *Hidden = nullptr;
9504 if (!hasVisibleDefinition(Def, &Hidden) &&
9505 (VDecl->getFormalLinkage() == InternalLinkage ||
9506 VDecl->getDescribedVarTemplate() ||
9507 VDecl->getNumTemplateParameterLists() ||
9508 VDecl->getDeclContext()->isDependentContext())) {
9509 // The previous definition is hidden, and multiple definitions are
9510 // permitted (in separate TUs). Form another definition of it.
9512 Diag(VDecl->getLocation(), diag::err_redefinition)
9513 << VDecl->getDeclName();
9514 Diag(Def->getLocation(), diag::note_previous_definition);
9515 VDecl->setInvalidDecl();
9520 if (getLangOpts().CPlusPlus) {
9521 // C++ [class.static.data]p4
9522 // If a static data member is of const integral or const
9523 // enumeration type, its declaration in the class definition can
9524 // specify a constant-initializer which shall be an integral
9525 // constant expression (5.19). In that case, the member can appear
9526 // in integral constant expressions. The member shall still be
9527 // defined in a namespace scope if it is used in the program and the
9528 // namespace scope definition shall not contain an initializer.
9530 // We already performed a redefinition check above, but for static
9531 // data members we also need to check whether there was an in-class
9532 // declaration with an initializer.
9533 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9534 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9535 << VDecl->getDeclName();
9536 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9537 diag::note_previous_initializer)
9542 if (VDecl->hasLocalStorage())
9543 getCurFunction()->setHasBranchProtectedScope();
9545 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9546 VDecl->setInvalidDecl();
9551 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9552 // a kernel function cannot be initialized."
9553 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9554 Diag(VDecl->getLocation(), diag::err_local_cant_init);
9555 VDecl->setInvalidDecl();
9559 // Get the decls type and save a reference for later, since
9560 // CheckInitializerTypes may change it.
9561 QualType DclT = VDecl->getType(), SavT = DclT;
9563 // Expressions default to 'id' when we're in a debugger
9564 // and we are assigning it to a variable of Objective-C pointer type.
9565 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9566 Init->getType() == Context.UnknownAnyTy) {
9567 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9568 if (Result.isInvalid()) {
9569 VDecl->setInvalidDecl();
9572 Init = Result.get();
9575 // Perform the initialization.
9576 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9577 if (!VDecl->isInvalidDecl()) {
9578 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9579 InitializationKind Kind =
9582 ? InitializationKind::CreateDirect(VDecl->getLocation(),
9583 Init->getLocStart(),
9585 : InitializationKind::CreateDirectList(VDecl->getLocation())
9586 : InitializationKind::CreateCopy(VDecl->getLocation(),
9587 Init->getLocStart());
9589 MultiExprArg Args = Init;
9591 Args = MultiExprArg(CXXDirectInit->getExprs(),
9592 CXXDirectInit->getNumExprs());
9594 // Try to correct any TypoExprs in the initialization arguments.
9595 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9596 ExprResult Res = CorrectDelayedTyposInExpr(
9597 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9598 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9599 return Init.Failed() ? ExprError() : E;
9601 if (Res.isInvalid()) {
9602 VDecl->setInvalidDecl();
9603 } else if (Res.get() != Args[Idx]) {
9604 Args[Idx] = Res.get();
9607 if (VDecl->isInvalidDecl())
9610 InitializationSequence InitSeq(*this, Entity, Kind, Args,
9611 /*TopLevelOfInitList=*/false,
9612 /*TreatUnavailableAsInvalid=*/false);
9613 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9614 if (Result.isInvalid()) {
9615 VDecl->setInvalidDecl();
9619 Init = Result.getAs<Expr>();
9622 // Check for self-references within variable initializers.
9623 // Variables declared within a function/method body (except for references)
9624 // are handled by a dataflow analysis.
9625 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9626 VDecl->getType()->isReferenceType()) {
9627 CheckSelfReference(*this, RealDecl, Init, DirectInit);
9630 // If the type changed, it means we had an incomplete type that was
9631 // completed by the initializer. For example:
9632 // int ary[] = { 1, 3, 5 };
9633 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9634 if (!VDecl->isInvalidDecl() && (DclT != SavT))
9635 VDecl->setType(DclT);
9637 if (!VDecl->isInvalidDecl()) {
9638 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9640 if (VDecl->hasAttr<BlocksAttr>())
9641 checkRetainCycles(VDecl, Init);
9643 // It is safe to assign a weak reference into a strong variable.
9644 // Although this code can still have problems:
9645 // id x = self.weakProp;
9646 // id y = self.weakProp;
9647 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9648 // paths through the function. This should be revisited if
9649 // -Wrepeated-use-of-weak is made flow-sensitive.
9650 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9651 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9652 Init->getLocStart()))
9653 getCurFunction()->markSafeWeakUse(Init);
9656 // The initialization is usually a full-expression.
9658 // FIXME: If this is a braced initialization of an aggregate, it is not
9659 // an expression, and each individual field initializer is a separate
9660 // full-expression. For instance, in:
9662 // struct Temp { ~Temp(); };
9663 // struct S { S(Temp); };
9664 // struct T { S a, b; } t = { Temp(), Temp() }
9666 // we should destroy the first Temp before constructing the second.
9667 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9669 VDecl->isConstexpr());
9670 if (Result.isInvalid()) {
9671 VDecl->setInvalidDecl();
9674 Init = Result.get();
9676 // Attach the initializer to the decl.
9677 VDecl->setInit(Init);
9679 if (VDecl->isLocalVarDecl()) {
9680 // C99 6.7.8p4: All the expressions in an initializer for an object that has
9681 // static storage duration shall be constant expressions or string literals.
9682 // C++ does not have this restriction.
9683 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9684 const Expr *Culprit;
9685 if (VDecl->getStorageClass() == SC_Static)
9686 CheckForConstantInitializer(Init, DclT);
9687 // C89 is stricter than C99 for non-static aggregate types.
9688 // C89 6.5.7p3: All the expressions [...] in an initializer list
9689 // for an object that has aggregate or union type shall be
9690 // constant expressions.
9691 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9692 isa<InitListExpr>(Init) &&
9693 !Init->isConstantInitializer(Context, false, &Culprit))
9694 Diag(Culprit->getExprLoc(),
9695 diag::ext_aggregate_init_not_constant)
9696 << Culprit->getSourceRange();
9698 } else if (VDecl->isStaticDataMember() &&
9699 VDecl->getLexicalDeclContext()->isRecord()) {
9700 // This is an in-class initialization for a static data member, e.g.,
9703 // static const int value = 17;
9706 // C++ [class.mem]p4:
9707 // A member-declarator can contain a constant-initializer only
9708 // if it declares a static member (9.4) of const integral or
9709 // const enumeration type, see 9.4.2.
9711 // C++11 [class.static.data]p3:
9712 // If a non-volatile const static data member is of integral or
9713 // enumeration type, its declaration in the class definition can
9714 // specify a brace-or-equal-initializer in which every initalizer-clause
9715 // that is an assignment-expression is a constant expression. A static
9716 // data member of literal type can be declared in the class definition
9717 // with the constexpr specifier; if so, its declaration shall specify a
9718 // brace-or-equal-initializer in which every initializer-clause that is
9719 // an assignment-expression is a constant expression.
9721 // Do nothing on dependent types.
9722 if (DclT->isDependentType()) {
9724 // Allow any 'static constexpr' members, whether or not they are of literal
9725 // type. We separately check that every constexpr variable is of literal
9727 } else if (VDecl->isConstexpr()) {
9729 // Require constness.
9730 } else if (!DclT.isConstQualified()) {
9731 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9732 << Init->getSourceRange();
9733 VDecl->setInvalidDecl();
9735 // We allow integer constant expressions in all cases.
9736 } else if (DclT->isIntegralOrEnumerationType()) {
9737 // Check whether the expression is a constant expression.
9739 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9740 // In C++11, a non-constexpr const static data member with an
9741 // in-class initializer cannot be volatile.
9742 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9743 else if (Init->isValueDependent())
9744 ; // Nothing to check.
9745 else if (Init->isIntegerConstantExpr(Context, &Loc))
9746 ; // Ok, it's an ICE!
9747 else if (Init->isEvaluatable(Context)) {
9748 // If we can constant fold the initializer through heroics, accept it,
9749 // but report this as a use of an extension for -pedantic.
9750 Diag(Loc, diag::ext_in_class_initializer_non_constant)
9751 << Init->getSourceRange();
9753 // Otherwise, this is some crazy unknown case. Report the issue at the
9754 // location provided by the isIntegerConstantExpr failed check.
9755 Diag(Loc, diag::err_in_class_initializer_non_constant)
9756 << Init->getSourceRange();
9757 VDecl->setInvalidDecl();
9760 // We allow foldable floating-point constants as an extension.
9761 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9762 // In C++98, this is a GNU extension. In C++11, it is not, but we support
9763 // it anyway and provide a fixit to add the 'constexpr'.
9764 if (getLangOpts().CPlusPlus11) {
9765 Diag(VDecl->getLocation(),
9766 diag::ext_in_class_initializer_float_type_cxx11)
9767 << DclT << Init->getSourceRange();
9768 Diag(VDecl->getLocStart(),
9769 diag::note_in_class_initializer_float_type_cxx11)
9770 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9772 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9773 << DclT << Init->getSourceRange();
9775 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9776 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9777 << Init->getSourceRange();
9778 VDecl->setInvalidDecl();
9782 // Suggest adding 'constexpr' in C++11 for literal types.
9783 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9784 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9785 << DclT << Init->getSourceRange()
9786 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9787 VDecl->setConstexpr(true);
9790 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9791 << DclT << Init->getSourceRange();
9792 VDecl->setInvalidDecl();
9794 } else if (VDecl->isFileVarDecl()) {
9795 if (VDecl->getStorageClass() == SC_Extern &&
9796 (!getLangOpts().CPlusPlus ||
9797 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9798 VDecl->isExternC())) &&
9799 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9800 Diag(VDecl->getLocation(), diag::warn_extern_init);
9802 // C99 6.7.8p4. All file scoped initializers need to be constant.
9803 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9804 CheckForConstantInitializer(Init, DclT);
9807 // We will represent direct-initialization similarly to copy-initialization:
9808 // int x(1); -as-> int x = 1;
9809 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9811 // Clients that want to distinguish between the two forms, can check for
9812 // direct initializer using VarDecl::getInitStyle().
9813 // A major benefit is that clients that don't particularly care about which
9814 // exactly form was it (like the CodeGen) can handle both cases without
9815 // special case code.
9818 // The form of initialization (using parentheses or '=') is generally
9819 // insignificant, but does matter when the entity being initialized has a
9821 if (CXXDirectInit) {
9822 assert(DirectInit && "Call-style initializer must be direct init.");
9823 VDecl->setInitStyle(VarDecl::CallInit);
9824 } else if (DirectInit) {
9825 // This must be list-initialization. No other way is direct-initialization.
9826 VDecl->setInitStyle(VarDecl::ListInit);
9829 CheckCompleteVariableDeclaration(VDecl);
9832 /// ActOnInitializerError - Given that there was an error parsing an
9833 /// initializer for the given declaration, try to return to some form
9835 void Sema::ActOnInitializerError(Decl *D) {
9836 // Our main concern here is re-establishing invariants like "a
9837 // variable's type is either dependent or complete".
9838 if (!D || D->isInvalidDecl()) return;
9840 VarDecl *VD = dyn_cast<VarDecl>(D);
9843 // Auto types are meaningless if we can't make sense of the initializer.
9844 if (ParsingInitForAutoVars.count(D)) {
9845 D->setInvalidDecl();
9849 QualType Ty = VD->getType();
9850 if (Ty->isDependentType()) return;
9852 // Require a complete type.
9853 if (RequireCompleteType(VD->getLocation(),
9854 Context.getBaseElementType(Ty),
9855 diag::err_typecheck_decl_incomplete_type)) {
9856 VD->setInvalidDecl();
9860 // Require a non-abstract type.
9861 if (RequireNonAbstractType(VD->getLocation(), Ty,
9862 diag::err_abstract_type_in_decl,
9863 AbstractVariableType)) {
9864 VD->setInvalidDecl();
9868 // Don't bother complaining about constructors or destructors,
9872 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9873 bool TypeMayContainAuto) {
9874 // If there is no declaration, there was an error parsing it. Just ignore it.
9878 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9879 QualType Type = Var->getType();
9881 // C++11 [dcl.spec.auto]p3
9882 if (TypeMayContainAuto && Type->getContainedAutoType()) {
9883 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9884 << Var->getDeclName() << Type;
9885 Var->setInvalidDecl();
9889 // C++11 [class.static.data]p3: A static data member can be declared with
9890 // the constexpr specifier; if so, its declaration shall specify
9891 // a brace-or-equal-initializer.
9892 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9893 // the definition of a variable [...] or the declaration of a static data
9895 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9896 if (Var->isStaticDataMember())
9897 Diag(Var->getLocation(),
9898 diag::err_constexpr_static_mem_var_requires_init)
9899 << Var->getDeclName();
9901 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9902 Var->setInvalidDecl();
9906 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
9907 // definition having the concept specifier is called a variable concept. A
9908 // concept definition refers to [...] a variable concept and its initializer.
9909 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9910 if (VTD->isConcept()) {
9911 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9912 Var->setInvalidDecl();
9917 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9919 if (!Var->isInvalidDecl() &&
9920 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9921 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9922 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9923 Var->setInvalidDecl();
9927 switch (Var->isThisDeclarationADefinition()) {
9928 case VarDecl::Definition:
9929 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9932 // We have an out-of-line definition of a static data member
9933 // that has an in-class initializer, so we type-check this like
9938 case VarDecl::DeclarationOnly:
9939 // It's only a declaration.
9941 // Block scope. C99 6.7p7: If an identifier for an object is
9942 // declared with no linkage (C99 6.2.2p6), the type for the
9943 // object shall be complete.
9944 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9945 !Var->hasLinkage() && !Var->isInvalidDecl() &&
9946 RequireCompleteType(Var->getLocation(), Type,
9947 diag::err_typecheck_decl_incomplete_type))
9948 Var->setInvalidDecl();
9950 // Make sure that the type is not abstract.
9951 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9952 RequireNonAbstractType(Var->getLocation(), Type,
9953 diag::err_abstract_type_in_decl,
9954 AbstractVariableType))
9955 Var->setInvalidDecl();
9956 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9957 Var->getStorageClass() == SC_PrivateExtern) {
9958 Diag(Var->getLocation(), diag::warn_private_extern);
9959 Diag(Var->getLocation(), diag::note_private_extern);
9964 case VarDecl::TentativeDefinition:
9965 // File scope. C99 6.9.2p2: A declaration of an identifier for an
9966 // object that has file scope without an initializer, and without a
9967 // storage-class specifier or with the storage-class specifier "static",
9968 // constitutes a tentative definition. Note: A tentative definition with
9969 // external linkage is valid (C99 6.2.2p5).
9970 if (!Var->isInvalidDecl()) {
9971 if (const IncompleteArrayType *ArrayT
9972 = Context.getAsIncompleteArrayType(Type)) {
9973 if (RequireCompleteType(Var->getLocation(),
9974 ArrayT->getElementType(),
9975 diag::err_illegal_decl_array_incomplete_type))
9976 Var->setInvalidDecl();
9977 } else if (Var->getStorageClass() == SC_Static) {
9978 // C99 6.9.2p3: If the declaration of an identifier for an object is
9979 // a tentative definition and has internal linkage (C99 6.2.2p3), the
9980 // declared type shall not be an incomplete type.
9981 // NOTE: code such as the following
9983 // struct s { int a; };
9984 // is accepted by gcc. Hence here we issue a warning instead of
9985 // an error and we do not invalidate the static declaration.
9986 // NOTE: to avoid multiple warnings, only check the first declaration.
9987 if (Var->isFirstDecl())
9988 RequireCompleteType(Var->getLocation(), Type,
9989 diag::ext_typecheck_decl_incomplete_type);
9993 // Record the tentative definition; we're done.
9994 if (!Var->isInvalidDecl())
9995 TentativeDefinitions.push_back(Var);
9999 // Provide a specific diagnostic for uninitialized variable
10000 // definitions with incomplete array type.
10001 if (Type->isIncompleteArrayType()) {
10002 Diag(Var->getLocation(),
10003 diag::err_typecheck_incomplete_array_needs_initializer);
10004 Var->setInvalidDecl();
10008 // Provide a specific diagnostic for uninitialized variable
10009 // definitions with reference type.
10010 if (Type->isReferenceType()) {
10011 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10012 << Var->getDeclName()
10013 << SourceRange(Var->getLocation(), Var->getLocation());
10014 Var->setInvalidDecl();
10018 // Do not attempt to type-check the default initializer for a
10019 // variable with dependent type.
10020 if (Type->isDependentType())
10023 if (Var->isInvalidDecl())
10026 if (!Var->hasAttr<AliasAttr>()) {
10027 if (RequireCompleteType(Var->getLocation(),
10028 Context.getBaseElementType(Type),
10029 diag::err_typecheck_decl_incomplete_type)) {
10030 Var->setInvalidDecl();
10037 // The variable can not have an abstract class type.
10038 if (RequireNonAbstractType(Var->getLocation(), Type,
10039 diag::err_abstract_type_in_decl,
10040 AbstractVariableType)) {
10041 Var->setInvalidDecl();
10045 // Check for jumps past the implicit initializer. C++0x
10046 // clarifies that this applies to a "variable with automatic
10047 // storage duration", not a "local variable".
10048 // C++11 [stmt.dcl]p3
10049 // A program that jumps from a point where a variable with automatic
10050 // storage duration is not in scope to a point where it is in scope is
10051 // ill-formed unless the variable has scalar type, class type with a
10052 // trivial default constructor and a trivial destructor, a cv-qualified
10053 // version of one of these types, or an array of one of the preceding
10054 // types and is declared without an initializer.
10055 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10056 if (const RecordType *Record
10057 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10058 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10059 // Mark the function for further checking even if the looser rules of
10060 // C++11 do not require such checks, so that we can diagnose
10061 // incompatibilities with C++98.
10062 if (!CXXRecord->isPOD())
10063 getCurFunction()->setHasBranchProtectedScope();
10067 // C++03 [dcl.init]p9:
10068 // If no initializer is specified for an object, and the
10069 // object is of (possibly cv-qualified) non-POD class type (or
10070 // array thereof), the object shall be default-initialized; if
10071 // the object is of const-qualified type, the underlying class
10072 // type shall have a user-declared default
10073 // constructor. Otherwise, if no initializer is specified for
10074 // a non- static object, the object and its subobjects, if
10075 // any, have an indeterminate initial value); if the object
10076 // or any of its subobjects are of const-qualified type, the
10077 // program is ill-formed.
10078 // C++0x [dcl.init]p11:
10079 // If no initializer is specified for an object, the object is
10080 // default-initialized; [...].
10081 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10082 InitializationKind Kind
10083 = InitializationKind::CreateDefault(Var->getLocation());
10085 InitializationSequence InitSeq(*this, Entity, Kind, None);
10086 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10087 if (Init.isInvalid())
10088 Var->setInvalidDecl();
10089 else if (Init.get()) {
10090 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10091 // This is important for template substitution.
10092 Var->setInitStyle(VarDecl::CallInit);
10095 CheckCompleteVariableDeclaration(Var);
10099 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10100 // If there is no declaration, there was an error parsing it. Ignore it.
10104 VarDecl *VD = dyn_cast<VarDecl>(D);
10106 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10107 D->setInvalidDecl();
10111 VD->setCXXForRangeDecl(true);
10113 // for-range-declaration cannot be given a storage class specifier.
10115 switch (VD->getStorageClass()) {
10124 case SC_PrivateExtern:
10135 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10136 << VD->getDeclName() << Error;
10137 D->setInvalidDecl();
10142 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10143 IdentifierInfo *Ident,
10144 ParsedAttributes &Attrs,
10145 SourceLocation AttrEnd) {
10146 // C++1y [stmt.iter]p1:
10147 // A range-based for statement of the form
10148 // for ( for-range-identifier : for-range-initializer ) statement
10149 // is equivalent to
10150 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10151 DeclSpec DS(Attrs.getPool().getFactory());
10153 const char *PrevSpec;
10155 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10156 getPrintingPolicy());
10158 Declarator D(DS, Declarator::ForContext);
10159 D.SetIdentifier(Ident, IdentLoc);
10160 D.takeAttributes(Attrs, AttrEnd);
10162 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10163 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10164 EmptyAttrs, IdentLoc);
10165 Decl *Var = ActOnDeclarator(S, D);
10166 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10167 FinalizeDeclaration(Var);
10168 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10169 AttrEnd.isValid() ? AttrEnd : IdentLoc);
10172 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10173 if (var->isInvalidDecl()) return;
10175 if (getLangOpts().OpenCL) {
10176 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10178 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10180 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10182 var->setInvalidDecl();
10187 // In Objective-C, don't allow jumps past the implicit initialization of a
10188 // local retaining variable.
10189 if (getLangOpts().ObjC1 &&
10190 var->hasLocalStorage()) {
10191 switch (var->getType().getObjCLifetime()) {
10192 case Qualifiers::OCL_None:
10193 case Qualifiers::OCL_ExplicitNone:
10194 case Qualifiers::OCL_Autoreleasing:
10197 case Qualifiers::OCL_Weak:
10198 case Qualifiers::OCL_Strong:
10199 getCurFunction()->setHasBranchProtectedScope();
10204 // Warn about externally-visible variables being defined without a
10205 // prior declaration. We only want to do this for global
10206 // declarations, but we also specifically need to avoid doing it for
10207 // class members because the linkage of an anonymous class can
10208 // change if it's later given a typedef name.
10209 if (var->isThisDeclarationADefinition() &&
10210 var->getDeclContext()->getRedeclContext()->isFileContext() &&
10211 var->isExternallyVisible() && var->hasLinkage() &&
10212 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10213 var->getLocation())) {
10214 // Find a previous declaration that's not a definition.
10215 VarDecl *prev = var->getPreviousDecl();
10216 while (prev && prev->isThisDeclarationADefinition())
10217 prev = prev->getPreviousDecl();
10220 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10223 if (var->getTLSKind() == VarDecl::TLS_Static) {
10224 const Expr *Culprit;
10225 if (var->getType().isDestructedType()) {
10226 // GNU C++98 edits for __thread, [basic.start.term]p3:
10227 // The type of an object with thread storage duration shall not
10228 // have a non-trivial destructor.
10229 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10230 if (getLangOpts().CPlusPlus11)
10231 Diag(var->getLocation(), diag::note_use_thread_local);
10232 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10233 !var->getInit()->isConstantInitializer(
10234 Context, var->getType()->isReferenceType(), &Culprit)) {
10235 // GNU C++98 edits for __thread, [basic.start.init]p4:
10236 // An object of thread storage duration shall not require dynamic
10238 // FIXME: Need strict checking here.
10239 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10240 << Culprit->getSourceRange();
10241 if (getLangOpts().CPlusPlus11)
10242 Diag(var->getLocation(), diag::note_use_thread_local);
10246 // Apply section attributes and pragmas to global variables.
10247 bool GlobalStorage = var->hasGlobalStorage();
10248 if (GlobalStorage && var->isThisDeclarationADefinition() &&
10249 ActiveTemplateInstantiations.empty()) {
10250 PragmaStack<StringLiteral *> *Stack = nullptr;
10251 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10252 if (var->getType().isConstQualified())
10253 Stack = &ConstSegStack;
10254 else if (!var->getInit()) {
10255 Stack = &BSSSegStack;
10256 SectionFlags |= ASTContext::PSF_Write;
10258 Stack = &DataSegStack;
10259 SectionFlags |= ASTContext::PSF_Write;
10261 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10262 var->addAttr(SectionAttr::CreateImplicit(
10263 Context, SectionAttr::Declspec_allocate,
10264 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10266 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10267 if (UnifySection(SA->getName(), SectionFlags, var))
10268 var->dropAttr<SectionAttr>();
10270 // Apply the init_seg attribute if this has an initializer. If the
10271 // initializer turns out to not be dynamic, we'll end up ignoring this
10273 if (CurInitSeg && var->getInit())
10274 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10278 // All the following checks are C++ only.
10279 if (!getLangOpts().CPlusPlus) return;
10281 QualType type = var->getType();
10282 if (type->isDependentType()) return;
10284 // __block variables might require us to capture a copy-initializer.
10285 if (var->hasAttr<BlocksAttr>()) {
10286 // It's currently invalid to ever have a __block variable with an
10287 // array type; should we diagnose that here?
10289 // Regardless, we don't want to ignore array nesting when
10290 // constructing this copy.
10291 if (type->isStructureOrClassType()) {
10292 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10293 SourceLocation poi = var->getLocation();
10294 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10296 = PerformMoveOrCopyInitialization(
10297 InitializedEntity::InitializeBlock(poi, type, false),
10298 var, var->getType(), varRef, /*AllowNRVO=*/true);
10299 if (!result.isInvalid()) {
10300 result = MaybeCreateExprWithCleanups(result);
10301 Expr *init = result.getAs<Expr>();
10302 Context.setBlockVarCopyInits(var, init);
10307 Expr *Init = var->getInit();
10308 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10309 QualType baseType = Context.getBaseElementType(type);
10311 if (!var->getDeclContext()->isDependentContext() &&
10312 Init && !Init->isValueDependent()) {
10313 if (IsGlobal && !var->isConstexpr() &&
10314 !getDiagnostics().isIgnored(diag::warn_global_constructor,
10315 var->getLocation())) {
10316 // Warn about globals which don't have a constant initializer. Don't
10317 // warn about globals with a non-trivial destructor because we already
10318 // warned about them.
10319 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10320 if (!(RD && !RD->hasTrivialDestructor()) &&
10321 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10322 Diag(var->getLocation(), diag::warn_global_constructor)
10323 << Init->getSourceRange();
10326 if (var->isConstexpr()) {
10327 SmallVector<PartialDiagnosticAt, 8> Notes;
10328 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10329 SourceLocation DiagLoc = var->getLocation();
10330 // If the note doesn't add any useful information other than a source
10331 // location, fold it into the primary diagnostic.
10332 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10333 diag::note_invalid_subexpr_in_const_expr) {
10334 DiagLoc = Notes[0].first;
10337 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10338 << var << Init->getSourceRange();
10339 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10340 Diag(Notes[I].first, Notes[I].second);
10342 } else if (var->isUsableInConstantExpressions(Context)) {
10343 // Check whether the initializer of a const variable of integral or
10344 // enumeration type is an ICE now, since we can't tell whether it was
10345 // initialized by a constant expression if we check later.
10346 var->checkInitIsICE();
10350 // Require the destructor.
10351 if (const RecordType *recordType = baseType->getAs<RecordType>())
10352 FinalizeVarWithDestructor(var, recordType);
10355 /// \brief Determines if a variable's alignment is dependent.
10356 static bool hasDependentAlignment(VarDecl *VD) {
10357 if (VD->getType()->isDependentType())
10359 for (auto *I : VD->specific_attrs<AlignedAttr>())
10360 if (I->isAlignmentDependent())
10365 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10366 /// any semantic actions necessary after any initializer has been attached.
10368 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10369 // Note that we are no longer parsing the initializer for this declaration.
10370 ParsingInitForAutoVars.erase(ThisDecl);
10372 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10376 checkAttributesAfterMerging(*this, *VD);
10378 // Perform TLS alignment check here after attributes attached to the variable
10379 // which may affect the alignment have been processed. Only perform the check
10380 // if the target has a maximum TLS alignment (zero means no constraints).
10381 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10382 // Protect the check so that it's not performed on dependent types and
10383 // dependent alignments (we can't determine the alignment in that case).
10384 if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10385 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10386 if (Context.getDeclAlign(VD) > MaxAlignChars) {
10387 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10388 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10389 << (unsigned)MaxAlignChars.getQuantity();
10394 if (VD->isStaticLocal()) {
10395 if (FunctionDecl *FD =
10396 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10397 // Static locals inherit dll attributes from their function.
10398 if (Attr *A = getDLLAttr(FD)) {
10399 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10400 NewAttr->setInherited(true);
10401 VD->addAttr(NewAttr);
10403 // CUDA E.2.9.4: Within the body of a __device__ or __global__
10404 // function, only __shared__ variables may be declared with
10405 // static storage class.
10406 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10407 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10408 !VD->hasAttr<CUDASharedAttr>()) {
10409 Diag(VD->getLocation(), diag::err_device_static_local_var);
10410 VD->setInvalidDecl();
10415 // Perform check for initializers of device-side global variables.
10416 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10417 // 7.5). CUDA also allows constant initializers for __constant__ and
10418 // __device__ variables.
10419 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10420 const Expr *Init = VD->getInit();
10421 const bool IsGlobal = VD->hasGlobalStorage() && !VD->isStaticLocal();
10422 if (Init && IsGlobal &&
10423 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10424 VD->hasAttr<CUDASharedAttr>())) {
10425 bool AllowedInit = false;
10426 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10428 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10429 // We'll allow constant initializers even if it's a non-empty
10430 // constructor according to CUDA rules. This deviates from NVCC,
10431 // but allows us to handle things like constexpr constructors.
10432 if (!AllowedInit &&
10433 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10434 AllowedInit = VD->getInit()->isConstantInitializer(
10435 Context, VD->getType()->isReferenceType());
10437 if (!AllowedInit) {
10438 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10439 ? diag::err_shared_var_init
10440 : diag::err_dynamic_var_init)
10441 << Init->getSourceRange();
10442 VD->setInvalidDecl();
10447 // Grab the dllimport or dllexport attribute off of the VarDecl.
10448 const InheritableAttr *DLLAttr = getDLLAttr(VD);
10450 // Imported static data members cannot be defined out-of-line.
10451 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10452 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10453 VD->isThisDeclarationADefinition()) {
10454 // We allow definitions of dllimport class template static data members
10456 CXXRecordDecl *Context =
10457 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10458 bool IsClassTemplateMember =
10459 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10460 Context->getDescribedClassTemplate();
10462 Diag(VD->getLocation(),
10463 IsClassTemplateMember
10464 ? diag::warn_attribute_dllimport_static_field_definition
10465 : diag::err_attribute_dllimport_static_field_definition);
10466 Diag(IA->getLocation(), diag::note_attribute);
10467 if (!IsClassTemplateMember)
10468 VD->setInvalidDecl();
10472 // dllimport/dllexport variables cannot be thread local, their TLS index
10473 // isn't exported with the variable.
10474 if (DLLAttr && VD->getTLSKind()) {
10475 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10476 if (F && getDLLAttr(F)) {
10477 assert(VD->isStaticLocal());
10478 // But if this is a static local in a dlimport/dllexport function, the
10479 // function will never be inlined, which means the var would never be
10480 // imported, so having it marked import/export is safe.
10482 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10484 VD->setInvalidDecl();
10488 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10489 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10490 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10491 VD->dropAttr<UsedAttr>();
10495 const DeclContext *DC = VD->getDeclContext();
10496 // If there's a #pragma GCC visibility in scope, and this isn't a class
10497 // member, set the visibility of this variable.
10498 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10499 AddPushedVisibilityAttribute(VD);
10501 // FIXME: Warn on unused templates.
10502 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10503 !isa<VarTemplatePartialSpecializationDecl>(VD))
10504 MarkUnusedFileScopedDecl(VD);
10506 // Now we have parsed the initializer and can update the table of magic
10508 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10509 !VD->getType()->isIntegralOrEnumerationType())
10512 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10513 const Expr *MagicValueExpr = VD->getInit();
10514 if (!MagicValueExpr) {
10517 llvm::APSInt MagicValueInt;
10518 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10519 Diag(I->getRange().getBegin(),
10520 diag::err_type_tag_for_datatype_not_ice)
10521 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10524 if (MagicValueInt.getActiveBits() > 64) {
10525 Diag(I->getRange().getBegin(),
10526 diag::err_type_tag_for_datatype_too_large)
10527 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10530 uint64_t MagicValue = MagicValueInt.getZExtValue();
10531 RegisterTypeTagForDatatype(I->getArgumentKind(),
10533 I->getMatchingCType(),
10534 I->getLayoutCompatible(),
10535 I->getMustBeNull());
10539 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10540 ArrayRef<Decl *> Group) {
10541 SmallVector<Decl*, 8> Decls;
10543 if (DS.isTypeSpecOwned())
10544 Decls.push_back(DS.getRepAsDecl());
10546 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10547 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10548 if (Decl *D = Group[i]) {
10549 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10550 if (!FirstDeclaratorInGroup)
10551 FirstDeclaratorInGroup = DD;
10552 Decls.push_back(D);
10555 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10556 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10557 handleTagNumbering(Tag, S);
10558 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10559 getLangOpts().CPlusPlus)
10560 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10564 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10567 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10568 /// group, performing any necessary semantic checking.
10569 Sema::DeclGroupPtrTy
10570 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10571 bool TypeMayContainAuto) {
10572 // C++0x [dcl.spec.auto]p7:
10573 // If the type deduced for the template parameter U is not the same in each
10574 // deduction, the program is ill-formed.
10575 // FIXME: When initializer-list support is added, a distinction is needed
10576 // between the deduced type U and the deduced type which 'auto' stands for.
10577 // auto a = 0, b = { 1, 2, 3 };
10578 // is legal because the deduced type U is 'int' in both cases.
10579 if (TypeMayContainAuto && Group.size() > 1) {
10581 CanQualType DeducedCanon;
10582 VarDecl *DeducedDecl = nullptr;
10583 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10584 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10585 AutoType *AT = D->getType()->getContainedAutoType();
10586 // Don't reissue diagnostics when instantiating a template.
10587 if (AT && D->isInvalidDecl())
10589 QualType U = AT ? AT->getDeducedType() : QualType();
10591 CanQualType UCanon = Context.getCanonicalType(U);
10592 if (Deduced.isNull()) {
10594 DeducedCanon = UCanon;
10596 } else if (DeducedCanon != UCanon) {
10597 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10598 diag::err_auto_different_deductions)
10599 << (unsigned)AT->getKeyword()
10600 << Deduced << DeducedDecl->getDeclName()
10601 << U << D->getDeclName()
10602 << DeducedDecl->getInit()->getSourceRange()
10603 << D->getInit()->getSourceRange();
10604 D->setInvalidDecl();
10612 ActOnDocumentableDecls(Group);
10614 return DeclGroupPtrTy::make(
10615 DeclGroupRef::Create(Context, Group.data(), Group.size()));
10618 void Sema::ActOnDocumentableDecl(Decl *D) {
10619 ActOnDocumentableDecls(D);
10622 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10623 // Don't parse the comment if Doxygen diagnostics are ignored.
10624 if (Group.empty() || !Group[0])
10627 if (Diags.isIgnored(diag::warn_doc_param_not_found,
10628 Group[0]->getLocation()) &&
10629 Diags.isIgnored(diag::warn_unknown_comment_command_name,
10630 Group[0]->getLocation()))
10633 if (Group.size() >= 2) {
10634 // This is a decl group. Normally it will contain only declarations
10635 // produced from declarator list. But in case we have any definitions or
10636 // additional declaration references:
10637 // 'typedef struct S {} S;'
10638 // 'typedef struct S *S;'
10640 // FinalizeDeclaratorGroup adds these as separate declarations.
10641 Decl *MaybeTagDecl = Group[0];
10642 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10643 Group = Group.slice(1);
10647 // See if there are any new comments that are not attached to a decl.
10648 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10649 if (!Comments.empty() &&
10650 !Comments.back()->isAttached()) {
10651 // There is at least one comment that not attached to a decl.
10652 // Maybe it should be attached to one of these decls?
10654 // Note that this way we pick up not only comments that precede the
10655 // declaration, but also comments that *follow* the declaration -- thanks to
10656 // the lookahead in the lexer: we've consumed the semicolon and looked
10657 // ahead through comments.
10658 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10659 Context.getCommentForDecl(Group[i], &PP);
10663 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10664 /// to introduce parameters into function prototype scope.
10665 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10666 const DeclSpec &DS = D.getDeclSpec();
10668 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10670 // C++03 [dcl.stc]p2 also permits 'auto'.
10671 StorageClass SC = SC_None;
10672 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10674 } else if (getLangOpts().CPlusPlus &&
10675 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10677 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10678 Diag(DS.getStorageClassSpecLoc(),
10679 diag::err_invalid_storage_class_in_func_decl);
10680 D.getMutableDeclSpec().ClearStorageClassSpecs();
10683 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10684 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10685 << DeclSpec::getSpecifierName(TSCS);
10686 if (DS.isConstexprSpecified())
10687 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10689 if (DS.isConceptSpecified())
10690 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10692 DiagnoseFunctionSpecifiers(DS);
10694 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10695 QualType parmDeclType = TInfo->getType();
10697 if (getLangOpts().CPlusPlus) {
10698 // Check that there are no default arguments inside the type of this
10700 CheckExtraCXXDefaultArguments(D);
10702 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10703 if (D.getCXXScopeSpec().isSet()) {
10704 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10705 << D.getCXXScopeSpec().getRange();
10706 D.getCXXScopeSpec().clear();
10710 // Ensure we have a valid name
10711 IdentifierInfo *II = nullptr;
10713 II = D.getIdentifier();
10715 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10716 << GetNameForDeclarator(D).getName();
10717 D.setInvalidType(true);
10721 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10723 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10726 if (R.isSingleResult()) {
10727 NamedDecl *PrevDecl = R.getFoundDecl();
10728 if (PrevDecl->isTemplateParameter()) {
10729 // Maybe we will complain about the shadowed template parameter.
10730 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10731 // Just pretend that we didn't see the previous declaration.
10732 PrevDecl = nullptr;
10733 } else if (S->isDeclScope(PrevDecl)) {
10734 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10735 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10737 // Recover by removing the name
10739 D.SetIdentifier(nullptr, D.getIdentifierLoc());
10740 D.setInvalidType(true);
10745 // Temporarily put parameter variables in the translation unit, not
10746 // the enclosing context. This prevents them from accidentally
10747 // looking like class members in C++.
10748 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10750 D.getIdentifierLoc(), II,
10751 parmDeclType, TInfo,
10754 if (D.isInvalidType())
10755 New->setInvalidDecl();
10757 assert(S->isFunctionPrototypeScope());
10758 assert(S->getFunctionPrototypeDepth() >= 1);
10759 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10760 S->getNextFunctionPrototypeIndex());
10762 // Add the parameter declaration into this scope.
10765 IdResolver.AddDecl(New);
10767 ProcessDeclAttributes(S, New, D);
10769 if (D.getDeclSpec().isModulePrivateSpecified())
10770 Diag(New->getLocation(), diag::err_module_private_local)
10771 << 1 << New->getDeclName()
10772 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10773 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10775 if (New->hasAttr<BlocksAttr>()) {
10776 Diag(New->getLocation(), diag::err_block_on_nonlocal);
10781 /// \brief Synthesizes a variable for a parameter arising from a
10783 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10784 SourceLocation Loc,
10786 /* FIXME: setting StartLoc == Loc.
10787 Would it be worth to modify callers so as to provide proper source
10788 location for the unnamed parameters, embedding the parameter's type? */
10789 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10790 T, Context.getTrivialTypeSourceInfo(T, Loc),
10792 Param->setImplicit();
10796 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10797 ParmVarDecl * const *ParamEnd) {
10798 // Don't diagnose unused-parameter errors in template instantiations; we
10799 // will already have done so in the template itself.
10800 if (!ActiveTemplateInstantiations.empty())
10803 for (; Param != ParamEnd; ++Param) {
10804 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10805 !(*Param)->hasAttr<UnusedAttr>()) {
10806 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10807 << (*Param)->getDeclName();
10812 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10813 ParmVarDecl * const *ParamEnd,
10816 if (LangOpts.NumLargeByValueCopy == 0) // No check.
10819 // Warn if the return value is pass-by-value and larger than the specified
10821 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10822 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10823 if (Size > LangOpts.NumLargeByValueCopy)
10824 Diag(D->getLocation(), diag::warn_return_value_size)
10825 << D->getDeclName() << Size;
10828 // Warn if any parameter is pass-by-value and larger than the specified
10830 for (; Param != ParamEnd; ++Param) {
10831 QualType T = (*Param)->getType();
10832 if (T->isDependentType() || !T.isPODType(Context))
10834 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10835 if (Size > LangOpts.NumLargeByValueCopy)
10836 Diag((*Param)->getLocation(), diag::warn_parameter_size)
10837 << (*Param)->getDeclName() << Size;
10841 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10842 SourceLocation NameLoc, IdentifierInfo *Name,
10843 QualType T, TypeSourceInfo *TSInfo,
10845 // In ARC, infer a lifetime qualifier for appropriate parameter types.
10846 if (getLangOpts().ObjCAutoRefCount &&
10847 T.getObjCLifetime() == Qualifiers::OCL_None &&
10848 T->isObjCLifetimeType()) {
10850 Qualifiers::ObjCLifetime lifetime;
10852 // Special cases for arrays:
10853 // - if it's const, use __unsafe_unretained
10854 // - otherwise, it's an error
10855 if (T->isArrayType()) {
10856 if (!T.isConstQualified()) {
10857 DelayedDiagnostics.add(
10858 sema::DelayedDiagnostic::makeForbiddenType(
10859 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10861 lifetime = Qualifiers::OCL_ExplicitNone;
10863 lifetime = T->getObjCARCImplicitLifetime();
10865 T = Context.getLifetimeQualifiedType(T, lifetime);
10868 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10869 Context.getAdjustedParameterType(T),
10870 TSInfo, SC, nullptr);
10872 // Parameters can not be abstract class types.
10873 // For record types, this is done by the AbstractClassUsageDiagnoser once
10874 // the class has been completely parsed.
10875 if (!CurContext->isRecord() &&
10876 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10877 AbstractParamType))
10878 New->setInvalidDecl();
10880 // Parameter declarators cannot be interface types. All ObjC objects are
10881 // passed by reference.
10882 if (T->isObjCObjectType()) {
10883 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10885 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10886 << FixItHint::CreateInsertion(TypeEndLoc, "*");
10887 T = Context.getObjCObjectPointerType(T);
10891 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10892 // duration shall not be qualified by an address-space qualifier."
10893 // Since all parameters have automatic store duration, they can not have
10894 // an address space.
10895 if (T.getAddressSpace() != 0) {
10896 // OpenCL allows function arguments declared to be an array of a type
10897 // to be qualified with an address space.
10898 if (!(getLangOpts().OpenCL && T->isArrayType())) {
10899 Diag(NameLoc, diag::err_arg_with_address_space);
10900 New->setInvalidDecl();
10904 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10905 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10906 if (getLangOpts().OpenCL && T->isPointerType()) {
10907 const QualType PTy = T->getPointeeType();
10908 if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10909 Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10910 New->setInvalidDecl();
10917 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10918 SourceLocation LocAfterDecls) {
10919 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10921 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10922 // for a K&R function.
10923 if (!FTI.hasPrototype) {
10924 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10926 if (FTI.Params[i].Param == nullptr) {
10927 SmallString<256> Code;
10928 llvm::raw_svector_ostream(Code)
10929 << " int " << FTI.Params[i].Ident->getName() << ";\n";
10930 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10931 << FTI.Params[i].Ident
10932 << FixItHint::CreateInsertion(LocAfterDecls, Code);
10934 // Implicitly declare the argument as type 'int' for lack of a better
10936 AttributeFactory attrs;
10937 DeclSpec DS(attrs);
10938 const char* PrevSpec; // unused
10939 unsigned DiagID; // unused
10940 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10941 DiagID, Context.getPrintingPolicy());
10942 // Use the identifier location for the type source range.
10943 DS.SetRangeStart(FTI.Params[i].IdentLoc);
10944 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10945 Declarator ParamD(DS, Declarator::KNRTypeListContext);
10946 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10947 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10954 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10955 MultiTemplateParamsArg TemplateParameterLists,
10956 SkipBodyInfo *SkipBody) {
10957 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10958 assert(D.isFunctionDeclarator() && "Not a function declarator!");
10959 Scope *ParentScope = FnBodyScope->getParent();
10961 D.setFunctionDefinitionKind(FDK_Definition);
10962 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10963 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10966 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
10967 Consumer.HandleInlineFunctionDefinition(D);
10970 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10971 const FunctionDecl*& PossibleZeroParamPrototype) {
10972 // Don't warn about invalid declarations.
10973 if (FD->isInvalidDecl())
10976 // Or declarations that aren't global.
10977 if (!FD->isGlobal())
10980 // Don't warn about C++ member functions.
10981 if (isa<CXXMethodDecl>(FD))
10984 // Don't warn about 'main'.
10988 // Don't warn about inline functions.
10989 if (FD->isInlined())
10992 // Don't warn about function templates.
10993 if (FD->getDescribedFunctionTemplate())
10996 // Don't warn about function template specializations.
10997 if (FD->isFunctionTemplateSpecialization())
11000 // Don't warn for OpenCL kernels.
11001 if (FD->hasAttr<OpenCLKernelAttr>())
11004 // Don't warn on explicitly deleted functions.
11005 if (FD->isDeleted())
11008 bool MissingPrototype = true;
11009 for (const FunctionDecl *Prev = FD->getPreviousDecl();
11010 Prev; Prev = Prev->getPreviousDecl()) {
11011 // Ignore any declarations that occur in function or method
11012 // scope, because they aren't visible from the header.
11013 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11016 MissingPrototype = !Prev->getType()->isFunctionProtoType();
11017 if (FD->getNumParams() == 0)
11018 PossibleZeroParamPrototype = Prev;
11022 return MissingPrototype;
11026 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11027 const FunctionDecl *EffectiveDefinition,
11028 SkipBodyInfo *SkipBody) {
11029 // Don't complain if we're in GNU89 mode and the previous definition
11030 // was an extern inline function.
11031 const FunctionDecl *Definition = EffectiveDefinition;
11033 if (!FD->isDefined(Definition))
11036 if (canRedefineFunction(Definition, getLangOpts()))
11039 // If we don't have a visible definition of the function, and it's inline or
11040 // a template, skip the new definition.
11041 if (SkipBody && !hasVisibleDefinition(Definition) &&
11042 (Definition->getFormalLinkage() == InternalLinkage ||
11043 Definition->isInlined() ||
11044 Definition->getDescribedFunctionTemplate() ||
11045 Definition->getNumTemplateParameterLists())) {
11046 SkipBody->ShouldSkip = true;
11047 if (auto *TD = Definition->getDescribedFunctionTemplate())
11048 makeMergedDefinitionVisible(TD, FD->getLocation());
11050 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11051 FD->getLocation());
11055 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11056 Definition->getStorageClass() == SC_Extern)
11057 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11058 << FD->getDeclName() << getLangOpts().CPlusPlus;
11060 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11062 Diag(Definition->getLocation(), diag::note_previous_definition);
11063 FD->setInvalidDecl();
11066 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11068 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11070 LambdaScopeInfo *LSI = S.PushLambdaScope();
11071 LSI->CallOperator = CallOperator;
11072 LSI->Lambda = LambdaClass;
11073 LSI->ReturnType = CallOperator->getReturnType();
11074 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11076 if (LCD == LCD_None)
11077 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11078 else if (LCD == LCD_ByCopy)
11079 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11080 else if (LCD == LCD_ByRef)
11081 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11082 DeclarationNameInfo DNI = CallOperator->getNameInfo();
11084 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11085 LSI->Mutable = !CallOperator->isConst();
11087 // Add the captures to the LSI so they can be noted as already
11088 // captured within tryCaptureVar.
11089 auto I = LambdaClass->field_begin();
11090 for (const auto &C : LambdaClass->captures()) {
11091 if (C.capturesVariable()) {
11092 VarDecl *VD = C.getCapturedVar();
11093 if (VD->isInitCapture())
11094 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11095 QualType CaptureType = VD->getType();
11096 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11097 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11098 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11099 /*EllipsisLoc*/C.isPackExpansion()
11100 ? C.getEllipsisLoc() : SourceLocation(),
11101 CaptureType, /*Expr*/ nullptr);
11103 } else if (C.capturesThis()) {
11104 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11105 S.getCurrentThisType(), /*Expr*/ nullptr,
11106 C.getCaptureKind() == LCK_StarThis);
11108 LSI->addVLATypeCapture(C.getLocation(), I->getType());
11114 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11115 SkipBodyInfo *SkipBody) {
11116 // Clear the last template instantiation error context.
11117 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11121 FunctionDecl *FD = nullptr;
11123 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11124 FD = FunTmpl->getTemplatedDecl();
11126 FD = cast<FunctionDecl>(D);
11128 // See if this is a redefinition.
11129 if (!FD->isLateTemplateParsed()) {
11130 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11132 // If we're skipping the body, we're done. Don't enter the scope.
11133 if (SkipBody && SkipBody->ShouldSkip)
11137 // If we are instantiating a generic lambda call operator, push
11138 // a LambdaScopeInfo onto the function stack. But use the information
11139 // that's already been calculated (ActOnLambdaExpr) to prime the current
11140 // LambdaScopeInfo.
11141 // When the template operator is being specialized, the LambdaScopeInfo,
11142 // has to be properly restored so that tryCaptureVariable doesn't try
11143 // and capture any new variables. In addition when calculating potential
11144 // captures during transformation of nested lambdas, it is necessary to
11145 // have the LSI properly restored.
11146 if (isGenericLambdaCallOperatorSpecialization(FD)) {
11147 assert(ActiveTemplateInstantiations.size() &&
11148 "There should be an active template instantiation on the stack "
11149 "when instantiating a generic lambda!");
11150 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11153 // Enter a new function scope
11154 PushFunctionScope();
11156 // Builtin functions cannot be defined.
11157 if (unsigned BuiltinID = FD->getBuiltinID()) {
11158 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11159 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11160 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11161 FD->setInvalidDecl();
11165 // The return type of a function definition must be complete
11166 // (C99 6.9.1p3, C++ [dcl.fct]p6).
11167 QualType ResultType = FD->getReturnType();
11168 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11169 !FD->isInvalidDecl() &&
11170 RequireCompleteType(FD->getLocation(), ResultType,
11171 diag::err_func_def_incomplete_result))
11172 FD->setInvalidDecl();
11175 PushDeclContext(FnBodyScope, FD);
11177 // Check the validity of our function parameters
11178 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11179 /*CheckParameterNames=*/true);
11181 // Introduce our parameters into the function scope
11182 for (auto Param : FD->params()) {
11183 Param->setOwningFunction(FD);
11185 // If this has an identifier, add it to the scope stack.
11186 if (Param->getIdentifier() && FnBodyScope) {
11187 CheckShadow(FnBodyScope, Param);
11189 PushOnScopeChains(Param, FnBodyScope);
11193 // If we had any tags defined in the function prototype,
11194 // introduce them into the function scope.
11196 for (ArrayRef<NamedDecl *>::iterator
11197 I = FD->getDeclsInPrototypeScope().begin(),
11198 E = FD->getDeclsInPrototypeScope().end();
11202 // Some of these decls (like enums) may have been pinned to the
11203 // translation unit for lack of a real context earlier. If so, remove
11204 // from the translation unit and reattach to the current context.
11205 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11206 // Is the decl actually in the context?
11207 if (Context.getTranslationUnitDecl()->containsDecl(D))
11208 Context.getTranslationUnitDecl()->removeDecl(D);
11209 // Either way, reassign the lexical decl context to our FunctionDecl.
11210 D->setLexicalDeclContext(CurContext);
11213 // If the decl has a non-null name, make accessible in the current scope.
11214 if (!D->getName().empty())
11215 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11217 // Similarly, dive into enums and fish their constants out, making them
11218 // accessible in this scope.
11219 if (auto *ED = dyn_cast<EnumDecl>(D)) {
11220 for (auto *EI : ED->enumerators())
11221 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11226 // Ensure that the function's exception specification is instantiated.
11227 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11228 ResolveExceptionSpec(D->getLocation(), FPT);
11230 // dllimport cannot be applied to non-inline function definitions.
11231 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11232 !FD->isTemplateInstantiation()) {
11233 assert(!FD->hasAttr<DLLExportAttr>());
11234 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11235 FD->setInvalidDecl();
11238 // We want to attach documentation to original Decl (which might be
11239 // a function template).
11240 ActOnDocumentableDecl(D);
11241 if (getCurLexicalContext()->isObjCContainer() &&
11242 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11243 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11244 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11249 /// \brief Given the set of return statements within a function body,
11250 /// compute the variables that are subject to the named return value
11253 /// Each of the variables that is subject to the named return value
11254 /// optimization will be marked as NRVO variables in the AST, and any
11255 /// return statement that has a marked NRVO variable as its NRVO candidate can
11256 /// use the named return value optimization.
11258 /// This function applies a very simplistic algorithm for NRVO: if every return
11259 /// statement in the scope of a variable has the same NRVO candidate, that
11260 /// candidate is an NRVO variable.
11261 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11262 ReturnStmt **Returns = Scope->Returns.data();
11264 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11265 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11266 if (!NRVOCandidate->isNRVOVariable())
11267 Returns[I]->setNRVOCandidate(nullptr);
11272 bool Sema::canDelayFunctionBody(const Declarator &D) {
11273 // We can't delay parsing the body of a constexpr function template (yet).
11274 if (D.getDeclSpec().isConstexprSpecified())
11277 // We can't delay parsing the body of a function template with a deduced
11278 // return type (yet).
11279 if (D.getDeclSpec().containsPlaceholderType()) {
11280 // If the placeholder introduces a non-deduced trailing return type,
11281 // we can still delay parsing it.
11282 if (D.getNumTypeObjects()) {
11283 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11284 if (Outer.Kind == DeclaratorChunk::Function &&
11285 Outer.Fun.hasTrailingReturnType()) {
11286 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11287 return Ty.isNull() || !Ty->isUndeducedType();
11296 bool Sema::canSkipFunctionBody(Decl *D) {
11297 // We cannot skip the body of a function (or function template) which is
11298 // constexpr, since we may need to evaluate its body in order to parse the
11299 // rest of the file.
11300 // We cannot skip the body of a function with an undeduced return type,
11301 // because any callers of that function need to know the type.
11302 if (const FunctionDecl *FD = D->getAsFunction())
11303 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11305 return Consumer.shouldSkipFunctionBody(D);
11308 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11309 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11310 FD->setHasSkippedBody();
11311 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11312 MD->setHasSkippedBody();
11313 return ActOnFinishFunctionBody(Decl, nullptr);
11316 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11317 return ActOnFinishFunctionBody(D, BodyArg, false);
11320 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11321 bool IsInstantiation) {
11322 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11324 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11325 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11327 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11328 CheckCompletedCoroutineBody(FD, Body);
11333 if (getLangOpts().CPlusPlus14) {
11334 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11335 FD->getReturnType()->isUndeducedType()) {
11336 // If the function has a deduced result type but contains no 'return'
11337 // statements, the result type as written must be exactly 'auto', and
11338 // the deduced result type is 'void'.
11339 if (!FD->getReturnType()->getAs<AutoType>()) {
11340 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11341 << FD->getReturnType();
11342 FD->setInvalidDecl();
11344 // Substitute 'void' for the 'auto' in the type.
11345 TypeLoc ResultType = getReturnTypeLoc(FD);
11346 Context.adjustDeducedFunctionResultType(
11347 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11350 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11351 // In C++11, we don't use 'auto' deduction rules for lambda call
11352 // operators because we don't support return type deduction.
11353 auto *LSI = getCurLambda();
11354 if (LSI->HasImplicitReturnType) {
11355 deduceClosureReturnType(*LSI);
11357 // C++11 [expr.prim.lambda]p4:
11358 // [...] if there are no return statements in the compound-statement
11359 // [the deduced type is] the type void
11361 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11363 // Update the return type to the deduced type.
11364 const FunctionProtoType *Proto =
11365 FD->getType()->getAs<FunctionProtoType>();
11366 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11367 Proto->getExtProtoInfo()));
11371 // The only way to be included in UndefinedButUsed is if there is an
11372 // ODR use before the definition. Avoid the expensive map lookup if this
11373 // is the first declaration.
11374 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11375 if (!FD->isExternallyVisible())
11376 UndefinedButUsed.erase(FD);
11377 else if (FD->isInlined() &&
11378 !LangOpts.GNUInline &&
11379 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11380 UndefinedButUsed.erase(FD);
11383 // If the function implicitly returns zero (like 'main') or is naked,
11384 // don't complain about missing return statements.
11385 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11386 WP.disableCheckFallThrough();
11388 // MSVC permits the use of pure specifier (=0) on function definition,
11389 // defined at class scope, warn about this non-standard construct.
11390 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11391 Diag(FD->getLocation(), diag::ext_pure_function_definition);
11393 if (!FD->isInvalidDecl()) {
11394 // Don't diagnose unused parameters of defaulted or deleted functions.
11395 if (!FD->isDeleted() && !FD->isDefaulted())
11396 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11397 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11398 FD->getReturnType(), FD);
11400 // If this is a structor, we need a vtable.
11401 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11402 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11403 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11404 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11406 // Try to apply the named return value optimization. We have to check
11407 // if we can do this here because lambdas keep return statements around
11408 // to deduce an implicit return type.
11409 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11410 !FD->isDependentContext())
11411 computeNRVO(Body, getCurFunction());
11414 // GNU warning -Wmissing-prototypes:
11415 // Warn if a global function is defined without a previous
11416 // prototype declaration. This warning is issued even if the
11417 // definition itself provides a prototype. The aim is to detect
11418 // global functions that fail to be declared in header files.
11419 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11420 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11421 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11423 if (PossibleZeroParamPrototype) {
11424 // We found a declaration that is not a prototype,
11425 // but that could be a zero-parameter prototype
11426 if (TypeSourceInfo *TI =
11427 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11428 TypeLoc TL = TI->getTypeLoc();
11429 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11430 Diag(PossibleZeroParamPrototype->getLocation(),
11431 diag::note_declaration_not_a_prototype)
11432 << PossibleZeroParamPrototype
11433 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11438 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11439 const CXXMethodDecl *KeyFunction;
11440 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11442 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11443 MD == KeyFunction->getCanonicalDecl()) {
11444 // Update the key-function state if necessary for this ABI.
11445 if (FD->isInlined() &&
11446 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11447 Context.setNonKeyFunction(MD);
11449 // If the newly-chosen key function is already defined, then we
11450 // need to mark the vtable as used retroactively.
11451 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11452 const FunctionDecl *Definition;
11453 if (KeyFunction && KeyFunction->isDefined(Definition))
11454 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11456 // We just defined they key function; mark the vtable as used.
11457 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11462 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11463 "Function parsing confused");
11464 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11465 assert(MD == getCurMethodDecl() && "Method parsing confused");
11467 if (!MD->isInvalidDecl()) {
11468 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11469 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11470 MD->getReturnType(), MD);
11473 computeNRVO(Body, getCurFunction());
11475 if (getCurFunction()->ObjCShouldCallSuper) {
11476 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11477 << MD->getSelector().getAsString();
11478 getCurFunction()->ObjCShouldCallSuper = false;
11480 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11481 const ObjCMethodDecl *InitMethod = nullptr;
11482 bool isDesignated =
11483 MD->isDesignatedInitializerForTheInterface(&InitMethod);
11484 assert(isDesignated && InitMethod);
11485 (void)isDesignated;
11487 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11488 auto IFace = MD->getClassInterface();
11491 auto SuperD = IFace->getSuperClass();
11494 return SuperD->getIdentifier() ==
11495 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11497 // Don't issue this warning for unavailable inits or direct subclasses
11499 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11500 Diag(MD->getLocation(),
11501 diag::warn_objc_designated_init_missing_super_call);
11502 Diag(InitMethod->getLocation(),
11503 diag::note_objc_designated_init_marked_here);
11505 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11507 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11508 // Don't issue this warning for unavaialable inits.
11509 if (!MD->isUnavailable())
11510 Diag(MD->getLocation(),
11511 diag::warn_objc_secondary_init_missing_init_call);
11512 getCurFunction()->ObjCWarnForNoInitDelegation = false;
11518 assert(!getCurFunction()->ObjCShouldCallSuper &&
11519 "This should only be set for ObjC methods, which should have been "
11520 "handled in the block above.");
11522 // Verify and clean out per-function state.
11523 if (Body && (!FD || !FD->isDefaulted())) {
11524 // C++ constructors that have function-try-blocks can't have return
11525 // statements in the handlers of that block. (C++ [except.handle]p14)
11527 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11528 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11530 // Verify that gotos and switch cases don't jump into scopes illegally.
11531 if (getCurFunction()->NeedsScopeChecking() &&
11532 !PP.isCodeCompletionEnabled())
11533 DiagnoseInvalidJumps(Body);
11535 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11536 if (!Destructor->getParent()->isDependentType())
11537 CheckDestructor(Destructor);
11539 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11540 Destructor->getParent());
11543 // If any errors have occurred, clear out any temporaries that may have
11544 // been leftover. This ensures that these temporaries won't be picked up for
11545 // deletion in some later function.
11546 if (getDiagnostics().hasErrorOccurred() ||
11547 getDiagnostics().getSuppressAllDiagnostics()) {
11548 DiscardCleanupsInEvaluationContext();
11550 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11551 !isa<FunctionTemplateDecl>(dcl)) {
11552 // Since the body is valid, issue any analysis-based warnings that are
11554 ActivePolicy = &WP;
11557 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11558 (!CheckConstexprFunctionDecl(FD) ||
11559 !CheckConstexprFunctionBody(FD, Body)))
11560 FD->setInvalidDecl();
11562 if (FD && FD->hasAttr<NakedAttr>()) {
11563 for (const Stmt *S : Body->children()) {
11564 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11565 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11566 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11567 FD->setInvalidDecl();
11573 assert(ExprCleanupObjects.size() ==
11574 ExprEvalContexts.back().NumCleanupObjects &&
11575 "Leftover temporaries in function");
11576 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11577 assert(MaybeODRUseExprs.empty() &&
11578 "Leftover expressions for odr-use checking");
11581 if (!IsInstantiation)
11584 PopFunctionScopeInfo(ActivePolicy, dcl);
11585 // If any errors have occurred, clear out any temporaries that may have
11586 // been leftover. This ensures that these temporaries won't be picked up for
11587 // deletion in some later function.
11588 if (getDiagnostics().hasErrorOccurred()) {
11589 DiscardCleanupsInEvaluationContext();
11595 /// When we finish delayed parsing of an attribute, we must attach it to the
11597 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11598 ParsedAttributes &Attrs) {
11599 // Always attach attributes to the underlying decl.
11600 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11601 D = TD->getTemplatedDecl();
11602 ProcessDeclAttributeList(S, D, Attrs.getList());
11604 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11605 if (Method->isStatic())
11606 checkThisInStaticMemberFunctionAttributes(Method);
11609 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11610 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11611 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11612 IdentifierInfo &II, Scope *S) {
11613 // Before we produce a declaration for an implicitly defined
11614 // function, see whether there was a locally-scoped declaration of
11615 // this name as a function or variable. If so, use that
11616 // (non-visible) declaration, and complain about it.
11617 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11618 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11619 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11620 return ExternCPrev;
11623 // Extension in C99. Legal in C90, but warn about it.
11625 if (II.getName().startswith("__builtin_"))
11626 diag_id = diag::warn_builtin_unknown;
11627 else if (getLangOpts().C99)
11628 diag_id = diag::ext_implicit_function_decl;
11630 diag_id = diag::warn_implicit_function_decl;
11631 Diag(Loc, diag_id) << &II;
11633 // Because typo correction is expensive, only do it if the implicit
11634 // function declaration is going to be treated as an error.
11635 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11636 TypoCorrection Corrected;
11638 (Corrected = CorrectTypo(
11639 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11640 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11641 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11642 /*ErrorRecovery*/false);
11645 // Set a Declarator for the implicit definition: int foo();
11647 AttributeFactory attrFactory;
11648 DeclSpec DS(attrFactory);
11650 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11651 Context.getPrintingPolicy());
11652 (void)Error; // Silence warning.
11653 assert(!Error && "Error setting up implicit decl!");
11654 SourceLocation NoLoc;
11655 Declarator D(DS, Declarator::BlockContext);
11656 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11657 /*IsAmbiguous=*/false,
11658 /*LParenLoc=*/NoLoc,
11659 /*Params=*/nullptr,
11661 /*EllipsisLoc=*/NoLoc,
11662 /*RParenLoc=*/NoLoc,
11664 /*RefQualifierIsLvalueRef=*/true,
11665 /*RefQualifierLoc=*/NoLoc,
11666 /*ConstQualifierLoc=*/NoLoc,
11667 /*VolatileQualifierLoc=*/NoLoc,
11668 /*RestrictQualifierLoc=*/NoLoc,
11669 /*MutableLoc=*/NoLoc,
11671 /*ESpecRange=*/SourceRange(),
11672 /*Exceptions=*/nullptr,
11673 /*ExceptionRanges=*/nullptr,
11674 /*NumExceptions=*/0,
11675 /*NoexceptExpr=*/nullptr,
11676 /*ExceptionSpecTokens=*/nullptr,
11678 DS.getAttributes(),
11680 D.SetIdentifier(&II, Loc);
11682 // Insert this function into translation-unit scope.
11684 DeclContext *PrevDC = CurContext;
11685 CurContext = Context.getTranslationUnitDecl();
11687 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11690 CurContext = PrevDC;
11692 AddKnownFunctionAttributes(FD);
11697 /// \brief Adds any function attributes that we know a priori based on
11698 /// the declaration of this function.
11700 /// These attributes can apply both to implicitly-declared builtins
11701 /// (like __builtin___printf_chk) or to library-declared functions
11702 /// like NSLog or printf.
11704 /// We need to check for duplicate attributes both here and where user-written
11705 /// attributes are applied to declarations.
11706 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11707 if (FD->isInvalidDecl())
11710 // If this is a built-in function, map its builtin attributes to
11711 // actual attributes.
11712 if (unsigned BuiltinID = FD->getBuiltinID()) {
11713 // Handle printf-formatting attributes.
11714 unsigned FormatIdx;
11716 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11717 if (!FD->hasAttr<FormatAttr>()) {
11718 const char *fmt = "printf";
11719 unsigned int NumParams = FD->getNumParams();
11720 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11721 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11723 FD->addAttr(FormatAttr::CreateImplicit(Context,
11724 &Context.Idents.get(fmt),
11726 HasVAListArg ? 0 : FormatIdx+2,
11727 FD->getLocation()));
11730 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11732 if (!FD->hasAttr<FormatAttr>())
11733 FD->addAttr(FormatAttr::CreateImplicit(Context,
11734 &Context.Idents.get("scanf"),
11736 HasVAListArg ? 0 : FormatIdx+2,
11737 FD->getLocation()));
11740 // Mark const if we don't care about errno and that is the only
11741 // thing preventing the function from being const. This allows
11742 // IRgen to use LLVM intrinsics for such functions.
11743 if (!getLangOpts().MathErrno &&
11744 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11745 if (!FD->hasAttr<ConstAttr>())
11746 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11749 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11750 !FD->hasAttr<ReturnsTwiceAttr>())
11751 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11752 FD->getLocation()));
11753 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11754 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11755 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11756 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11757 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11758 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11759 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11760 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11761 // Add the appropriate attribute, depending on the CUDA compilation mode
11762 // and which target the builtin belongs to. For example, during host
11763 // compilation, aux builtins are __device__, while the rest are __host__.
11764 if (getLangOpts().CUDAIsDevice !=
11765 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11766 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11768 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11772 // If C++ exceptions are enabled but we are told extern "C" functions cannot
11773 // throw, add an implicit nothrow attribute to any extern "C" function we come
11775 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11776 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11777 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11778 if (!FPT || FPT->getExceptionSpecType() == EST_None)
11779 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11782 IdentifierInfo *Name = FD->getIdentifier();
11785 if ((!getLangOpts().CPlusPlus &&
11786 FD->getDeclContext()->isTranslationUnit()) ||
11787 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11788 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11789 LinkageSpecDecl::lang_c)) {
11790 // Okay: this could be a libc/libm/Objective-C function we know
11795 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11796 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11797 // target-specific builtins, perhaps?
11798 if (!FD->hasAttr<FormatAttr>())
11799 FD->addAttr(FormatAttr::CreateImplicit(Context,
11800 &Context.Idents.get("printf"), 2,
11801 Name->isStr("vasprintf") ? 0 : 3,
11802 FD->getLocation()));
11805 if (Name->isStr("__CFStringMakeConstantString")) {
11806 // We already have a __builtin___CFStringMakeConstantString,
11807 // but builds that use -fno-constant-cfstrings don't go through that.
11808 if (!FD->hasAttr<FormatArgAttr>())
11809 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11810 FD->getLocation()));
11814 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11815 TypeSourceInfo *TInfo) {
11816 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11817 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11820 assert(D.isInvalidType() && "no declarator info for valid type");
11821 TInfo = Context.getTrivialTypeSourceInfo(T);
11824 // Scope manipulation handled by caller.
11825 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11827 D.getIdentifierLoc(),
11831 // Bail out immediately if we have an invalid declaration.
11832 if (D.isInvalidType()) {
11833 NewTD->setInvalidDecl();
11837 if (D.getDeclSpec().isModulePrivateSpecified()) {
11838 if (CurContext->isFunctionOrMethod())
11839 Diag(NewTD->getLocation(), diag::err_module_private_local)
11840 << 2 << NewTD->getDeclName()
11841 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11842 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11844 NewTD->setModulePrivate();
11847 // C++ [dcl.typedef]p8:
11848 // If the typedef declaration defines an unnamed class (or
11849 // enum), the first typedef-name declared by the declaration
11850 // to be that class type (or enum type) is used to denote the
11851 // class type (or enum type) for linkage purposes only.
11852 // We need to check whether the type was declared in the declaration.
11853 switch (D.getDeclSpec().getTypeSpecType()) {
11856 case TST_interface:
11859 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11860 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11871 /// \brief Check that this is a valid underlying type for an enum declaration.
11872 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11873 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11874 QualType T = TI->getType();
11876 if (T->isDependentType())
11879 if (const BuiltinType *BT = T->getAs<BuiltinType>())
11880 if (BT->isInteger())
11883 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11887 /// Check whether this is a valid redeclaration of a previous enumeration.
11888 /// \return true if the redeclaration was invalid.
11889 bool Sema::CheckEnumRedeclaration(
11890 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11891 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11892 bool IsFixed = !EnumUnderlyingTy.isNull();
11894 if (IsScoped != Prev->isScoped()) {
11895 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11896 << Prev->isScoped();
11897 Diag(Prev->getLocation(), diag::note_previous_declaration);
11901 if (IsFixed && Prev->isFixed()) {
11902 if (!EnumUnderlyingTy->isDependentType() &&
11903 !Prev->getIntegerType()->isDependentType() &&
11904 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11905 Prev->getIntegerType())) {
11906 // TODO: Highlight the underlying type of the redeclaration.
11907 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11908 << EnumUnderlyingTy << Prev->getIntegerType();
11909 Diag(Prev->getLocation(), diag::note_previous_declaration)
11910 << Prev->getIntegerTypeRange();
11913 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11915 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11917 } else if (IsFixed != Prev->isFixed()) {
11918 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11919 << Prev->isFixed();
11920 Diag(Prev->getLocation(), diag::note_previous_declaration);
11927 /// \brief Get diagnostic %select index for tag kind for
11928 /// redeclaration diagnostic message.
11929 /// WARNING: Indexes apply to particular diagnostics only!
11931 /// \returns diagnostic %select index.
11932 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11934 case TTK_Struct: return 0;
11935 case TTK_Interface: return 1;
11936 case TTK_Class: return 2;
11937 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11941 /// \brief Determine if tag kind is a class-key compatible with
11942 /// class for redeclaration (class, struct, or __interface).
11944 /// \returns true iff the tag kind is compatible.
11945 static bool isClassCompatTagKind(TagTypeKind Tag)
11947 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11950 /// \brief Determine whether a tag with a given kind is acceptable
11951 /// as a redeclaration of the given tag declaration.
11953 /// \returns true if the new tag kind is acceptable, false otherwise.
11954 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11955 TagTypeKind NewTag, bool isDefinition,
11956 SourceLocation NewTagLoc,
11957 const IdentifierInfo *Name) {
11958 // C++ [dcl.type.elab]p3:
11959 // The class-key or enum keyword present in the
11960 // elaborated-type-specifier shall agree in kind with the
11961 // declaration to which the name in the elaborated-type-specifier
11962 // refers. This rule also applies to the form of
11963 // elaborated-type-specifier that declares a class-name or
11964 // friend class since it can be construed as referring to the
11965 // definition of the class. Thus, in any
11966 // elaborated-type-specifier, the enum keyword shall be used to
11967 // refer to an enumeration (7.2), the union class-key shall be
11968 // used to refer to a union (clause 9), and either the class or
11969 // struct class-key shall be used to refer to a class (clause 9)
11970 // declared using the class or struct class-key.
11971 TagTypeKind OldTag = Previous->getTagKind();
11972 if (!isDefinition || !isClassCompatTagKind(NewTag))
11973 if (OldTag == NewTag)
11976 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11977 // Warn about the struct/class tag mismatch.
11978 bool isTemplate = false;
11979 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11980 isTemplate = Record->getDescribedClassTemplate();
11982 if (!ActiveTemplateInstantiations.empty()) {
11983 // In a template instantiation, do not offer fix-its for tag mismatches
11984 // since they usually mess up the template instead of fixing the problem.
11985 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11986 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11987 << getRedeclDiagFromTagKind(OldTag);
11991 if (isDefinition) {
11992 // On definitions, check previous tags and issue a fix-it for each
11993 // one that doesn't match the current tag.
11994 if (Previous->getDefinition()) {
11995 // Don't suggest fix-its for redefinitions.
11999 bool previousMismatch = false;
12000 for (auto I : Previous->redecls()) {
12001 if (I->getTagKind() != NewTag) {
12002 if (!previousMismatch) {
12003 previousMismatch = true;
12004 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12005 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12006 << getRedeclDiagFromTagKind(I->getTagKind());
12008 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12009 << getRedeclDiagFromTagKind(NewTag)
12010 << FixItHint::CreateReplacement(I->getInnerLocStart(),
12011 TypeWithKeyword::getTagTypeKindName(NewTag));
12017 // Check for a previous definition. If current tag and definition
12018 // are same type, do nothing. If no definition, but disagree with
12019 // with previous tag type, give a warning, but no fix-it.
12020 const TagDecl *Redecl = Previous->getDefinition() ?
12021 Previous->getDefinition() : Previous;
12022 if (Redecl->getTagKind() == NewTag) {
12026 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12027 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12028 << getRedeclDiagFromTagKind(OldTag);
12029 Diag(Redecl->getLocation(), diag::note_previous_use);
12031 // If there is a previous definition, suggest a fix-it.
12032 if (Previous->getDefinition()) {
12033 Diag(NewTagLoc, diag::note_struct_class_suggestion)
12034 << getRedeclDiagFromTagKind(Redecl->getTagKind())
12035 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12036 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12044 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12045 /// from an outer enclosing namespace or file scope inside a friend declaration.
12046 /// This should provide the commented out code in the following snippet:
12050 /// struct Y { friend struct /*N::*/ X; };
12053 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12054 SourceLocation NameLoc) {
12055 // While the decl is in a namespace, do repeated lookup of that name and see
12056 // if we get the same namespace back. If we do not, continue until
12057 // translation unit scope, at which point we have a fully qualified NNS.
12058 SmallVector<IdentifierInfo *, 4> Namespaces;
12059 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12060 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12061 // This tag should be declared in a namespace, which can only be enclosed by
12062 // other namespaces. Bail if there's an anonymous namespace in the chain.
12063 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12064 if (!Namespace || Namespace->isAnonymousNamespace())
12065 return FixItHint();
12066 IdentifierInfo *II = Namespace->getIdentifier();
12067 Namespaces.push_back(II);
12068 NamedDecl *Lookup = SemaRef.LookupSingleName(
12069 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12070 if (Lookup == Namespace)
12074 // Once we have all the namespaces, reverse them to go outermost first, and
12076 SmallString<64> Insertion;
12077 llvm::raw_svector_ostream OS(Insertion);
12078 if (DC->isTranslationUnit())
12080 std::reverse(Namespaces.begin(), Namespaces.end());
12081 for (auto *II : Namespaces)
12082 OS << II->getName() << "::";
12083 return FixItHint::CreateInsertion(NameLoc, Insertion);
12086 /// \brief Determine whether a tag originally declared in context \p OldDC can
12087 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12088 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12089 /// using-declaration).
12090 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12091 DeclContext *NewDC) {
12092 OldDC = OldDC->getRedeclContext();
12093 NewDC = NewDC->getRedeclContext();
12095 if (OldDC->Equals(NewDC))
12098 // In MSVC mode, we allow a redeclaration if the contexts are related (either
12099 // encloses the other).
12100 if (S.getLangOpts().MSVCCompat &&
12101 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12107 /// Find the DeclContext in which a tag is implicitly declared if we see an
12108 /// elaborated type specifier in the specified context, and lookup finds
12110 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12111 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12112 DC = DC->getParent();
12116 /// Find the Scope in which a tag is implicitly declared if we see an
12117 /// elaborated type specifier in the specified context, and lookup finds
12119 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12120 while (S->isClassScope() ||
12121 (LangOpts.CPlusPlus &&
12122 S->isFunctionPrototypeScope()) ||
12123 ((S->getFlags() & Scope::DeclScope) == 0) ||
12124 (S->getEntity() && S->getEntity()->isTransparentContext()))
12125 S = S->getParent();
12129 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
12130 /// former case, Name will be non-null. In the later case, Name will be null.
12131 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12132 /// reference/declaration/definition of a tag.
12134 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12135 /// trailing-type-specifier) other than one in an alias-declaration.
12137 /// \param SkipBody If non-null, will be set to indicate if the caller should
12138 /// skip the definition of this tag and treat it as if it were a declaration.
12139 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12140 SourceLocation KWLoc, CXXScopeSpec &SS,
12141 IdentifierInfo *Name, SourceLocation NameLoc,
12142 AttributeList *Attr, AccessSpecifier AS,
12143 SourceLocation ModulePrivateLoc,
12144 MultiTemplateParamsArg TemplateParameterLists,
12145 bool &OwnedDecl, bool &IsDependent,
12146 SourceLocation ScopedEnumKWLoc,
12147 bool ScopedEnumUsesClassTag,
12148 TypeResult UnderlyingType,
12149 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12150 // If this is not a definition, it must have a name.
12151 IdentifierInfo *OrigName = Name;
12152 assert((Name != nullptr || TUK == TUK_Definition) &&
12153 "Nameless record must be a definition!");
12154 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12157 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12158 bool ScopedEnum = ScopedEnumKWLoc.isValid();
12160 // FIXME: Check explicit specializations more carefully.
12161 bool isExplicitSpecialization = false;
12162 bool Invalid = false;
12164 // We only need to do this matching if we have template parameters
12165 // or a scope specifier, which also conveniently avoids this work
12166 // for non-C++ cases.
12167 if (TemplateParameterLists.size() > 0 ||
12168 (SS.isNotEmpty() && TUK != TUK_Reference)) {
12169 if (TemplateParameterList *TemplateParams =
12170 MatchTemplateParametersToScopeSpecifier(
12171 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12172 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12173 if (Kind == TTK_Enum) {
12174 Diag(KWLoc, diag::err_enum_template);
12178 if (TemplateParams->size() > 0) {
12179 // This is a declaration or definition of a class template (which may
12180 // be a member of another template).
12186 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12187 SS, Name, NameLoc, Attr,
12188 TemplateParams, AS,
12190 /*FriendLoc*/SourceLocation(),
12191 TemplateParameterLists.size()-1,
12192 TemplateParameterLists.data(),
12194 return Result.get();
12196 // The "template<>" header is extraneous.
12197 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12198 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12199 isExplicitSpecialization = true;
12204 // Figure out the underlying type if this a enum declaration. We need to do
12205 // this early, because it's needed to detect if this is an incompatible
12207 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12208 bool EnumUnderlyingIsImplicit = false;
12210 if (Kind == TTK_Enum) {
12211 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12212 // No underlying type explicitly specified, or we failed to parse the
12213 // type, default to int.
12214 EnumUnderlying = Context.IntTy.getTypePtr();
12215 else if (UnderlyingType.get()) {
12216 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12217 // integral type; any cv-qualification is ignored.
12218 TypeSourceInfo *TI = nullptr;
12219 GetTypeFromParser(UnderlyingType.get(), &TI);
12220 EnumUnderlying = TI;
12222 if (CheckEnumUnderlyingType(TI))
12223 // Recover by falling back to int.
12224 EnumUnderlying = Context.IntTy.getTypePtr();
12226 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12227 UPPC_FixedUnderlyingType))
12228 EnumUnderlying = Context.IntTy.getTypePtr();
12230 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12231 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12232 // Microsoft enums are always of int type.
12233 EnumUnderlying = Context.IntTy.getTypePtr();
12234 EnumUnderlyingIsImplicit = true;
12239 DeclContext *SearchDC = CurContext;
12240 DeclContext *DC = CurContext;
12241 bool isStdBadAlloc = false;
12243 RedeclarationKind Redecl = ForRedeclaration;
12244 if (TUK == TUK_Friend || TUK == TUK_Reference)
12245 Redecl = NotForRedeclaration;
12247 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12248 if (Name && SS.isNotEmpty()) {
12249 // We have a nested-name tag ('struct foo::bar').
12251 // Check for invalid 'foo::'.
12252 if (SS.isInvalid()) {
12254 goto CreateNewDecl;
12257 // If this is a friend or a reference to a class in a dependent
12258 // context, don't try to make a decl for it.
12259 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12260 DC = computeDeclContext(SS, false);
12262 IsDependent = true;
12266 DC = computeDeclContext(SS, true);
12268 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12274 if (RequireCompleteDeclContext(SS, DC))
12278 // Look-up name inside 'foo::'.
12279 LookupQualifiedName(Previous, DC);
12281 if (Previous.isAmbiguous())
12284 if (Previous.empty()) {
12285 // Name lookup did not find anything. However, if the
12286 // nested-name-specifier refers to the current instantiation,
12287 // and that current instantiation has any dependent base
12288 // classes, we might find something at instantiation time: treat
12289 // this as a dependent elaborated-type-specifier.
12290 // But this only makes any sense for reference-like lookups.
12291 if (Previous.wasNotFoundInCurrentInstantiation() &&
12292 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12293 IsDependent = true;
12297 // A tag 'foo::bar' must already exist.
12298 Diag(NameLoc, diag::err_not_tag_in_scope)
12299 << Kind << Name << DC << SS.getRange();
12302 goto CreateNewDecl;
12305 // C++14 [class.mem]p14:
12306 // If T is the name of a class, then each of the following shall have a
12307 // name different from T:
12308 // -- every member of class T that is itself a type
12309 if (TUK != TUK_Reference && TUK != TUK_Friend &&
12310 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12313 // If this is a named struct, check to see if there was a previous forward
12314 // declaration or definition.
12315 // FIXME: We're looking into outer scopes here, even when we
12316 // shouldn't be. Doing so can result in ambiguities that we
12317 // shouldn't be diagnosing.
12318 LookupName(Previous, S);
12320 // When declaring or defining a tag, ignore ambiguities introduced
12321 // by types using'ed into this scope.
12322 if (Previous.isAmbiguous() &&
12323 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12324 LookupResult::Filter F = Previous.makeFilter();
12325 while (F.hasNext()) {
12326 NamedDecl *ND = F.next();
12327 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12333 // C++11 [namespace.memdef]p3:
12334 // If the name in a friend declaration is neither qualified nor
12335 // a template-id and the declaration is a function or an
12336 // elaborated-type-specifier, the lookup to determine whether
12337 // the entity has been previously declared shall not consider
12338 // any scopes outside the innermost enclosing namespace.
12340 // MSVC doesn't implement the above rule for types, so a friend tag
12341 // declaration may be a redeclaration of a type declared in an enclosing
12342 // scope. They do implement this rule for friend functions.
12344 // Does it matter that this should be by scope instead of by
12345 // semantic context?
12346 if (!Previous.empty() && TUK == TUK_Friend) {
12347 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12348 LookupResult::Filter F = Previous.makeFilter();
12349 bool FriendSawTagOutsideEnclosingNamespace = false;
12350 while (F.hasNext()) {
12351 NamedDecl *ND = F.next();
12352 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12353 if (DC->isFileContext() &&
12354 !EnclosingNS->Encloses(ND->getDeclContext())) {
12355 if (getLangOpts().MSVCCompat)
12356 FriendSawTagOutsideEnclosingNamespace = true;
12363 // Diagnose this MSVC extension in the easy case where lookup would have
12364 // unambiguously found something outside the enclosing namespace.
12365 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12366 NamedDecl *ND = Previous.getFoundDecl();
12367 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12368 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12372 // Note: there used to be some attempt at recovery here.
12373 if (Previous.isAmbiguous())
12376 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12377 // FIXME: This makes sure that we ignore the contexts associated
12378 // with C structs, unions, and enums when looking for a matching
12379 // tag declaration or definition. See the similar lookup tweak
12380 // in Sema::LookupName; is there a better way to deal with this?
12381 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12382 SearchDC = SearchDC->getParent();
12386 if (Previous.isSingleResult() &&
12387 Previous.getFoundDecl()->isTemplateParameter()) {
12388 // Maybe we will complain about the shadowed template parameter.
12389 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12390 // Just pretend that we didn't see the previous declaration.
12394 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12395 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12396 // This is a declaration of or a reference to "std::bad_alloc".
12397 isStdBadAlloc = true;
12399 if (Previous.empty() && StdBadAlloc) {
12400 // std::bad_alloc has been implicitly declared (but made invisible to
12401 // name lookup). Fill in this implicit declaration as the previous
12402 // declaration, so that the declarations get chained appropriately.
12403 Previous.addDecl(getStdBadAlloc());
12407 // If we didn't find a previous declaration, and this is a reference
12408 // (or friend reference), move to the correct scope. In C++, we
12409 // also need to do a redeclaration lookup there, just in case
12410 // there's a shadow friend decl.
12411 if (Name && Previous.empty() &&
12412 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12413 if (Invalid) goto CreateNewDecl;
12414 assert(SS.isEmpty());
12416 if (TUK == TUK_Reference) {
12417 // C++ [basic.scope.pdecl]p5:
12418 // -- for an elaborated-type-specifier of the form
12420 // class-key identifier
12422 // if the elaborated-type-specifier is used in the
12423 // decl-specifier-seq or parameter-declaration-clause of a
12424 // function defined in namespace scope, the identifier is
12425 // declared as a class-name in the namespace that contains
12426 // the declaration; otherwise, except as a friend
12427 // declaration, the identifier is declared in the smallest
12428 // non-class, non-function-prototype scope that contains the
12431 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12432 // C structs and unions.
12434 // It is an error in C++ to declare (rather than define) an enum
12435 // type, including via an elaborated type specifier. We'll
12436 // diagnose that later; for now, declare the enum in the same
12437 // scope as we would have picked for any other tag type.
12439 // GNU C also supports this behavior as part of its incomplete
12440 // enum types extension, while GNU C++ does not.
12442 // Find the context where we'll be declaring the tag.
12443 // FIXME: We would like to maintain the current DeclContext as the
12444 // lexical context,
12445 SearchDC = getTagInjectionContext(SearchDC);
12447 // Find the scope where we'll be declaring the tag.
12448 S = getTagInjectionScope(S, getLangOpts());
12450 assert(TUK == TUK_Friend);
12451 // C++ [namespace.memdef]p3:
12452 // If a friend declaration in a non-local class first declares a
12453 // class or function, the friend class or function is a member of
12454 // the innermost enclosing namespace.
12455 SearchDC = SearchDC->getEnclosingNamespaceContext();
12458 // In C++, we need to do a redeclaration lookup to properly
12459 // diagnose some problems.
12460 // FIXME: redeclaration lookup is also used (with and without C++) to find a
12461 // hidden declaration so that we don't get ambiguity errors when using a
12462 // type declared by an elaborated-type-specifier. In C that is not correct
12463 // and we should instead merge compatible types found by lookup.
12464 if (getLangOpts().CPlusPlus) {
12465 Previous.setRedeclarationKind(ForRedeclaration);
12466 LookupQualifiedName(Previous, SearchDC);
12468 Previous.setRedeclarationKind(ForRedeclaration);
12469 LookupName(Previous, S);
12473 // If we have a known previous declaration to use, then use it.
12474 if (Previous.empty() && SkipBody && SkipBody->Previous)
12475 Previous.addDecl(SkipBody->Previous);
12477 if (!Previous.empty()) {
12478 NamedDecl *PrevDecl = Previous.getFoundDecl();
12479 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12481 // It's okay to have a tag decl in the same scope as a typedef
12482 // which hides a tag decl in the same scope. Finding this
12483 // insanity with a redeclaration lookup can only actually happen
12486 // This is also okay for elaborated-type-specifiers, which is
12487 // technically forbidden by the current standard but which is
12488 // okay according to the likely resolution of an open issue;
12489 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12490 if (getLangOpts().CPlusPlus) {
12491 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12492 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12493 TagDecl *Tag = TT->getDecl();
12494 if (Tag->getDeclName() == Name &&
12495 Tag->getDeclContext()->getRedeclContext()
12496 ->Equals(TD->getDeclContext()->getRedeclContext())) {
12499 Previous.addDecl(Tag);
12500 Previous.resolveKind();
12506 // If this is a redeclaration of a using shadow declaration, it must
12507 // declare a tag in the same context. In MSVC mode, we allow a
12508 // redefinition if either context is within the other.
12509 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12510 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12511 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12512 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12513 !(OldTag && isAcceptableTagRedeclContext(
12514 *this, OldTag->getDeclContext(), SearchDC))) {
12515 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12516 Diag(Shadow->getTargetDecl()->getLocation(),
12517 diag::note_using_decl_target);
12518 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12520 // Recover by ignoring the old declaration.
12522 goto CreateNewDecl;
12526 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12527 // If this is a use of a previous tag, or if the tag is already declared
12528 // in the same scope (so that the definition/declaration completes or
12529 // rementions the tag), reuse the decl.
12530 if (TUK == TUK_Reference || TUK == TUK_Friend ||
12531 isDeclInScope(DirectPrevDecl, SearchDC, S,
12532 SS.isNotEmpty() || isExplicitSpecialization)) {
12533 // Make sure that this wasn't declared as an enum and now used as a
12534 // struct or something similar.
12535 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12536 TUK == TUK_Definition, KWLoc,
12538 bool SafeToContinue
12539 = (PrevTagDecl->getTagKind() != TTK_Enum &&
12541 if (SafeToContinue)
12542 Diag(KWLoc, diag::err_use_with_wrong_tag)
12544 << FixItHint::CreateReplacement(SourceRange(KWLoc),
12545 PrevTagDecl->getKindName());
12547 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12548 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12550 if (SafeToContinue)
12551 Kind = PrevTagDecl->getTagKind();
12553 // Recover by making this an anonymous redefinition.
12560 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12561 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12563 // If this is an elaborated-type-specifier for a scoped enumeration,
12564 // the 'class' keyword is not necessary and not permitted.
12565 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12567 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12568 << PrevEnum->isScoped()
12569 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12570 return PrevTagDecl;
12573 QualType EnumUnderlyingTy;
12574 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12575 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12576 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12577 EnumUnderlyingTy = QualType(T, 0);
12579 // All conflicts with previous declarations are recovered by
12580 // returning the previous declaration, unless this is a definition,
12581 // in which case we want the caller to bail out.
12582 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12583 ScopedEnum, EnumUnderlyingTy,
12584 EnumUnderlyingIsImplicit, PrevEnum))
12585 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12588 // C++11 [class.mem]p1:
12589 // A member shall not be declared twice in the member-specification,
12590 // except that a nested class or member class template can be declared
12591 // and then later defined.
12592 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12593 S->isDeclScope(PrevDecl)) {
12594 Diag(NameLoc, diag::ext_member_redeclared);
12595 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12599 // If this is a use, just return the declaration we found, unless
12600 // we have attributes.
12601 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12603 // FIXME: Diagnose these attributes. For now, we create a new
12604 // declaration to hold them.
12605 } else if (TUK == TUK_Reference &&
12606 (PrevTagDecl->getFriendObjectKind() ==
12607 Decl::FOK_Undeclared ||
12608 PP.getModuleContainingLocation(
12609 PrevDecl->getLocation()) !=
12610 PP.getModuleContainingLocation(KWLoc)) &&
12612 // This declaration is a reference to an existing entity, but
12613 // has different visibility from that entity: it either makes
12614 // a friend visible or it makes a type visible in a new module.
12615 // In either case, create a new declaration. We only do this if
12616 // the declaration would have meant the same thing if no prior
12617 // declaration were found, that is, if it was found in the same
12618 // scope where we would have injected a declaration.
12619 if (!getTagInjectionContext(CurContext)->getRedeclContext()
12620 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12621 return PrevTagDecl;
12622 // This is in the injected scope, create a new declaration in
12624 S = getTagInjectionScope(S, getLangOpts());
12626 return PrevTagDecl;
12630 // Diagnose attempts to redefine a tag.
12631 if (TUK == TUK_Definition) {
12632 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12633 // If we're defining a specialization and the previous definition
12634 // is from an implicit instantiation, don't emit an error
12635 // here; we'll catch this in the general case below.
12636 bool IsExplicitSpecializationAfterInstantiation = false;
12637 if (isExplicitSpecialization) {
12638 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12639 IsExplicitSpecializationAfterInstantiation =
12640 RD->getTemplateSpecializationKind() !=
12641 TSK_ExplicitSpecialization;
12642 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12643 IsExplicitSpecializationAfterInstantiation =
12644 ED->getTemplateSpecializationKind() !=
12645 TSK_ExplicitSpecialization;
12648 NamedDecl *Hidden = nullptr;
12649 if (SkipBody && getLangOpts().CPlusPlus &&
12650 !hasVisibleDefinition(Def, &Hidden)) {
12651 // There is a definition of this tag, but it is not visible. We
12652 // explicitly make use of C++'s one definition rule here, and
12653 // assume that this definition is identical to the hidden one
12654 // we already have. Make the existing definition visible and
12655 // use it in place of this one.
12656 SkipBody->ShouldSkip = true;
12657 makeMergedDefinitionVisible(Hidden, KWLoc);
12659 } else if (!IsExplicitSpecializationAfterInstantiation) {
12660 // A redeclaration in function prototype scope in C isn't
12661 // visible elsewhere, so merely issue a warning.
12662 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12663 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12665 Diag(NameLoc, diag::err_redefinition) << Name;
12666 Diag(Def->getLocation(), diag::note_previous_definition);
12667 // If this is a redefinition, recover by making this
12668 // struct be anonymous, which will make any later
12669 // references get the previous definition.
12675 // If the type is currently being defined, complain
12676 // about a nested redefinition.
12677 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12678 if (TD->isBeingDefined()) {
12679 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12680 Diag(PrevTagDecl->getLocation(),
12681 diag::note_previous_definition);
12688 // Okay, this is definition of a previously declared or referenced
12689 // tag. We're going to create a new Decl for it.
12692 // Okay, we're going to make a redeclaration. If this is some kind
12693 // of reference, make sure we build the redeclaration in the same DC
12694 // as the original, and ignore the current access specifier.
12695 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12696 SearchDC = PrevTagDecl->getDeclContext();
12700 // If we get here we have (another) forward declaration or we
12701 // have a definition. Just create a new decl.
12704 // If we get here, this is a definition of a new tag type in a nested
12705 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12706 // new decl/type. We set PrevDecl to NULL so that the entities
12707 // have distinct types.
12710 // If we get here, we're going to create a new Decl. If PrevDecl
12711 // is non-NULL, it's a definition of the tag declared by
12712 // PrevDecl. If it's NULL, we have a new definition.
12714 // Otherwise, PrevDecl is not a tag, but was found with tag
12715 // lookup. This is only actually possible in C++, where a few
12716 // things like templates still live in the tag namespace.
12718 // Use a better diagnostic if an elaborated-type-specifier
12719 // found the wrong kind of type on the first
12720 // (non-redeclaration) lookup.
12721 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12722 !Previous.isForRedeclaration()) {
12724 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12725 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12726 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12727 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12728 Diag(PrevDecl->getLocation(), diag::note_declared_at);
12731 // Otherwise, only diagnose if the declaration is in scope.
12732 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12733 SS.isNotEmpty() || isExplicitSpecialization)) {
12736 // Diagnose implicit declarations introduced by elaborated types.
12737 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12739 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12740 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12741 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12742 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12743 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12746 // Otherwise it's a declaration. Call out a particularly common
12748 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12750 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12751 Diag(NameLoc, diag::err_tag_definition_of_typedef)
12752 << Name << Kind << TND->getUnderlyingType();
12753 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12756 // Otherwise, diagnose.
12758 // The tag name clashes with something else in the target scope,
12759 // issue an error and recover by making this tag be anonymous.
12760 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12761 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12766 // The existing declaration isn't relevant to us; we're in a
12767 // new scope, so clear out the previous declaration.
12774 TagDecl *PrevDecl = nullptr;
12775 if (Previous.isSingleResult())
12776 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12778 // If there is an identifier, use the location of the identifier as the
12779 // location of the decl, otherwise use the location of the struct/union
12781 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12783 // Otherwise, create a new declaration. If there is a previous
12784 // declaration of the same entity, the two will be linked via
12788 bool IsForwardReference = false;
12789 if (Kind == TTK_Enum) {
12790 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12791 // enum X { A, B, C } D; D should chain to X.
12792 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12793 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12794 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12795 // If this is an undefined enum, warn.
12796 if (TUK != TUK_Definition && !Invalid) {
12798 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12799 cast<EnumDecl>(New)->isFixed()) {
12800 // C++0x: 7.2p2: opaque-enum-declaration.
12801 // Conflicts are diagnosed above. Do nothing.
12803 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12804 Diag(Loc, diag::ext_forward_ref_enum_def)
12806 Diag(Def->getLocation(), diag::note_previous_definition);
12808 unsigned DiagID = diag::ext_forward_ref_enum;
12809 if (getLangOpts().MSVCCompat)
12810 DiagID = diag::ext_ms_forward_ref_enum;
12811 else if (getLangOpts().CPlusPlus)
12812 DiagID = diag::err_forward_ref_enum;
12815 // If this is a forward-declared reference to an enumeration, make a
12816 // note of it; we won't actually be introducing the declaration into
12817 // the declaration context.
12818 if (TUK == TUK_Reference)
12819 IsForwardReference = true;
12823 if (EnumUnderlying) {
12824 EnumDecl *ED = cast<EnumDecl>(New);
12825 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12826 ED->setIntegerTypeSourceInfo(TI);
12828 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12829 ED->setPromotionType(ED->getIntegerType());
12832 // struct/union/class
12834 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12835 // struct X { int A; } D; D should chain to X.
12836 if (getLangOpts().CPlusPlus) {
12837 // FIXME: Look for a way to use RecordDecl for simple structs.
12838 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12839 cast_or_null<CXXRecordDecl>(PrevDecl));
12841 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12842 StdBadAlloc = cast<CXXRecordDecl>(New);
12844 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12845 cast_or_null<RecordDecl>(PrevDecl));
12848 // C++11 [dcl.type]p3:
12849 // A type-specifier-seq shall not define a class or enumeration [...].
12850 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12851 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12852 << Context.getTagDeclType(New);
12856 // Maybe add qualifier info.
12857 if (SS.isNotEmpty()) {
12859 // If this is either a declaration or a definition, check the
12860 // nested-name-specifier against the current context. We don't do this
12861 // for explicit specializations, because they have similar checking
12862 // (with more specific diagnostics) in the call to
12863 // CheckMemberSpecialization, below.
12864 if (!isExplicitSpecialization &&
12865 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12866 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12869 New->setQualifierInfo(SS.getWithLocInContext(Context));
12870 if (TemplateParameterLists.size() > 0) {
12871 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12878 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12879 // Add alignment attributes if necessary; these attributes are checked when
12880 // the ASTContext lays out the structure.
12882 // It is important for implementing the correct semantics that this
12883 // happen here (in act on tag decl). The #pragma pack stack is
12884 // maintained as a result of parser callbacks which can occur at
12885 // many points during the parsing of a struct declaration (because
12886 // the #pragma tokens are effectively skipped over during the
12887 // parsing of the struct).
12888 if (TUK == TUK_Definition) {
12889 AddAlignmentAttributesForRecord(RD);
12890 AddMsStructLayoutForRecord(RD);
12894 if (ModulePrivateLoc.isValid()) {
12895 if (isExplicitSpecialization)
12896 Diag(New->getLocation(), diag::err_module_private_specialization)
12898 << FixItHint::CreateRemoval(ModulePrivateLoc);
12899 // __module_private__ does not apply to local classes. However, we only
12900 // diagnose this as an error when the declaration specifiers are
12901 // freestanding. Here, we just ignore the __module_private__.
12902 else if (!SearchDC->isFunctionOrMethod())
12903 New->setModulePrivate();
12906 // If this is a specialization of a member class (of a class template),
12907 // check the specialization.
12908 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12911 // If we're declaring or defining a tag in function prototype scope in C,
12912 // note that this type can only be used within the function and add it to
12913 // the list of decls to inject into the function definition scope.
12914 if ((Name || Kind == TTK_Enum) &&
12915 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12916 if (getLangOpts().CPlusPlus) {
12917 // C++ [dcl.fct]p6:
12918 // Types shall not be defined in return or parameter types.
12919 if (TUK == TUK_Definition && !IsTypeSpecifier) {
12920 Diag(Loc, diag::err_type_defined_in_param_type)
12924 } else if (!PrevDecl) {
12925 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12927 DeclsInPrototypeScope.push_back(New);
12931 New->setInvalidDecl();
12934 ProcessDeclAttributeList(S, New, Attr);
12936 // Set the lexical context. If the tag has a C++ scope specifier, the
12937 // lexical context will be different from the semantic context.
12938 New->setLexicalDeclContext(CurContext);
12940 // Mark this as a friend decl if applicable.
12941 // In Microsoft mode, a friend declaration also acts as a forward
12942 // declaration so we always pass true to setObjectOfFriendDecl to make
12943 // the tag name visible.
12944 if (TUK == TUK_Friend)
12945 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12947 // Set the access specifier.
12948 if (!Invalid && SearchDC->isRecord())
12949 SetMemberAccessSpecifier(New, PrevDecl, AS);
12951 if (TUK == TUK_Definition)
12952 New->startDefinition();
12954 // If this has an identifier, add it to the scope stack.
12955 if (TUK == TUK_Friend) {
12956 // We might be replacing an existing declaration in the lookup tables;
12957 // if so, borrow its access specifier.
12959 New->setAccess(PrevDecl->getAccess());
12961 DeclContext *DC = New->getDeclContext()->getRedeclContext();
12962 DC->makeDeclVisibleInContext(New);
12963 if (Name) // can be null along some error paths
12964 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12965 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12967 S = getNonFieldDeclScope(S);
12968 PushOnScopeChains(New, S, !IsForwardReference);
12969 if (IsForwardReference)
12970 SearchDC->makeDeclVisibleInContext(New);
12972 CurContext->addDecl(New);
12975 // If this is the C FILE type, notify the AST context.
12976 if (IdentifierInfo *II = New->getIdentifier())
12977 if (!New->isInvalidDecl() &&
12978 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12980 Context.setFILEDecl(New);
12983 mergeDeclAttributes(New, PrevDecl);
12985 // If there's a #pragma GCC visibility in scope, set the visibility of this
12987 AddPushedVisibilityAttribute(New);
12990 // In C++, don't return an invalid declaration. We can't recover well from
12991 // the cases where we make the type anonymous.
12992 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12995 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12996 AdjustDeclIfTemplate(TagD);
12997 TagDecl *Tag = cast<TagDecl>(TagD);
12999 // Enter the tag context.
13000 PushDeclContext(S, Tag);
13002 ActOnDocumentableDecl(TagD);
13004 // If there's a #pragma GCC visibility in scope, set the visibility of this
13006 AddPushedVisibilityAttribute(Tag);
13009 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13010 assert(isa<ObjCContainerDecl>(IDecl) &&
13011 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13012 DeclContext *OCD = cast<DeclContext>(IDecl);
13013 assert(getContainingDC(OCD) == CurContext &&
13014 "The next DeclContext should be lexically contained in the current one.");
13019 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13020 SourceLocation FinalLoc,
13021 bool IsFinalSpelledSealed,
13022 SourceLocation LBraceLoc) {
13023 AdjustDeclIfTemplate(TagD);
13024 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13026 FieldCollector->StartClass();
13028 if (!Record->getIdentifier())
13031 if (FinalLoc.isValid())
13032 Record->addAttr(new (Context)
13033 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13036 // [...] The class-name is also inserted into the scope of the
13037 // class itself; this is known as the injected-class-name. For
13038 // purposes of access checking, the injected-class-name is treated
13039 // as if it were a public member name.
13040 CXXRecordDecl *InjectedClassName
13041 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13042 Record->getLocStart(), Record->getLocation(),
13043 Record->getIdentifier(),
13044 /*PrevDecl=*/nullptr,
13045 /*DelayTypeCreation=*/true);
13046 Context.getTypeDeclType(InjectedClassName, Record);
13047 InjectedClassName->setImplicit();
13048 InjectedClassName->setAccess(AS_public);
13049 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13050 InjectedClassName->setDescribedClassTemplate(Template);
13051 PushOnScopeChains(InjectedClassName, S);
13052 assert(InjectedClassName->isInjectedClassName() &&
13053 "Broken injected-class-name");
13056 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13057 SourceLocation RBraceLoc) {
13058 AdjustDeclIfTemplate(TagD);
13059 TagDecl *Tag = cast<TagDecl>(TagD);
13060 Tag->setRBraceLoc(RBraceLoc);
13062 // Make sure we "complete" the definition even it is invalid.
13063 if (Tag->isBeingDefined()) {
13064 assert(Tag->isInvalidDecl() && "We should already have completed it");
13065 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13066 RD->completeDefinition();
13069 if (isa<CXXRecordDecl>(Tag))
13070 FieldCollector->FinishClass();
13072 // Exit this scope of this tag's definition.
13075 if (getCurLexicalContext()->isObjCContainer() &&
13076 Tag->getDeclContext()->isFileContext())
13077 Tag->setTopLevelDeclInObjCContainer();
13079 // Notify the consumer that we've defined a tag.
13080 if (!Tag->isInvalidDecl())
13081 Consumer.HandleTagDeclDefinition(Tag);
13084 void Sema::ActOnObjCContainerFinishDefinition() {
13085 // Exit this scope of this interface definition.
13089 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13090 assert(DC == CurContext && "Mismatch of container contexts");
13091 OriginalLexicalContext = DC;
13092 ActOnObjCContainerFinishDefinition();
13095 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13096 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13097 OriginalLexicalContext = nullptr;
13100 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13101 AdjustDeclIfTemplate(TagD);
13102 TagDecl *Tag = cast<TagDecl>(TagD);
13103 Tag->setInvalidDecl();
13105 // Make sure we "complete" the definition even it is invalid.
13106 if (Tag->isBeingDefined()) {
13107 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13108 RD->completeDefinition();
13111 // We're undoing ActOnTagStartDefinition here, not
13112 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13113 // the FieldCollector.
13118 // Note that FieldName may be null for anonymous bitfields.
13119 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13120 IdentifierInfo *FieldName,
13121 QualType FieldTy, bool IsMsStruct,
13122 Expr *BitWidth, bool *ZeroWidth) {
13123 // Default to true; that shouldn't confuse checks for emptiness
13127 // C99 6.7.2.1p4 - verify the field type.
13128 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13129 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13130 // Handle incomplete types with specific error.
13131 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13132 return ExprError();
13134 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13135 << FieldName << FieldTy << BitWidth->getSourceRange();
13136 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13137 << FieldTy << BitWidth->getSourceRange();
13138 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13139 UPPC_BitFieldWidth))
13140 return ExprError();
13142 // If the bit-width is type- or value-dependent, don't try to check
13144 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13147 llvm::APSInt Value;
13148 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13149 if (ICE.isInvalid())
13151 BitWidth = ICE.get();
13153 if (Value != 0 && ZeroWidth)
13154 *ZeroWidth = false;
13156 // Zero-width bitfield is ok for anonymous field.
13157 if (Value == 0 && FieldName)
13158 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13160 if (Value.isSigned() && Value.isNegative()) {
13162 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13163 << FieldName << Value.toString(10);
13164 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13165 << Value.toString(10);
13168 if (!FieldTy->isDependentType()) {
13169 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13170 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13171 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13173 // Over-wide bitfields are an error in C or when using the MSVC bitfield
13175 bool CStdConstraintViolation =
13176 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13177 bool MSBitfieldViolation =
13178 Value.ugt(TypeStorageSize) &&
13179 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13180 if (CStdConstraintViolation || MSBitfieldViolation) {
13181 unsigned DiagWidth =
13182 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13184 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13185 << FieldName << (unsigned)Value.getZExtValue()
13186 << !CStdConstraintViolation << DiagWidth;
13188 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13189 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13193 // Warn on types where the user might conceivably expect to get all
13194 // specified bits as value bits: that's all integral types other than
13196 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13198 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13199 << FieldName << (unsigned)Value.getZExtValue()
13200 << (unsigned)TypeWidth;
13202 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13203 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13210 /// ActOnField - Each field of a C struct/union is passed into this in order
13211 /// to create a FieldDecl object for it.
13212 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13213 Declarator &D, Expr *BitfieldWidth) {
13214 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13215 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13216 /*InitStyle=*/ICIS_NoInit, AS_public);
13220 /// HandleField - Analyze a field of a C struct or a C++ data member.
13222 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13223 SourceLocation DeclStart,
13224 Declarator &D, Expr *BitWidth,
13225 InClassInitStyle InitStyle,
13226 AccessSpecifier AS) {
13227 IdentifierInfo *II = D.getIdentifier();
13228 SourceLocation Loc = DeclStart;
13229 if (II) Loc = D.getIdentifierLoc();
13231 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13232 QualType T = TInfo->getType();
13233 if (getLangOpts().CPlusPlus) {
13234 CheckExtraCXXDefaultArguments(D);
13236 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13237 UPPC_DataMemberType)) {
13238 D.setInvalidType();
13240 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13244 // TR 18037 does not allow fields to be declared with address spaces.
13245 if (T.getQualifiers().hasAddressSpace()) {
13246 Diag(Loc, diag::err_field_with_address_space);
13247 D.setInvalidType();
13250 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13251 // used as structure or union field: image, sampler, event or block types.
13252 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13253 T->isSamplerT() || T->isBlockPointerType())) {
13254 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13255 D.setInvalidType();
13258 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13260 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13261 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13262 diag::err_invalid_thread)
13263 << DeclSpec::getSpecifierName(TSCS);
13265 // Check to see if this name was declared as a member previously
13266 NamedDecl *PrevDecl = nullptr;
13267 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13268 LookupName(Previous, S);
13269 switch (Previous.getResultKind()) {
13270 case LookupResult::Found:
13271 case LookupResult::FoundUnresolvedValue:
13272 PrevDecl = Previous.getAsSingle<NamedDecl>();
13275 case LookupResult::FoundOverloaded:
13276 PrevDecl = Previous.getRepresentativeDecl();
13279 case LookupResult::NotFound:
13280 case LookupResult::NotFoundInCurrentInstantiation:
13281 case LookupResult::Ambiguous:
13284 Previous.suppressDiagnostics();
13286 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13287 // Maybe we will complain about the shadowed template parameter.
13288 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13289 // Just pretend that we didn't see the previous declaration.
13290 PrevDecl = nullptr;
13293 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13294 PrevDecl = nullptr;
13297 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13298 SourceLocation TSSL = D.getLocStart();
13300 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13301 TSSL, AS, PrevDecl, &D);
13303 if (NewFD->isInvalidDecl())
13304 Record->setInvalidDecl();
13306 if (D.getDeclSpec().isModulePrivateSpecified())
13307 NewFD->setModulePrivate();
13309 if (NewFD->isInvalidDecl() && PrevDecl) {
13310 // Don't introduce NewFD into scope; there's already something
13311 // with the same name in the same scope.
13313 PushOnScopeChains(NewFD, S);
13315 Record->addDecl(NewFD);
13320 /// \brief Build a new FieldDecl and check its well-formedness.
13322 /// This routine builds a new FieldDecl given the fields name, type,
13323 /// record, etc. \p PrevDecl should refer to any previous declaration
13324 /// with the same name and in the same scope as the field to be
13327 /// \returns a new FieldDecl.
13329 /// \todo The Declarator argument is a hack. It will be removed once
13330 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13331 TypeSourceInfo *TInfo,
13332 RecordDecl *Record, SourceLocation Loc,
13333 bool Mutable, Expr *BitWidth,
13334 InClassInitStyle InitStyle,
13335 SourceLocation TSSL,
13336 AccessSpecifier AS, NamedDecl *PrevDecl,
13338 IdentifierInfo *II = Name.getAsIdentifierInfo();
13339 bool InvalidDecl = false;
13340 if (D) InvalidDecl = D->isInvalidType();
13342 // If we receive a broken type, recover by assuming 'int' and
13343 // marking this declaration as invalid.
13345 InvalidDecl = true;
13349 QualType EltTy = Context.getBaseElementType(T);
13350 if (!EltTy->isDependentType()) {
13351 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13352 // Fields of incomplete type force their record to be invalid.
13353 Record->setInvalidDecl();
13354 InvalidDecl = true;
13357 EltTy->isIncompleteType(&Def);
13358 if (Def && Def->isInvalidDecl()) {
13359 Record->setInvalidDecl();
13360 InvalidDecl = true;
13365 // OpenCL v1.2 s6.9.c: bitfields are not supported.
13366 if (BitWidth && getLangOpts().OpenCL) {
13367 Diag(Loc, diag::err_opencl_bitfields);
13368 InvalidDecl = true;
13371 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13372 // than a variably modified type.
13373 if (!InvalidDecl && T->isVariablyModifiedType()) {
13374 bool SizeIsNegative;
13375 llvm::APSInt Oversized;
13377 TypeSourceInfo *FixedTInfo =
13378 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13382 Diag(Loc, diag::warn_illegal_constant_array_size);
13383 TInfo = FixedTInfo;
13384 T = FixedTInfo->getType();
13386 if (SizeIsNegative)
13387 Diag(Loc, diag::err_typecheck_negative_array_size);
13388 else if (Oversized.getBoolValue())
13389 Diag(Loc, diag::err_array_too_large)
13390 << Oversized.toString(10);
13392 Diag(Loc, diag::err_typecheck_field_variable_size);
13393 InvalidDecl = true;
13397 // Fields can not have abstract class types
13398 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13399 diag::err_abstract_type_in_decl,
13400 AbstractFieldType))
13401 InvalidDecl = true;
13403 bool ZeroWidth = false;
13405 BitWidth = nullptr;
13406 // If this is declared as a bit-field, check the bit-field.
13408 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13411 InvalidDecl = true;
13412 BitWidth = nullptr;
13417 // Check that 'mutable' is consistent with the type of the declaration.
13418 if (!InvalidDecl && Mutable) {
13419 unsigned DiagID = 0;
13420 if (T->isReferenceType())
13421 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13422 : diag::err_mutable_reference;
13423 else if (T.isConstQualified())
13424 DiagID = diag::err_mutable_const;
13427 SourceLocation ErrLoc = Loc;
13428 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13429 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13430 Diag(ErrLoc, DiagID);
13431 if (DiagID != diag::ext_mutable_reference) {
13433 InvalidDecl = true;
13438 // C++11 [class.union]p8 (DR1460):
13439 // At most one variant member of a union may have a
13440 // brace-or-equal-initializer.
13441 if (InitStyle != ICIS_NoInit)
13442 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13444 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13445 BitWidth, Mutable, InitStyle);
13447 NewFD->setInvalidDecl();
13449 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13450 Diag(Loc, diag::err_duplicate_member) << II;
13451 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13452 NewFD->setInvalidDecl();
13455 if (!InvalidDecl && getLangOpts().CPlusPlus) {
13456 if (Record->isUnion()) {
13457 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13458 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13459 if (RDecl->getDefinition()) {
13460 // C++ [class.union]p1: An object of a class with a non-trivial
13461 // constructor, a non-trivial copy constructor, a non-trivial
13462 // destructor, or a non-trivial copy assignment operator
13463 // cannot be a member of a union, nor can an array of such
13465 if (CheckNontrivialField(NewFD))
13466 NewFD->setInvalidDecl();
13470 // C++ [class.union]p1: If a union contains a member of reference type,
13471 // the program is ill-formed, except when compiling with MSVC extensions
13473 if (EltTy->isReferenceType()) {
13474 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13475 diag::ext_union_member_of_reference_type :
13476 diag::err_union_member_of_reference_type)
13477 << NewFD->getDeclName() << EltTy;
13478 if (!getLangOpts().MicrosoftExt)
13479 NewFD->setInvalidDecl();
13484 // FIXME: We need to pass in the attributes given an AST
13485 // representation, not a parser representation.
13487 // FIXME: The current scope is almost... but not entirely... correct here.
13488 ProcessDeclAttributes(getCurScope(), NewFD, *D);
13490 if (NewFD->hasAttrs())
13491 CheckAlignasUnderalignment(NewFD);
13494 // In auto-retain/release, infer strong retension for fields of
13495 // retainable type.
13496 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13497 NewFD->setInvalidDecl();
13499 if (T.isObjCGCWeak())
13500 Diag(Loc, diag::warn_attribute_weak_on_field);
13502 NewFD->setAccess(AS);
13506 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13508 assert(getLangOpts().CPlusPlus && "valid check only for C++");
13510 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13513 QualType EltTy = Context.getBaseElementType(FD->getType());
13514 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13515 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13516 if (RDecl->getDefinition()) {
13517 // We check for copy constructors before constructors
13518 // because otherwise we'll never get complaints about
13519 // copy constructors.
13521 CXXSpecialMember member = CXXInvalid;
13522 // We're required to check for any non-trivial constructors. Since the
13523 // implicit default constructor is suppressed if there are any
13524 // user-declared constructors, we just need to check that there is a
13525 // trivial default constructor and a trivial copy constructor. (We don't
13526 // worry about move constructors here, since this is a C++98 check.)
13527 if (RDecl->hasNonTrivialCopyConstructor())
13528 member = CXXCopyConstructor;
13529 else if (!RDecl->hasTrivialDefaultConstructor())
13530 member = CXXDefaultConstructor;
13531 else if (RDecl->hasNonTrivialCopyAssignment())
13532 member = CXXCopyAssignment;
13533 else if (RDecl->hasNonTrivialDestructor())
13534 member = CXXDestructor;
13536 if (member != CXXInvalid) {
13537 if (!getLangOpts().CPlusPlus11 &&
13538 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13539 // Objective-C++ ARC: it is an error to have a non-trivial field of
13540 // a union. However, system headers in Objective-C programs
13541 // occasionally have Objective-C lifetime objects within unions,
13542 // and rather than cause the program to fail, we make those
13543 // members unavailable.
13544 SourceLocation Loc = FD->getLocation();
13545 if (getSourceManager().isInSystemHeader(Loc)) {
13546 if (!FD->hasAttr<UnavailableAttr>())
13547 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13548 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13553 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13554 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13555 diag::err_illegal_union_or_anon_struct_member)
13556 << FD->getParent()->isUnion() << FD->getDeclName() << member;
13557 DiagnoseNontrivial(RDecl, member);
13558 return !getLangOpts().CPlusPlus11;
13566 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13567 /// AST enum value.
13568 static ObjCIvarDecl::AccessControl
13569 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13570 switch (ivarVisibility) {
13571 default: llvm_unreachable("Unknown visitibility kind");
13572 case tok::objc_private: return ObjCIvarDecl::Private;
13573 case tok::objc_public: return ObjCIvarDecl::Public;
13574 case tok::objc_protected: return ObjCIvarDecl::Protected;
13575 case tok::objc_package: return ObjCIvarDecl::Package;
13579 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13580 /// in order to create an IvarDecl object for it.
13581 Decl *Sema::ActOnIvar(Scope *S,
13582 SourceLocation DeclStart,
13583 Declarator &D, Expr *BitfieldWidth,
13584 tok::ObjCKeywordKind Visibility) {
13586 IdentifierInfo *II = D.getIdentifier();
13587 Expr *BitWidth = (Expr*)BitfieldWidth;
13588 SourceLocation Loc = DeclStart;
13589 if (II) Loc = D.getIdentifierLoc();
13591 // FIXME: Unnamed fields can be handled in various different ways, for
13592 // example, unnamed unions inject all members into the struct namespace!
13594 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13595 QualType T = TInfo->getType();
13598 // 6.7.2.1p3, 6.7.2.1p4
13599 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13601 D.setInvalidType();
13608 if (T->isReferenceType()) {
13609 Diag(Loc, diag::err_ivar_reference_type);
13610 D.setInvalidType();
13612 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13613 // than a variably modified type.
13614 else if (T->isVariablyModifiedType()) {
13615 Diag(Loc, diag::err_typecheck_ivar_variable_size);
13616 D.setInvalidType();
13619 // Get the visibility (access control) for this ivar.
13620 ObjCIvarDecl::AccessControl ac =
13621 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13622 : ObjCIvarDecl::None;
13623 // Must set ivar's DeclContext to its enclosing interface.
13624 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13625 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13627 ObjCContainerDecl *EnclosingContext;
13628 if (ObjCImplementationDecl *IMPDecl =
13629 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13630 if (LangOpts.ObjCRuntime.isFragile()) {
13631 // Case of ivar declared in an implementation. Context is that of its class.
13632 EnclosingContext = IMPDecl->getClassInterface();
13633 assert(EnclosingContext && "Implementation has no class interface!");
13636 EnclosingContext = EnclosingDecl;
13638 if (ObjCCategoryDecl *CDecl =
13639 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13640 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13641 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13645 EnclosingContext = EnclosingDecl;
13648 // Construct the decl.
13649 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13650 DeclStart, Loc, II, T,
13651 TInfo, ac, (Expr *)BitfieldWidth);
13654 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13656 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13657 && !isa<TagDecl>(PrevDecl)) {
13658 Diag(Loc, diag::err_duplicate_member) << II;
13659 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13660 NewID->setInvalidDecl();
13664 // Process attributes attached to the ivar.
13665 ProcessDeclAttributes(S, NewID, D);
13667 if (D.isInvalidType())
13668 NewID->setInvalidDecl();
13670 // In ARC, infer 'retaining' for ivars of retainable type.
13671 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13672 NewID->setInvalidDecl();
13674 if (D.getDeclSpec().isModulePrivateSpecified())
13675 NewID->setModulePrivate();
13678 // FIXME: When interfaces are DeclContexts, we'll need to add
13679 // these to the interface.
13681 IdResolver.AddDecl(NewID);
13684 if (LangOpts.ObjCRuntime.isNonFragile() &&
13685 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13686 Diag(Loc, diag::warn_ivars_in_interface);
13691 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13692 /// class and class extensions. For every class \@interface and class
13693 /// extension \@interface, if the last ivar is a bitfield of any type,
13694 /// then add an implicit `char :0` ivar to the end of that interface.
13695 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13696 SmallVectorImpl<Decl *> &AllIvarDecls) {
13697 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13700 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13701 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13703 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13705 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13707 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13708 if (!CD->IsClassExtension())
13711 // No need to add this to end of @implementation.
13715 // All conditions are met. Add a new bitfield to the tail end of ivars.
13716 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13717 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13719 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13720 DeclLoc, DeclLoc, nullptr,
13722 Context.getTrivialTypeSourceInfo(Context.CharTy,
13724 ObjCIvarDecl::Private, BW,
13726 AllIvarDecls.push_back(Ivar);
13729 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13730 ArrayRef<Decl *> Fields, SourceLocation LBrac,
13731 SourceLocation RBrac, AttributeList *Attr) {
13732 assert(EnclosingDecl && "missing record or interface decl");
13734 // If this is an Objective-C @implementation or category and we have
13735 // new fields here we should reset the layout of the interface since
13736 // it will now change.
13737 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13738 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13739 switch (DC->getKind()) {
13741 case Decl::ObjCCategory:
13742 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13744 case Decl::ObjCImplementation:
13746 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13751 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13753 // Start counting up the number of named members; make sure to include
13754 // members of anonymous structs and unions in the total.
13755 unsigned NumNamedMembers = 0;
13757 for (const auto *I : Record->decls()) {
13758 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13759 if (IFD->getDeclName())
13764 // Verify that all the fields are okay.
13765 SmallVector<FieldDecl*, 32> RecFields;
13767 bool ARCErrReported = false;
13768 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13770 FieldDecl *FD = cast<FieldDecl>(*i);
13772 // Get the type for the field.
13773 const Type *FDTy = FD->getType().getTypePtr();
13775 if (!FD->isAnonymousStructOrUnion()) {
13776 // Remember all fields written by the user.
13777 RecFields.push_back(FD);
13780 // If the field is already invalid for some reason, don't emit more
13781 // diagnostics about it.
13782 if (FD->isInvalidDecl()) {
13783 EnclosingDecl->setInvalidDecl();
13788 // A structure or union shall not contain a member with
13789 // incomplete or function type (hence, a structure shall not
13790 // contain an instance of itself, but may contain a pointer to
13791 // an instance of itself), except that the last member of a
13792 // structure with more than one named member may have incomplete
13793 // array type; such a structure (and any union containing,
13794 // possibly recursively, a member that is such a structure)
13795 // shall not be a member of a structure or an element of an
13797 if (FDTy->isFunctionType()) {
13798 // Field declared as a function.
13799 Diag(FD->getLocation(), diag::err_field_declared_as_function)
13800 << FD->getDeclName();
13801 FD->setInvalidDecl();
13802 EnclosingDecl->setInvalidDecl();
13804 } else if (FDTy->isIncompleteArrayType() && Record &&
13805 ((i + 1 == Fields.end() && !Record->isUnion()) ||
13806 ((getLangOpts().MicrosoftExt ||
13807 getLangOpts().CPlusPlus) &&
13808 (i + 1 == Fields.end() || Record->isUnion())))) {
13809 // Flexible array member.
13810 // Microsoft and g++ is more permissive regarding flexible array.
13811 // It will accept flexible array in union and also
13812 // as the sole element of a struct/class.
13813 unsigned DiagID = 0;
13814 if (Record->isUnion())
13815 DiagID = getLangOpts().MicrosoftExt
13816 ? diag::ext_flexible_array_union_ms
13817 : getLangOpts().CPlusPlus
13818 ? diag::ext_flexible_array_union_gnu
13819 : diag::err_flexible_array_union;
13820 else if (Fields.size() == 1)
13821 DiagID = getLangOpts().MicrosoftExt
13822 ? diag::ext_flexible_array_empty_aggregate_ms
13823 : getLangOpts().CPlusPlus
13824 ? diag::ext_flexible_array_empty_aggregate_gnu
13825 : NumNamedMembers < 1
13826 ? diag::err_flexible_array_empty_aggregate
13830 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13831 << Record->getTagKind();
13832 // While the layout of types that contain virtual bases is not specified
13833 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13834 // virtual bases after the derived members. This would make a flexible
13835 // array member declared at the end of an object not adjacent to the end
13837 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13838 if (RD->getNumVBases() != 0)
13839 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13840 << FD->getDeclName() << Record->getTagKind();
13841 if (!getLangOpts().C99)
13842 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13843 << FD->getDeclName() << Record->getTagKind();
13845 // If the element type has a non-trivial destructor, we would not
13846 // implicitly destroy the elements, so disallow it for now.
13848 // FIXME: GCC allows this. We should probably either implicitly delete
13849 // the destructor of the containing class, or just allow this.
13850 QualType BaseElem = Context.getBaseElementType(FD->getType());
13851 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13852 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13853 << FD->getDeclName() << FD->getType();
13854 FD->setInvalidDecl();
13855 EnclosingDecl->setInvalidDecl();
13858 // Okay, we have a legal flexible array member at the end of the struct.
13859 Record->setHasFlexibleArrayMember(true);
13860 } else if (!FDTy->isDependentType() &&
13861 RequireCompleteType(FD->getLocation(), FD->getType(),
13862 diag::err_field_incomplete)) {
13864 FD->setInvalidDecl();
13865 EnclosingDecl->setInvalidDecl();
13867 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13868 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13869 // A type which contains a flexible array member is considered to be a
13870 // flexible array member.
13871 Record->setHasFlexibleArrayMember(true);
13872 if (!Record->isUnion()) {
13873 // If this is a struct/class and this is not the last element, reject
13874 // it. Note that GCC supports variable sized arrays in the middle of
13876 if (i + 1 != Fields.end())
13877 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13878 << FD->getDeclName() << FD->getType();
13880 // We support flexible arrays at the end of structs in
13881 // other structs as an extension.
13882 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13883 << FD->getDeclName();
13887 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13888 RequireNonAbstractType(FD->getLocation(), FD->getType(),
13889 diag::err_abstract_type_in_decl,
13890 AbstractIvarType)) {
13891 // Ivars can not have abstract class types
13892 FD->setInvalidDecl();
13894 if (Record && FDTTy->getDecl()->hasObjectMember())
13895 Record->setHasObjectMember(true);
13896 if (Record && FDTTy->getDecl()->hasVolatileMember())
13897 Record->setHasVolatileMember(true);
13898 } else if (FDTy->isObjCObjectType()) {
13899 /// A field cannot be an Objective-c object
13900 Diag(FD->getLocation(), diag::err_statically_allocated_object)
13901 << FixItHint::CreateInsertion(FD->getLocation(), "*");
13902 QualType T = Context.getObjCObjectPointerType(FD->getType());
13904 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13905 (!getLangOpts().CPlusPlus || Record->isUnion())) {
13906 // It's an error in ARC if a field has lifetime.
13907 // We don't want to report this in a system header, though,
13908 // so we just make the field unavailable.
13909 // FIXME: that's really not sufficient; we need to make the type
13910 // itself invalid to, say, initialize or copy.
13911 QualType T = FD->getType();
13912 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13913 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13914 SourceLocation loc = FD->getLocation();
13915 if (getSourceManager().isInSystemHeader(loc)) {
13916 if (!FD->hasAttr<UnavailableAttr>()) {
13917 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13918 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13921 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13922 << T->isBlockPointerType() << Record->getTagKind();
13924 ARCErrReported = true;
13926 } else if (getLangOpts().ObjC1 &&
13927 getLangOpts().getGC() != LangOptions::NonGC &&
13928 Record && !Record->hasObjectMember()) {
13929 if (FD->getType()->isObjCObjectPointerType() ||
13930 FD->getType().isObjCGCStrong())
13931 Record->setHasObjectMember(true);
13932 else if (Context.getAsArrayType(FD->getType())) {
13933 QualType BaseType = Context.getBaseElementType(FD->getType());
13934 if (BaseType->isRecordType() &&
13935 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13936 Record->setHasObjectMember(true);
13937 else if (BaseType->isObjCObjectPointerType() ||
13938 BaseType.isObjCGCStrong())
13939 Record->setHasObjectMember(true);
13942 if (Record && FD->getType().isVolatileQualified())
13943 Record->setHasVolatileMember(true);
13944 // Keep track of the number of named members.
13945 if (FD->getIdentifier())
13949 // Okay, we successfully defined 'Record'.
13951 bool Completed = false;
13952 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13953 if (!CXXRecord->isInvalidDecl()) {
13954 // Set access bits correctly on the directly-declared conversions.
13955 for (CXXRecordDecl::conversion_iterator
13956 I = CXXRecord->conversion_begin(),
13957 E = CXXRecord->conversion_end(); I != E; ++I)
13958 I.setAccess((*I)->getAccess());
13961 if (!CXXRecord->isDependentType()) {
13962 if (CXXRecord->hasUserDeclaredDestructor()) {
13963 // Adjust user-defined destructor exception spec.
13964 if (getLangOpts().CPlusPlus11)
13965 AdjustDestructorExceptionSpec(CXXRecord,
13966 CXXRecord->getDestructor());
13969 if (!CXXRecord->isInvalidDecl()) {
13970 // Add any implicitly-declared members to this class.
13971 AddImplicitlyDeclaredMembersToClass(CXXRecord);
13973 // If we have virtual base classes, we may end up finding multiple
13974 // final overriders for a given virtual function. Check for this
13976 if (CXXRecord->getNumVBases()) {
13977 CXXFinalOverriderMap FinalOverriders;
13978 CXXRecord->getFinalOverriders(FinalOverriders);
13980 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13981 MEnd = FinalOverriders.end();
13983 for (OverridingMethods::iterator SO = M->second.begin(),
13984 SOEnd = M->second.end();
13985 SO != SOEnd; ++SO) {
13986 assert(SO->second.size() > 0 &&
13987 "Virtual function without overridding functions?");
13988 if (SO->second.size() == 1)
13991 // C++ [class.virtual]p2:
13992 // In a derived class, if a virtual member function of a base
13993 // class subobject has more than one final overrider the
13994 // program is ill-formed.
13995 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13996 << (const NamedDecl *)M->first << Record;
13997 Diag(M->first->getLocation(),
13998 diag::note_overridden_virtual_function);
13999 for (OverridingMethods::overriding_iterator
14000 OM = SO->second.begin(),
14001 OMEnd = SO->second.end();
14003 Diag(OM->Method->getLocation(), diag::note_final_overrider)
14004 << (const NamedDecl *)M->first << OM->Method->getParent();
14006 Record->setInvalidDecl();
14009 CXXRecord->completeDefinition(&FinalOverriders);
14017 Record->completeDefinition();
14019 if (Record->hasAttrs()) {
14020 CheckAlignasUnderalignment(Record);
14022 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14023 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14024 IA->getRange(), IA->getBestCase(),
14025 IA->getSemanticSpelling());
14028 // Check if the structure/union declaration is a type that can have zero
14029 // size in C. For C this is a language extension, for C++ it may cause
14030 // compatibility problems.
14031 bool CheckForZeroSize;
14032 if (!getLangOpts().CPlusPlus) {
14033 CheckForZeroSize = true;
14035 // For C++ filter out types that cannot be referenced in C code.
14036 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14038 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14039 !CXXRecord->isDependentType() &&
14040 CXXRecord->isCLike();
14042 if (CheckForZeroSize) {
14043 bool ZeroSize = true;
14044 bool IsEmpty = true;
14045 unsigned NonBitFields = 0;
14046 for (RecordDecl::field_iterator I = Record->field_begin(),
14047 E = Record->field_end();
14048 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14050 if (I->isUnnamedBitfield()) {
14051 if (I->getBitWidthValue(Context) > 0)
14055 QualType FieldType = I->getType();
14056 if (FieldType->isIncompleteType() ||
14057 !Context.getTypeSizeInChars(FieldType).isZero())
14062 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14063 // allowed in C++, but warn if its declaration is inside
14064 // extern "C" block.
14066 Diag(RecLoc, getLangOpts().CPlusPlus ?
14067 diag::warn_zero_size_struct_union_in_extern_c :
14068 diag::warn_zero_size_struct_union_compat)
14069 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14072 // Structs without named members are extension in C (C99 6.7.2.1p7),
14073 // but are accepted by GCC.
14074 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14075 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14076 diag::ext_no_named_members_in_struct_union)
14077 << Record->isUnion();
14081 ObjCIvarDecl **ClsFields =
14082 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14083 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14084 ID->setEndOfDefinitionLoc(RBrac);
14085 // Add ivar's to class's DeclContext.
14086 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14087 ClsFields[i]->setLexicalDeclContext(ID);
14088 ID->addDecl(ClsFields[i]);
14090 // Must enforce the rule that ivars in the base classes may not be
14092 if (ID->getSuperClass())
14093 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14094 } else if (ObjCImplementationDecl *IMPDecl =
14095 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14096 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14097 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14098 // Ivar declared in @implementation never belongs to the implementation.
14099 // Only it is in implementation's lexical context.
14100 ClsFields[I]->setLexicalDeclContext(IMPDecl);
14101 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14102 IMPDecl->setIvarLBraceLoc(LBrac);
14103 IMPDecl->setIvarRBraceLoc(RBrac);
14104 } else if (ObjCCategoryDecl *CDecl =
14105 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14106 // case of ivars in class extension; all other cases have been
14107 // reported as errors elsewhere.
14108 // FIXME. Class extension does not have a LocEnd field.
14109 // CDecl->setLocEnd(RBrac);
14110 // Add ivar's to class extension's DeclContext.
14111 // Diagnose redeclaration of private ivars.
14112 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14113 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14115 if (const ObjCIvarDecl *ClsIvar =
14116 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14117 Diag(ClsFields[i]->getLocation(),
14118 diag::err_duplicate_ivar_declaration);
14119 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14122 for (const auto *Ext : IDecl->known_extensions()) {
14123 if (const ObjCIvarDecl *ClsExtIvar
14124 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14125 Diag(ClsFields[i]->getLocation(),
14126 diag::err_duplicate_ivar_declaration);
14127 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14132 ClsFields[i]->setLexicalDeclContext(CDecl);
14133 CDecl->addDecl(ClsFields[i]);
14135 CDecl->setIvarLBraceLoc(LBrac);
14136 CDecl->setIvarRBraceLoc(RBrac);
14141 ProcessDeclAttributeList(S, Record, Attr);
14144 /// \brief Determine whether the given integral value is representable within
14145 /// the given type T.
14146 static bool isRepresentableIntegerValue(ASTContext &Context,
14147 llvm::APSInt &Value,
14149 assert(T->isIntegralType(Context) && "Integral type required!");
14150 unsigned BitWidth = Context.getIntWidth(T);
14152 if (Value.isUnsigned() || Value.isNonNegative()) {
14153 if (T->isSignedIntegerOrEnumerationType())
14155 return Value.getActiveBits() <= BitWidth;
14157 return Value.getMinSignedBits() <= BitWidth;
14160 // \brief Given an integral type, return the next larger integral type
14161 // (or a NULL type of no such type exists).
14162 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14163 // FIXME: Int128/UInt128 support, which also needs to be introduced into
14164 // enum checking below.
14165 assert(T->isIntegralType(Context) && "Integral type required!");
14166 const unsigned NumTypes = 4;
14167 QualType SignedIntegralTypes[NumTypes] = {
14168 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14170 QualType UnsignedIntegralTypes[NumTypes] = {
14171 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14172 Context.UnsignedLongLongTy
14175 unsigned BitWidth = Context.getTypeSize(T);
14176 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14177 : UnsignedIntegralTypes;
14178 for (unsigned I = 0; I != NumTypes; ++I)
14179 if (Context.getTypeSize(Types[I]) > BitWidth)
14185 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14186 EnumConstantDecl *LastEnumConst,
14187 SourceLocation IdLoc,
14188 IdentifierInfo *Id,
14190 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14191 llvm::APSInt EnumVal(IntWidth);
14194 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14198 Val = DefaultLvalueConversion(Val).get();
14201 if (Enum->isDependentType() || Val->isTypeDependent())
14202 EltTy = Context.DependentTy;
14204 SourceLocation ExpLoc;
14205 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14206 !getLangOpts().MSVCCompat) {
14207 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14208 // constant-expression in the enumerator-definition shall be a converted
14209 // constant expression of the underlying type.
14210 EltTy = Enum->getIntegerType();
14211 ExprResult Converted =
14212 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14214 if (Converted.isInvalid())
14217 Val = Converted.get();
14218 } else if (!Val->isValueDependent() &&
14219 !(Val = VerifyIntegerConstantExpression(Val,
14220 &EnumVal).get())) {
14221 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14223 if (Enum->isFixed()) {
14224 EltTy = Enum->getIntegerType();
14226 // In Obj-C and Microsoft mode, require the enumeration value to be
14227 // representable in the underlying type of the enumeration. In C++11,
14228 // we perform a non-narrowing conversion as part of converted constant
14229 // expression checking.
14230 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14231 if (getLangOpts().MSVCCompat) {
14232 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14233 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14235 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14237 Val = ImpCastExprToType(Val, EltTy,
14238 EltTy->isBooleanType() ?
14239 CK_IntegralToBoolean : CK_IntegralCast)
14241 } else if (getLangOpts().CPlusPlus) {
14242 // C++11 [dcl.enum]p5:
14243 // If the underlying type is not fixed, the type of each enumerator
14244 // is the type of its initializing value:
14245 // - If an initializer is specified for an enumerator, the
14246 // initializing value has the same type as the expression.
14247 EltTy = Val->getType();
14250 // The expression that defines the value of an enumeration constant
14251 // shall be an integer constant expression that has a value
14252 // representable as an int.
14254 // Complain if the value is not representable in an int.
14255 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14256 Diag(IdLoc, diag::ext_enum_value_not_int)
14257 << EnumVal.toString(10) << Val->getSourceRange()
14258 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14259 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14260 // Force the type of the expression to 'int'.
14261 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14263 EltTy = Val->getType();
14270 if (Enum->isDependentType())
14271 EltTy = Context.DependentTy;
14272 else if (!LastEnumConst) {
14273 // C++0x [dcl.enum]p5:
14274 // If the underlying type is not fixed, the type of each enumerator
14275 // is the type of its initializing value:
14276 // - If no initializer is specified for the first enumerator, the
14277 // initializing value has an unspecified integral type.
14279 // GCC uses 'int' for its unspecified integral type, as does
14281 if (Enum->isFixed()) {
14282 EltTy = Enum->getIntegerType();
14285 EltTy = Context.IntTy;
14288 // Assign the last value + 1.
14289 EnumVal = LastEnumConst->getInitVal();
14291 EltTy = LastEnumConst->getType();
14293 // Check for overflow on increment.
14294 if (EnumVal < LastEnumConst->getInitVal()) {
14295 // C++0x [dcl.enum]p5:
14296 // If the underlying type is not fixed, the type of each enumerator
14297 // is the type of its initializing value:
14299 // - Otherwise the type of the initializing value is the same as
14300 // the type of the initializing value of the preceding enumerator
14301 // unless the incremented value is not representable in that type,
14302 // in which case the type is an unspecified integral type
14303 // sufficient to contain the incremented value. If no such type
14304 // exists, the program is ill-formed.
14305 QualType T = getNextLargerIntegralType(Context, EltTy);
14306 if (T.isNull() || Enum->isFixed()) {
14307 // There is no integral type larger enough to represent this
14308 // value. Complain, then allow the value to wrap around.
14309 EnumVal = LastEnumConst->getInitVal();
14310 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14312 if (Enum->isFixed())
14313 // When the underlying type is fixed, this is ill-formed.
14314 Diag(IdLoc, diag::err_enumerator_wrapped)
14315 << EnumVal.toString(10)
14318 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14319 << EnumVal.toString(10);
14324 // Retrieve the last enumerator's value, extent that type to the
14325 // type that is supposed to be large enough to represent the incremented
14326 // value, then increment.
14327 EnumVal = LastEnumConst->getInitVal();
14328 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14329 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14332 // If we're not in C++, diagnose the overflow of enumerator values,
14333 // which in C99 means that the enumerator value is not representable in
14334 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14335 // permits enumerator values that are representable in some larger
14337 if (!getLangOpts().CPlusPlus && !T.isNull())
14338 Diag(IdLoc, diag::warn_enum_value_overflow);
14339 } else if (!getLangOpts().CPlusPlus &&
14340 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14341 // Enforce C99 6.7.2.2p2 even when we compute the next value.
14342 Diag(IdLoc, diag::ext_enum_value_not_int)
14343 << EnumVal.toString(10) << 1;
14348 if (!EltTy->isDependentType()) {
14349 // Make the enumerator value match the signedness and size of the
14350 // enumerator's type.
14351 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14352 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14355 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14359 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14360 SourceLocation IILoc) {
14361 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14362 !getLangOpts().CPlusPlus)
14363 return SkipBodyInfo();
14365 // We have an anonymous enum definition. Look up the first enumerator to
14366 // determine if we should merge the definition with an existing one and
14368 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14370 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14372 return SkipBodyInfo();
14374 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14376 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14378 Skip.Previous = Hidden;
14382 return SkipBodyInfo();
14385 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14386 SourceLocation IdLoc, IdentifierInfo *Id,
14387 AttributeList *Attr,
14388 SourceLocation EqualLoc, Expr *Val) {
14389 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14390 EnumConstantDecl *LastEnumConst =
14391 cast_or_null<EnumConstantDecl>(lastEnumConst);
14393 // The scope passed in may not be a decl scope. Zip up the scope tree until
14394 // we find one that is.
14395 S = getNonFieldDeclScope(S);
14397 // Verify that there isn't already something declared with this name in this
14399 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14401 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14402 // Maybe we will complain about the shadowed template parameter.
14403 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14404 // Just pretend that we didn't see the previous declaration.
14405 PrevDecl = nullptr;
14408 // C++ [class.mem]p15:
14409 // If T is the name of a class, then each of the following shall have a name
14410 // different from T:
14411 // - every enumerator of every member of class T that is an unscoped
14413 if (!TheEnumDecl->isScoped())
14414 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14415 DeclarationNameInfo(Id, IdLoc));
14417 EnumConstantDecl *New =
14418 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14423 // When in C++, we may get a TagDecl with the same name; in this case the
14424 // enum constant will 'hide' the tag.
14425 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14426 "Received TagDecl when not in C++!");
14427 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14428 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14429 if (isa<EnumConstantDecl>(PrevDecl))
14430 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14432 Diag(IdLoc, diag::err_redefinition) << Id;
14433 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14438 // Process attributes.
14439 if (Attr) ProcessDeclAttributeList(S, New, Attr);
14441 // Register this decl in the current scope stack.
14442 New->setAccess(TheEnumDecl->getAccess());
14443 PushOnScopeChains(New, S);
14445 ActOnDocumentableDecl(New);
14450 // Returns true when the enum initial expression does not trigger the
14451 // duplicate enum warning. A few common cases are exempted as follows:
14452 // Element2 = Element1
14453 // Element2 = Element1 + 1
14454 // Element2 = Element1 - 1
14455 // Where Element2 and Element1 are from the same enum.
14456 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14457 Expr *InitExpr = ECD->getInitExpr();
14460 InitExpr = InitExpr->IgnoreImpCasts();
14462 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14463 if (!BO->isAdditiveOp())
14465 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14468 if (IL->getValue() != 1)
14471 InitExpr = BO->getLHS();
14474 // This checks if the elements are from the same enum.
14475 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14479 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14483 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14493 bool isTombstoneOrEmptyKey;
14494 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14495 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14498 static DupKey GetDupKey(const llvm::APSInt& Val) {
14499 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14503 struct DenseMapInfoDupKey {
14504 static DupKey getEmptyKey() { return DupKey(0, true); }
14505 static DupKey getTombstoneKey() { return DupKey(1, true); }
14506 static unsigned getHashValue(const DupKey Key) {
14507 return (unsigned)(Key.val * 37);
14509 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14510 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14511 LHS.val == RHS.val;
14514 } // end anonymous namespace
14516 // Emits a warning when an element is implicitly set a value that
14517 // a previous element has already been set to.
14518 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14520 QualType EnumType) {
14521 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14523 // Avoid anonymous enums
14524 if (!Enum->getIdentifier())
14527 // Only check for small enums.
14528 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14531 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14532 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14534 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14535 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14538 DuplicatesVector DupVector;
14539 ValueToVectorMap EnumMap;
14541 // Populate the EnumMap with all values represented by enum constants without
14543 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14544 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14546 // Null EnumConstantDecl means a previous diagnostic has been emitted for
14547 // this constant. Skip this enum since it may be ill-formed.
14552 if (ECD->getInitExpr())
14555 DupKey Key = GetDupKey(ECD->getInitVal());
14556 DeclOrVector &Entry = EnumMap[Key];
14558 // First time encountering this value.
14559 if (Entry.isNull())
14563 // Create vectors for any values that has duplicates.
14564 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14565 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14566 if (!ValidDuplicateEnum(ECD, Enum))
14569 DupKey Key = GetDupKey(ECD->getInitVal());
14571 DeclOrVector& Entry = EnumMap[Key];
14572 if (Entry.isNull())
14575 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14576 // Ensure constants are different.
14580 // Create new vector and push values onto it.
14581 ECDVector *Vec = new ECDVector();
14583 Vec->push_back(ECD);
14585 // Update entry to point to the duplicates vector.
14588 // Store the vector somewhere we can consult later for quick emission of
14590 DupVector.push_back(Vec);
14594 ECDVector *Vec = Entry.get<ECDVector*>();
14595 // Make sure constants are not added more than once.
14596 if (*Vec->begin() == ECD)
14599 Vec->push_back(ECD);
14602 // Emit diagnostics.
14603 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14604 DupVectorEnd = DupVector.end();
14605 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14606 ECDVector *Vec = *DupVectorIter;
14607 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14609 // Emit warning for one enum constant.
14610 ECDVector::iterator I = Vec->begin();
14611 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14612 << (*I)->getName() << (*I)->getInitVal().toString(10)
14613 << (*I)->getSourceRange();
14616 // Emit one note for each of the remaining enum constants with
14618 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14619 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14620 << (*I)->getName() << (*I)->getInitVal().toString(10)
14621 << (*I)->getSourceRange();
14626 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14627 bool AllowMask) const {
14628 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14629 assert(ED->isCompleteDefinition() && "expected enum definition");
14631 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14632 llvm::APInt &FlagBits = R.first->second;
14635 for (auto *E : ED->enumerators()) {
14636 const auto &EVal = E->getInitVal();
14637 // Only single-bit enumerators introduce new flag values.
14638 if (EVal.isPowerOf2())
14639 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14643 // A value is in a flag enum if either its bits are a subset of the enum's
14644 // flag bits (the first condition) or we are allowing masks and the same is
14645 // true of its complement (the second condition). When masks are allowed, we
14646 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14648 // While it's true that any value could be used as a mask, the assumption is
14649 // that a mask will have all of the insignificant bits set. Anything else is
14650 // likely a logic error.
14651 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14652 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14655 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14656 SourceLocation RBraceLoc, Decl *EnumDeclX,
14657 ArrayRef<Decl *> Elements,
14658 Scope *S, AttributeList *Attr) {
14659 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14660 QualType EnumType = Context.getTypeDeclType(Enum);
14663 ProcessDeclAttributeList(S, Enum, Attr);
14665 if (Enum->isDependentType()) {
14666 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14667 EnumConstantDecl *ECD =
14668 cast_or_null<EnumConstantDecl>(Elements[i]);
14669 if (!ECD) continue;
14671 ECD->setType(EnumType);
14674 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14678 // TODO: If the result value doesn't fit in an int, it must be a long or long
14679 // long value. ISO C does not support this, but GCC does as an extension,
14681 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14682 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14683 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14685 // Verify that all the values are okay, compute the size of the values, and
14686 // reverse the list.
14687 unsigned NumNegativeBits = 0;
14688 unsigned NumPositiveBits = 0;
14690 // Keep track of whether all elements have type int.
14691 bool AllElementsInt = true;
14693 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14694 EnumConstantDecl *ECD =
14695 cast_or_null<EnumConstantDecl>(Elements[i]);
14696 if (!ECD) continue; // Already issued a diagnostic.
14698 const llvm::APSInt &InitVal = ECD->getInitVal();
14700 // Keep track of the size of positive and negative values.
14701 if (InitVal.isUnsigned() || InitVal.isNonNegative())
14702 NumPositiveBits = std::max(NumPositiveBits,
14703 (unsigned)InitVal.getActiveBits());
14705 NumNegativeBits = std::max(NumNegativeBits,
14706 (unsigned)InitVal.getMinSignedBits());
14708 // Keep track of whether every enum element has type int (very commmon).
14709 if (AllElementsInt)
14710 AllElementsInt = ECD->getType() == Context.IntTy;
14713 // Figure out the type that should be used for this enum.
14715 unsigned BestWidth;
14717 // C++0x N3000 [conv.prom]p3:
14718 // An rvalue of an unscoped enumeration type whose underlying
14719 // type is not fixed can be converted to an rvalue of the first
14720 // of the following types that can represent all the values of
14721 // the enumeration: int, unsigned int, long int, unsigned long
14722 // int, long long int, or unsigned long long int.
14724 // An identifier declared as an enumeration constant has type int.
14725 // The C99 rule is modified by a gcc extension
14726 QualType BestPromotionType;
14728 bool Packed = Enum->hasAttr<PackedAttr>();
14729 // -fshort-enums is the equivalent to specifying the packed attribute on all
14730 // enum definitions.
14731 if (LangOpts.ShortEnums)
14734 if (Enum->isFixed()) {
14735 BestType = Enum->getIntegerType();
14736 if (BestType->isPromotableIntegerType())
14737 BestPromotionType = Context.getPromotedIntegerType(BestType);
14739 BestPromotionType = BestType;
14741 BestWidth = Context.getIntWidth(BestType);
14743 else if (NumNegativeBits) {
14744 // If there is a negative value, figure out the smallest integer type (of
14745 // int/long/longlong) that fits.
14746 // If it's packed, check also if it fits a char or a short.
14747 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14748 BestType = Context.SignedCharTy;
14749 BestWidth = CharWidth;
14750 } else if (Packed && NumNegativeBits <= ShortWidth &&
14751 NumPositiveBits < ShortWidth) {
14752 BestType = Context.ShortTy;
14753 BestWidth = ShortWidth;
14754 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14755 BestType = Context.IntTy;
14756 BestWidth = IntWidth;
14758 BestWidth = Context.getTargetInfo().getLongWidth();
14760 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14761 BestType = Context.LongTy;
14763 BestWidth = Context.getTargetInfo().getLongLongWidth();
14765 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14766 Diag(Enum->getLocation(), diag::ext_enum_too_large);
14767 BestType = Context.LongLongTy;
14770 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14772 // If there is no negative value, figure out the smallest type that fits
14773 // all of the enumerator values.
14774 // If it's packed, check also if it fits a char or a short.
14775 if (Packed && NumPositiveBits <= CharWidth) {
14776 BestType = Context.UnsignedCharTy;
14777 BestPromotionType = Context.IntTy;
14778 BestWidth = CharWidth;
14779 } else if (Packed && NumPositiveBits <= ShortWidth) {
14780 BestType = Context.UnsignedShortTy;
14781 BestPromotionType = Context.IntTy;
14782 BestWidth = ShortWidth;
14783 } else if (NumPositiveBits <= IntWidth) {
14784 BestType = Context.UnsignedIntTy;
14785 BestWidth = IntWidth;
14787 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14788 ? Context.UnsignedIntTy : Context.IntTy;
14789 } else if (NumPositiveBits <=
14790 (BestWidth = Context.getTargetInfo().getLongWidth())) {
14791 BestType = Context.UnsignedLongTy;
14793 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14794 ? Context.UnsignedLongTy : Context.LongTy;
14796 BestWidth = Context.getTargetInfo().getLongLongWidth();
14797 assert(NumPositiveBits <= BestWidth &&
14798 "How could an initializer get larger than ULL?");
14799 BestType = Context.UnsignedLongLongTy;
14801 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14802 ? Context.UnsignedLongLongTy : Context.LongLongTy;
14806 // Loop over all of the enumerator constants, changing their types to match
14807 // the type of the enum if needed.
14808 for (auto *D : Elements) {
14809 auto *ECD = cast_or_null<EnumConstantDecl>(D);
14810 if (!ECD) continue; // Already issued a diagnostic.
14812 // Standard C says the enumerators have int type, but we allow, as an
14813 // extension, the enumerators to be larger than int size. If each
14814 // enumerator value fits in an int, type it as an int, otherwise type it the
14815 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14816 // that X has type 'int', not 'unsigned'.
14818 // Determine whether the value fits into an int.
14819 llvm::APSInt InitVal = ECD->getInitVal();
14821 // If it fits into an integer type, force it. Otherwise force it to match
14822 // the enum decl type.
14826 if (!getLangOpts().CPlusPlus &&
14827 !Enum->isFixed() &&
14828 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14829 NewTy = Context.IntTy;
14830 NewWidth = IntWidth;
14832 } else if (ECD->getType() == BestType) {
14833 // Already the right type!
14834 if (getLangOpts().CPlusPlus)
14835 // C++ [dcl.enum]p4: Following the closing brace of an
14836 // enum-specifier, each enumerator has the type of its
14838 ECD->setType(EnumType);
14842 NewWidth = BestWidth;
14843 NewSign = BestType->isSignedIntegerOrEnumerationType();
14846 // Adjust the APSInt value.
14847 InitVal = InitVal.extOrTrunc(NewWidth);
14848 InitVal.setIsSigned(NewSign);
14849 ECD->setInitVal(InitVal);
14851 // Adjust the Expr initializer and type.
14852 if (ECD->getInitExpr() &&
14853 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14854 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14856 ECD->getInitExpr(),
14857 /*base paths*/ nullptr,
14859 if (getLangOpts().CPlusPlus)
14860 // C++ [dcl.enum]p4: Following the closing brace of an
14861 // enum-specifier, each enumerator has the type of its
14863 ECD->setType(EnumType);
14865 ECD->setType(NewTy);
14868 Enum->completeDefinition(BestType, BestPromotionType,
14869 NumPositiveBits, NumNegativeBits);
14871 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14873 if (Enum->hasAttr<FlagEnumAttr>()) {
14874 for (Decl *D : Elements) {
14875 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14876 if (!ECD) continue; // Already issued a diagnostic.
14878 llvm::APSInt InitVal = ECD->getInitVal();
14879 if (InitVal != 0 && !InitVal.isPowerOf2() &&
14880 !IsValueInFlagEnum(Enum, InitVal, true))
14881 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14886 // Now that the enum type is defined, ensure it's not been underaligned.
14887 if (Enum->hasAttrs())
14888 CheckAlignasUnderalignment(Enum);
14891 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14892 SourceLocation StartLoc,
14893 SourceLocation EndLoc) {
14894 StringLiteral *AsmString = cast<StringLiteral>(expr);
14896 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14897 AsmString, StartLoc,
14899 CurContext->addDecl(New);
14903 static void checkModuleImportContext(Sema &S, Module *M,
14904 SourceLocation ImportLoc, DeclContext *DC,
14905 bool FromInclude = false) {
14906 SourceLocation ExternCLoc;
14908 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14909 switch (LSD->getLanguage()) {
14910 case LinkageSpecDecl::lang_c:
14911 if (ExternCLoc.isInvalid())
14912 ExternCLoc = LSD->getLocStart();
14914 case LinkageSpecDecl::lang_cxx:
14917 DC = LSD->getParent();
14920 while (isa<LinkageSpecDecl>(DC))
14921 DC = DC->getParent();
14923 if (!isa<TranslationUnitDecl>(DC)) {
14924 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14925 ? diag::ext_module_import_not_at_top_level_noop
14926 : diag::err_module_import_not_at_top_level_fatal)
14927 << M->getFullModuleName() << DC;
14928 S.Diag(cast<Decl>(DC)->getLocStart(),
14929 diag::note_module_import_not_at_top_level) << DC;
14930 } else if (!M->IsExternC && ExternCLoc.isValid()) {
14931 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14932 << M->getFullModuleName();
14933 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14937 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14938 return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14941 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14942 SourceLocation ImportLoc,
14943 ModuleIdPath Path) {
14945 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14946 /*IsIncludeDirective=*/false);
14950 VisibleModules.setVisible(Mod, ImportLoc);
14952 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14954 // FIXME: we should support importing a submodule within a different submodule
14955 // of the same top-level module. Until we do, make it an error rather than
14956 // silently ignoring the import.
14957 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14958 Diag(ImportLoc, getLangOpts().CompilingModule
14959 ? diag::err_module_self_import
14960 : diag::err_module_import_in_implementation)
14961 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14963 SmallVector<SourceLocation, 2> IdentifierLocs;
14964 Module *ModCheck = Mod;
14965 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14966 // If we've run out of module parents, just drop the remaining identifiers.
14967 // We need the length to be consistent.
14970 ModCheck = ModCheck->Parent;
14972 IdentifierLocs.push_back(Path[I].second);
14975 ImportDecl *Import = ImportDecl::Create(Context,
14976 Context.getTranslationUnitDecl(),
14977 AtLoc.isValid()? AtLoc : ImportLoc,
14978 Mod, IdentifierLocs);
14979 Context.getTranslationUnitDecl()->addDecl(Import);
14983 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14984 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14986 // Determine whether we're in the #include buffer for a module. The #includes
14987 // in that buffer do not qualify as module imports; they're just an
14988 // implementation detail of us building the module.
14990 // FIXME: Should we even get ActOnModuleInclude calls for those?
14991 bool IsInModuleIncludes =
14992 TUKind == TU_Module &&
14993 getSourceManager().isWrittenInMainFile(DirectiveLoc);
14995 // Similarly, if we're in the implementation of a module, don't
14996 // synthesize an illegal module import. FIXME: Why not?
14997 bool ShouldAddImport =
14998 !IsInModuleIncludes &&
14999 (getLangOpts().CompilingModule ||
15000 getLangOpts().CurrentModule.empty() ||
15001 getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15003 // If this module import was due to an inclusion directive, create an
15004 // implicit import declaration to capture it in the AST.
15005 if (ShouldAddImport) {
15006 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15007 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15010 TU->addDecl(ImportD);
15011 Consumer.HandleImplicitImportDecl(ImportD);
15014 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15015 VisibleModules.setVisible(Mod, DirectiveLoc);
15018 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15019 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15021 if (getLangOpts().ModulesLocalVisibility)
15022 VisibleModulesStack.push_back(std::move(VisibleModules));
15023 VisibleModules.setVisible(Mod, DirectiveLoc);
15026 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15027 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15029 if (getLangOpts().ModulesLocalVisibility) {
15030 VisibleModules = std::move(VisibleModulesStack.back());
15031 VisibleModulesStack.pop_back();
15032 VisibleModules.setVisible(Mod, DirectiveLoc);
15033 // Leaving a module hides namespace names, so our visible namespace cache
15034 // is now out of date.
15035 VisibleNamespaceCache.clear();
15039 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15041 // Bail if we're not allowed to implicitly import a module here.
15042 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15045 // Create the implicit import declaration.
15046 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15047 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15049 TU->addDecl(ImportD);
15050 Consumer.HandleImplicitImportDecl(ImportD);
15052 // Make the module visible.
15053 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15054 VisibleModules.setVisible(Mod, Loc);
15057 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15058 IdentifierInfo* AliasName,
15059 SourceLocation PragmaLoc,
15060 SourceLocation NameLoc,
15061 SourceLocation AliasNameLoc) {
15062 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15063 LookupOrdinaryName);
15064 AsmLabelAttr *Attr =
15065 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15067 // If a declaration that:
15068 // 1) declares a function or a variable
15069 // 2) has external linkage
15070 // already exists, add a label attribute to it.
15071 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15072 if (isDeclExternC(PrevDecl))
15073 PrevDecl->addAttr(Attr);
15075 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15076 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15077 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15079 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15082 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15083 SourceLocation PragmaLoc,
15084 SourceLocation NameLoc) {
15085 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15088 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15090 (void)WeakUndeclaredIdentifiers.insert(
15091 std::pair<IdentifierInfo*,WeakInfo>
15092 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15096 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15097 IdentifierInfo* AliasName,
15098 SourceLocation PragmaLoc,
15099 SourceLocation NameLoc,
15100 SourceLocation AliasNameLoc) {
15101 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15102 LookupOrdinaryName);
15103 WeakInfo W = WeakInfo(Name, NameLoc);
15105 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15106 if (!PrevDecl->hasAttr<AliasAttr>())
15107 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15108 DeclApplyPragmaWeak(TUScope, ND, W);
15110 (void)WeakUndeclaredIdentifiers.insert(
15111 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15115 Decl *Sema::getObjCDeclContext() const {
15116 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15119 AvailabilityResult Sema::getCurContextAvailability() const {
15120 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15122 return AR_Available;
15124 // If we are within an Objective-C method, we should consult
15125 // both the availability of the method as well as the
15126 // enclosing class. If the class is (say) deprecated,
15127 // the entire method is considered deprecated from the
15128 // purpose of checking if the current context is deprecated.
15129 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15130 AvailabilityResult R = MD->getAvailability();
15131 if (R != AR_Available)
15133 D = MD->getClassInterface();
15135 // If we are within an Objective-c @implementation, it
15136 // gets the same availability context as the @interface.
15137 else if (const ObjCImplementationDecl *ID =
15138 dyn_cast<ObjCImplementationDecl>(D)) {
15139 D = ID->getClassInterface();
15141 // Recover from user error.
15142 return D ? D->getAvailability() : AR_Available;