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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.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 if (auto *BasePrimaryTemplate =
167 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169 BaseRD = BasePrimaryTemplate;
170 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171 if (const ClassTemplatePartialSpecializationDecl *PS =
172 CTD->findPartialSpecialization(Base.getType()))
173 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
179 for (NamedDecl *ND : BaseRD->lookup(&II)) {
180 if (!isa<TypeDecl>(ND))
181 return UnqualifiedTypeNameLookupResult::FoundNonType;
182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186 case UnqualifiedTypeNameLookupResult::FoundNonType:
187 return UnqualifiedTypeNameLookupResult::FoundNonType;
188 case UnqualifiedTypeNameLookupResult::FoundType:
189 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
191 case UnqualifiedTypeNameLookupResult::NotFound:
198 return FoundTypeDecl;
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202 const IdentifierInfo &II,
203 SourceLocation NameLoc) {
204 // Lookup in the parent class template context, if any.
205 const CXXRecordDecl *RD = nullptr;
206 UnqualifiedTypeNameLookupResult FoundTypeDecl =
207 UnqualifiedTypeNameLookupResult::NotFound;
208 for (DeclContext *DC = S.CurContext;
209 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210 DC = DC->getParent()) {
211 // Look for type decls in dependent base classes that have known primary
213 RD = dyn_cast<CXXRecordDecl>(DC);
214 if (RD && RD->getDescribedClassTemplate())
215 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
217 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
220 // We found some types in dependent base classes. Recover as if the user
221 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
222 // lookup during template instantiation.
223 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
225 ASTContext &Context = S.Context;
226 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227 cast<Type>(Context.getRecordType(RD)));
228 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
231 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
233 TypeLocBuilder Builder;
234 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235 DepTL.setNameLoc(NameLoc);
236 DepTL.setElaboratedKeywordLoc(SourceLocation());
237 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250 Scope *S, CXXScopeSpec *SS,
251 bool isClassName, bool HasTrailingDot,
252 ParsedType ObjectTypePtr,
253 bool IsCtorOrDtorName,
254 bool WantNontrivialTypeSourceInfo,
255 IdentifierInfo **CorrectedII) {
256 // Determine where we will perform name lookup.
257 DeclContext *LookupCtx = nullptr;
259 QualType ObjectType = ObjectTypePtr.get();
260 if (ObjectType->isRecordType())
261 LookupCtx = computeDeclContext(ObjectType);
262 } else if (SS && SS->isNotEmpty()) {
263 LookupCtx = computeDeclContext(*SS, false);
266 if (isDependentScopeSpecifier(*SS)) {
268 // A qualified-id that refers to a type and in which the
269 // nested-name-specifier depends on a template-parameter (14.6.2)
270 // shall be prefixed by the keyword typename to indicate that the
271 // qualified-id denotes a type, forming an
272 // elaborated-type-specifier (7.1.5.3).
274 // We therefore do not perform any name lookup if the result would
275 // refer to a member of an unknown specialization.
276 if (!isClassName && !IsCtorOrDtorName)
279 // We know from the grammar that this name refers to a type,
280 // so build a dependent node to describe the type.
281 if (WantNontrivialTypeSourceInfo)
282 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
284 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
287 return ParsedType::make(T);
293 if (!LookupCtx->isDependentContext() &&
294 RequireCompleteDeclContext(*SS, LookupCtx))
298 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299 // lookup for class-names.
300 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
302 LookupResult Result(*this, &II, NameLoc, Kind);
304 // Perform "qualified" name lookup into the declaration context we
305 // computed, which is either the type of the base of a member access
306 // expression or the declaration context associated with a prior
307 // nested-name-specifier.
308 LookupQualifiedName(Result, LookupCtx);
310 if (ObjectTypePtr && Result.empty()) {
311 // C++ [basic.lookup.classref]p3:
312 // If the unqualified-id is ~type-name, the type-name is looked up
313 // in the context of the entire postfix-expression. If the type T of
314 // the object expression is of a class type C, the type-name is also
315 // looked up in the scope of class C. At least one of the lookups shall
316 // find a name that refers to (possibly cv-qualified) T.
317 LookupName(Result, S);
320 // Perform unqualified name lookup.
321 LookupName(Result, S);
323 // For unqualified lookup in a class template in MSVC mode, look into
324 // dependent base classes where the primary class template is known.
325 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326 if (ParsedType TypeInBase =
327 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
332 NamedDecl *IIDecl = nullptr;
333 switch (Result.getResultKind()) {
334 case LookupResult::NotFound:
335 case LookupResult::NotFoundInCurrentInstantiation:
337 TypoCorrection Correction = CorrectTypo(
338 Result.getLookupNameInfo(), Kind, S, SS,
339 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
341 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
343 bool MemberOfUnknownSpecialization;
344 UnqualifiedId TemplateName;
345 TemplateName.setIdentifier(NewII, NameLoc);
346 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347 CXXScopeSpec NewSS, *NewSSPtr = SS;
349 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
352 if (Correction && (NNS || NewII != &II) &&
353 // Ignore a correction to a template type as the to-be-corrected
354 // identifier is not a template (typo correction for template names
355 // is handled elsewhere).
356 !(getLangOpts().CPlusPlus && NewSSPtr &&
357 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358 Template, MemberOfUnknownSpecialization))) {
359 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360 isClassName, HasTrailingDot, ObjectTypePtr,
362 WantNontrivialTypeSourceInfo);
364 diagnoseTypo(Correction,
365 PDiag(diag::err_unknown_type_or_class_name_suggest)
366 << Result.getLookupName() << isClassName);
368 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369 *CorrectedII = NewII;
374 // If typo correction failed or was not performed, fall through
375 case LookupResult::FoundOverloaded:
376 case LookupResult::FoundUnresolvedValue:
377 Result.suppressDiagnostics();
380 case LookupResult::Ambiguous:
381 // Recover from type-hiding ambiguities by hiding the type. We'll
382 // do the lookup again when looking for an object, and we can
383 // diagnose the error then. If we don't do this, then the error
384 // about hiding the type will be immediately followed by an error
385 // that only makes sense if the identifier was treated like a type.
386 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387 Result.suppressDiagnostics();
391 // Look to see if we have a type anywhere in the list of results.
392 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393 Res != ResEnd; ++Res) {
394 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
396 (*Res)->getLocation().getRawEncoding() <
397 IIDecl->getLocation().getRawEncoding())
403 // None of the entities we found is a type, so there is no way
404 // to even assume that the result is a type. In this case, don't
405 // complain about the ambiguity. The parser will either try to
406 // perform this lookup again (e.g., as an object name), which
407 // will produce the ambiguity, or will complain that it expected
409 Result.suppressDiagnostics();
413 // We found a type within the ambiguous lookup; diagnose the
414 // ambiguity and then return that type. This might be the right
415 // answer, or it might not be, but it suppresses any attempt to
416 // perform the name lookup again.
419 case LookupResult::Found:
420 IIDecl = Result.getFoundDecl();
424 assert(IIDecl && "Didn't find decl");
427 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428 DiagnoseUseOfDecl(IIDecl, NameLoc);
430 T = Context.getTypeDeclType(TD);
431 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
433 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434 // constructor or destructor name (in such a case, the scope specifier
435 // will be attached to the enclosing Expr or Decl node).
436 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437 if (WantNontrivialTypeSourceInfo) {
438 // Construct a type with type-source information.
439 TypeLocBuilder Builder;
440 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
442 T = getElaboratedType(ETK_None, *SS, T);
443 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444 ElabTL.setElaboratedKeywordLoc(SourceLocation());
445 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
448 T = getElaboratedType(ETK_None, *SS, T);
451 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
454 T = Context.getObjCInterfaceType(IDecl);
458 // If it's not plausibly a type, suppress diagnostics.
459 Result.suppressDiagnostics();
462 return ParsedType::make(T);
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468 for (;; DC = DC->getLookupParent()) {
469 DC = DC->getPrimaryContext();
470 auto *ND = dyn_cast<NamespaceDecl>(DC);
471 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472 return NestedNameSpecifier::Create(Context, nullptr, ND);
473 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475 RD->getTypeForDecl());
476 else if (isa<TranslationUnitDecl>(DC))
477 return NestedNameSpecifier::GlobalSpecifier(Context);
479 llvm_unreachable("something isn't in TU scope?");
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489 DC = DC->getPrimaryContext();
490 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491 if (MD->getParent()->hasAnyDependentBases())
492 return MD->getParent();
497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498 SourceLocation NameLoc,
499 bool IsTemplateTypeArg) {
500 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
502 NestedNameSpecifier *NNS = nullptr;
503 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504 // If we weren't able to parse a default template argument, delay lookup
505 // until instantiation time by making a non-dependent DependentTypeName. We
506 // pretend we saw a NestedNameSpecifier referring to the current scope, and
507 // lookup is retried.
508 // FIXME: This hurts our diagnostic quality, since we get errors like "no
509 // type named 'Foo' in 'current_namespace'" when the user didn't write any
511 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513 } else if (const CXXRecordDecl *RD =
514 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515 // Build a DependentNameType that will perform lookup into RD at
516 // instantiation time.
517 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518 RD->getTypeForDecl());
520 // Diagnose that this identifier was undeclared, and retry the lookup during
521 // template instantiation.
522 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
525 // This is not a situation that we should recover from.
529 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
531 // Build type location information. We synthesized the qualifier, so we have
532 // to build a fake NestedNameSpecifierLoc.
533 NestedNameSpecifierLocBuilder NNSLocBuilder;
534 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
537 TypeLocBuilder Builder;
538 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539 DepTL.setNameLoc(NameLoc);
540 DepTL.setElaboratedKeywordLoc(SourceLocation());
541 DepTL.setQualifierLoc(QualifierLoc);
542 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo"). If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551 // Do a tag name lookup in this scope.
552 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553 LookupName(R, S, false);
554 R.suppressDiagnostics();
555 if (R.getResultKind() == LookupResult::Found)
556 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557 switch (TD->getTagKind()) {
558 case TTK_Struct: return DeclSpec::TST_struct;
559 case TTK_Interface: return DeclSpec::TST_interface;
560 case TTK_Union: return DeclSpec::TST_union;
561 case TTK_Class: return DeclSpec::TST_class;
562 case TTK_Enum: return DeclSpec::TST_enum;
566 return DeclSpec::TST_unspecified;
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
574 /// template<class T> class A {
576 /// typedef int TYPE;
578 /// template<class T> class B : public A<T> {
580 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584 if (CurContext->isRecord()) {
585 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
588 const Type *Ty = SS->getScopeRep()->getAsType();
590 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591 for (const auto &Base : RD->bases())
592 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
594 return S->isFunctionPrototypeScope();
596 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600 SourceLocation IILoc,
603 ParsedType &SuggestedType,
604 bool AllowClassTemplates) {
605 // We don't have anything to suggest (yet).
606 SuggestedType = nullptr;
608 // There may have been a typo in the name of the type. Look up typo
609 // results, in case we have something that we can suggest.
610 if (TypoCorrection Corrected =
611 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612 llvm::make_unique<TypeNameValidatorCCC>(
613 false, false, AllowClassTemplates),
614 CTK_ErrorRecovery)) {
615 if (Corrected.isKeyword()) {
616 // We corrected to a keyword.
617 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618 II = Corrected.getCorrectionAsIdentifierInfo();
620 // We found a similarly-named type or interface; suggest that.
621 if (!SS || !SS->isSet()) {
622 diagnoseTypo(Corrected,
623 PDiag(diag::err_unknown_typename_suggest) << II);
624 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627 II->getName().equals(CorrectedStr);
628 diagnoseTypo(Corrected,
629 PDiag(diag::err_unknown_nested_typename_suggest)
630 << II << DC << DroppedSpecifier << SS->getRange());
632 llvm_unreachable("could not have corrected a typo here");
636 if (Corrected.getCorrectionSpecifier())
637 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
640 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642 /*IsCtorOrDtorName=*/false,
643 /*NonTrivialTypeSourceInfo=*/true);
648 if (getLangOpts().CPlusPlus) {
649 // See if II is a class template that the user forgot to pass arguments to.
651 Name.setIdentifier(II, IILoc);
652 CXXScopeSpec EmptySS;
653 TemplateTy TemplateResult;
654 bool MemberOfUnknownSpecialization;
655 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656 Name, nullptr, true, TemplateResult,
657 MemberOfUnknownSpecialization) == TNK_Type_template) {
658 TemplateName TplName = TemplateResult.get();
659 Diag(IILoc, diag::err_template_missing_args) << TplName;
660 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662 << TplDecl->getTemplateParameters()->getSourceRange();
668 // FIXME: Should we move the logic that tries to recover from a missing tag
669 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
671 if (!SS || (!SS->isSet() && !SS->isInvalid()))
672 Diag(IILoc, diag::err_unknown_typename) << II;
673 else if (DeclContext *DC = computeDeclContext(*SS, false))
674 Diag(IILoc, diag::err_typename_nested_not_found)
675 << II << DC << SS->getRange();
676 else if (isDependentScopeSpecifier(*SS)) {
677 unsigned DiagID = diag::err_typename_missing;
678 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679 DiagID = diag::ext_typename_missing;
681 Diag(SS->getRange().getBegin(), DiagID)
682 << SS->getScopeRep() << II->getName()
683 << SourceRange(SS->getRange().getBegin(), IILoc)
684 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685 SuggestedType = ActOnTypenameType(S, SourceLocation(),
686 *SS, *II, IILoc).get();
688 assert(SS && SS->isInvalid() &&
689 "Invalid scope specifier has already been diagnosed");
693 /// \brief Determine whether the given result set contains either a type name
695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697 NextToken.is(tok::less);
699 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
703 if (CheckTemplate && isa<TemplateDecl>(*I))
710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711 Scope *S, CXXScopeSpec &SS,
712 IdentifierInfo *&Name,
713 SourceLocation NameLoc) {
714 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715 SemaRef.LookupParsedName(R, S, &SS);
716 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717 StringRef FixItTagName;
718 switch (Tag->getTagKind()) {
720 FixItTagName = "class ";
724 FixItTagName = "enum ";
728 FixItTagName = "struct ";
732 FixItTagName = "__interface ";
736 FixItTagName = "union ";
740 StringRef TagName = FixItTagName.drop_back();
741 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
745 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
747 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
750 // Replace lookup results with just the tag decl.
751 Result.clear(Sema::LookupTagName);
752 SemaRef.LookupParsedName(Result, S, &SS);
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761 QualType T, SourceLocation NameLoc) {
762 ASTContext &Context = S.Context;
764 TypeLocBuilder Builder;
765 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
767 T = S.getElaboratedType(ETK_None, SS, T);
768 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769 ElabTL.setElaboratedKeywordLoc(SourceLocation());
770 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
774 Sema::NameClassification
775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776 SourceLocation NameLoc, const Token &NextToken,
777 bool IsAddressOfOperand,
778 std::unique_ptr<CorrectionCandidateCallback> CCC) {
779 DeclarationNameInfo NameInfo(Name, NameLoc);
780 ObjCMethodDecl *CurMethod = getCurMethodDecl();
782 if (NextToken.is(tok::coloncolon)) {
783 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
784 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
787 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788 LookupParsedName(Result, S, &SS, !CurMethod);
790 // For unqualified lookup in a class template in MSVC mode, look into
791 // dependent base classes where the primary class template is known.
792 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793 if (ParsedType TypeInBase =
794 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
798 // Perform lookup for Objective-C instance variables (including automatically
799 // synthesized instance variables), if we're in an Objective-C method.
800 // FIXME: This lookup really, really needs to be folded in to the normal
801 // unqualified lookup mechanism.
802 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804 if (E.get() || E.isInvalid())
808 bool SecondTry = false;
809 bool IsFilteredTemplateName = false;
812 switch (Result.getResultKind()) {
813 case LookupResult::NotFound:
814 // If an unqualified-id is followed by a '(', then we have a function
816 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817 // In C++, this is an ADL-only call.
819 if (getLangOpts().CPlusPlus)
820 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
823 // If the expression that precedes the parenthesized argument list in a
824 // function call consists solely of an identifier, and if no
825 // declaration is visible for this identifier, the identifier is
826 // implicitly declared exactly as if, in the innermost block containing
827 // the function call, the declaration
829 // extern int identifier ();
833 // We also allow this in C99 as an extension.
834 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
836 Result.resolveKind();
837 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
841 // In C, we first see whether there is a tag type by the same name, in
842 // which case it's likely that the user just forgot to write "enum",
843 // "struct", or "union".
844 if (!getLangOpts().CPlusPlus && !SecondTry &&
845 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
849 // Perform typo correction to determine if there is another name that is
850 // close to this name.
851 if (!SecondTry && CCC) {
853 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854 Result.getLookupKind(), S,
856 CTK_ErrorRecovery)) {
857 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858 unsigned QualifiedDiag = diag::err_no_member_suggest;
860 NamedDecl *FirstDecl = Corrected.getFoundDecl();
861 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864 UnqualifiedDiag = diag::err_no_template_suggest;
865 QualifiedDiag = diag::err_no_member_template_suggest;
866 } else if (UnderlyingFirstDecl &&
867 (isa<TypeDecl>(UnderlyingFirstDecl) ||
868 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870 UnqualifiedDiag = diag::err_unknown_typename_suggest;
871 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
875 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876 } else {// FIXME: is this even reachable? Test it.
877 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879 Name->getName().equals(CorrectedStr);
880 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881 << Name << computeDeclContext(SS, false)
882 << DroppedSpecifier << SS.getRange());
885 // Update the name, so that the caller has the new name.
886 Name = Corrected.getCorrectionAsIdentifierInfo();
888 // Typo correction corrected to a keyword.
889 if (Corrected.isKeyword())
892 // Also update the LookupResult...
893 // FIXME: This should probably go away at some point
895 Result.setLookupName(Corrected.getCorrection());
897 Result.addDecl(FirstDecl);
899 // If we found an Objective-C instance variable, let
900 // LookupInObjCMethod build the appropriate expression to
901 // reference the ivar.
902 // FIXME: This is a gross hack.
903 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
905 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
913 // We failed to correct; just fall through and let the parser deal with it.
914 Result.suppressDiagnostics();
915 return NameClassification::Unknown();
917 case LookupResult::NotFoundInCurrentInstantiation: {
918 // We performed name lookup into the current instantiation, and there were
919 // dependent bases, so we treat this result the same way as any other
920 // dependent nested-name-specifier.
923 // A name used in a template declaration or definition and that is
924 // dependent on a template-parameter is assumed not to name a type
925 // unless the applicable name lookup finds a type name or the name is
926 // qualified by the keyword typename.
928 // FIXME: If the next token is '<', we might want to ask the parser to
929 // perform some heroics to see if we actually have a
930 // template-argument-list, which would indicate a missing 'template'
932 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933 NameInfo, IsAddressOfOperand,
934 /*TemplateArgs=*/nullptr);
937 case LookupResult::Found:
938 case LookupResult::FoundOverloaded:
939 case LookupResult::FoundUnresolvedValue:
942 case LookupResult::Ambiguous:
943 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944 hasAnyAcceptableTemplateNames(Result)) {
945 // C++ [temp.local]p3:
946 // A lookup that finds an injected-class-name (10.2) can result in an
947 // ambiguity in certain cases (for example, if it is found in more than
948 // one base class). If all of the injected-class-names that are found
949 // refer to specializations of the same class template, and if the name
950 // is followed by a template-argument-list, the reference refers to the
951 // class template itself and not a specialization thereof, and is not
954 // This filtering can make an ambiguous result into an unambiguous one,
955 // so try again after filtering out template names.
956 FilterAcceptableTemplateNames(Result);
957 if (!Result.isAmbiguous()) {
958 IsFilteredTemplateName = true;
963 // Diagnose the ambiguity and return an error.
964 return NameClassification::Error();
967 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969 // C++ [temp.names]p3:
970 // After name lookup (3.4) finds that a name is a template-name or that
971 // an operator-function-id or a literal- operator-id refers to a set of
972 // overloaded functions any member of which is a function template if
973 // this is followed by a <, the < is always taken as the delimiter of a
974 // template-argument-list and never as the less-than operator.
975 if (!IsFilteredTemplateName)
976 FilterAcceptableTemplateNames(Result);
978 if (!Result.empty()) {
979 bool IsFunctionTemplate;
981 TemplateName Template;
982 if (Result.end() - Result.begin() > 1) {
983 IsFunctionTemplate = true;
984 Template = Context.getOverloadedTemplateName(Result.begin(),
988 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990 IsVarTemplate = isa<VarTemplateDecl>(TD);
992 if (SS.isSet() && !SS.isInvalid())
993 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994 /*TemplateKeyword=*/false,
997 Template = TemplateName(TD);
1000 if (IsFunctionTemplate) {
1001 // Function templates always go through overload resolution, at which
1002 // point we'll perform the various checks (e.g., accessibility) we need
1003 // to based on which function we selected.
1004 Result.suppressDiagnostics();
1006 return NameClassification::FunctionTemplate(Template);
1009 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010 : NameClassification::TypeTemplate(Template);
1014 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016 DiagnoseUseOfDecl(Type, NameLoc);
1017 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018 QualType T = Context.getTypeDeclType(Type);
1019 if (SS.isNotEmpty())
1020 return buildNestedType(*this, SS, T, NameLoc);
1021 return ParsedType::make(T);
1024 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1026 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027 if (ObjCCompatibleAliasDecl *Alias =
1028 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029 Class = Alias->getClassInterface();
1033 DiagnoseUseOfDecl(Class, NameLoc);
1035 if (NextToken.is(tok::period)) {
1036 // Interface. <something> is parsed as a property reference expression.
1037 // Just return "unknown" as a fall-through for now.
1038 Result.suppressDiagnostics();
1039 return NameClassification::Unknown();
1042 QualType T = Context.getObjCInterfaceType(Class);
1043 return ParsedType::make(T);
1046 // We can have a type template here if we're classifying a template argument.
1047 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048 return NameClassification::TypeTemplate(
1049 TemplateName(cast<TemplateDecl>(FirstDecl)));
1051 // Check for a tag type hidden by a non-type decl in a few cases where it
1052 // seems likely a type is wanted instead of the non-type that was found.
1053 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054 if ((NextToken.is(tok::identifier) ||
1056 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059 DiagnoseUseOfDecl(Type, NameLoc);
1060 QualType T = Context.getTypeDeclType(Type);
1061 if (SS.isNotEmpty())
1062 return buildNestedType(*this, SS, T, NameLoc);
1063 return ParsedType::make(T);
1066 if (FirstDecl->isCXXClassMember())
1067 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1070 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071 return BuildDeclarationNameExpr(SS, Result, ADL);
1074 // Determines the context to return to after temporarily entering a
1075 // context. This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1079 // Functions defined inline within classes aren't parsed until we've
1080 // finished parsing the top-level class, so the top-level class is
1081 // the context we'll need to return to.
1082 // A Lambda call operator whose parent is a class must not be treated
1083 // as an inline member function. A Lambda can be used legally
1084 // either as an in-class member initializer or a default argument. These
1085 // are parsed once the class has been marked complete and so the containing
1086 // context would be the nested class (when the lambda is defined in one);
1087 // If the class is not complete, then the lambda is being used in an
1088 // ill-formed fashion (such as to specify the width of a bit-field, or
1089 // in an array-bound) - in which case we still want to return the
1090 // lexically containing DC (which could be a nested class).
1091 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092 DC = DC->getLexicalParent();
1094 // A function not defined within a class will always return to its
1096 if (!isa<CXXRecordDecl>(DC))
1099 // A C++ inline method/friend is parsed *after* the topmost class
1100 // it was declared in is fully parsed ("complete"); the topmost
1101 // class is the context we need to return to.
1102 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1105 // Return the declaration context of the topmost class the inline method is
1110 return DC->getLexicalParent();
1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114 assert(getContainingDC(DC) == CurContext &&
1115 "The next DeclContext should be lexically contained in the current one.");
1120 void Sema::PopDeclContext() {
1121 assert(CurContext && "DeclContext imbalance!");
1123 CurContext = getContainingDC(CurContext);
1124 assert(CurContext && "Popped translation unit!");
1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1129 // Unlike PushDeclContext, the context to which we return is not necessarily
1130 // the containing DC of TD, because the new context will be some pre-existing
1131 // TagDecl definition instead of a fresh one.
1132 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133 CurContext = cast<TagDecl>(D)->getDefinition();
1134 assert(CurContext && "skipping definition of undefined tag");
1135 // Start lookups from the parent of the current context; we don't want to look
1136 // into the pre-existing complete definition.
1137 S->setEntity(CurContext->getLookupParent());
1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142 CurContext = static_cast<decltype(CurContext)>(Context);
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149 // C++0x [basic.lookup.unqual]p13:
1150 // A name used in the definition of a static data member of class
1151 // X (after the qualified-id of the static member) is looked up as
1152 // if the name was used in a member function of X.
1153 // C++0x [basic.lookup.unqual]p14:
1154 // If a variable member of a namespace is defined outside of the
1155 // scope of its namespace then any name used in the definition of
1156 // the variable member (after the declarator-id) is looked up as
1157 // if the definition of the variable member occurred in its
1159 // Both of these imply that we should push a scope whose context
1160 // is the semantic context of the declaration. We can't use
1161 // PushDeclContext here because that context is not necessarily
1162 // lexically contained in the current context. Fortunately,
1163 // the containing scope should have the appropriate information.
1165 assert(!S->getEntity() && "scope already has entity");
1168 Scope *Ancestor = S->getParent();
1169 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178 assert(S->getEntity() == CurContext && "Context imbalance!");
1180 // Switch back to the lexical context. The safety of this is
1181 // enforced by an assert in EnterDeclaratorContext.
1182 Scope *Ancestor = S->getParent();
1183 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184 CurContext = Ancestor->getEntity();
1186 // We don't need to do anything with the scope, which is going to
1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191 // We assume that the caller has already called
1192 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193 FunctionDecl *FD = D->getAsFunction();
1197 // Same implementation as PushDeclContext, but enters the context
1198 // from the lexical parent, rather than the top-level class.
1199 assert(CurContext == FD->getLexicalParent() &&
1200 "The next DeclContext should be lexically contained in the current one.");
1202 S->setEntity(CurContext);
1204 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205 ParmVarDecl *Param = FD->getParamDecl(P);
1206 // If the parameter has an identifier, then add it to the scope
1207 if (Param->getIdentifier()) {
1209 IdResolver.AddDecl(Param);
1214 void Sema::ActOnExitFunctionContext() {
1215 // Same implementation as PopDeclContext, but returns to the lexical parent,
1216 // rather than the top-level class.
1217 assert(CurContext && "DeclContext imbalance!");
1218 CurContext = CurContext->getLexicalParent();
1219 assert(CurContext && "Popped translation unit!");
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232 ASTContext &Context) {
1233 if (Context.getLangOpts().CPlusPlus)
1236 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1239 return (Previous.getResultKind() == LookupResult::Found
1240 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1243 /// Add this decl to the scope shadowed decl chains.
1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245 // Move up the scope chain until we find the nearest enclosing
1246 // non-transparent context. The declaration will be introduced into this
1248 while (S->getEntity() && S->getEntity()->isTransparentContext())
1251 // Add scoped declarations into their context, so that they can be
1252 // found later. Declarations without a context won't be inserted
1253 // into any context.
1255 CurContext->addDecl(D);
1257 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258 // are function-local declarations.
1259 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260 !D->getDeclContext()->getRedeclContext()->Equals(
1261 D->getLexicalDeclContext()->getRedeclContext()) &&
1262 !D->getLexicalDeclContext()->isFunctionOrMethod())
1265 // Template instantiations should also not be pushed into scope.
1266 if (isa<FunctionDecl>(D) &&
1267 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1270 // If this replaces anything in the current scope,
1271 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272 IEnd = IdResolver.end();
1273 for (; I != IEnd; ++I) {
1274 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1276 IdResolver.RemoveDecl(*I);
1278 // Should only need to replace one decl.
1285 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286 // Implicitly-generated labels may end up getting generated in an order that
1287 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288 // the label at the appropriate place in the identifier chain.
1289 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291 if (IDC == CurContext) {
1292 if (!S->isDeclScope(*I))
1294 } else if (IDC->Encloses(CurContext))
1298 IdResolver.InsertDeclAfter(I, D);
1300 IdResolver.AddDecl(D);
1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306 TUScope->AddDecl(D);
1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310 bool AllowInlineNamespace) {
1311 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315 DeclContext *TargetDC = DC->getPrimaryContext();
1317 if (DeclContext *ScopeDC = S->getEntity())
1318 if (ScopeDC->getPrimaryContext() == TargetDC)
1320 } while ((S = S->getParent()));
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332 bool ConsiderLinkage,
1333 bool AllowInlineNamespace) {
1334 LookupResult::Filter F = R.makeFilter();
1335 while (F.hasNext()) {
1336 NamedDecl *D = F.next();
1338 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1341 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1350 static bool isUsingDecl(NamedDecl *D) {
1351 return isa<UsingShadowDecl>(D) ||
1352 isa<UnresolvedUsingTypenameDecl>(D) ||
1353 isa<UnresolvedUsingValueDecl>(D);
1356 /// Removes using shadow declarations from the lookup results.
1357 static void RemoveUsingDecls(LookupResult &R) {
1358 LookupResult::Filter F = R.makeFilter();
1360 if (isUsingDecl(F.next()))
1366 /// \brief Check for this common pattern:
1369 /// S(const S&); // DO NOT IMPLEMENT
1370 /// void operator=(const S&); // DO NOT IMPLEMENT
1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374 // FIXME: Should check for private access too but access is set after we get
1376 if (D->doesThisDeclarationHaveABody())
1379 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380 return CD->isCopyConstructor();
1381 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382 return Method->isCopyAssignmentOperator();
1386 // We need this to handle
1389 // void *foo() { return 0; }
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399 const DeclContext *DC = D->getDeclContext();
1400 while (!DC->isTranslationUnit()) {
1401 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402 if (!RD->hasNameForLinkage())
1405 DC = DC->getParent();
1408 return !D->isExternallyVisible();
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414 if (S.TUKind != TU_Complete)
1416 return S.SourceMgr.isInMainFile(Loc);
1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1422 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1425 // Ignore all entities declared within templates, and out-of-line definitions
1426 // of members of class templates.
1427 if (D->getDeclContext()->isDependentContext() ||
1428 D->getLexicalDeclContext()->isDependentContext())
1431 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1435 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1439 // 'static inline' functions are defined in headers; don't warn.
1440 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1444 if (FD->doesThisDeclarationHaveABody() &&
1445 Context.DeclMustBeEmitted(FD))
1447 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448 // Constants and utility variables are defined in headers with internal
1449 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1451 if (!isMainFileLoc(*this, VD->getLocation()))
1454 if (Context.DeclMustBeEmitted(VD))
1457 if (VD->isStaticDataMember() &&
1458 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1461 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1467 // Only warn for unused decls internal to the translation unit.
1468 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469 // for inline functions defined in the main source file, for instance.
1470 return mightHaveNonExternalLinkage(D);
1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478 const FunctionDecl *First = FD->getFirstDecl();
1479 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480 return; // First should already be in the vector.
1483 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484 const VarDecl *First = VD->getFirstDecl();
1485 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486 return; // First should already be in the vector.
1489 if (ShouldWarnIfUnusedFileScopedDecl(D))
1490 UnusedFileScopedDecls.push_back(D);
1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494 if (D->isInvalidDecl())
1497 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498 D->hasAttr<ObjCPreciseLifetimeAttr>())
1501 if (isa<LabelDecl>(D))
1504 // Except for labels, we only care about unused decls that are local to
1506 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508 // For dependent types, the diagnostic is deferred.
1510 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511 if (!WithinFunction)
1514 if (isa<TypedefNameDecl>(D))
1517 // White-list anything that isn't a local variable.
1518 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1521 // Types of valid local variables should be complete, so this should succeed.
1522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1524 // White-list anything with an __attribute__((unused)) type.
1525 QualType Ty = VD->getType();
1527 // Only look at the outermost level of typedef.
1528 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529 if (TT->getDecl()->hasAttr<UnusedAttr>())
1533 // If we failed to complete the type for some reason, or if the type is
1534 // dependent, don't diagnose the variable.
1535 if (Ty->isIncompleteType() || Ty->isDependentType())
1538 if (const TagType *TT = Ty->getAs<TagType>()) {
1539 const TagDecl *Tag = TT->getDecl();
1540 if (Tag->hasAttr<UnusedAttr>())
1543 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1544 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1547 if (const Expr *Init = VD->getInit()) {
1548 if (const ExprWithCleanups *Cleanups =
1549 dyn_cast<ExprWithCleanups>(Init))
1550 Init = Cleanups->getSubExpr();
1551 const CXXConstructExpr *Construct =
1552 dyn_cast<CXXConstructExpr>(Init);
1553 if (Construct && !Construct->isElidable()) {
1554 CXXConstructorDecl *CD = Construct->getConstructor();
1555 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1562 // TODO: __attribute__((unused)) templates?
1568 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1570 if (isa<LabelDecl>(D)) {
1571 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1572 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1573 if (AfterColon.isInvalid())
1575 Hint = FixItHint::CreateRemoval(CharSourceRange::
1576 getCharRange(D->getLocStart(), AfterColon));
1580 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1581 if (D->getTypeForDecl()->isDependentType())
1584 for (auto *TmpD : D->decls()) {
1585 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1586 DiagnoseUnusedDecl(T);
1587 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1588 DiagnoseUnusedNestedTypedefs(R);
1592 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1593 /// unless they are marked attr(unused).
1594 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1595 if (!ShouldDiagnoseUnusedDecl(D))
1598 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1599 // typedefs can be referenced later on, so the diagnostics are emitted
1600 // at end-of-translation-unit.
1601 UnusedLocalTypedefNameCandidates.insert(TD);
1606 GenerateFixForUnusedDecl(D, Context, Hint);
1609 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1610 DiagID = diag::warn_unused_exception_param;
1611 else if (isa<LabelDecl>(D))
1612 DiagID = diag::warn_unused_label;
1614 DiagID = diag::warn_unused_variable;
1616 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1619 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1620 // Verify that we have no forward references left. If so, there was a goto
1621 // or address of a label taken, but no definition of it. Label fwd
1622 // definitions are indicated with a null substmt which is also not a resolved
1623 // MS inline assembly label name.
1624 bool Diagnose = false;
1625 if (L->isMSAsmLabel())
1626 Diagnose = !L->isResolvedMSAsmLabel();
1628 Diagnose = L->getStmt() == nullptr;
1630 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1633 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1634 S->mergeNRVOIntoParent();
1636 if (S->decl_empty()) return;
1637 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1638 "Scope shouldn't contain decls!");
1640 for (auto *TmpD : S->decls()) {
1641 assert(TmpD && "This decl didn't get pushed??");
1643 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1644 NamedDecl *D = cast<NamedDecl>(TmpD);
1646 if (!D->getDeclName()) continue;
1648 // Diagnose unused variables in this scope.
1649 if (!S->hasUnrecoverableErrorOccurred()) {
1650 DiagnoseUnusedDecl(D);
1651 if (const auto *RD = dyn_cast<RecordDecl>(D))
1652 DiagnoseUnusedNestedTypedefs(RD);
1655 // If this was a forward reference to a label, verify it was defined.
1656 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1657 CheckPoppedLabel(LD, *this);
1659 // Remove this name from our lexical scope, and warn on it if we haven't
1661 IdResolver.RemoveDecl(D);
1662 auto ShadowI = ShadowingDecls.find(D);
1663 if (ShadowI != ShadowingDecls.end()) {
1664 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1665 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1666 << D << FD << FD->getParent();
1667 Diag(FD->getLocation(), diag::note_previous_declaration);
1669 ShadowingDecls.erase(ShadowI);
1674 /// \brief Look for an Objective-C class in the translation unit.
1676 /// \param Id The name of the Objective-C class we're looking for. If
1677 /// typo-correction fixes this name, the Id will be updated
1678 /// to the fixed name.
1680 /// \param IdLoc The location of the name in the translation unit.
1682 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1683 /// if there is no class with the given name.
1685 /// \returns The declaration of the named Objective-C class, or NULL if the
1686 /// class could not be found.
1687 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1688 SourceLocation IdLoc,
1689 bool DoTypoCorrection) {
1690 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1691 // creation from this context.
1692 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1694 if (!IDecl && DoTypoCorrection) {
1695 // Perform typo correction at the given location, but only if we
1696 // find an Objective-C class name.
1697 if (TypoCorrection C = CorrectTypo(
1698 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1699 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1700 CTK_ErrorRecovery)) {
1701 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1702 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1703 Id = IDecl->getIdentifier();
1706 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1707 // This routine must always return a class definition, if any.
1708 if (Def && Def->getDefinition())
1709 Def = Def->getDefinition();
1713 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1714 /// from S, where a non-field would be declared. This routine copes
1715 /// with the difference between C and C++ scoping rules in structs and
1716 /// unions. For example, the following code is well-formed in C but
1717 /// ill-formed in C++:
1723 /// void test_S6() {
1728 /// For the declaration of BAR, this routine will return a different
1729 /// scope. The scope S will be the scope of the unnamed enumeration
1730 /// within S6. In C++, this routine will return the scope associated
1731 /// with S6, because the enumeration's scope is a transparent
1732 /// context but structures can contain non-field names. In C, this
1733 /// routine will return the translation unit scope, since the
1734 /// enumeration's scope is a transparent context and structures cannot
1735 /// contain non-field names.
1736 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1737 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1738 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1739 (S->isClassScope() && !getLangOpts().CPlusPlus))
1744 /// \brief Looks up the declaration of "struct objc_super" and
1745 /// saves it for later use in building builtin declaration of
1746 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1747 /// pre-existing declaration exists no action takes place.
1748 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1749 IdentifierInfo *II) {
1750 if (!II->isStr("objc_msgSendSuper"))
1752 ASTContext &Context = ThisSema.Context;
1754 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1755 SourceLocation(), Sema::LookupTagName);
1756 ThisSema.LookupName(Result, S);
1757 if (Result.getResultKind() == LookupResult::Found)
1758 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1759 Context.setObjCSuperType(Context.getTagDeclType(TD));
1762 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1764 case ASTContext::GE_None:
1766 case ASTContext::GE_Missing_stdio:
1768 case ASTContext::GE_Missing_setjmp:
1770 case ASTContext::GE_Missing_ucontext:
1771 return "ucontext.h";
1773 llvm_unreachable("unhandled error kind");
1776 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1777 /// file scope. lazily create a decl for it. ForRedeclaration is true
1778 /// if we're creating this built-in in anticipation of redeclaring the
1780 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1781 Scope *S, bool ForRedeclaration,
1782 SourceLocation Loc) {
1783 LookupPredefedObjCSuperType(*this, S, II);
1785 ASTContext::GetBuiltinTypeError Error;
1786 QualType R = Context.GetBuiltinType(ID, Error);
1788 if (ForRedeclaration)
1789 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1790 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1794 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1795 Diag(Loc, diag::ext_implicit_lib_function_decl)
1796 << Context.BuiltinInfo.getName(ID) << R;
1797 if (Context.BuiltinInfo.getHeaderName(ID) &&
1798 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1799 Diag(Loc, diag::note_include_header_or_declare)
1800 << Context.BuiltinInfo.getHeaderName(ID)
1801 << Context.BuiltinInfo.getName(ID);
1807 DeclContext *Parent = Context.getTranslationUnitDecl();
1808 if (getLangOpts().CPlusPlus) {
1809 LinkageSpecDecl *CLinkageDecl =
1810 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1811 LinkageSpecDecl::lang_c, false);
1812 CLinkageDecl->setImplicit();
1813 Parent->addDecl(CLinkageDecl);
1814 Parent = CLinkageDecl;
1817 FunctionDecl *New = FunctionDecl::Create(Context,
1819 Loc, Loc, II, R, /*TInfo=*/nullptr,
1822 R->isFunctionProtoType());
1825 // Create Decl objects for each parameter, adding them to the
1827 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1828 SmallVector<ParmVarDecl*, 16> Params;
1829 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1831 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1832 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1834 parm->setScopeInfo(0, i);
1835 Params.push_back(parm);
1837 New->setParams(Params);
1840 AddKnownFunctionAttributes(New);
1841 RegisterLocallyScopedExternCDecl(New, S);
1843 // TUScope is the translation-unit scope to insert this function into.
1844 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1845 // relate Scopes to DeclContexts, and probably eliminate CurContext
1846 // entirely, but we're not there yet.
1847 DeclContext *SavedContext = CurContext;
1848 CurContext = Parent;
1849 PushOnScopeChains(New, TUScope);
1850 CurContext = SavedContext;
1854 /// Typedef declarations don't have linkage, but they still denote the same
1855 /// entity if their types are the same.
1856 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1858 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1859 TypedefNameDecl *Decl,
1860 LookupResult &Previous) {
1861 // This is only interesting when modules are enabled.
1862 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1865 // Empty sets are uninteresting.
1866 if (Previous.empty())
1869 LookupResult::Filter Filter = Previous.makeFilter();
1870 while (Filter.hasNext()) {
1871 NamedDecl *Old = Filter.next();
1873 // Non-hidden declarations are never ignored.
1874 if (S.isVisible(Old))
1877 // Declarations of the same entity are not ignored, even if they have
1878 // different linkages.
1879 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1880 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1881 Decl->getUnderlyingType()))
1884 // If both declarations give a tag declaration a typedef name for linkage
1885 // purposes, then they declare the same entity.
1886 if (S.getLangOpts().CPlusPlus &&
1887 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1888 Decl->getAnonDeclWithTypedefName())
1898 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1900 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1901 OldType = OldTypedef->getUnderlyingType();
1903 OldType = Context.getTypeDeclType(Old);
1904 QualType NewType = New->getUnderlyingType();
1906 if (NewType->isVariablyModifiedType()) {
1907 // Must not redefine a typedef with a variably-modified type.
1908 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1909 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1911 if (Old->getLocation().isValid())
1912 Diag(Old->getLocation(), diag::note_previous_definition);
1913 New->setInvalidDecl();
1917 if (OldType != NewType &&
1918 !OldType->isDependentType() &&
1919 !NewType->isDependentType() &&
1920 !Context.hasSameType(OldType, NewType)) {
1921 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1922 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1923 << Kind << NewType << OldType;
1924 if (Old->getLocation().isValid())
1925 Diag(Old->getLocation(), diag::note_previous_definition);
1926 New->setInvalidDecl();
1932 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1933 /// same name and scope as a previous declaration 'Old'. Figure out
1934 /// how to resolve this situation, merging decls or emitting
1935 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1937 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1938 LookupResult &OldDecls) {
1939 // If the new decl is known invalid already, don't bother doing any
1941 if (New->isInvalidDecl()) return;
1943 // Allow multiple definitions for ObjC built-in typedefs.
1944 // FIXME: Verify the underlying types are equivalent!
1945 if (getLangOpts().ObjC1) {
1946 const IdentifierInfo *TypeID = New->getIdentifier();
1947 switch (TypeID->getLength()) {
1951 if (!TypeID->isStr("id"))
1953 QualType T = New->getUnderlyingType();
1954 if (!T->isPointerType())
1956 if (!T->isVoidPointerType()) {
1957 QualType PT = T->getAs<PointerType>()->getPointeeType();
1958 if (!PT->isStructureType())
1961 Context.setObjCIdRedefinitionType(T);
1962 // Install the built-in type for 'id', ignoring the current definition.
1963 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1967 if (!TypeID->isStr("Class"))
1969 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1970 // Install the built-in type for 'Class', ignoring the current definition.
1971 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1974 if (!TypeID->isStr("SEL"))
1976 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1977 // Install the built-in type for 'SEL', ignoring the current definition.
1978 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1981 // Fall through - the typedef name was not a builtin type.
1984 // Verify the old decl was also a type.
1985 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1987 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1988 << New->getDeclName();
1990 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1991 if (OldD->getLocation().isValid())
1992 Diag(OldD->getLocation(), diag::note_previous_definition);
1994 return New->setInvalidDecl();
1997 // If the old declaration is invalid, just give up here.
1998 if (Old->isInvalidDecl())
1999 return New->setInvalidDecl();
2001 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2002 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2003 auto *NewTag = New->getAnonDeclWithTypedefName();
2004 NamedDecl *Hidden = nullptr;
2005 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2006 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2007 !hasVisibleDefinition(OldTag, &Hidden)) {
2008 // There is a definition of this tag, but it is not visible. Use it
2009 // instead of our tag.
2010 New->setTypeForDecl(OldTD->getTypeForDecl());
2011 if (OldTD->isModed())
2012 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2013 OldTD->getUnderlyingType());
2015 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2017 // Make the old tag definition visible.
2018 makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2020 // If this was an unscoped enumeration, yank all of its enumerators
2021 // out of the scope.
2022 if (isa<EnumDecl>(NewTag)) {
2023 Scope *EnumScope = getNonFieldDeclScope(S);
2024 for (auto *D : NewTag->decls()) {
2025 auto *ED = cast<EnumConstantDecl>(D);
2026 assert(EnumScope->isDeclScope(ED));
2027 EnumScope->RemoveDecl(ED);
2028 IdResolver.RemoveDecl(ED);
2029 ED->getLexicalDeclContext()->removeDecl(ED);
2035 // If the typedef types are not identical, reject them in all languages and
2036 // with any extensions enabled.
2037 if (isIncompatibleTypedef(Old, New))
2040 // The types match. Link up the redeclaration chain and merge attributes if
2041 // the old declaration was a typedef.
2042 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2043 New->setPreviousDecl(Typedef);
2044 mergeDeclAttributes(New, Old);
2047 if (getLangOpts().MicrosoftExt)
2050 if (getLangOpts().CPlusPlus) {
2051 // C++ [dcl.typedef]p2:
2052 // In a given non-class scope, a typedef specifier can be used to
2053 // redefine the name of any type declared in that scope to refer
2054 // to the type to which it already refers.
2055 if (!isa<CXXRecordDecl>(CurContext))
2058 // C++0x [dcl.typedef]p4:
2059 // In a given class scope, a typedef specifier can be used to redefine
2060 // any class-name declared in that scope that is not also a typedef-name
2061 // to refer to the type to which it already refers.
2063 // This wording came in via DR424, which was a correction to the
2064 // wording in DR56, which accidentally banned code like:
2067 // typedef struct A { } A;
2070 // in the C++03 standard. We implement the C++0x semantics, which
2071 // allow the above but disallow
2078 // since that was the intent of DR56.
2079 if (!isa<TypedefNameDecl>(Old))
2082 Diag(New->getLocation(), diag::err_redefinition)
2083 << New->getDeclName();
2084 Diag(Old->getLocation(), diag::note_previous_definition);
2085 return New->setInvalidDecl();
2088 // Modules always permit redefinition of typedefs, as does C11.
2089 if (getLangOpts().Modules || getLangOpts().C11)
2092 // If we have a redefinition of a typedef in C, emit a warning. This warning
2093 // is normally mapped to an error, but can be controlled with
2094 // -Wtypedef-redefinition. If either the original or the redefinition is
2095 // in a system header, don't emit this for compatibility with GCC.
2096 if (getDiagnostics().getSuppressSystemWarnings() &&
2097 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2098 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2101 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2102 << New->getDeclName();
2103 Diag(Old->getLocation(), diag::note_previous_definition);
2106 /// DeclhasAttr - returns true if decl Declaration already has the target
2108 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2109 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2110 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2111 for (const auto *i : D->attrs())
2112 if (i->getKind() == A->getKind()) {
2114 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2118 // FIXME: Don't hardcode this check
2119 if (OA && isa<OwnershipAttr>(i))
2120 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2127 static bool isAttributeTargetADefinition(Decl *D) {
2128 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2129 return VD->isThisDeclarationADefinition();
2130 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2131 return TD->isCompleteDefinition() || TD->isBeingDefined();
2135 /// Merge alignment attributes from \p Old to \p New, taking into account the
2136 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2138 /// \return \c true if any attributes were added to \p New.
2139 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2140 // Look for alignas attributes on Old, and pick out whichever attribute
2141 // specifies the strictest alignment requirement.
2142 AlignedAttr *OldAlignasAttr = nullptr;
2143 AlignedAttr *OldStrictestAlignAttr = nullptr;
2144 unsigned OldAlign = 0;
2145 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2146 // FIXME: We have no way of representing inherited dependent alignments
2148 // template<int A, int B> struct alignas(A) X;
2149 // template<int A, int B> struct alignas(B) X {};
2150 // For now, we just ignore any alignas attributes which are not on the
2151 // definition in such a case.
2152 if (I->isAlignmentDependent())
2158 unsigned Align = I->getAlignment(S.Context);
2159 if (Align > OldAlign) {
2161 OldStrictestAlignAttr = I;
2165 // Look for alignas attributes on New.
2166 AlignedAttr *NewAlignasAttr = nullptr;
2167 unsigned NewAlign = 0;
2168 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2169 if (I->isAlignmentDependent())
2175 unsigned Align = I->getAlignment(S.Context);
2176 if (Align > NewAlign)
2180 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2181 // Both declarations have 'alignas' attributes. We require them to match.
2182 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2183 // fall short. (If two declarations both have alignas, they must both match
2184 // every definition, and so must match each other if there is a definition.)
2186 // If either declaration only contains 'alignas(0)' specifiers, then it
2187 // specifies the natural alignment for the type.
2188 if (OldAlign == 0 || NewAlign == 0) {
2190 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2193 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2196 OldAlign = S.Context.getTypeAlign(Ty);
2198 NewAlign = S.Context.getTypeAlign(Ty);
2201 if (OldAlign != NewAlign) {
2202 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2203 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2204 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2205 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2209 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2210 // C++11 [dcl.align]p6:
2211 // if any declaration of an entity has an alignment-specifier,
2212 // every defining declaration of that entity shall specify an
2213 // equivalent alignment.
2215 // If the definition of an object does not have an alignment
2216 // specifier, any other declaration of that object shall also
2217 // have no alignment specifier.
2218 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2220 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2224 bool AnyAdded = false;
2226 // Ensure we have an attribute representing the strictest alignment.
2227 if (OldAlign > NewAlign) {
2228 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2229 Clone->setInherited(true);
2230 New->addAttr(Clone);
2234 // Ensure we have an alignas attribute if the old declaration had one.
2235 if (OldAlignasAttr && !NewAlignasAttr &&
2236 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2237 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2238 Clone->setInherited(true);
2239 New->addAttr(Clone);
2246 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2247 const InheritableAttr *Attr,
2248 Sema::AvailabilityMergeKind AMK) {
2249 InheritableAttr *NewAttr = nullptr;
2250 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2251 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2252 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2253 AA->isImplicit(), AA->getIntroduced(),
2254 AA->getDeprecated(),
2255 AA->getObsoleted(), AA->getUnavailable(),
2256 AA->getMessage(), AA->getStrict(),
2257 AA->getReplacement(), AMK,
2258 AttrSpellingListIndex);
2259 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2260 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2261 AttrSpellingListIndex);
2262 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2263 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2264 AttrSpellingListIndex);
2265 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2266 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2267 AttrSpellingListIndex);
2268 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2269 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2270 AttrSpellingListIndex);
2271 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2272 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2273 FA->getFormatIdx(), FA->getFirstArg(),
2274 AttrSpellingListIndex);
2275 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2276 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2277 AttrSpellingListIndex);
2278 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2279 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2280 AttrSpellingListIndex,
2281 IA->getSemanticSpelling());
2282 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2283 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2284 &S.Context.Idents.get(AA->getSpelling()),
2285 AttrSpellingListIndex);
2286 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2287 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2288 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2289 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2290 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2291 NewAttr = S.mergeInternalLinkageAttr(
2292 D, InternalLinkageA->getRange(),
2293 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2294 AttrSpellingListIndex);
2295 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2296 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2297 &S.Context.Idents.get(CommonA->getSpelling()),
2298 AttrSpellingListIndex);
2299 else if (isa<AlignedAttr>(Attr))
2300 // AlignedAttrs are handled separately, because we need to handle all
2301 // such attributes on a declaration at the same time.
2303 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2304 (AMK == Sema::AMK_Override ||
2305 AMK == Sema::AMK_ProtocolImplementation))
2307 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2308 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2311 NewAttr->setInherited(true);
2312 D->addAttr(NewAttr);
2313 if (isa<MSInheritanceAttr>(NewAttr))
2314 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2321 static const Decl *getDefinition(const Decl *D) {
2322 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2323 return TD->getDefinition();
2324 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2325 const VarDecl *Def = VD->getDefinition();
2328 return VD->getActingDefinition();
2330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2331 return FD->getDefinition();
2335 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2336 for (const auto *Attribute : D->attrs())
2337 if (Attribute->getKind() == Kind)
2342 /// checkNewAttributesAfterDef - If we already have a definition, check that
2343 /// there are no new attributes in this declaration.
2344 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2345 if (!New->hasAttrs())
2348 const Decl *Def = getDefinition(Old);
2349 if (!Def || Def == New)
2352 AttrVec &NewAttributes = New->getAttrs();
2353 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2354 const Attr *NewAttribute = NewAttributes[I];
2356 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2357 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2358 Sema::SkipBodyInfo SkipBody;
2359 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2361 // If we're skipping this definition, drop the "alias" attribute.
2362 if (SkipBody.ShouldSkip) {
2363 NewAttributes.erase(NewAttributes.begin() + I);
2368 VarDecl *VD = cast<VarDecl>(New);
2369 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2370 VarDecl::TentativeDefinition
2371 ? diag::err_alias_after_tentative
2372 : diag::err_redefinition;
2373 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2374 S.Diag(Def->getLocation(), diag::note_previous_definition);
2375 VD->setInvalidDecl();
2381 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2382 // Tentative definitions are only interesting for the alias check above.
2383 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2389 if (hasAttribute(Def, NewAttribute->getKind())) {
2391 continue; // regular attr merging will take care of validating this.
2394 if (isa<C11NoReturnAttr>(NewAttribute)) {
2395 // C's _Noreturn is allowed to be added to a function after it is defined.
2398 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2399 if (AA->isAlignas()) {
2400 // C++11 [dcl.align]p6:
2401 // if any declaration of an entity has an alignment-specifier,
2402 // every defining declaration of that entity shall specify an
2403 // equivalent alignment.
2405 // If the definition of an object does not have an alignment
2406 // specifier, any other declaration of that object shall also
2407 // have no alignment specifier.
2408 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2410 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2412 NewAttributes.erase(NewAttributes.begin() + I);
2418 S.Diag(NewAttribute->getLocation(),
2419 diag::warn_attribute_precede_definition);
2420 S.Diag(Def->getLocation(), diag::note_previous_definition);
2421 NewAttributes.erase(NewAttributes.begin() + I);
2426 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2427 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2428 AvailabilityMergeKind AMK) {
2429 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2430 UsedAttr *NewAttr = OldAttr->clone(Context);
2431 NewAttr->setInherited(true);
2432 New->addAttr(NewAttr);
2435 if (!Old->hasAttrs() && !New->hasAttrs())
2438 // Attributes declared post-definition are currently ignored.
2439 checkNewAttributesAfterDef(*this, New, Old);
2441 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2442 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2443 if (OldA->getLabel() != NewA->getLabel()) {
2444 // This redeclaration changes __asm__ label.
2445 Diag(New->getLocation(), diag::err_different_asm_label);
2446 Diag(OldA->getLocation(), diag::note_previous_declaration);
2448 } else if (Old->isUsed()) {
2449 // This redeclaration adds an __asm__ label to a declaration that has
2450 // already been ODR-used.
2451 Diag(New->getLocation(), diag::err_late_asm_label_name)
2452 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2456 // Re-declaration cannot add abi_tag's.
2457 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2458 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2459 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2460 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2461 NewTag) == OldAbiTagAttr->tags_end()) {
2462 Diag(NewAbiTagAttr->getLocation(),
2463 diag::err_new_abi_tag_on_redeclaration)
2465 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2469 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2470 Diag(Old->getLocation(), diag::note_previous_declaration);
2474 if (!Old->hasAttrs())
2477 bool foundAny = New->hasAttrs();
2479 // Ensure that any moving of objects within the allocated map is done before
2481 if (!foundAny) New->setAttrs(AttrVec());
2483 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2484 // Ignore deprecated/unavailable/availability attributes if requested.
2485 AvailabilityMergeKind LocalAMK = AMK_None;
2486 if (isa<DeprecatedAttr>(I) ||
2487 isa<UnavailableAttr>(I) ||
2488 isa<AvailabilityAttr>(I)) {
2493 case AMK_Redeclaration:
2495 case AMK_ProtocolImplementation:
2502 if (isa<UsedAttr>(I))
2505 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2509 if (mergeAlignedAttrs(*this, New, Old))
2512 if (!foundAny) New->dropAttrs();
2515 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2517 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2518 const ParmVarDecl *oldDecl,
2520 // C++11 [dcl.attr.depend]p2:
2521 // The first declaration of a function shall specify the
2522 // carries_dependency attribute for its declarator-id if any declaration
2523 // of the function specifies the carries_dependency attribute.
2524 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2525 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2526 S.Diag(CDA->getLocation(),
2527 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2528 // Find the first declaration of the parameter.
2529 // FIXME: Should we build redeclaration chains for function parameters?
2530 const FunctionDecl *FirstFD =
2531 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2532 const ParmVarDecl *FirstVD =
2533 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2534 S.Diag(FirstVD->getLocation(),
2535 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2538 if (!oldDecl->hasAttrs())
2541 bool foundAny = newDecl->hasAttrs();
2543 // Ensure that any moving of objects within the allocated map is
2544 // done before we process them.
2545 if (!foundAny) newDecl->setAttrs(AttrVec());
2547 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2548 if (!DeclHasAttr(newDecl, I)) {
2549 InheritableAttr *newAttr =
2550 cast<InheritableParamAttr>(I->clone(S.Context));
2551 newAttr->setInherited(true);
2552 newDecl->addAttr(newAttr);
2557 if (!foundAny) newDecl->dropAttrs();
2560 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2561 const ParmVarDecl *OldParam,
2563 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2564 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2565 if (*Oldnullability != *Newnullability) {
2566 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2567 << DiagNullabilityKind(
2569 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2571 << DiagNullabilityKind(
2573 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2575 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2578 QualType NewT = NewParam->getType();
2579 NewT = S.Context.getAttributedType(
2580 AttributedType::getNullabilityAttrKind(*Oldnullability),
2582 NewParam->setType(NewT);
2589 /// Used in MergeFunctionDecl to keep track of function parameters in
2591 struct GNUCompatibleParamWarning {
2592 ParmVarDecl *OldParm;
2593 ParmVarDecl *NewParm;
2594 QualType PromotedType;
2597 } // end anonymous namespace
2599 /// getSpecialMember - get the special member enum for a method.
2600 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2601 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2602 if (Ctor->isDefaultConstructor())
2603 return Sema::CXXDefaultConstructor;
2605 if (Ctor->isCopyConstructor())
2606 return Sema::CXXCopyConstructor;
2608 if (Ctor->isMoveConstructor())
2609 return Sema::CXXMoveConstructor;
2610 } else if (isa<CXXDestructorDecl>(MD)) {
2611 return Sema::CXXDestructor;
2612 } else if (MD->isCopyAssignmentOperator()) {
2613 return Sema::CXXCopyAssignment;
2614 } else if (MD->isMoveAssignmentOperator()) {
2615 return Sema::CXXMoveAssignment;
2618 return Sema::CXXInvalid;
2621 // Determine whether the previous declaration was a definition, implicit
2622 // declaration, or a declaration.
2623 template <typename T>
2624 static std::pair<diag::kind, SourceLocation>
2625 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2626 diag::kind PrevDiag;
2627 SourceLocation OldLocation = Old->getLocation();
2628 if (Old->isThisDeclarationADefinition())
2629 PrevDiag = diag::note_previous_definition;
2630 else if (Old->isImplicit()) {
2631 PrevDiag = diag::note_previous_implicit_declaration;
2632 if (OldLocation.isInvalid())
2633 OldLocation = New->getLocation();
2635 PrevDiag = diag::note_previous_declaration;
2636 return std::make_pair(PrevDiag, OldLocation);
2639 /// canRedefineFunction - checks if a function can be redefined. Currently,
2640 /// only extern inline functions can be redefined, and even then only in
2642 static bool canRedefineFunction(const FunctionDecl *FD,
2643 const LangOptions& LangOpts) {
2644 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2645 !LangOpts.CPlusPlus &&
2646 FD->isInlineSpecified() &&
2647 FD->getStorageClass() == SC_Extern);
2650 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2651 const AttributedType *AT = T->getAs<AttributedType>();
2652 while (AT && !AT->isCallingConv())
2653 AT = AT->getModifiedType()->getAs<AttributedType>();
2657 template <typename T>
2658 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2659 const DeclContext *DC = Old->getDeclContext();
2663 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2664 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2666 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2671 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2672 static bool isExternC(VarTemplateDecl *) { return false; }
2674 /// \brief Check whether a redeclaration of an entity introduced by a
2675 /// using-declaration is valid, given that we know it's not an overload
2676 /// (nor a hidden tag declaration).
2677 template<typename ExpectedDecl>
2678 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2679 ExpectedDecl *New) {
2680 // C++11 [basic.scope.declarative]p4:
2681 // Given a set of declarations in a single declarative region, each of
2682 // which specifies the same unqualified name,
2683 // -- they shall all refer to the same entity, or all refer to functions
2684 // and function templates; or
2685 // -- exactly one declaration shall declare a class name or enumeration
2686 // name that is not a typedef name and the other declarations shall all
2687 // refer to the same variable or enumerator, or all refer to functions
2688 // and function templates; in this case the class name or enumeration
2689 // name is hidden (3.3.10).
2691 // C++11 [namespace.udecl]p14:
2692 // If a function declaration in namespace scope or block scope has the
2693 // same name and the same parameter-type-list as a function introduced
2694 // by a using-declaration, and the declarations do not declare the same
2695 // function, the program is ill-formed.
2697 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2699 !Old->getDeclContext()->getRedeclContext()->Equals(
2700 New->getDeclContext()->getRedeclContext()) &&
2701 !(isExternC(Old) && isExternC(New)))
2705 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2706 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2707 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2713 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2714 const FunctionDecl *B) {
2715 assert(A->getNumParams() == B->getNumParams());
2717 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2718 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2719 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2722 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2725 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2728 /// MergeFunctionDecl - We just parsed a function 'New' from
2729 /// declarator D which has the same name and scope as a previous
2730 /// declaration 'Old'. Figure out how to resolve this situation,
2731 /// merging decls or emitting diagnostics as appropriate.
2733 /// In C++, New and Old must be declarations that are not
2734 /// overloaded. Use IsOverload to determine whether New and Old are
2735 /// overloaded, and to select the Old declaration that New should be
2738 /// Returns true if there was an error, false otherwise.
2739 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2740 Scope *S, bool MergeTypeWithOld) {
2741 // Verify the old decl was also a function.
2742 FunctionDecl *Old = OldD->getAsFunction();
2744 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2745 if (New->getFriendObjectKind()) {
2746 Diag(New->getLocation(), diag::err_using_decl_friend);
2747 Diag(Shadow->getTargetDecl()->getLocation(),
2748 diag::note_using_decl_target);
2749 Diag(Shadow->getUsingDecl()->getLocation(),
2750 diag::note_using_decl) << 0;
2754 // Check whether the two declarations might declare the same function.
2755 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2757 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2759 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2760 << New->getDeclName();
2761 Diag(OldD->getLocation(), diag::note_previous_definition);
2766 // If the old declaration is invalid, just give up here.
2767 if (Old->isInvalidDecl())
2770 diag::kind PrevDiag;
2771 SourceLocation OldLocation;
2772 std::tie(PrevDiag, OldLocation) =
2773 getNoteDiagForInvalidRedeclaration(Old, New);
2775 // Don't complain about this if we're in GNU89 mode and the old function
2776 // is an extern inline function.
2777 // Don't complain about specializations. They are not supposed to have
2779 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2780 New->getStorageClass() == SC_Static &&
2781 Old->hasExternalFormalLinkage() &&
2782 !New->getTemplateSpecializationInfo() &&
2783 !canRedefineFunction(Old, getLangOpts())) {
2784 if (getLangOpts().MicrosoftExt) {
2785 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2786 Diag(OldLocation, PrevDiag);
2788 Diag(New->getLocation(), diag::err_static_non_static) << New;
2789 Diag(OldLocation, PrevDiag);
2794 if (New->hasAttr<InternalLinkageAttr>() &&
2795 !Old->hasAttr<InternalLinkageAttr>()) {
2796 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2797 << New->getDeclName();
2798 Diag(Old->getLocation(), diag::note_previous_definition);
2799 New->dropAttr<InternalLinkageAttr>();
2802 // If a function is first declared with a calling convention, but is later
2803 // declared or defined without one, all following decls assume the calling
2804 // convention of the first.
2806 // It's OK if a function is first declared without a calling convention,
2807 // but is later declared or defined with the default calling convention.
2809 // To test if either decl has an explicit calling convention, we look for
2810 // AttributedType sugar nodes on the type as written. If they are missing or
2811 // were canonicalized away, we assume the calling convention was implicit.
2813 // Note also that we DO NOT return at this point, because we still have
2814 // other tests to run.
2815 QualType OldQType = Context.getCanonicalType(Old->getType());
2816 QualType NewQType = Context.getCanonicalType(New->getType());
2817 const FunctionType *OldType = cast<FunctionType>(OldQType);
2818 const FunctionType *NewType = cast<FunctionType>(NewQType);
2819 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2820 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2821 bool RequiresAdjustment = false;
2823 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2824 FunctionDecl *First = Old->getFirstDecl();
2825 const FunctionType *FT =
2826 First->getType().getCanonicalType()->castAs<FunctionType>();
2827 FunctionType::ExtInfo FI = FT->getExtInfo();
2828 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2829 if (!NewCCExplicit) {
2830 // Inherit the CC from the previous declaration if it was specified
2831 // there but not here.
2832 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2833 RequiresAdjustment = true;
2835 // Calling conventions aren't compatible, so complain.
2836 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2837 Diag(New->getLocation(), diag::err_cconv_change)
2838 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2840 << (!FirstCCExplicit ? "" :
2841 FunctionType::getNameForCallConv(FI.getCC()));
2843 // Put the note on the first decl, since it is the one that matters.
2844 Diag(First->getLocation(), diag::note_previous_declaration);
2849 // FIXME: diagnose the other way around?
2850 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2851 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2852 RequiresAdjustment = true;
2855 // Merge regparm attribute.
2856 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2857 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2858 if (NewTypeInfo.getHasRegParm()) {
2859 Diag(New->getLocation(), diag::err_regparm_mismatch)
2860 << NewType->getRegParmType()
2861 << OldType->getRegParmType();
2862 Diag(OldLocation, diag::note_previous_declaration);
2866 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2867 RequiresAdjustment = true;
2870 // Merge ns_returns_retained attribute.
2871 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2872 if (NewTypeInfo.getProducesResult()) {
2873 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2874 Diag(OldLocation, diag::note_previous_declaration);
2878 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2879 RequiresAdjustment = true;
2882 if (RequiresAdjustment) {
2883 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2884 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2885 New->setType(QualType(AdjustedType, 0));
2886 NewQType = Context.getCanonicalType(New->getType());
2887 NewType = cast<FunctionType>(NewQType);
2890 // If this redeclaration makes the function inline, we may need to add it to
2891 // UndefinedButUsed.
2892 if (!Old->isInlined() && New->isInlined() &&
2893 !New->hasAttr<GNUInlineAttr>() &&
2894 !getLangOpts().GNUInline &&
2895 Old->isUsed(false) &&
2896 !Old->isDefined() && !New->isThisDeclarationADefinition())
2897 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2900 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2902 if (New->hasAttr<GNUInlineAttr>() &&
2903 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2904 UndefinedButUsed.erase(Old->getCanonicalDecl());
2907 // If pass_object_size params don't match up perfectly, this isn't a valid
2909 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2910 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2911 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2912 << New->getDeclName();
2913 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2917 if (getLangOpts().CPlusPlus) {
2919 // Certain function declarations cannot be overloaded:
2920 // -- Function declarations that differ only in the return type
2921 // cannot be overloaded.
2923 // Go back to the type source info to compare the declared return types,
2924 // per C++1y [dcl.type.auto]p13:
2925 // Redeclarations or specializations of a function or function template
2926 // with a declared return type that uses a placeholder type shall also
2927 // use that placeholder, not a deduced type.
2928 QualType OldDeclaredReturnType =
2929 (Old->getTypeSourceInfo()
2930 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2931 : OldType)->getReturnType();
2932 QualType NewDeclaredReturnType =
2933 (New->getTypeSourceInfo()
2934 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2935 : NewType)->getReturnType();
2937 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2938 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2939 New->isLocalExternDecl())) {
2940 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2941 OldDeclaredReturnType->isObjCObjectPointerType())
2942 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2943 if (ResQT.isNull()) {
2944 if (New->isCXXClassMember() && New->isOutOfLine())
2945 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2946 << New << New->getReturnTypeSourceRange();
2948 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2949 << New->getReturnTypeSourceRange();
2950 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2951 << Old->getReturnTypeSourceRange();
2958 QualType OldReturnType = OldType->getReturnType();
2959 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2960 if (OldReturnType != NewReturnType) {
2961 // If this function has a deduced return type and has already been
2962 // defined, copy the deduced value from the old declaration.
2963 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2964 if (OldAT && OldAT->isDeduced()) {
2966 SubstAutoType(New->getType(),
2967 OldAT->isDependentType() ? Context.DependentTy
2968 : OldAT->getDeducedType()));
2969 NewQType = Context.getCanonicalType(
2970 SubstAutoType(NewQType,
2971 OldAT->isDependentType() ? Context.DependentTy
2972 : OldAT->getDeducedType()));
2976 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2977 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2978 if (OldMethod && NewMethod) {
2979 // Preserve triviality.
2980 NewMethod->setTrivial(OldMethod->isTrivial());
2982 // MSVC allows explicit template specialization at class scope:
2983 // 2 CXXMethodDecls referring to the same function will be injected.
2984 // We don't want a redeclaration error.
2985 bool IsClassScopeExplicitSpecialization =
2986 OldMethod->isFunctionTemplateSpecialization() &&
2987 NewMethod->isFunctionTemplateSpecialization();
2988 bool isFriend = NewMethod->getFriendObjectKind();
2990 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2991 !IsClassScopeExplicitSpecialization) {
2992 // -- Member function declarations with the same name and the
2993 // same parameter types cannot be overloaded if any of them
2994 // is a static member function declaration.
2995 if (OldMethod->isStatic() != NewMethod->isStatic()) {
2996 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2997 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3001 // C++ [class.mem]p1:
3002 // [...] A member shall not be declared twice in the
3003 // member-specification, except that a nested class or member
3004 // class template can be declared and then later defined.
3005 if (ActiveTemplateInstantiations.empty()) {
3007 if (isa<CXXConstructorDecl>(OldMethod))
3008 NewDiag = diag::err_constructor_redeclared;
3009 else if (isa<CXXDestructorDecl>(NewMethod))
3010 NewDiag = diag::err_destructor_redeclared;
3011 else if (isa<CXXConversionDecl>(NewMethod))
3012 NewDiag = diag::err_conv_function_redeclared;
3014 NewDiag = diag::err_member_redeclared;
3016 Diag(New->getLocation(), NewDiag);
3018 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3019 << New << New->getType();
3021 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3024 // Complain if this is an explicit declaration of a special
3025 // member that was initially declared implicitly.
3027 // As an exception, it's okay to befriend such methods in order
3028 // to permit the implicit constructor/destructor/operator calls.
3029 } else if (OldMethod->isImplicit()) {
3031 NewMethod->setImplicit();
3033 Diag(NewMethod->getLocation(),
3034 diag::err_definition_of_implicitly_declared_member)
3035 << New << getSpecialMember(OldMethod);
3038 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3039 Diag(NewMethod->getLocation(),
3040 diag::err_definition_of_explicitly_defaulted_member)
3041 << getSpecialMember(OldMethod);
3046 // C++11 [dcl.attr.noreturn]p1:
3047 // The first declaration of a function shall specify the noreturn
3048 // attribute if any declaration of that function specifies the noreturn
3050 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3051 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3052 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3053 Diag(Old->getFirstDecl()->getLocation(),
3054 diag::note_noreturn_missing_first_decl);
3057 // C++11 [dcl.attr.depend]p2:
3058 // The first declaration of a function shall specify the
3059 // carries_dependency attribute for its declarator-id if any declaration
3060 // of the function specifies the carries_dependency attribute.
3061 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3062 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3063 Diag(CDA->getLocation(),
3064 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3065 Diag(Old->getFirstDecl()->getLocation(),
3066 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3070 // All declarations for a function shall agree exactly in both the
3071 // return type and the parameter-type-list.
3072 // We also want to respect all the extended bits except noreturn.
3074 // noreturn should now match unless the old type info didn't have it.
3075 QualType OldQTypeForComparison = OldQType;
3076 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3077 assert(OldQType == QualType(OldType, 0));
3078 const FunctionType *OldTypeForComparison
3079 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3080 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3081 assert(OldQTypeForComparison.isCanonical());
3084 if (haveIncompatibleLanguageLinkages(Old, New)) {
3085 // As a special case, retain the language linkage from previous
3086 // declarations of a friend function as an extension.
3088 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3089 // and is useful because there's otherwise no way to specify language
3090 // linkage within class scope.
3092 // Check cautiously as the friend object kind isn't yet complete.
3093 if (New->getFriendObjectKind() != Decl::FOK_None) {
3094 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3095 Diag(OldLocation, PrevDiag);
3097 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3098 Diag(OldLocation, PrevDiag);
3103 if (OldQTypeForComparison == NewQType)
3104 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3106 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3107 New->isLocalExternDecl()) {
3108 // It's OK if we couldn't merge types for a local function declaraton
3109 // if either the old or new type is dependent. We'll merge the types
3110 // when we instantiate the function.
3114 // Fall through for conflicting redeclarations and redefinitions.
3117 // C: Function types need to be compatible, not identical. This handles
3118 // duplicate function decls like "void f(int); void f(enum X);" properly.
3119 if (!getLangOpts().CPlusPlus &&
3120 Context.typesAreCompatible(OldQType, NewQType)) {
3121 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3122 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3123 const FunctionProtoType *OldProto = nullptr;
3124 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3125 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3126 // The old declaration provided a function prototype, but the
3127 // new declaration does not. Merge in the prototype.
3128 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3129 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3131 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3132 OldProto->getExtProtoInfo());
3133 New->setType(NewQType);
3134 New->setHasInheritedPrototype();
3136 // Synthesize parameters with the same types.
3137 SmallVector<ParmVarDecl*, 16> Params;
3138 for (const auto &ParamType : OldProto->param_types()) {
3139 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3140 SourceLocation(), nullptr,
3141 ParamType, /*TInfo=*/nullptr,
3143 Param->setScopeInfo(0, Params.size());
3144 Param->setImplicit();
3145 Params.push_back(Param);
3148 New->setParams(Params);
3151 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3154 // GNU C permits a K&R definition to follow a prototype declaration
3155 // if the declared types of the parameters in the K&R definition
3156 // match the types in the prototype declaration, even when the
3157 // promoted types of the parameters from the K&R definition differ
3158 // from the types in the prototype. GCC then keeps the types from
3161 // If a variadic prototype is followed by a non-variadic K&R definition,
3162 // the K&R definition becomes variadic. This is sort of an edge case, but
3163 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3165 if (!getLangOpts().CPlusPlus &&
3166 Old->hasPrototype() && !New->hasPrototype() &&
3167 New->getType()->getAs<FunctionProtoType>() &&
3168 Old->getNumParams() == New->getNumParams()) {
3169 SmallVector<QualType, 16> ArgTypes;
3170 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3171 const FunctionProtoType *OldProto
3172 = Old->getType()->getAs<FunctionProtoType>();
3173 const FunctionProtoType *NewProto
3174 = New->getType()->getAs<FunctionProtoType>();
3176 // Determine whether this is the GNU C extension.
3177 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3178 NewProto->getReturnType());
3179 bool LooseCompatible = !MergedReturn.isNull();
3180 for (unsigned Idx = 0, End = Old->getNumParams();
3181 LooseCompatible && Idx != End; ++Idx) {
3182 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3183 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3184 if (Context.typesAreCompatible(OldParm->getType(),
3185 NewProto->getParamType(Idx))) {
3186 ArgTypes.push_back(NewParm->getType());
3187 } else if (Context.typesAreCompatible(OldParm->getType(),
3189 /*CompareUnqualified=*/true)) {
3190 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3191 NewProto->getParamType(Idx) };
3192 Warnings.push_back(Warn);
3193 ArgTypes.push_back(NewParm->getType());
3195 LooseCompatible = false;
3198 if (LooseCompatible) {
3199 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3200 Diag(Warnings[Warn].NewParm->getLocation(),
3201 diag::ext_param_promoted_not_compatible_with_prototype)
3202 << Warnings[Warn].PromotedType
3203 << Warnings[Warn].OldParm->getType();
3204 if (Warnings[Warn].OldParm->getLocation().isValid())
3205 Diag(Warnings[Warn].OldParm->getLocation(),
3206 diag::note_previous_declaration);
3209 if (MergeTypeWithOld)
3210 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3211 OldProto->getExtProtoInfo()));
3212 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3215 // Fall through to diagnose conflicting types.
3218 // A function that has already been declared has been redeclared or
3219 // defined with a different type; show an appropriate diagnostic.
3221 // If the previous declaration was an implicitly-generated builtin
3222 // declaration, then at the very least we should use a specialized note.
3224 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3225 // If it's actually a library-defined builtin function like 'malloc'
3226 // or 'printf', just warn about the incompatible redeclaration.
3227 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3228 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3229 Diag(OldLocation, diag::note_previous_builtin_declaration)
3230 << Old << Old->getType();
3232 // If this is a global redeclaration, just forget hereafter
3233 // about the "builtin-ness" of the function.
3235 // Doing this for local extern declarations is problematic. If
3236 // the builtin declaration remains visible, a second invalid
3237 // local declaration will produce a hard error; if it doesn't
3238 // remain visible, a single bogus local redeclaration (which is
3239 // actually only a warning) could break all the downstream code.
3240 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3241 New->getIdentifier()->revertBuiltin();
3246 PrevDiag = diag::note_previous_builtin_declaration;
3249 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3250 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3254 /// \brief Completes the merge of two function declarations that are
3255 /// known to be compatible.
3257 /// This routine handles the merging of attributes and other
3258 /// properties of function declarations from the old declaration to
3259 /// the new declaration, once we know that New is in fact a
3260 /// redeclaration of Old.
3263 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3264 Scope *S, bool MergeTypeWithOld) {
3265 // Merge the attributes
3266 mergeDeclAttributes(New, Old);
3268 // Merge "pure" flag.
3272 // Merge "used" flag.
3273 if (Old->getMostRecentDecl()->isUsed(false))
3276 // Merge attributes from the parameters. These can mismatch with K&R
3278 if (New->getNumParams() == Old->getNumParams())
3279 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3280 ParmVarDecl *NewParam = New->getParamDecl(i);
3281 ParmVarDecl *OldParam = Old->getParamDecl(i);
3282 mergeParamDeclAttributes(NewParam, OldParam, *this);
3283 mergeParamDeclTypes(NewParam, OldParam, *this);
3286 if (getLangOpts().CPlusPlus)
3287 return MergeCXXFunctionDecl(New, Old, S);
3289 // Merge the function types so the we get the composite types for the return
3290 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3292 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3293 if (!Merged.isNull() && MergeTypeWithOld)
3294 New->setType(Merged);
3299 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3300 ObjCMethodDecl *oldMethod) {
3301 // Merge the attributes, including deprecated/unavailable
3302 AvailabilityMergeKind MergeKind =
3303 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3304 ? AMK_ProtocolImplementation
3305 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3308 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3310 // Merge attributes from the parameters.
3311 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3312 oe = oldMethod->param_end();
3313 for (ObjCMethodDecl::param_iterator
3314 ni = newMethod->param_begin(), ne = newMethod->param_end();
3315 ni != ne && oi != oe; ++ni, ++oi)
3316 mergeParamDeclAttributes(*ni, *oi, *this);
3318 CheckObjCMethodOverride(newMethod, oldMethod);
3321 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3322 assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3324 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3325 ? diag::err_redefinition_different_type
3326 : diag::err_redeclaration_different_type)
3327 << New->getDeclName() << New->getType() << Old->getType();
3329 diag::kind PrevDiag;
3330 SourceLocation OldLocation;
3331 std::tie(PrevDiag, OldLocation)
3332 = getNoteDiagForInvalidRedeclaration(Old, New);
3333 S.Diag(OldLocation, PrevDiag);
3334 New->setInvalidDecl();
3337 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3338 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3339 /// emitting diagnostics as appropriate.
3341 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3342 /// to here in AddInitializerToDecl. We can't check them before the initializer
3344 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3345 bool MergeTypeWithOld) {
3346 if (New->isInvalidDecl() || Old->isInvalidDecl())
3350 if (getLangOpts().CPlusPlus) {
3351 if (New->getType()->isUndeducedType()) {
3352 // We don't know what the new type is until the initializer is attached.
3354 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3355 // These could still be something that needs exception specs checked.
3356 return MergeVarDeclExceptionSpecs(New, Old);
3358 // C++ [basic.link]p10:
3359 // [...] the types specified by all declarations referring to a given
3360 // object or function shall be identical, except that declarations for an
3361 // array object can specify array types that differ by the presence or
3362 // absence of a major array bound (8.3.4).
3363 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3364 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3365 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3367 // We are merging a variable declaration New into Old. If it has an array
3368 // bound, and that bound differs from Old's bound, we should diagnose the
3370 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3371 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3372 PrevVD = PrevVD->getPreviousDecl()) {
3373 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3374 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3377 if (!Context.hasSameType(NewArray, PrevVDTy))
3378 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3382 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3383 if (Context.hasSameType(OldArray->getElementType(),
3384 NewArray->getElementType()))
3385 MergedT = New->getType();
3387 // FIXME: Check visibility. New is hidden but has a complete type. If New
3388 // has no array bound, it should not inherit one from Old, if Old is not
3390 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3391 if (Context.hasSameType(OldArray->getElementType(),
3392 NewArray->getElementType()))
3393 MergedT = Old->getType();
3396 else if (New->getType()->isObjCObjectPointerType() &&
3397 Old->getType()->isObjCObjectPointerType()) {
3398 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3403 // All declarations that refer to the same object or function shall have
3405 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3407 if (MergedT.isNull()) {
3408 // It's OK if we couldn't merge types if either type is dependent, for a
3409 // block-scope variable. In other cases (static data members of class
3410 // templates, variable templates, ...), we require the types to be
3412 // FIXME: The C++ standard doesn't say anything about this.
3413 if ((New->getType()->isDependentType() ||
3414 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3415 // If the old type was dependent, we can't merge with it, so the new type
3416 // becomes dependent for now. We'll reproduce the original type when we
3417 // instantiate the TypeSourceInfo for the variable.
3418 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3419 New->setType(Context.DependentTy);
3422 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3425 // Don't actually update the type on the new declaration if the old
3426 // declaration was an extern declaration in a different scope.
3427 if (MergeTypeWithOld)
3428 New->setType(MergedT);
3431 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3432 LookupResult &Previous) {
3434 // For an identifier with internal or external linkage declared
3435 // in a scope in which a prior declaration of that identifier is
3436 // visible, if the prior declaration specifies internal or
3437 // external linkage, the type of the identifier at the later
3438 // declaration becomes the composite type.
3440 // If the variable isn't visible, we do not merge with its type.
3441 if (Previous.isShadowed())
3444 if (S.getLangOpts().CPlusPlus) {
3445 // C++11 [dcl.array]p3:
3446 // If there is a preceding declaration of the entity in the same
3447 // scope in which the bound was specified, an omitted array bound
3448 // is taken to be the same as in that earlier declaration.
3449 return NewVD->isPreviousDeclInSameBlockScope() ||
3450 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3451 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3453 // If the old declaration was function-local, don't merge with its
3454 // type unless we're in the same function.
3455 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3456 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3460 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3461 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3462 /// situation, merging decls or emitting diagnostics as appropriate.
3464 /// Tentative definition rules (C99 6.9.2p2) are checked by
3465 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3466 /// definitions here, since the initializer hasn't been attached.
3468 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3469 // If the new decl is already invalid, don't do any other checking.
3470 if (New->isInvalidDecl())
3473 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3476 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3478 // Verify the old decl was also a variable or variable template.
3479 VarDecl *Old = nullptr;
3480 VarTemplateDecl *OldTemplate = nullptr;
3481 if (Previous.isSingleResult()) {
3483 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3484 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3487 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3488 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3489 return New->setInvalidDecl();
3491 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3494 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3495 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3496 return New->setInvalidDecl();
3500 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3501 << New->getDeclName();
3502 Diag(Previous.getRepresentativeDecl()->getLocation(),
3503 diag::note_previous_definition);
3504 return New->setInvalidDecl();
3507 // Ensure the template parameters are compatible.
3509 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3510 OldTemplate->getTemplateParameters(),
3511 /*Complain=*/true, TPL_TemplateMatch))
3512 return New->setInvalidDecl();
3514 // C++ [class.mem]p1:
3515 // A member shall not be declared twice in the member-specification [...]
3517 // Here, we need only consider static data members.
3518 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3519 Diag(New->getLocation(), diag::err_duplicate_member)
3520 << New->getIdentifier();
3521 Diag(Old->getLocation(), diag::note_previous_declaration);
3522 New->setInvalidDecl();
3525 mergeDeclAttributes(New, Old);
3526 // Warn if an already-declared variable is made a weak_import in a subsequent
3528 if (New->hasAttr<WeakImportAttr>() &&
3529 Old->getStorageClass() == SC_None &&
3530 !Old->hasAttr<WeakImportAttr>()) {
3531 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3532 Diag(Old->getLocation(), diag::note_previous_definition);
3533 // Remove weak_import attribute on new declaration.
3534 New->dropAttr<WeakImportAttr>();
3537 if (New->hasAttr<InternalLinkageAttr>() &&
3538 !Old->hasAttr<InternalLinkageAttr>()) {
3539 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3540 << New->getDeclName();
3541 Diag(Old->getLocation(), diag::note_previous_definition);
3542 New->dropAttr<InternalLinkageAttr>();
3546 VarDecl *MostRecent = Old->getMostRecentDecl();
3547 if (MostRecent != Old) {
3548 MergeVarDeclTypes(New, MostRecent,
3549 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3550 if (New->isInvalidDecl())
3554 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3555 if (New->isInvalidDecl())
3558 diag::kind PrevDiag;
3559 SourceLocation OldLocation;
3560 std::tie(PrevDiag, OldLocation) =
3561 getNoteDiagForInvalidRedeclaration(Old, New);
3563 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3564 if (New->getStorageClass() == SC_Static &&
3565 !New->isStaticDataMember() &&
3566 Old->hasExternalFormalLinkage()) {
3567 if (getLangOpts().MicrosoftExt) {
3568 Diag(New->getLocation(), diag::ext_static_non_static)
3569 << New->getDeclName();
3570 Diag(OldLocation, PrevDiag);
3572 Diag(New->getLocation(), diag::err_static_non_static)
3573 << New->getDeclName();
3574 Diag(OldLocation, PrevDiag);
3575 return New->setInvalidDecl();
3579 // For an identifier declared with the storage-class specifier
3580 // extern in a scope in which a prior declaration of that
3581 // identifier is visible,23) if the prior declaration specifies
3582 // internal or external linkage, the linkage of the identifier at
3583 // the later declaration is the same as the linkage specified at
3584 // the prior declaration. If no prior declaration is visible, or
3585 // if the prior declaration specifies no linkage, then the
3586 // identifier has external linkage.
3587 if (New->hasExternalStorage() && Old->hasLinkage())
3589 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3590 !New->isStaticDataMember() &&
3591 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3592 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3593 Diag(OldLocation, PrevDiag);
3594 return New->setInvalidDecl();
3597 // Check if extern is followed by non-extern and vice-versa.
3598 if (New->hasExternalStorage() &&
3599 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3600 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3601 Diag(OldLocation, PrevDiag);
3602 return New->setInvalidDecl();
3604 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3605 !New->hasExternalStorage()) {
3606 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3607 Diag(OldLocation, PrevDiag);
3608 return New->setInvalidDecl();
3611 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3613 // FIXME: The test for external storage here seems wrong? We still
3614 // need to check for mismatches.
3615 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3616 // Don't complain about out-of-line definitions of static members.
3617 !(Old->getLexicalDeclContext()->isRecord() &&
3618 !New->getLexicalDeclContext()->isRecord())) {
3619 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3620 Diag(OldLocation, PrevDiag);
3621 return New->setInvalidDecl();
3624 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3625 if (VarDecl *Def = Old->getDefinition()) {
3626 // C++1z [dcl.fcn.spec]p4:
3627 // If the definition of a variable appears in a translation unit before
3628 // its first declaration as inline, the program is ill-formed.
3629 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3630 Diag(Def->getLocation(), diag::note_previous_definition);
3634 // If this redeclaration makes the function inline, we may need to add it to
3635 // UndefinedButUsed.
3636 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3637 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3638 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3641 if (New->getTLSKind() != Old->getTLSKind()) {
3642 if (!Old->getTLSKind()) {
3643 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3644 Diag(OldLocation, PrevDiag);
3645 } else if (!New->getTLSKind()) {
3646 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3647 Diag(OldLocation, PrevDiag);
3649 // Do not allow redeclaration to change the variable between requiring
3650 // static and dynamic initialization.
3651 // FIXME: GCC allows this, but uses the TLS keyword on the first
3652 // declaration to determine the kind. Do we need to be compatible here?
3653 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3654 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3655 Diag(OldLocation, PrevDiag);
3659 // C++ doesn't have tentative definitions, so go right ahead and check here.
3661 if (getLangOpts().CPlusPlus &&
3662 New->isThisDeclarationADefinition() == VarDecl::Definition &&
3663 (Def = Old->getDefinition())) {
3664 NamedDecl *Hidden = nullptr;
3665 if (!hasVisibleDefinition(Def, &Hidden) &&
3666 (New->getFormalLinkage() == InternalLinkage ||
3667 New->getDescribedVarTemplate() ||
3668 New->getNumTemplateParameterLists() ||
3669 New->getDeclContext()->isDependentContext())) {
3670 // The previous definition is hidden, and multiple definitions are
3671 // permitted (in separate TUs). Form another definition of it.
3672 } else if (Old->isStaticDataMember() &&
3673 Old->getCanonicalDecl()->isInline() &&
3674 Old->getCanonicalDecl()->isConstexpr()) {
3675 // This definition won't be a definition any more once it's been merged.
3676 Diag(New->getLocation(),
3677 diag::warn_deprecated_redundant_constexpr_static_def);
3679 Diag(New->getLocation(), diag::err_redefinition) << New;
3680 Diag(Def->getLocation(), diag::note_previous_definition);
3681 New->setInvalidDecl();
3686 if (haveIncompatibleLanguageLinkages(Old, New)) {
3687 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3688 Diag(OldLocation, PrevDiag);
3689 New->setInvalidDecl();
3693 // Merge "used" flag.
3694 if (Old->getMostRecentDecl()->isUsed(false))
3697 // Keep a chain of previous declarations.
3698 New->setPreviousDecl(Old);
3700 NewTemplate->setPreviousDecl(OldTemplate);
3702 // Inherit access appropriately.
3703 New->setAccess(Old->getAccess());
3705 NewTemplate->setAccess(New->getAccess());
3707 if (Old->isInline())
3708 New->setImplicitlyInline();
3711 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3712 /// no declarator (e.g. "struct foo;") is parsed.
3714 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3715 RecordDecl *&AnonRecord) {
3716 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3720 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3721 // disambiguate entities defined in different scopes.
3722 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3724 // We will pick our mangling number depending on which version of MSVC is being
3726 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3727 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3728 ? S->getMSCurManglingNumber()
3729 : S->getMSLastManglingNumber();
3732 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3733 if (!Context.getLangOpts().CPlusPlus)
3736 if (isa<CXXRecordDecl>(Tag->getParent())) {
3737 // If this tag is the direct child of a class, number it if
3739 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3741 MangleNumberingContext &MCtx =
3742 Context.getManglingNumberContext(Tag->getParent());
3743 Context.setManglingNumber(
3744 Tag, MCtx.getManglingNumber(
3745 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3749 // If this tag isn't a direct child of a class, number it if it is local.
3750 Decl *ManglingContextDecl;
3751 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3752 Tag->getDeclContext(), ManglingContextDecl)) {
3753 Context.setManglingNumber(
3754 Tag, MCtx->getManglingNumber(
3755 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3759 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3760 TypedefNameDecl *NewTD) {
3761 if (TagFromDeclSpec->isInvalidDecl())
3764 // Do nothing if the tag already has a name for linkage purposes.
3765 if (TagFromDeclSpec->hasNameForLinkage())
3768 // A well-formed anonymous tag must always be a TUK_Definition.
3769 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3771 // The type must match the tag exactly; no qualifiers allowed.
3772 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3773 Context.getTagDeclType(TagFromDeclSpec))) {
3774 if (getLangOpts().CPlusPlus)
3775 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3779 // If we've already computed linkage for the anonymous tag, then
3780 // adding a typedef name for the anonymous decl can change that
3781 // linkage, which might be a serious problem. Diagnose this as
3782 // unsupported and ignore the typedef name. TODO: we should
3783 // pursue this as a language defect and establish a formal rule
3784 // for how to handle it.
3785 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3786 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3788 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3789 tagLoc = getLocForEndOfToken(tagLoc);
3791 llvm::SmallString<40> textToInsert;
3792 textToInsert += ' ';
3793 textToInsert += NewTD->getIdentifier()->getName();
3794 Diag(tagLoc, diag::note_typedef_changes_linkage)
3795 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3799 // Otherwise, set this is the anon-decl typedef for the tag.
3800 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3803 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3805 case DeclSpec::TST_class:
3807 case DeclSpec::TST_struct:
3809 case DeclSpec::TST_interface:
3811 case DeclSpec::TST_union:
3813 case DeclSpec::TST_enum:
3816 llvm_unreachable("unexpected type specifier");
3820 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3821 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3822 /// parameters to cope with template friend declarations.
3824 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3825 MultiTemplateParamsArg TemplateParams,
3826 bool IsExplicitInstantiation,
3827 RecordDecl *&AnonRecord) {
3828 Decl *TagD = nullptr;
3829 TagDecl *Tag = nullptr;
3830 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3831 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3832 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3833 DS.getTypeSpecType() == DeclSpec::TST_union ||
3834 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3835 TagD = DS.getRepAsDecl();
3837 if (!TagD) // We probably had an error
3840 // Note that the above type specs guarantee that the
3841 // type rep is a Decl, whereas in many of the others
3843 if (isa<TagDecl>(TagD))
3844 Tag = cast<TagDecl>(TagD);
3845 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3846 Tag = CTD->getTemplatedDecl();
3850 handleTagNumbering(Tag, S);
3851 Tag->setFreeStanding();
3852 if (Tag->isInvalidDecl())
3856 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3857 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3858 // or incomplete types shall not be restrict-qualified."
3859 if (TypeQuals & DeclSpec::TQ_restrict)
3860 Diag(DS.getRestrictSpecLoc(),
3861 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3862 << DS.getSourceRange();
3865 if (DS.isInlineSpecified())
3866 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3867 << getLangOpts().CPlusPlus1z;
3869 if (DS.isConstexprSpecified()) {
3870 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3871 // and definitions of functions and variables.
3873 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3874 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3876 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3877 // Don't emit warnings after this error.
3881 if (DS.isConceptSpecified()) {
3882 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3883 // either a function concept and its definition or a variable concept and
3885 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3889 DiagnoseFunctionSpecifiers(DS);
3891 if (DS.isFriendSpecified()) {
3892 // If we're dealing with a decl but not a TagDecl, assume that
3893 // whatever routines created it handled the friendship aspect.
3896 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3899 const CXXScopeSpec &SS = DS.getTypeSpecScope();
3900 bool IsExplicitSpecialization =
3901 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3902 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3903 !IsExplicitInstantiation && !IsExplicitSpecialization &&
3904 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3905 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3906 // nested-name-specifier unless it is an explicit instantiation
3907 // or an explicit specialization.
3909 // FIXME: We allow class template partial specializations here too, per the
3910 // obvious intent of DR1819.
3912 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3913 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3914 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3918 // Track whether this decl-specifier declares anything.
3919 bool DeclaresAnything = true;
3921 // Handle anonymous struct definitions.
3922 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3923 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3924 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3925 if (getLangOpts().CPlusPlus ||
3926 Record->getDeclContext()->isRecord()) {
3927 // If CurContext is a DeclContext that can contain statements,
3928 // RecursiveASTVisitor won't visit the decls that
3929 // BuildAnonymousStructOrUnion() will put into CurContext.
3930 // Also store them here so that they can be part of the
3931 // DeclStmt that gets created in this case.
3932 // FIXME: Also return the IndirectFieldDecls created by
3933 // BuildAnonymousStructOr union, for the same reason?
3934 if (CurContext->isFunctionOrMethod())
3935 AnonRecord = Record;
3936 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3937 Context.getPrintingPolicy());
3940 DeclaresAnything = false;
3945 // A struct-declaration that does not declare an anonymous structure or
3946 // anonymous union shall contain a struct-declarator-list.
3948 // This rule also existed in C89 and C99; the grammar for struct-declaration
3949 // did not permit a struct-declaration without a struct-declarator-list.
3950 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3951 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3952 // Check for Microsoft C extension: anonymous struct/union member.
3953 // Handle 2 kinds of anonymous struct/union:
3957 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3958 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3959 if ((Tag && Tag->getDeclName()) ||
3960 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3961 RecordDecl *Record = nullptr;
3963 Record = dyn_cast<RecordDecl>(Tag);
3964 else if (const RecordType *RT =
3965 DS.getRepAsType().get()->getAsStructureType())
3966 Record = RT->getDecl();
3967 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3968 Record = UT->getDecl();
3970 if (Record && getLangOpts().MicrosoftExt) {
3971 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3972 << Record->isUnion() << DS.getSourceRange();
3973 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3976 DeclaresAnything = false;
3980 // Skip all the checks below if we have a type error.
3981 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3982 (TagD && TagD->isInvalidDecl()))
3985 if (getLangOpts().CPlusPlus &&
3986 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3987 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3988 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3989 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3990 DeclaresAnything = false;
3992 if (!DS.isMissingDeclaratorOk()) {
3993 // Customize diagnostic for a typedef missing a name.
3994 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3995 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3996 << DS.getSourceRange();
3998 DeclaresAnything = false;
4001 if (DS.isModulePrivateSpecified() &&
4002 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4003 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4004 << Tag->getTagKind()
4005 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4007 ActOnDocumentableDecl(TagD);
4010 // A declaration [...] shall declare at least a declarator [...], a tag,
4011 // or the members of an enumeration.
4013 // [If there are no declarators], and except for the declaration of an
4014 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4015 // names into the program, or shall redeclare a name introduced by a
4016 // previous declaration.
4017 if (!DeclaresAnything) {
4018 // In C, we allow this as a (popular) extension / bug. Don't bother
4019 // producing further diagnostics for redundant qualifiers after this.
4020 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4025 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4026 // init-declarator-list of the declaration shall not be empty.
4027 // C++ [dcl.fct.spec]p1:
4028 // If a cv-qualifier appears in a decl-specifier-seq, the
4029 // init-declarator-list of the declaration shall not be empty.
4031 // Spurious qualifiers here appear to be valid in C.
4032 unsigned DiagID = diag::warn_standalone_specifier;
4033 if (getLangOpts().CPlusPlus)
4034 DiagID = diag::ext_standalone_specifier;
4036 // Note that a linkage-specification sets a storage class, but
4037 // 'extern "C" struct foo;' is actually valid and not theoretically
4039 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4040 if (SCS == DeclSpec::SCS_mutable)
4041 // Since mutable is not a viable storage class specifier in C, there is
4042 // no reason to treat it as an extension. Instead, diagnose as an error.
4043 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4044 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4045 Diag(DS.getStorageClassSpecLoc(), DiagID)
4046 << DeclSpec::getSpecifierName(SCS);
4049 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4050 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4051 << DeclSpec::getSpecifierName(TSCS);
4052 if (DS.getTypeQualifiers()) {
4053 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4054 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4055 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4056 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4057 // Restrict is covered above.
4058 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4059 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4060 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4061 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4064 // Warn about ignored type attributes, for example:
4065 // __attribute__((aligned)) struct A;
4066 // Attributes should be placed after tag to apply to type declaration.
4067 if (!DS.getAttributes().empty()) {
4068 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4069 if (TypeSpecType == DeclSpec::TST_class ||
4070 TypeSpecType == DeclSpec::TST_struct ||
4071 TypeSpecType == DeclSpec::TST_interface ||
4072 TypeSpecType == DeclSpec::TST_union ||
4073 TypeSpecType == DeclSpec::TST_enum) {
4074 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4075 attrs = attrs->getNext())
4076 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4077 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4084 /// We are trying to inject an anonymous member into the given scope;
4085 /// check if there's an existing declaration that can't be overloaded.
4087 /// \return true if this is a forbidden redeclaration
4088 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4091 DeclarationName Name,
4092 SourceLocation NameLoc,
4094 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4095 Sema::ForRedeclaration);
4096 if (!SemaRef.LookupName(R, S)) return false;
4098 // Pick a representative declaration.
4099 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4100 assert(PrevDecl && "Expected a non-null Decl");
4102 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4105 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4107 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4112 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4113 /// anonymous struct or union AnonRecord into the owning context Owner
4114 /// and scope S. This routine will be invoked just after we realize
4115 /// that an unnamed union or struct is actually an anonymous union or
4122 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4123 /// // f into the surrounding scope.x
4126 /// This routine is recursive, injecting the names of nested anonymous
4127 /// structs/unions into the owning context and scope as well.
4129 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4130 RecordDecl *AnonRecord, AccessSpecifier AS,
4131 SmallVectorImpl<NamedDecl *> &Chaining) {
4132 bool Invalid = false;
4134 // Look every FieldDecl and IndirectFieldDecl with a name.
4135 for (auto *D : AnonRecord->decls()) {
4136 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4137 cast<NamedDecl>(D)->getDeclName()) {
4138 ValueDecl *VD = cast<ValueDecl>(D);
4139 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4141 AnonRecord->isUnion())) {
4142 // C++ [class.union]p2:
4143 // The names of the members of an anonymous union shall be
4144 // distinct from the names of any other entity in the
4145 // scope in which the anonymous union is declared.
4148 // C++ [class.union]p2:
4149 // For the purpose of name lookup, after the anonymous union
4150 // definition, the members of the anonymous union are
4151 // considered to have been defined in the scope in which the
4152 // anonymous union is declared.
4153 unsigned OldChainingSize = Chaining.size();
4154 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4155 Chaining.append(IF->chain_begin(), IF->chain_end());
4157 Chaining.push_back(VD);
4159 assert(Chaining.size() >= 2);
4160 NamedDecl **NamedChain =
4161 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4162 for (unsigned i = 0; i < Chaining.size(); i++)
4163 NamedChain[i] = Chaining[i];
4165 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4166 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4167 VD->getType(), {NamedChain, Chaining.size()});
4169 for (const auto *Attr : VD->attrs())
4170 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4172 IndirectField->setAccess(AS);
4173 IndirectField->setImplicit();
4174 SemaRef.PushOnScopeChains(IndirectField, S);
4176 // That includes picking up the appropriate access specifier.
4177 if (AS != AS_none) IndirectField->setAccess(AS);
4179 Chaining.resize(OldChainingSize);
4187 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4188 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4189 /// illegal input values are mapped to SC_None.
4191 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4192 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4193 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4194 "Parser allowed 'typedef' as storage class VarDecl.");
4195 switch (StorageClassSpec) {
4196 case DeclSpec::SCS_unspecified: return SC_None;
4197 case DeclSpec::SCS_extern:
4198 if (DS.isExternInLinkageSpec())
4201 case DeclSpec::SCS_static: return SC_Static;
4202 case DeclSpec::SCS_auto: return SC_Auto;
4203 case DeclSpec::SCS_register: return SC_Register;
4204 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4205 // Illegal SCSs map to None: error reporting is up to the caller.
4206 case DeclSpec::SCS_mutable: // Fall through.
4207 case DeclSpec::SCS_typedef: return SC_None;
4209 llvm_unreachable("unknown storage class specifier");
4212 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4213 assert(Record->hasInClassInitializer());
4215 for (const auto *I : Record->decls()) {
4216 const auto *FD = dyn_cast<FieldDecl>(I);
4217 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4218 FD = IFD->getAnonField();
4219 if (FD && FD->hasInClassInitializer())
4220 return FD->getLocation();
4223 llvm_unreachable("couldn't find in-class initializer");
4226 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4227 SourceLocation DefaultInitLoc) {
4228 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4231 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4232 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4235 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4236 CXXRecordDecl *AnonUnion) {
4237 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4240 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4243 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4244 /// anonymous structure or union. Anonymous unions are a C++ feature
4245 /// (C++ [class.union]) and a C11 feature; anonymous structures
4246 /// are a C11 feature and GNU C++ extension.
4247 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4250 const PrintingPolicy &Policy) {
4251 DeclContext *Owner = Record->getDeclContext();
4253 // Diagnose whether this anonymous struct/union is an extension.
4254 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4255 Diag(Record->getLocation(), diag::ext_anonymous_union);
4256 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4257 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4258 else if (!Record->isUnion() && !getLangOpts().C11)
4259 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4261 // C and C++ require different kinds of checks for anonymous
4263 bool Invalid = false;
4264 if (getLangOpts().CPlusPlus) {
4265 const char *PrevSpec = nullptr;
4267 if (Record->isUnion()) {
4268 // C++ [class.union]p6:
4269 // Anonymous unions declared in a named namespace or in the
4270 // global namespace shall be declared static.
4271 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4272 (isa<TranslationUnitDecl>(Owner) ||
4273 (isa<NamespaceDecl>(Owner) &&
4274 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4275 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4276 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4278 // Recover by adding 'static'.
4279 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4280 PrevSpec, DiagID, Policy);
4282 // C++ [class.union]p6:
4283 // A storage class is not allowed in a declaration of an
4284 // anonymous union in a class scope.
4285 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4286 isa<RecordDecl>(Owner)) {
4287 Diag(DS.getStorageClassSpecLoc(),
4288 diag::err_anonymous_union_with_storage_spec)
4289 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4291 // Recover by removing the storage specifier.
4292 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4294 PrevSpec, DiagID, Context.getPrintingPolicy());
4298 // Ignore const/volatile/restrict qualifiers.
4299 if (DS.getTypeQualifiers()) {
4300 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4301 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4302 << Record->isUnion() << "const"
4303 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4304 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4305 Diag(DS.getVolatileSpecLoc(),
4306 diag::ext_anonymous_struct_union_qualified)
4307 << Record->isUnion() << "volatile"
4308 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4309 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4310 Diag(DS.getRestrictSpecLoc(),
4311 diag::ext_anonymous_struct_union_qualified)
4312 << Record->isUnion() << "restrict"
4313 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4314 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4315 Diag(DS.getAtomicSpecLoc(),
4316 diag::ext_anonymous_struct_union_qualified)
4317 << Record->isUnion() << "_Atomic"
4318 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4319 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4320 Diag(DS.getUnalignedSpecLoc(),
4321 diag::ext_anonymous_struct_union_qualified)
4322 << Record->isUnion() << "__unaligned"
4323 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4325 DS.ClearTypeQualifiers();
4328 // C++ [class.union]p2:
4329 // The member-specification of an anonymous union shall only
4330 // define non-static data members. [Note: nested types and
4331 // functions cannot be declared within an anonymous union. ]
4332 for (auto *Mem : Record->decls()) {
4333 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4334 // C++ [class.union]p3:
4335 // An anonymous union shall not have private or protected
4336 // members (clause 11).
4337 assert(FD->getAccess() != AS_none);
4338 if (FD->getAccess() != AS_public) {
4339 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4340 << Record->isUnion() << (FD->getAccess() == AS_protected);
4344 // C++ [class.union]p1
4345 // An object of a class with a non-trivial constructor, a non-trivial
4346 // copy constructor, a non-trivial destructor, or a non-trivial copy
4347 // assignment operator cannot be a member of a union, nor can an
4348 // array of such objects.
4349 if (CheckNontrivialField(FD))
4351 } else if (Mem->isImplicit()) {
4352 // Any implicit members are fine.
4353 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4354 // This is a type that showed up in an
4355 // elaborated-type-specifier inside the anonymous struct or
4356 // union, but which actually declares a type outside of the
4357 // anonymous struct or union. It's okay.
4358 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4359 if (!MemRecord->isAnonymousStructOrUnion() &&
4360 MemRecord->getDeclName()) {
4361 // Visual C++ allows type definition in anonymous struct or union.
4362 if (getLangOpts().MicrosoftExt)
4363 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4364 << Record->isUnion();
4366 // This is a nested type declaration.
4367 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4368 << Record->isUnion();
4372 // This is an anonymous type definition within another anonymous type.
4373 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4374 // not part of standard C++.
4375 Diag(MemRecord->getLocation(),
4376 diag::ext_anonymous_record_with_anonymous_type)
4377 << Record->isUnion();
4379 } else if (isa<AccessSpecDecl>(Mem)) {
4380 // Any access specifier is fine.
4381 } else if (isa<StaticAssertDecl>(Mem)) {
4382 // In C++1z, static_assert declarations are also fine.
4384 // We have something that isn't a non-static data
4385 // member. Complain about it.
4386 unsigned DK = diag::err_anonymous_record_bad_member;
4387 if (isa<TypeDecl>(Mem))
4388 DK = diag::err_anonymous_record_with_type;
4389 else if (isa<FunctionDecl>(Mem))
4390 DK = diag::err_anonymous_record_with_function;
4391 else if (isa<VarDecl>(Mem))
4392 DK = diag::err_anonymous_record_with_static;
4394 // Visual C++ allows type definition in anonymous struct or union.
4395 if (getLangOpts().MicrosoftExt &&
4396 DK == diag::err_anonymous_record_with_type)
4397 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4398 << Record->isUnion();
4400 Diag(Mem->getLocation(), DK) << Record->isUnion();
4406 // C++11 [class.union]p8 (DR1460):
4407 // At most one variant member of a union may have a
4408 // brace-or-equal-initializer.
4409 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4411 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4412 cast<CXXRecordDecl>(Record));
4415 if (!Record->isUnion() && !Owner->isRecord()) {
4416 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4417 << getLangOpts().CPlusPlus;
4421 // Mock up a declarator.
4422 Declarator Dc(DS, Declarator::MemberContext);
4423 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4424 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4426 // Create a declaration for this anonymous struct/union.
4427 NamedDecl *Anon = nullptr;
4428 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4429 Anon = FieldDecl::Create(Context, OwningClass,
4431 Record->getLocation(),
4432 /*IdentifierInfo=*/nullptr,
4433 Context.getTypeDeclType(Record),
4435 /*BitWidth=*/nullptr, /*Mutable=*/false,
4436 /*InitStyle=*/ICIS_NoInit);
4437 Anon->setAccess(AS);
4438 if (getLangOpts().CPlusPlus)
4439 FieldCollector->Add(cast<FieldDecl>(Anon));
4441 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4442 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4443 if (SCSpec == DeclSpec::SCS_mutable) {
4444 // mutable can only appear on non-static class members, so it's always
4446 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4451 Anon = VarDecl::Create(Context, Owner,
4453 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4454 Context.getTypeDeclType(Record),
4457 // Default-initialize the implicit variable. This initialization will be
4458 // trivial in almost all cases, except if a union member has an in-class
4460 // union { int n = 0; };
4461 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4463 Anon->setImplicit();
4465 // Mark this as an anonymous struct/union type.
4466 Record->setAnonymousStructOrUnion(true);
4468 // Add the anonymous struct/union object to the current
4469 // context. We'll be referencing this object when we refer to one of
4471 Owner->addDecl(Anon);
4473 // Inject the members of the anonymous struct/union into the owning
4474 // context and into the identifier resolver chain for name lookup
4476 SmallVector<NamedDecl*, 2> Chain;
4477 Chain.push_back(Anon);
4479 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4482 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4483 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4484 Decl *ManglingContextDecl;
4485 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4486 NewVD->getDeclContext(), ManglingContextDecl)) {
4487 Context.setManglingNumber(
4488 NewVD, MCtx->getManglingNumber(
4489 NewVD, getMSManglingNumber(getLangOpts(), S)));
4490 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4496 Anon->setInvalidDecl();
4501 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4502 /// Microsoft C anonymous structure.
4503 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4506 /// struct A { int a; };
4507 /// struct B { struct A; int b; };
4514 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4515 RecordDecl *Record) {
4516 assert(Record && "expected a record!");
4518 // Mock up a declarator.
4519 Declarator Dc(DS, Declarator::TypeNameContext);
4520 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4521 assert(TInfo && "couldn't build declarator info for anonymous struct");
4523 auto *ParentDecl = cast<RecordDecl>(CurContext);
4524 QualType RecTy = Context.getTypeDeclType(Record);
4526 // Create a declaration for this anonymous struct.
4527 NamedDecl *Anon = FieldDecl::Create(Context,
4531 /*IdentifierInfo=*/nullptr,
4534 /*BitWidth=*/nullptr, /*Mutable=*/false,
4535 /*InitStyle=*/ICIS_NoInit);
4536 Anon->setImplicit();
4538 // Add the anonymous struct object to the current context.
4539 CurContext->addDecl(Anon);
4541 // Inject the members of the anonymous struct into the current
4542 // context and into the identifier resolver chain for name lookup
4544 SmallVector<NamedDecl*, 2> Chain;
4545 Chain.push_back(Anon);
4547 RecordDecl *RecordDef = Record->getDefinition();
4548 if (RequireCompleteType(Anon->getLocation(), RecTy,
4549 diag::err_field_incomplete) ||
4550 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4552 Anon->setInvalidDecl();
4553 ParentDecl->setInvalidDecl();
4559 /// GetNameForDeclarator - Determine the full declaration name for the
4560 /// given Declarator.
4561 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4562 return GetNameFromUnqualifiedId(D.getName());
4565 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4567 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4568 DeclarationNameInfo NameInfo;
4569 NameInfo.setLoc(Name.StartLocation);
4571 switch (Name.getKind()) {
4573 case UnqualifiedId::IK_ImplicitSelfParam:
4574 case UnqualifiedId::IK_Identifier:
4575 NameInfo.setName(Name.Identifier);
4576 NameInfo.setLoc(Name.StartLocation);
4579 case UnqualifiedId::IK_OperatorFunctionId:
4580 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4581 Name.OperatorFunctionId.Operator));
4582 NameInfo.setLoc(Name.StartLocation);
4583 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4584 = Name.OperatorFunctionId.SymbolLocations[0];
4585 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4586 = Name.EndLocation.getRawEncoding();
4589 case UnqualifiedId::IK_LiteralOperatorId:
4590 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4592 NameInfo.setLoc(Name.StartLocation);
4593 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4596 case UnqualifiedId::IK_ConversionFunctionId: {
4597 TypeSourceInfo *TInfo;
4598 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4600 return DeclarationNameInfo();
4601 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4602 Context.getCanonicalType(Ty)));
4603 NameInfo.setLoc(Name.StartLocation);
4604 NameInfo.setNamedTypeInfo(TInfo);
4608 case UnqualifiedId::IK_ConstructorName: {
4609 TypeSourceInfo *TInfo;
4610 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4612 return DeclarationNameInfo();
4613 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4614 Context.getCanonicalType(Ty)));
4615 NameInfo.setLoc(Name.StartLocation);
4616 NameInfo.setNamedTypeInfo(TInfo);
4620 case UnqualifiedId::IK_ConstructorTemplateId: {
4621 // In well-formed code, we can only have a constructor
4622 // template-id that refers to the current context, so go there
4623 // to find the actual type being constructed.
4624 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4625 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4626 return DeclarationNameInfo();
4628 // Determine the type of the class being constructed.
4629 QualType CurClassType = Context.getTypeDeclType(CurClass);
4631 // FIXME: Check two things: that the template-id names the same type as
4632 // CurClassType, and that the template-id does not occur when the name
4635 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4636 Context.getCanonicalType(CurClassType)));
4637 NameInfo.setLoc(Name.StartLocation);
4638 // FIXME: should we retrieve TypeSourceInfo?
4639 NameInfo.setNamedTypeInfo(nullptr);
4643 case UnqualifiedId::IK_DestructorName: {
4644 TypeSourceInfo *TInfo;
4645 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4647 return DeclarationNameInfo();
4648 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4649 Context.getCanonicalType(Ty)));
4650 NameInfo.setLoc(Name.StartLocation);
4651 NameInfo.setNamedTypeInfo(TInfo);
4655 case UnqualifiedId::IK_TemplateId: {
4656 TemplateName TName = Name.TemplateId->Template.get();
4657 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4658 return Context.getNameForTemplate(TName, TNameLoc);
4661 } // switch (Name.getKind())
4663 llvm_unreachable("Unknown name kind");
4666 static QualType getCoreType(QualType Ty) {
4668 if (Ty->isPointerType() || Ty->isReferenceType())
4669 Ty = Ty->getPointeeType();
4670 else if (Ty->isArrayType())
4671 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4673 return Ty.withoutLocalFastQualifiers();
4677 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4678 /// and Definition have "nearly" matching parameters. This heuristic is
4679 /// used to improve diagnostics in the case where an out-of-line function
4680 /// definition doesn't match any declaration within the class or namespace.
4681 /// Also sets Params to the list of indices to the parameters that differ
4682 /// between the declaration and the definition. If hasSimilarParameters
4683 /// returns true and Params is empty, then all of the parameters match.
4684 static bool hasSimilarParameters(ASTContext &Context,
4685 FunctionDecl *Declaration,
4686 FunctionDecl *Definition,
4687 SmallVectorImpl<unsigned> &Params) {
4689 if (Declaration->param_size() != Definition->param_size())
4691 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4692 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4693 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4695 // The parameter types are identical
4696 if (Context.hasSameType(DefParamTy, DeclParamTy))
4699 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4700 QualType DefParamBaseTy = getCoreType(DefParamTy);
4701 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4702 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4704 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4705 (DeclTyName && DeclTyName == DefTyName))
4706 Params.push_back(Idx);
4707 else // The two parameters aren't even close
4714 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4715 /// declarator needs to be rebuilt in the current instantiation.
4716 /// Any bits of declarator which appear before the name are valid for
4717 /// consideration here. That's specifically the type in the decl spec
4718 /// and the base type in any member-pointer chunks.
4719 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4720 DeclarationName Name) {
4721 // The types we specifically need to rebuild are:
4722 // - typenames, typeofs, and decltypes
4723 // - types which will become injected class names
4724 // Of course, we also need to rebuild any type referencing such a
4725 // type. It's safest to just say "dependent", but we call out a
4728 DeclSpec &DS = D.getMutableDeclSpec();
4729 switch (DS.getTypeSpecType()) {
4730 case DeclSpec::TST_typename:
4731 case DeclSpec::TST_typeofType:
4732 case DeclSpec::TST_underlyingType:
4733 case DeclSpec::TST_atomic: {
4734 // Grab the type from the parser.
4735 TypeSourceInfo *TSI = nullptr;
4736 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4737 if (T.isNull() || !T->isDependentType()) break;
4739 // Make sure there's a type source info. This isn't really much
4740 // of a waste; most dependent types should have type source info
4741 // attached already.
4743 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4745 // Rebuild the type in the current instantiation.
4746 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4747 if (!TSI) return true;
4749 // Store the new type back in the decl spec.
4750 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4751 DS.UpdateTypeRep(LocType);
4755 case DeclSpec::TST_decltype:
4756 case DeclSpec::TST_typeofExpr: {
4757 Expr *E = DS.getRepAsExpr();
4758 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4759 if (Result.isInvalid()) return true;
4760 DS.UpdateExprRep(Result.get());
4765 // Nothing to do for these decl specs.
4769 // It doesn't matter what order we do this in.
4770 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4771 DeclaratorChunk &Chunk = D.getTypeObject(I);
4773 // The only type information in the declarator which can come
4774 // before the declaration name is the base type of a member
4776 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4779 // Rebuild the scope specifier in-place.
4780 CXXScopeSpec &SS = Chunk.Mem.Scope();
4781 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4788 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4789 D.setFunctionDefinitionKind(FDK_Declaration);
4790 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4792 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4793 Dcl && Dcl->getDeclContext()->isFileContext())
4794 Dcl->setTopLevelDeclInObjCContainer();
4799 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4800 /// If T is the name of a class, then each of the following shall have a
4801 /// name different from T:
4802 /// - every static data member of class T;
4803 /// - every member function of class T
4804 /// - every member of class T that is itself a type;
4805 /// \returns true if the declaration name violates these rules.
4806 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4807 DeclarationNameInfo NameInfo) {
4808 DeclarationName Name = NameInfo.getName();
4810 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4811 while (Record && Record->isAnonymousStructOrUnion())
4812 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4813 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4814 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4821 /// \brief Diagnose a declaration whose declarator-id has the given
4822 /// nested-name-specifier.
4824 /// \param SS The nested-name-specifier of the declarator-id.
4826 /// \param DC The declaration context to which the nested-name-specifier
4829 /// \param Name The name of the entity being declared.
4831 /// \param Loc The location of the name of the entity being declared.
4833 /// \returns true if we cannot safely recover from this error, false otherwise.
4834 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4835 DeclarationName Name,
4836 SourceLocation Loc) {
4837 DeclContext *Cur = CurContext;
4838 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4839 Cur = Cur->getParent();
4841 // If the user provided a superfluous scope specifier that refers back to the
4842 // class in which the entity is already declared, diagnose and ignore it.
4848 // Note, it was once ill-formed to give redundant qualification in all
4849 // contexts, but that rule was removed by DR482.
4850 if (Cur->Equals(DC)) {
4851 if (Cur->isRecord()) {
4852 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4853 : diag::err_member_extra_qualification)
4854 << Name << FixItHint::CreateRemoval(SS.getRange());
4857 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4862 // Check whether the qualifying scope encloses the scope of the original
4864 if (!Cur->Encloses(DC)) {
4865 if (Cur->isRecord())
4866 Diag(Loc, diag::err_member_qualification)
4867 << Name << SS.getRange();
4868 else if (isa<TranslationUnitDecl>(DC))
4869 Diag(Loc, diag::err_invalid_declarator_global_scope)
4870 << Name << SS.getRange();
4871 else if (isa<FunctionDecl>(Cur))
4872 Diag(Loc, diag::err_invalid_declarator_in_function)
4873 << Name << SS.getRange();
4874 else if (isa<BlockDecl>(Cur))
4875 Diag(Loc, diag::err_invalid_declarator_in_block)
4876 << Name << SS.getRange();
4878 Diag(Loc, diag::err_invalid_declarator_scope)
4879 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4884 if (Cur->isRecord()) {
4885 // Cannot qualify members within a class.
4886 Diag(Loc, diag::err_member_qualification)
4887 << Name << SS.getRange();
4890 // C++ constructors and destructors with incorrect scopes can break
4891 // our AST invariants by having the wrong underlying types. If
4892 // that's the case, then drop this declaration entirely.
4893 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4894 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4895 !Context.hasSameType(Name.getCXXNameType(),
4896 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4902 // C++11 [dcl.meaning]p1:
4903 // [...] "The nested-name-specifier of the qualified declarator-id shall
4904 // not begin with a decltype-specifer"
4905 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4906 while (SpecLoc.getPrefix())
4907 SpecLoc = SpecLoc.getPrefix();
4908 if (dyn_cast_or_null<DecltypeType>(
4909 SpecLoc.getNestedNameSpecifier()->getAsType()))
4910 Diag(Loc, diag::err_decltype_in_declarator)
4911 << SpecLoc.getTypeLoc().getSourceRange();
4916 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4917 MultiTemplateParamsArg TemplateParamLists) {
4918 // TODO: consider using NameInfo for diagnostic.
4919 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4920 DeclarationName Name = NameInfo.getName();
4922 // All of these full declarators require an identifier. If it doesn't have
4923 // one, the ParsedFreeStandingDeclSpec action should be used.
4924 if (D.isDecompositionDeclarator()) {
4925 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
4927 if (!D.isInvalidType()) // Reject this if we think it is valid.
4928 Diag(D.getDeclSpec().getLocStart(),
4929 diag::err_declarator_need_ident)
4930 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4932 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4935 // The scope passed in may not be a decl scope. Zip up the scope tree until
4936 // we find one that is.
4937 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4938 (S->getFlags() & Scope::TemplateParamScope) != 0)
4941 DeclContext *DC = CurContext;
4942 if (D.getCXXScopeSpec().isInvalid())
4944 else if (D.getCXXScopeSpec().isSet()) {
4945 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4946 UPPC_DeclarationQualifier))
4949 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4950 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4951 if (!DC || isa<EnumDecl>(DC)) {
4952 // If we could not compute the declaration context, it's because the
4953 // declaration context is dependent but does not refer to a class,
4954 // class template, or class template partial specialization. Complain
4955 // and return early, to avoid the coming semantic disaster.
4956 Diag(D.getIdentifierLoc(),
4957 diag::err_template_qualified_declarator_no_match)
4958 << D.getCXXScopeSpec().getScopeRep()
4959 << D.getCXXScopeSpec().getRange();
4962 bool IsDependentContext = DC->isDependentContext();
4964 if (!IsDependentContext &&
4965 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4968 // If a class is incomplete, do not parse entities inside it.
4969 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4970 Diag(D.getIdentifierLoc(),
4971 diag::err_member_def_undefined_record)
4972 << Name << DC << D.getCXXScopeSpec().getRange();
4975 if (!D.getDeclSpec().isFriendSpecified()) {
4976 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4977 Name, D.getIdentifierLoc())) {
4985 // Check whether we need to rebuild the type of the given
4986 // declaration in the current instantiation.
4987 if (EnteringContext && IsDependentContext &&
4988 TemplateParamLists.size() != 0) {
4989 ContextRAII SavedContext(*this, DC);
4990 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4995 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4996 QualType R = TInfo->getType();
4998 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4999 // If this is a typedef, we'll end up spewing multiple diagnostics.
5000 // Just return early; it's safer. If this is a function, let the
5001 // "constructor cannot have a return type" diagnostic handle it.
5002 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5005 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5006 UPPC_DeclarationType))
5009 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5012 // See if this is a redefinition of a variable in the same scope.
5013 if (!D.getCXXScopeSpec().isSet()) {
5014 bool IsLinkageLookup = false;
5015 bool CreateBuiltins = false;
5017 // If the declaration we're planning to build will be a function
5018 // or object with linkage, then look for another declaration with
5019 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5021 // If the declaration we're planning to build will be declared with
5022 // external linkage in the translation unit, create any builtin with
5024 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5026 else if (CurContext->isFunctionOrMethod() &&
5027 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5028 R->isFunctionType())) {
5029 IsLinkageLookup = true;
5031 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5032 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5033 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5034 CreateBuiltins = true;
5036 if (IsLinkageLookup)
5037 Previous.clear(LookupRedeclarationWithLinkage);
5039 LookupName(Previous, S, CreateBuiltins);
5040 } else { // Something like "int foo::x;"
5041 LookupQualifiedName(Previous, DC);
5043 // C++ [dcl.meaning]p1:
5044 // When the declarator-id is qualified, the declaration shall refer to a
5045 // previously declared member of the class or namespace to which the
5046 // qualifier refers (or, in the case of a namespace, of an element of the
5047 // inline namespace set of that namespace (7.3.1)) or to a specialization
5050 // Note that we already checked the context above, and that we do not have
5051 // enough information to make sure that Previous contains the declaration
5052 // we want to match. For example, given:
5059 // void X::f(int) { } // ill-formed
5061 // In this case, Previous will point to the overload set
5062 // containing the two f's declared in X, but neither of them
5065 // C++ [dcl.meaning]p1:
5066 // [...] the member shall not merely have been introduced by a
5067 // using-declaration in the scope of the class or namespace nominated by
5068 // the nested-name-specifier of the declarator-id.
5069 RemoveUsingDecls(Previous);
5072 if (Previous.isSingleResult() &&
5073 Previous.getFoundDecl()->isTemplateParameter()) {
5074 // Maybe we will complain about the shadowed template parameter.
5075 if (!D.isInvalidType())
5076 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5077 Previous.getFoundDecl());
5079 // Just pretend that we didn't see the previous declaration.
5083 // In C++, the previous declaration we find might be a tag type
5084 // (class or enum). In this case, the new declaration will hide the
5085 // tag type. Note that this does does not apply if we're declaring a
5086 // typedef (C++ [dcl.typedef]p4).
5087 if (Previous.isSingleTagDecl() &&
5088 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5091 // Check that there are no default arguments other than in the parameters
5092 // of a function declaration (C++ only).
5093 if (getLangOpts().CPlusPlus)
5094 CheckExtraCXXDefaultArguments(D);
5096 if (D.getDeclSpec().isConceptSpecified()) {
5097 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5098 // applied only to the definition of a function template or variable
5099 // template, declared in namespace scope
5100 if (!TemplateParamLists.size()) {
5101 Diag(D.getDeclSpec().getConceptSpecLoc(),
5102 diag:: err_concept_wrong_decl_kind);
5106 if (!DC->getRedeclContext()->isFileContext()) {
5107 Diag(D.getIdentifierLoc(),
5108 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5115 bool AddToScope = true;
5116 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5117 if (TemplateParamLists.size()) {
5118 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5122 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5123 } else if (R->isFunctionType()) {
5124 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5128 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5135 // If this has an identifier and is not a function template specialization,
5136 // add it to the scope stack.
5137 if (New->getDeclName() && AddToScope) {
5138 // Only make a locally-scoped extern declaration visible if it is the first
5139 // declaration of this entity. Qualified lookup for such an entity should
5140 // only find this declaration if there is no visible declaration of it.
5141 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5142 PushOnScopeChains(New, S, AddToContext);
5144 CurContext->addHiddenDecl(New);
5147 if (isInOpenMPDeclareTargetContext())
5148 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5153 /// Helper method to turn variable array types into constant array
5154 /// types in certain situations which would otherwise be errors (for
5155 /// GCC compatibility).
5156 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5157 ASTContext &Context,
5158 bool &SizeIsNegative,
5159 llvm::APSInt &Oversized) {
5160 // This method tries to turn a variable array into a constant
5161 // array even when the size isn't an ICE. This is necessary
5162 // for compatibility with code that depends on gcc's buggy
5163 // constant expression folding, like struct {char x[(int)(char*)2];}
5164 SizeIsNegative = false;
5167 if (T->isDependentType())
5170 QualifierCollector Qs;
5171 const Type *Ty = Qs.strip(T);
5173 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5174 QualType Pointee = PTy->getPointeeType();
5175 QualType FixedType =
5176 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5178 if (FixedType.isNull()) return FixedType;
5179 FixedType = Context.getPointerType(FixedType);
5180 return Qs.apply(Context, FixedType);
5182 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5183 QualType Inner = PTy->getInnerType();
5184 QualType FixedType =
5185 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5187 if (FixedType.isNull()) return FixedType;
5188 FixedType = Context.getParenType(FixedType);
5189 return Qs.apply(Context, FixedType);
5192 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5195 // FIXME: We should probably handle this case
5196 if (VLATy->getElementType()->isVariablyModifiedType())
5200 if (!VLATy->getSizeExpr() ||
5201 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5204 // Check whether the array size is negative.
5205 if (Res.isSigned() && Res.isNegative()) {
5206 SizeIsNegative = true;
5210 // Check whether the array is too large to be addressed.
5211 unsigned ActiveSizeBits
5212 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5214 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5219 return Context.getConstantArrayType(VLATy->getElementType(),
5220 Res, ArrayType::Normal, 0);
5224 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5225 SrcTL = SrcTL.getUnqualifiedLoc();
5226 DstTL = DstTL.getUnqualifiedLoc();
5227 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5228 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5229 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5230 DstPTL.getPointeeLoc());
5231 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5234 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5235 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5236 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5237 DstPTL.getInnerLoc());
5238 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5239 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5242 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5243 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5244 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5245 TypeLoc DstElemTL = DstATL.getElementLoc();
5246 DstElemTL.initializeFullCopy(SrcElemTL);
5247 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5248 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5249 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5252 /// Helper method to turn variable array types into constant array
5253 /// types in certain situations which would otherwise be errors (for
5254 /// GCC compatibility).
5255 static TypeSourceInfo*
5256 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5257 ASTContext &Context,
5258 bool &SizeIsNegative,
5259 llvm::APSInt &Oversized) {
5261 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5262 SizeIsNegative, Oversized);
5263 if (FixedTy.isNull())
5265 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5266 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5267 FixedTInfo->getTypeLoc());
5271 /// \brief Register the given locally-scoped extern "C" declaration so
5272 /// that it can be found later for redeclarations. We include any extern "C"
5273 /// declaration that is not visible in the translation unit here, not just
5274 /// function-scope declarations.
5276 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5277 if (!getLangOpts().CPlusPlus &&
5278 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5279 // Don't need to track declarations in the TU in C.
5282 // Note that we have a locally-scoped external with this name.
5283 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5286 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5287 // FIXME: We can have multiple results via __attribute__((overloadable)).
5288 auto Result = Context.getExternCContextDecl()->lookup(Name);
5289 return Result.empty() ? nullptr : *Result.begin();
5292 /// \brief Diagnose function specifiers on a declaration of an identifier that
5293 /// does not identify a function.
5294 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5295 // FIXME: We should probably indicate the identifier in question to avoid
5296 // confusion for constructs like "virtual int a(), b;"
5297 if (DS.isVirtualSpecified())
5298 Diag(DS.getVirtualSpecLoc(),
5299 diag::err_virtual_non_function);
5301 if (DS.isExplicitSpecified())
5302 Diag(DS.getExplicitSpecLoc(),
5303 diag::err_explicit_non_function);
5305 if (DS.isNoreturnSpecified())
5306 Diag(DS.getNoreturnSpecLoc(),
5307 diag::err_noreturn_non_function);
5311 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5312 TypeSourceInfo *TInfo, LookupResult &Previous) {
5313 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5314 if (D.getCXXScopeSpec().isSet()) {
5315 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5316 << D.getCXXScopeSpec().getRange();
5318 // Pretend we didn't see the scope specifier.
5323 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5325 if (D.getDeclSpec().isInlineSpecified())
5326 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5327 << getLangOpts().CPlusPlus1z;
5328 if (D.getDeclSpec().isConstexprSpecified())
5329 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5331 if (D.getDeclSpec().isConceptSpecified())
5332 Diag(D.getDeclSpec().getConceptSpecLoc(),
5333 diag::err_concept_wrong_decl_kind);
5335 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5336 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5337 << D.getName().getSourceRange();
5341 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5342 if (!NewTD) return nullptr;
5344 // Handle attributes prior to checking for duplicates in MergeVarDecl
5345 ProcessDeclAttributes(S, NewTD, D);
5347 CheckTypedefForVariablyModifiedType(S, NewTD);
5349 bool Redeclaration = D.isRedeclaration();
5350 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5351 D.setRedeclaration(Redeclaration);
5356 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5357 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5358 // then it shall have block scope.
5359 // Note that variably modified types must be fixed before merging the decl so
5360 // that redeclarations will match.
5361 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5362 QualType T = TInfo->getType();
5363 if (T->isVariablyModifiedType()) {
5364 getCurFunction()->setHasBranchProtectedScope();
5366 if (S->getFnParent() == nullptr) {
5367 bool SizeIsNegative;
5368 llvm::APSInt Oversized;
5369 TypeSourceInfo *FixedTInfo =
5370 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5374 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5375 NewTD->setTypeSourceInfo(FixedTInfo);
5378 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5379 else if (T->isVariableArrayType())
5380 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5381 else if (Oversized.getBoolValue())
5382 Diag(NewTD->getLocation(), diag::err_array_too_large)
5383 << Oversized.toString(10);
5385 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5386 NewTD->setInvalidDecl();
5392 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5393 /// declares a typedef-name, either using the 'typedef' type specifier or via
5394 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5396 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5397 LookupResult &Previous, bool &Redeclaration) {
5398 // Merge the decl with the existing one if appropriate. If the decl is
5399 // in an outer scope, it isn't the same thing.
5400 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5401 /*AllowInlineNamespace*/false);
5402 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5403 if (!Previous.empty()) {
5404 Redeclaration = true;
5405 MergeTypedefNameDecl(S, NewTD, Previous);
5408 // If this is the C FILE type, notify the AST context.
5409 if (IdentifierInfo *II = NewTD->getIdentifier())
5410 if (!NewTD->isInvalidDecl() &&
5411 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5412 if (II->isStr("FILE"))
5413 Context.setFILEDecl(NewTD);
5414 else if (II->isStr("jmp_buf"))
5415 Context.setjmp_bufDecl(NewTD);
5416 else if (II->isStr("sigjmp_buf"))
5417 Context.setsigjmp_bufDecl(NewTD);
5418 else if (II->isStr("ucontext_t"))
5419 Context.setucontext_tDecl(NewTD);
5425 /// \brief Determines whether the given declaration is an out-of-scope
5426 /// previous declaration.
5428 /// This routine should be invoked when name lookup has found a
5429 /// previous declaration (PrevDecl) that is not in the scope where a
5430 /// new declaration by the same name is being introduced. If the new
5431 /// declaration occurs in a local scope, previous declarations with
5432 /// linkage may still be considered previous declarations (C99
5433 /// 6.2.2p4-5, C++ [basic.link]p6).
5435 /// \param PrevDecl the previous declaration found by name
5438 /// \param DC the context in which the new declaration is being
5441 /// \returns true if PrevDecl is an out-of-scope previous declaration
5442 /// for a new delcaration with the same name.
5444 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5445 ASTContext &Context) {
5449 if (!PrevDecl->hasLinkage())
5452 if (Context.getLangOpts().CPlusPlus) {
5453 // C++ [basic.link]p6:
5454 // If there is a visible declaration of an entity with linkage
5455 // having the same name and type, ignoring entities declared
5456 // outside the innermost enclosing namespace scope, the block
5457 // scope declaration declares that same entity and receives the
5458 // linkage of the previous declaration.
5459 DeclContext *OuterContext = DC->getRedeclContext();
5460 if (!OuterContext->isFunctionOrMethod())
5461 // This rule only applies to block-scope declarations.
5464 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5465 if (PrevOuterContext->isRecord())
5466 // We found a member function: ignore it.
5469 // Find the innermost enclosing namespace for the new and
5470 // previous declarations.
5471 OuterContext = OuterContext->getEnclosingNamespaceContext();
5472 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5474 // The previous declaration is in a different namespace, so it
5475 // isn't the same function.
5476 if (!OuterContext->Equals(PrevOuterContext))
5483 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5484 CXXScopeSpec &SS = D.getCXXScopeSpec();
5485 if (!SS.isSet()) return;
5486 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5489 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5490 QualType type = decl->getType();
5491 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5492 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5493 // Various kinds of declaration aren't allowed to be __autoreleasing.
5494 unsigned kind = -1U;
5495 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5496 if (var->hasAttr<BlocksAttr>())
5497 kind = 0; // __block
5498 else if (!var->hasLocalStorage())
5500 } else if (isa<ObjCIvarDecl>(decl)) {
5502 } else if (isa<FieldDecl>(decl)) {
5507 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5510 } else if (lifetime == Qualifiers::OCL_None) {
5511 // Try to infer lifetime.
5512 if (!type->isObjCLifetimeType())
5515 lifetime = type->getObjCARCImplicitLifetime();
5516 type = Context.getLifetimeQualifiedType(type, lifetime);
5517 decl->setType(type);
5520 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5521 // Thread-local variables cannot have lifetime.
5522 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5523 var->getTLSKind()) {
5524 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5533 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5534 // Ensure that an auto decl is deduced otherwise the checks below might cache
5535 // the wrong linkage.
5536 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5538 // 'weak' only applies to declarations with external linkage.
5539 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5540 if (!ND.isExternallyVisible()) {
5541 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5542 ND.dropAttr<WeakAttr>();
5545 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5546 if (ND.isExternallyVisible()) {
5547 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5548 ND.dropAttr<WeakRefAttr>();
5549 ND.dropAttr<AliasAttr>();
5553 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5554 if (VD->hasInit()) {
5555 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5556 assert(VD->isThisDeclarationADefinition() &&
5557 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5558 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5559 VD->dropAttr<AliasAttr>();
5564 // 'selectany' only applies to externally visible variable declarations.
5565 // It does not apply to functions.
5566 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5567 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5568 S.Diag(Attr->getLocation(),
5569 diag::err_attribute_selectany_non_extern_data);
5570 ND.dropAttr<SelectAnyAttr>();
5574 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5575 // dll attributes require external linkage. Static locals may have external
5576 // linkage but still cannot be explicitly imported or exported.
5577 auto *VD = dyn_cast<VarDecl>(&ND);
5578 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5579 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5581 ND.setInvalidDecl();
5585 // Virtual functions cannot be marked as 'notail'.
5586 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5587 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5588 if (MD->isVirtual()) {
5589 S.Diag(ND.getLocation(),
5590 diag::err_invalid_attribute_on_virtual_function)
5592 ND.dropAttr<NotTailCalledAttr>();
5596 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5598 bool IsSpecialization,
5599 bool IsDefinition) {
5600 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5601 OldDecl = OldTD->getTemplatedDecl();
5602 if (!IsSpecialization)
5603 IsDefinition = false;
5605 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5606 NewDecl = NewTD->getTemplatedDecl();
5608 if (!OldDecl || !NewDecl)
5611 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5612 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5613 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5614 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5616 // dllimport and dllexport are inheritable attributes so we have to exclude
5617 // inherited attribute instances.
5618 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5619 (NewExportAttr && !NewExportAttr->isInherited());
5621 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5622 // the only exception being explicit specializations.
5623 // Implicitly generated declarations are also excluded for now because there
5624 // is no other way to switch these to use dllimport or dllexport.
5625 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5627 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5628 // Allow with a warning for free functions and global variables.
5629 bool JustWarn = false;
5630 if (!OldDecl->isCXXClassMember()) {
5631 auto *VD = dyn_cast<VarDecl>(OldDecl);
5632 if (VD && !VD->getDescribedVarTemplate())
5634 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5635 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5639 // We cannot change a declaration that's been used because IR has already
5640 // been emitted. Dllimported functions will still work though (modulo
5641 // address equality) as they can use the thunk.
5642 if (OldDecl->isUsed())
5643 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5646 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5647 : diag::err_attribute_dll_redeclaration;
5648 S.Diag(NewDecl->getLocation(), DiagID)
5650 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5651 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5653 NewDecl->setInvalidDecl();
5658 // A redeclaration is not allowed to drop a dllimport attribute, the only
5659 // exceptions being inline function definitions, local extern declarations,
5660 // qualified friend declarations or special MSVC extension: in the last case,
5661 // the declaration is treated as if it were marked dllexport.
5662 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5663 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5664 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5665 // Ignore static data because out-of-line definitions are diagnosed
5667 IsStaticDataMember = VD->isStaticDataMember();
5668 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5669 VarDecl::DeclarationOnly;
5670 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5671 IsInline = FD->isInlined();
5672 IsQualifiedFriend = FD->getQualifier() &&
5673 FD->getFriendObjectKind() == Decl::FOK_Declared;
5676 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5677 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5678 if (IsMicrosoft && IsDefinition) {
5679 S.Diag(NewDecl->getLocation(),
5680 diag::warn_redeclaration_without_import_attribute)
5682 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5683 NewDecl->dropAttr<DLLImportAttr>();
5684 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5685 NewImportAttr->getRange(), S.Context,
5686 NewImportAttr->getSpellingListIndex()));
5688 S.Diag(NewDecl->getLocation(),
5689 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5690 << NewDecl << OldImportAttr;
5691 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5692 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5693 OldDecl->dropAttr<DLLImportAttr>();
5694 NewDecl->dropAttr<DLLImportAttr>();
5696 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5697 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5698 OldDecl->dropAttr<DLLImportAttr>();
5699 NewDecl->dropAttr<DLLImportAttr>();
5700 S.Diag(NewDecl->getLocation(),
5701 diag::warn_dllimport_dropped_from_inline_function)
5702 << NewDecl << OldImportAttr;
5706 /// Given that we are within the definition of the given function,
5707 /// will that definition behave like C99's 'inline', where the
5708 /// definition is discarded except for optimization purposes?
5709 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5710 // Try to avoid calling GetGVALinkageForFunction.
5712 // All cases of this require the 'inline' keyword.
5713 if (!FD->isInlined()) return false;
5715 // This is only possible in C++ with the gnu_inline attribute.
5716 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5719 // Okay, go ahead and call the relatively-more-expensive function.
5722 // AST quite reasonably asserts that it's working on a function
5723 // definition. We don't really have a way to tell it that we're
5724 // currently defining the function, so just lie to it in +Asserts
5725 // builds. This is an awful hack.
5730 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5739 /// Determine whether a variable is extern "C" prior to attaching
5740 /// an initializer. We can't just call isExternC() here, because that
5741 /// will also compute and cache whether the declaration is externally
5742 /// visible, which might change when we attach the initializer.
5744 /// This can only be used if the declaration is known to not be a
5745 /// redeclaration of an internal linkage declaration.
5751 /// Attaching the initializer here makes this declaration not externally
5752 /// visible, because its type has internal linkage.
5754 /// FIXME: This is a hack.
5755 template<typename T>
5756 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5757 if (S.getLangOpts().CPlusPlus) {
5758 // In C++, the overloadable attribute negates the effects of extern "C".
5759 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5762 // So do CUDA's host/device attributes.
5763 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5764 D->template hasAttr<CUDAHostAttr>()))
5767 return D->isExternC();
5770 static bool shouldConsiderLinkage(const VarDecl *VD) {
5771 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5772 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5773 return VD->hasExternalStorage();
5774 if (DC->isFileContext())
5778 llvm_unreachable("Unexpected context");
5781 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5782 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5783 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5784 isa<OMPDeclareReductionDecl>(DC))
5788 llvm_unreachable("Unexpected context");
5791 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5792 AttributeList::Kind Kind) {
5793 for (const AttributeList *L = AttrList; L; L = L->getNext())
5794 if (L->getKind() == Kind)
5799 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5800 AttributeList::Kind Kind) {
5801 // Check decl attributes on the DeclSpec.
5802 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5805 // Walk the declarator structure, checking decl attributes that were in a type
5806 // position to the decl itself.
5807 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5808 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5812 // Finally, check attributes on the decl itself.
5813 return hasParsedAttr(S, PD.getAttributes(), Kind);
5816 /// Adjust the \c DeclContext for a function or variable that might be a
5817 /// function-local external declaration.
5818 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5819 if (!DC->isFunctionOrMethod())
5822 // If this is a local extern function or variable declared within a function
5823 // template, don't add it into the enclosing namespace scope until it is
5824 // instantiated; it might have a dependent type right now.
5825 if (DC->isDependentContext())
5828 // C++11 [basic.link]p7:
5829 // When a block scope declaration of an entity with linkage is not found to
5830 // refer to some other declaration, then that entity is a member of the
5831 // innermost enclosing namespace.
5833 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5834 // semantically-enclosing namespace, not a lexically-enclosing one.
5835 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5836 DC = DC->getParent();
5840 /// \brief Returns true if given declaration has external C language linkage.
5841 static bool isDeclExternC(const Decl *D) {
5842 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5843 return FD->isExternC();
5844 if (const auto *VD = dyn_cast<VarDecl>(D))
5845 return VD->isExternC();
5847 llvm_unreachable("Unknown type of decl!");
5850 NamedDecl *Sema::ActOnVariableDeclarator(
5851 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5852 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5853 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5854 QualType R = TInfo->getType();
5855 DeclarationName Name = GetNameForDeclarator(D).getName();
5857 IdentifierInfo *II = Name.getAsIdentifierInfo();
5859 if (D.isDecompositionDeclarator()) {
5861 // Take the name of the first declarator as our name for diagnostic
5863 auto &Decomp = D.getDecompositionDeclarator();
5864 if (!Decomp.bindings().empty()) {
5865 II = Decomp.bindings()[0].Name;
5869 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5874 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5875 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5877 if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5878 Diag(D.getIdentifierLoc(),
5879 diag::err_opencl_type_can_only_be_used_as_function_parameter)
5885 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5886 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5888 // dllimport globals without explicit storage class are treated as extern. We
5889 // have to change the storage class this early to get the right DeclContext.
5890 if (SC == SC_None && !DC->isRecord() &&
5891 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5892 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5895 DeclContext *OriginalDC = DC;
5896 bool IsLocalExternDecl = SC == SC_Extern &&
5897 adjustContextForLocalExternDecl(DC);
5899 if (getLangOpts().OpenCL) {
5900 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5902 while (NR->isPointerType()) {
5903 if (NR->isFunctionPointerType()) {
5904 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5908 NR = NR->getPointeeType();
5911 if (!getOpenCLOptions().cl_khr_fp16) {
5912 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5913 // half array type (unless the cl_khr_fp16 extension is enabled).
5914 if (Context.getBaseElementType(R)->isHalfType()) {
5915 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5921 if (SCSpec == DeclSpec::SCS_mutable) {
5922 // mutable can only appear on non-static class members, so it's always
5924 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5929 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5930 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5931 D.getDeclSpec().getStorageClassSpecLoc())) {
5932 // In C++11, the 'register' storage class specifier is deprecated.
5933 // Suppress the warning in system macros, it's used in macros in some
5934 // popular C system headers, such as in glibc's htonl() macro.
5935 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5936 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5937 : diag::warn_deprecated_register)
5938 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5941 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5943 if (!DC->isRecord() && S->getFnParent() == nullptr) {
5944 // C99 6.9p2: The storage-class specifiers auto and register shall not
5945 // appear in the declaration specifiers in an external declaration.
5946 // Global Register+Asm is a GNU extension we support.
5947 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5948 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5953 if (getLangOpts().OpenCL) {
5954 // OpenCL v1.2 s6.9.b p4:
5955 // The sampler type cannot be used with the __local and __global address
5956 // space qualifiers.
5957 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5958 R.getAddressSpace() == LangAS::opencl_global)) {
5959 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5962 // OpenCL 1.2 spec, p6.9 r:
5963 // The event type cannot be used to declare a program scope variable.
5964 // The event type cannot be used with the __local, __constant and __global
5965 // address space qualifiers.
5966 if (R->isEventT()) {
5967 if (S->getParent() == nullptr) {
5968 Diag(D.getLocStart(), diag::err_event_t_global_var);
5972 if (R.getAddressSpace()) {
5973 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5979 bool IsExplicitSpecialization = false;
5980 bool IsVariableTemplateSpecialization = false;
5981 bool IsPartialSpecialization = false;
5982 bool IsVariableTemplate = false;
5983 VarDecl *NewVD = nullptr;
5984 VarTemplateDecl *NewTemplate = nullptr;
5985 TemplateParameterList *TemplateParams = nullptr;
5986 if (!getLangOpts().CPlusPlus) {
5987 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5988 D.getIdentifierLoc(), II,
5991 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5992 ParsingInitForAutoVars.insert(NewVD);
5994 if (D.isInvalidType())
5995 NewVD->setInvalidDecl();
5997 bool Invalid = false;
5999 if (DC->isRecord() && !CurContext->isRecord()) {
6000 // This is an out-of-line definition of a static data member.
6005 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6006 diag::err_static_out_of_line)
6007 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6012 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6013 // to names of variables declared in a block or to function parameters.
6014 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6017 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6018 diag::err_storage_class_for_static_member)
6019 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6021 case SC_PrivateExtern:
6022 llvm_unreachable("C storage class in c++!");
6026 if (SC == SC_Static && CurContext->isRecord()) {
6027 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6028 if (RD->isLocalClass())
6029 Diag(D.getIdentifierLoc(),
6030 diag::err_static_data_member_not_allowed_in_local_class)
6031 << Name << RD->getDeclName();
6033 // C++98 [class.union]p1: If a union contains a static data member,
6034 // the program is ill-formed. C++11 drops this restriction.
6036 Diag(D.getIdentifierLoc(),
6037 getLangOpts().CPlusPlus11
6038 ? diag::warn_cxx98_compat_static_data_member_in_union
6039 : diag::ext_static_data_member_in_union) << Name;
6040 // We conservatively disallow static data members in anonymous structs.
6041 else if (!RD->getDeclName())
6042 Diag(D.getIdentifierLoc(),
6043 diag::err_static_data_member_not_allowed_in_anon_struct)
6044 << Name << RD->isUnion();
6048 // Match up the template parameter lists with the scope specifier, then
6049 // determine whether we have a template or a template specialization.
6050 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6051 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6052 D.getCXXScopeSpec(),
6053 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6054 ? D.getName().TemplateId
6057 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6059 if (TemplateParams) {
6060 if (!TemplateParams->size() &&
6061 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6062 // There is an extraneous 'template<>' for this variable. Complain
6063 // about it, but allow the declaration of the variable.
6064 Diag(TemplateParams->getTemplateLoc(),
6065 diag::err_template_variable_noparams)
6067 << SourceRange(TemplateParams->getTemplateLoc(),
6068 TemplateParams->getRAngleLoc());
6069 TemplateParams = nullptr;
6071 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6072 // This is an explicit specialization or a partial specialization.
6073 // FIXME: Check that we can declare a specialization here.
6074 IsVariableTemplateSpecialization = true;
6075 IsPartialSpecialization = TemplateParams->size() > 0;
6076 } else { // if (TemplateParams->size() > 0)
6077 // This is a template declaration.
6078 IsVariableTemplate = true;
6080 // Check that we can declare a template here.
6081 if (CheckTemplateDeclScope(S, TemplateParams))
6084 // Only C++1y supports variable templates (N3651).
6085 Diag(D.getIdentifierLoc(),
6086 getLangOpts().CPlusPlus14
6087 ? diag::warn_cxx11_compat_variable_template
6088 : diag::ext_variable_template);
6093 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6094 "should have a 'template<>' for this decl");
6097 if (IsVariableTemplateSpecialization) {
6098 SourceLocation TemplateKWLoc =
6099 TemplateParamLists.size() > 0
6100 ? TemplateParamLists[0]->getTemplateLoc()
6102 DeclResult Res = ActOnVarTemplateSpecialization(
6103 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6104 IsPartialSpecialization);
6105 if (Res.isInvalid())
6107 NewVD = cast<VarDecl>(Res.get());
6109 } else if (D.isDecompositionDeclarator()) {
6110 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6111 D.getIdentifierLoc(), R, TInfo, SC,
6114 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6115 D.getIdentifierLoc(), II, R, TInfo, SC);
6117 // If this is supposed to be a variable template, create it as such.
6118 if (IsVariableTemplate) {
6120 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6121 TemplateParams, NewVD);
6122 NewVD->setDescribedVarTemplate(NewTemplate);
6125 // If this decl has an auto type in need of deduction, make a note of the
6126 // Decl so we can diagnose uses of it in its own initializer.
6127 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6128 ParsingInitForAutoVars.insert(NewVD);
6130 if (D.isInvalidType() || Invalid) {
6131 NewVD->setInvalidDecl();
6133 NewTemplate->setInvalidDecl();
6136 SetNestedNameSpecifier(NewVD, D);
6138 // If we have any template parameter lists that don't directly belong to
6139 // the variable (matching the scope specifier), store them.
6140 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6141 if (TemplateParamLists.size() > VDTemplateParamLists)
6142 NewVD->setTemplateParameterListsInfo(
6143 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6145 if (D.getDeclSpec().isConstexprSpecified()) {
6146 NewVD->setConstexpr(true);
6147 // C++1z [dcl.spec.constexpr]p1:
6148 // A static data member declared with the constexpr specifier is
6149 // implicitly an inline variable.
6150 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6151 NewVD->setImplicitlyInline();
6154 if (D.getDeclSpec().isConceptSpecified()) {
6155 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6158 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6159 // be declared with the thread_local, inline, friend, or constexpr
6160 // specifiers, [...]
6161 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6162 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6163 diag::err_concept_decl_invalid_specifiers)
6165 NewVD->setInvalidDecl(true);
6168 if (D.getDeclSpec().isConstexprSpecified()) {
6169 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6170 diag::err_concept_decl_invalid_specifiers)
6172 NewVD->setInvalidDecl(true);
6175 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6176 // applied only to the definition of a function template or variable
6177 // template, declared in namespace scope.
6178 if (IsVariableTemplateSpecialization) {
6179 Diag(D.getDeclSpec().getConceptSpecLoc(),
6180 diag::err_concept_specified_specialization)
6181 << (IsPartialSpecialization ? 2 : 1);
6184 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6185 // following restrictions:
6186 // - The declared type shall have the type bool.
6187 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6188 !NewVD->isInvalidDecl()) {
6189 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6190 NewVD->setInvalidDecl(true);
6195 if (D.getDeclSpec().isInlineSpecified()) {
6196 if (!getLangOpts().CPlusPlus) {
6197 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6199 } else if (CurContext->isFunctionOrMethod()) {
6200 // 'inline' is not allowed on block scope variable declaration.
6201 Diag(D.getDeclSpec().getInlineSpecLoc(),
6202 diag::err_inline_declaration_block_scope) << Name
6203 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6205 Diag(D.getDeclSpec().getInlineSpecLoc(),
6206 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6207 : diag::ext_inline_variable);
6208 NewVD->setInlineSpecified();
6212 // Set the lexical context. If the declarator has a C++ scope specifier, the
6213 // lexical context will be different from the semantic context.
6214 NewVD->setLexicalDeclContext(CurContext);
6216 NewTemplate->setLexicalDeclContext(CurContext);
6218 if (IsLocalExternDecl) {
6219 if (D.isDecompositionDeclarator())
6220 for (auto *B : Bindings)
6221 B->setLocalExternDecl();
6223 NewVD->setLocalExternDecl();
6226 bool EmitTLSUnsupportedError = false;
6227 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6228 // C++11 [dcl.stc]p4:
6229 // When thread_local is applied to a variable of block scope the
6230 // storage-class-specifier static is implied if it does not appear
6232 // Core issue: 'static' is not implied if the variable is declared
6234 if (NewVD->hasLocalStorage() &&
6235 (SCSpec != DeclSpec::SCS_unspecified ||
6236 TSCS != DeclSpec::TSCS_thread_local ||
6237 !DC->isFunctionOrMethod()))
6238 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6239 diag::err_thread_non_global)
6240 << DeclSpec::getSpecifierName(TSCS);
6241 else if (!Context.getTargetInfo().isTLSSupported()) {
6242 if (getLangOpts().CUDA) {
6243 // Postpone error emission until we've collected attributes required to
6244 // figure out whether it's a host or device variable and whether the
6245 // error should be ignored.
6246 EmitTLSUnsupportedError = true;
6247 // We still need to mark the variable as TLS so it shows up in AST with
6248 // proper storage class for other tools to use even if we're not going
6249 // to emit any code for it.
6250 NewVD->setTSCSpec(TSCS);
6252 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6253 diag::err_thread_unsupported);
6255 NewVD->setTSCSpec(TSCS);
6259 // An inline definition of a function with external linkage shall
6260 // not contain a definition of a modifiable object with static or
6261 // thread storage duration...
6262 // We only apply this when the function is required to be defined
6263 // elsewhere, i.e. when the function is not 'extern inline'. Note
6264 // that a local variable with thread storage duration still has to
6265 // be marked 'static'. Also note that it's possible to get these
6266 // semantics in C++ using __attribute__((gnu_inline)).
6267 if (SC == SC_Static && S->getFnParent() != nullptr &&
6268 !NewVD->getType().isConstQualified()) {
6269 FunctionDecl *CurFD = getCurFunctionDecl();
6270 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6271 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6272 diag::warn_static_local_in_extern_inline);
6273 MaybeSuggestAddingStaticToDecl(CurFD);
6277 if (D.getDeclSpec().isModulePrivateSpecified()) {
6278 if (IsVariableTemplateSpecialization)
6279 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6280 << (IsPartialSpecialization ? 1 : 0)
6281 << FixItHint::CreateRemoval(
6282 D.getDeclSpec().getModulePrivateSpecLoc());
6283 else if (IsExplicitSpecialization)
6284 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6286 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6287 else if (NewVD->hasLocalStorage())
6288 Diag(NewVD->getLocation(), diag::err_module_private_local)
6289 << 0 << NewVD->getDeclName()
6290 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6291 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6293 NewVD->setModulePrivate();
6295 NewTemplate->setModulePrivate();
6296 for (auto *B : Bindings)
6297 B->setModulePrivate();
6301 // Handle attributes prior to checking for duplicates in MergeVarDecl
6302 ProcessDeclAttributes(S, NewVD, D);
6304 if (getLangOpts().CUDA) {
6305 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6306 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6307 diag::err_thread_unsupported);
6308 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6309 // storage [duration]."
6310 if (SC == SC_None && S->getFnParent() != nullptr &&
6311 (NewVD->hasAttr<CUDASharedAttr>() ||
6312 NewVD->hasAttr<CUDAConstantAttr>())) {
6313 NewVD->setStorageClass(SC_Static);
6317 // Ensure that dllimport globals without explicit storage class are treated as
6318 // extern. The storage class is set above using parsed attributes. Now we can
6319 // check the VarDecl itself.
6320 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6321 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6322 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6324 // In auto-retain/release, infer strong retension for variables of
6326 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6327 NewVD->setInvalidDecl();
6329 // Handle GNU asm-label extension (encoded as an attribute).
6330 if (Expr *E = (Expr*)D.getAsmLabel()) {
6331 // The parser guarantees this is a string.
6332 StringLiteral *SE = cast<StringLiteral>(E);
6333 StringRef Label = SE->getString();
6334 if (S->getFnParent() != nullptr) {
6338 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6341 // Local Named register
6342 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6343 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6344 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6348 case SC_PrivateExtern:
6351 } else if (SC == SC_Register) {
6352 // Global Named register
6353 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6354 const auto &TI = Context.getTargetInfo();
6355 bool HasSizeMismatch;
6357 if (!TI.isValidGCCRegisterName(Label))
6358 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6359 else if (!TI.validateGlobalRegisterVariable(Label,
6360 Context.getTypeSize(R),
6362 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6363 else if (HasSizeMismatch)
6364 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6367 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6368 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6369 NewVD->setInvalidDecl(true);
6373 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6374 Context, Label, 0));
6375 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6376 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6377 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6378 if (I != ExtnameUndeclaredIdentifiers.end()) {
6379 if (isDeclExternC(NewVD)) {
6380 NewVD->addAttr(I->second);
6381 ExtnameUndeclaredIdentifiers.erase(I);
6383 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6384 << /*Variable*/1 << NewVD;
6388 // Diagnose shadowed variables before filtering for scope.
6389 if (D.getCXXScopeSpec().isEmpty())
6390 CheckShadow(S, NewVD, Previous);
6392 // Don't consider existing declarations that are in a different
6393 // scope and are out-of-semantic-context declarations (if the new
6394 // declaration has linkage).
6395 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6396 D.getCXXScopeSpec().isNotEmpty() ||
6397 IsExplicitSpecialization ||
6398 IsVariableTemplateSpecialization);
6400 // Check whether the previous declaration is in the same block scope. This
6401 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6402 if (getLangOpts().CPlusPlus &&
6403 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6404 NewVD->setPreviousDeclInSameBlockScope(
6405 Previous.isSingleResult() && !Previous.isShadowed() &&
6406 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6408 if (!getLangOpts().CPlusPlus) {
6409 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6411 // If this is an explicit specialization of a static data member, check it.
6412 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6413 CheckMemberSpecialization(NewVD, Previous))
6414 NewVD->setInvalidDecl();
6416 // Merge the decl with the existing one if appropriate.
6417 if (!Previous.empty()) {
6418 if (Previous.isSingleResult() &&
6419 isa<FieldDecl>(Previous.getFoundDecl()) &&
6420 D.getCXXScopeSpec().isSet()) {
6421 // The user tried to define a non-static data member
6422 // out-of-line (C++ [dcl.meaning]p1).
6423 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6424 << D.getCXXScopeSpec().getRange();
6426 NewVD->setInvalidDecl();
6428 } else if (D.getCXXScopeSpec().isSet()) {
6429 // No previous declaration in the qualifying scope.
6430 Diag(D.getIdentifierLoc(), diag::err_no_member)
6431 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6432 << D.getCXXScopeSpec().getRange();
6433 NewVD->setInvalidDecl();
6436 if (!IsVariableTemplateSpecialization)
6437 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6439 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6440 // an explicit specialization (14.8.3) or a partial specialization of a
6441 // concept definition.
6442 if (IsVariableTemplateSpecialization &&
6443 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6444 Previous.isSingleResult()) {
6445 NamedDecl *PreviousDecl = Previous.getFoundDecl();
6446 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6447 if (VarTmpl->isConcept()) {
6448 Diag(NewVD->getLocation(), diag::err_concept_specialized)
6450 << (IsPartialSpecialization ? 2 /*partially specialized*/
6451 : 1 /*explicitly specialized*/);
6452 Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6453 NewVD->setInvalidDecl();
6459 VarTemplateDecl *PrevVarTemplate =
6460 NewVD->getPreviousDecl()
6461 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6464 // Check the template parameter list of this declaration, possibly
6465 // merging in the template parameter list from the previous variable
6466 // template declaration.
6467 if (CheckTemplateParameterList(
6469 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6471 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6472 DC->isDependentContext())
6473 ? TPC_ClassTemplateMember
6475 NewVD->setInvalidDecl();
6477 // If we are providing an explicit specialization of a static variable
6478 // template, make a note of that.
6479 if (PrevVarTemplate &&
6480 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6481 PrevVarTemplate->setMemberSpecialization();
6485 ProcessPragmaWeak(S, NewVD);
6487 // If this is the first declaration of an extern C variable, update
6488 // the map of such variables.
6489 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6490 isIncompleteDeclExternC(*this, NewVD))
6491 RegisterLocallyScopedExternCDecl(NewVD, S);
6493 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6494 Decl *ManglingContextDecl;
6495 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6496 NewVD->getDeclContext(), ManglingContextDecl)) {
6497 Context.setManglingNumber(
6498 NewVD, MCtx->getManglingNumber(
6499 NewVD, getMSManglingNumber(getLangOpts(), S)));
6500 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6504 // Special handling of variable named 'main'.
6505 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6506 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6507 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6509 // C++ [basic.start.main]p3
6510 // A program that declares a variable main at global scope is ill-formed.
6511 if (getLangOpts().CPlusPlus)
6512 Diag(D.getLocStart(), diag::err_main_global_variable);
6514 // In C, and external-linkage variable named main results in undefined
6516 else if (NewVD->hasExternalFormalLinkage())
6517 Diag(D.getLocStart(), diag::warn_main_redefined);
6520 if (D.isRedeclaration() && !Previous.empty()) {
6521 checkDLLAttributeRedeclaration(
6522 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6523 IsExplicitSpecialization, D.isFunctionDefinition());
6527 if (NewVD->isInvalidDecl())
6528 NewTemplate->setInvalidDecl();
6529 ActOnDocumentableDecl(NewTemplate);
6536 /// Enum describing the %select options in diag::warn_decl_shadow.
6537 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6539 /// Determine what kind of declaration we're shadowing.
6540 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6541 const DeclContext *OldDC) {
6542 if (isa<RecordDecl>(OldDC))
6543 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6544 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6547 /// \brief Diagnose variable or built-in function shadowing. Implements
6550 /// This method is called whenever a VarDecl is added to a "useful"
6553 /// \param S the scope in which the shadowing name is being declared
6554 /// \param R the lookup of the name
6556 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6557 // Return if warning is ignored.
6558 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6561 // Don't diagnose declarations at file scope.
6562 if (D->hasGlobalStorage())
6565 DeclContext *NewDC = D->getDeclContext();
6567 // Only diagnose if we're shadowing an unambiguous field or variable.
6568 if (R.getResultKind() != LookupResult::Found)
6571 NamedDecl* ShadowedDecl = R.getFoundDecl();
6572 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6575 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6576 // Fields are not shadowed by variables in C++ static methods.
6577 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6581 // Fields shadowed by constructor parameters are a special case. Usually
6582 // the constructor initializes the field with the parameter.
6583 if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6584 // Remember that this was shadowed so we can either warn about its
6585 // modification or its existence depending on warning settings.
6586 D = D->getCanonicalDecl();
6587 ShadowingDecls.insert({D, FD});
6592 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6593 if (shadowedVar->isExternC()) {
6594 // For shadowing external vars, make sure that we point to the global
6595 // declaration, not a locally scoped extern declaration.
6596 for (auto I : shadowedVar->redecls())
6597 if (I->isFileVarDecl()) {
6603 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6605 // Only warn about certain kinds of shadowing for class members.
6606 if (NewDC && NewDC->isRecord()) {
6607 // In particular, don't warn about shadowing non-class members.
6608 if (!OldDC->isRecord())
6611 // TODO: should we warn about static data members shadowing
6612 // static data members from base classes?
6614 // TODO: don't diagnose for inaccessible shadowed members.
6615 // This is hard to do perfectly because we might friend the
6616 // shadowing context, but that's just a false negative.
6620 DeclarationName Name = R.getLookupName();
6622 // Emit warning and note.
6623 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6625 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6626 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6627 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6630 /// \brief Check -Wshadow without the advantage of a previous lookup.
6631 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6632 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6635 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6636 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6638 CheckShadow(S, D, R);
6641 /// Check if 'E', which is an expression that is about to be modified, refers
6642 /// to a constructor parameter that shadows a field.
6643 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6644 // Quickly ignore expressions that can't be shadowing ctor parameters.
6645 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6647 E = E->IgnoreParenImpCasts();
6648 auto *DRE = dyn_cast<DeclRefExpr>(E);
6651 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6652 auto I = ShadowingDecls.find(D);
6653 if (I == ShadowingDecls.end())
6655 const NamedDecl *ShadowedDecl = I->second;
6656 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6657 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6658 Diag(D->getLocation(), diag::note_var_declared_here) << D;
6659 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6661 // Avoid issuing multiple warnings about the same decl.
6662 ShadowingDecls.erase(I);
6665 /// Check for conflict between this global or extern "C" declaration and
6666 /// previous global or extern "C" declarations. This is only used in C++.
6667 template<typename T>
6668 static bool checkGlobalOrExternCConflict(
6669 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6670 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6671 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6673 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6674 // The common case: this global doesn't conflict with any extern "C"
6680 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6681 // Both the old and new declarations have C language linkage. This is a
6684 Previous.addDecl(Prev);
6688 // This is a global, non-extern "C" declaration, and there is a previous
6689 // non-global extern "C" declaration. Diagnose if this is a variable
6691 if (!isa<VarDecl>(ND))
6694 // The declaration is extern "C". Check for any declaration in the
6695 // translation unit which might conflict.
6697 // We have already performed the lookup into the translation unit.
6699 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6701 if (isa<VarDecl>(*I)) {
6707 DeclContext::lookup_result R =
6708 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6709 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6711 if (isa<VarDecl>(*I)) {
6715 // FIXME: If we have any other entity with this name in global scope,
6716 // the declaration is ill-formed, but that is a defect: it breaks the
6717 // 'stat' hack, for instance. Only variables can have mangled name
6718 // clashes with extern "C" declarations, so only they deserve a
6727 // Use the first declaration's location to ensure we point at something which
6728 // is lexically inside an extern "C" linkage-spec.
6729 assert(Prev && "should have found a previous declaration to diagnose");
6730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6731 Prev = FD->getFirstDecl();
6733 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6735 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6737 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6742 /// Apply special rules for handling extern "C" declarations. Returns \c true
6743 /// if we have found that this is a redeclaration of some prior entity.
6745 /// Per C++ [dcl.link]p6:
6746 /// Two declarations [for a function or variable] with C language linkage
6747 /// with the same name that appear in different scopes refer to the same
6748 /// [entity]. An entity with C language linkage shall not be declared with
6749 /// the same name as an entity in global scope.
6750 template<typename T>
6751 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6752 LookupResult &Previous) {
6753 if (!S.getLangOpts().CPlusPlus) {
6754 // In C, when declaring a global variable, look for a corresponding 'extern'
6755 // variable declared in function scope. We don't need this in C++, because
6756 // we find local extern decls in the surrounding file-scope DeclContext.
6757 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6758 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6760 Previous.addDecl(Prev);
6767 // A declaration in the translation unit can conflict with an extern "C"
6769 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6770 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6772 // An extern "C" declaration can conflict with a declaration in the
6773 // translation unit or can be a redeclaration of an extern "C" declaration
6774 // in another scope.
6775 if (isIncompleteDeclExternC(S,ND))
6776 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6778 // Neither global nor extern "C": nothing to do.
6782 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6783 // If the decl is already known invalid, don't check it.
6784 if (NewVD->isInvalidDecl())
6787 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6788 QualType T = TInfo->getType();
6790 // Defer checking an 'auto' type until its initializer is attached.
6791 if (T->isUndeducedType())
6794 if (NewVD->hasAttrs())
6795 CheckAlignasUnderalignment(NewVD);
6797 if (T->isObjCObjectType()) {
6798 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6799 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6800 T = Context.getObjCObjectPointerType(T);
6804 // Emit an error if an address space was applied to decl with local storage.
6805 // This includes arrays of objects with address space qualifiers, but not
6806 // automatic variables that point to other address spaces.
6807 // ISO/IEC TR 18037 S5.1.2
6808 if (!getLangOpts().OpenCL
6809 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6810 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6811 NewVD->setInvalidDecl();
6815 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6817 if (getLangOpts().OpenCLVersion == 120 &&
6818 !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6819 NewVD->isStaticLocal()) {
6820 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6821 NewVD->setInvalidDecl();
6825 if (getLangOpts().OpenCL) {
6826 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6827 if (NewVD->hasAttr<BlocksAttr>()) {
6828 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6832 if (T->isBlockPointerType()) {
6833 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6834 // can't use 'extern' storage class.
6835 if (!T.isConstQualified()) {
6836 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6838 NewVD->setInvalidDecl();
6841 if (NewVD->hasExternalStorage()) {
6842 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6843 NewVD->setInvalidDecl();
6846 // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6847 // TODO: this check is not enough as it doesn't diagnose the typedef
6848 const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6849 const FunctionProtoType *FTy =
6850 BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6851 if (FTy && FTy->isVariadic()) {
6852 Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6853 << T << NewVD->getSourceRange();
6854 NewVD->setInvalidDecl();
6858 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6859 // __constant address space.
6860 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6861 // variables inside a function can also be declared in the global
6863 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6864 NewVD->hasExternalStorage()) {
6865 if (!T->isSamplerT() &&
6866 !(T.getAddressSpace() == LangAS::opencl_constant ||
6867 (T.getAddressSpace() == LangAS::opencl_global &&
6868 getLangOpts().OpenCLVersion == 200))) {
6869 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6870 if (getLangOpts().OpenCLVersion == 200)
6871 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6872 << Scope << "global or constant";
6874 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6875 << Scope << "constant";
6876 NewVD->setInvalidDecl();
6880 if (T.getAddressSpace() == LangAS::opencl_global) {
6881 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6882 << 1 /*is any function*/ << "global";
6883 NewVD->setInvalidDecl();
6886 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6888 if (T.getAddressSpace() == LangAS::opencl_constant ||
6889 T.getAddressSpace() == LangAS::opencl_local) {
6890 FunctionDecl *FD = getCurFunctionDecl();
6891 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6892 if (T.getAddressSpace() == LangAS::opencl_constant)
6893 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6894 << 0 /*non-kernel only*/ << "constant";
6896 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6897 << 0 /*non-kernel only*/ << "local";
6898 NewVD->setInvalidDecl();
6905 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6906 && !NewVD->hasAttr<BlocksAttr>()) {
6907 if (getLangOpts().getGC() != LangOptions::NonGC)
6908 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6910 assert(!getLangOpts().ObjCAutoRefCount);
6911 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6915 bool isVM = T->isVariablyModifiedType();
6916 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6917 NewVD->hasAttr<BlocksAttr>())
6918 getCurFunction()->setHasBranchProtectedScope();
6920 if ((isVM && NewVD->hasLinkage()) ||
6921 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6922 bool SizeIsNegative;
6923 llvm::APSInt Oversized;
6924 TypeSourceInfo *FixedTInfo =
6925 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6926 SizeIsNegative, Oversized);
6927 if (!FixedTInfo && T->isVariableArrayType()) {
6928 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6929 // FIXME: This won't give the correct result for
6931 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6933 if (NewVD->isFileVarDecl())
6934 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6936 else if (NewVD->isStaticLocal())
6937 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6940 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6942 NewVD->setInvalidDecl();
6947 if (NewVD->isFileVarDecl())
6948 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6950 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6951 NewVD->setInvalidDecl();
6955 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6956 NewVD->setType(FixedTInfo->getType());
6957 NewVD->setTypeSourceInfo(FixedTInfo);
6960 if (T->isVoidType()) {
6961 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6962 // of objects and functions.
6963 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6964 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6966 NewVD->setInvalidDecl();
6971 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6972 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6973 NewVD->setInvalidDecl();
6977 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6978 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6979 NewVD->setInvalidDecl();
6983 if (NewVD->isConstexpr() && !T->isDependentType() &&
6984 RequireLiteralType(NewVD->getLocation(), T,
6985 diag::err_constexpr_var_non_literal)) {
6986 NewVD->setInvalidDecl();
6991 /// \brief Perform semantic checking on a newly-created variable
6994 /// This routine performs all of the type-checking required for a
6995 /// variable declaration once it has been built. It is used both to
6996 /// check variables after they have been parsed and their declarators
6997 /// have been translated into a declaration, and to check variables
6998 /// that have been instantiated from a template.
7000 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7002 /// Returns true if the variable declaration is a redeclaration.
7003 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7004 CheckVariableDeclarationType(NewVD);
7006 // If the decl is already known invalid, don't check it.
7007 if (NewVD->isInvalidDecl())
7010 // If we did not find anything by this name, look for a non-visible
7011 // extern "C" declaration with the same name.
7012 if (Previous.empty() &&
7013 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7014 Previous.setShadowed();
7016 if (!Previous.empty()) {
7017 MergeVarDecl(NewVD, Previous);
7024 struct FindOverriddenMethod {
7026 CXXMethodDecl *Method;
7028 /// Member lookup function that determines whether a given C++
7029 /// method overrides a method in a base class, to be used with
7030 /// CXXRecordDecl::lookupInBases().
7031 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7032 RecordDecl *BaseRecord =
7033 Specifier->getType()->getAs<RecordType>()->getDecl();
7035 DeclarationName Name = Method->getDeclName();
7037 // FIXME: Do we care about other names here too?
7038 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7039 // We really want to find the base class destructor here.
7040 QualType T = S->Context.getTypeDeclType(BaseRecord);
7041 CanQualType CT = S->Context.getCanonicalType(T);
7043 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7046 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7047 Path.Decls = Path.Decls.slice(1)) {
7048 NamedDecl *D = Path.Decls.front();
7049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7050 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7059 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7060 } // end anonymous namespace
7062 /// \brief Report an error regarding overriding, along with any relevant
7063 /// overriden methods.
7065 /// \param DiagID the primary error to report.
7066 /// \param MD the overriding method.
7067 /// \param OEK which overrides to include as notes.
7068 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7069 OverrideErrorKind OEK = OEK_All) {
7070 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7071 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7072 E = MD->end_overridden_methods();
7074 // This check (& the OEK parameter) could be replaced by a predicate, but
7075 // without lambdas that would be overkill. This is still nicer than writing
7076 // out the diag loop 3 times.
7077 if ((OEK == OEK_All) ||
7078 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7079 (OEK == OEK_Deleted && (*I)->isDeleted()))
7080 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7084 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7085 /// and if so, check that it's a valid override and remember it.
7086 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7087 // Look for methods in base classes that this method might override.
7089 FindOverriddenMethod FOM;
7092 bool hasDeletedOverridenMethods = false;
7093 bool hasNonDeletedOverridenMethods = false;
7094 bool AddedAny = false;
7095 if (DC->lookupInBases(FOM, Paths)) {
7096 for (auto *I : Paths.found_decls()) {
7097 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7098 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7099 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7100 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7101 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7102 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7103 hasDeletedOverridenMethods |= OldMD->isDeleted();
7104 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7111 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7112 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7114 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7115 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7122 // Struct for holding all of the extra arguments needed by
7123 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7124 struct ActOnFDArgs {
7127 MultiTemplateParamsArg TemplateParamLists;
7130 } // end anonymous namespace
7134 // Callback to only accept typo corrections that have a non-zero edit distance.
7135 // Also only accept corrections that have the same parent decl.
7136 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7138 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7139 CXXRecordDecl *Parent)
7140 : Context(Context), OriginalFD(TypoFD),
7141 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7143 bool ValidateCandidate(const TypoCorrection &candidate) override {
7144 if (candidate.getEditDistance() == 0)
7147 SmallVector<unsigned, 1> MismatchedParams;
7148 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7149 CDeclEnd = candidate.end();
7150 CDecl != CDeclEnd; ++CDecl) {
7151 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7153 if (FD && !FD->hasBody() &&
7154 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7155 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7156 CXXRecordDecl *Parent = MD->getParent();
7157 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7159 } else if (!ExpectedParent) {
7169 ASTContext &Context;
7170 FunctionDecl *OriginalFD;
7171 CXXRecordDecl *ExpectedParent;
7174 } // end anonymous namespace
7176 /// \brief Generate diagnostics for an invalid function redeclaration.
7178 /// This routine handles generating the diagnostic messages for an invalid
7179 /// function redeclaration, including finding possible similar declarations
7180 /// or performing typo correction if there are no previous declarations with
7183 /// Returns a NamedDecl iff typo correction was performed and substituting in
7184 /// the new declaration name does not cause new errors.
7185 static NamedDecl *DiagnoseInvalidRedeclaration(
7186 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7187 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7188 DeclarationName Name = NewFD->getDeclName();
7189 DeclContext *NewDC = NewFD->getDeclContext();
7190 SmallVector<unsigned, 1> MismatchedParams;
7191 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7192 TypoCorrection Correction;
7193 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7194 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7195 : diag::err_member_decl_does_not_match;
7196 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7197 IsLocalFriend ? Sema::LookupLocalFriendName
7198 : Sema::LookupOrdinaryName,
7199 Sema::ForRedeclaration);
7201 NewFD->setInvalidDecl();
7203 SemaRef.LookupName(Prev, S);
7205 SemaRef.LookupQualifiedName(Prev, NewDC);
7206 assert(!Prev.isAmbiguous() &&
7207 "Cannot have an ambiguity in previous-declaration lookup");
7208 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7209 if (!Prev.empty()) {
7210 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7211 Func != FuncEnd; ++Func) {
7212 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7214 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7215 // Add 1 to the index so that 0 can mean the mismatch didn't
7216 // involve a parameter
7218 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7219 NearMatches.push_back(std::make_pair(FD, ParamNum));
7222 // If the qualified name lookup yielded nothing, try typo correction
7223 } else if ((Correction = SemaRef.CorrectTypo(
7224 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7225 &ExtraArgs.D.getCXXScopeSpec(),
7226 llvm::make_unique<DifferentNameValidatorCCC>(
7227 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7228 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7229 // Set up everything for the call to ActOnFunctionDeclarator
7230 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7231 ExtraArgs.D.getIdentifierLoc());
7233 Previous.setLookupName(Correction.getCorrection());
7234 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7235 CDeclEnd = Correction.end();
7236 CDecl != CDeclEnd; ++CDecl) {
7237 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7238 if (FD && !FD->hasBody() &&
7239 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7240 Previous.addDecl(FD);
7243 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7246 // Retry building the function declaration with the new previous
7247 // declarations, and with errors suppressed.
7250 Sema::SFINAETrap Trap(SemaRef);
7252 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7253 // pieces need to verify the typo-corrected C++ declaration and hopefully
7254 // eliminate the need for the parameter pack ExtraArgs.
7255 Result = SemaRef.ActOnFunctionDeclarator(
7256 ExtraArgs.S, ExtraArgs.D,
7257 Correction.getCorrectionDecl()->getDeclContext(),
7258 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7259 ExtraArgs.AddToScope);
7261 if (Trap.hasErrorOccurred())
7266 // Determine which correction we picked.
7267 Decl *Canonical = Result->getCanonicalDecl();
7268 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7270 if ((*I)->getCanonicalDecl() == Canonical)
7271 Correction.setCorrectionDecl(*I);
7273 SemaRef.diagnoseTypo(
7275 SemaRef.PDiag(IsLocalFriend
7276 ? diag::err_no_matching_local_friend_suggest
7277 : diag::err_member_decl_does_not_match_suggest)
7278 << Name << NewDC << IsDefinition);
7282 // Pretend the typo correction never occurred
7283 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7284 ExtraArgs.D.getIdentifierLoc());
7285 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7287 Previous.setLookupName(Name);
7290 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7291 << Name << NewDC << IsDefinition << NewFD->getLocation();
7293 bool NewFDisConst = false;
7294 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7295 NewFDisConst = NewMD->isConst();
7297 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7298 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7299 NearMatch != NearMatchEnd; ++NearMatch) {
7300 FunctionDecl *FD = NearMatch->first;
7301 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7302 bool FDisConst = MD && MD->isConst();
7303 bool IsMember = MD || !IsLocalFriend;
7305 // FIXME: These notes are poorly worded for the local friend case.
7306 if (unsigned Idx = NearMatch->second) {
7307 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7308 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7309 if (Loc.isInvalid()) Loc = FD->getLocation();
7310 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7311 : diag::note_local_decl_close_param_match)
7312 << Idx << FDParam->getType()
7313 << NewFD->getParamDecl(Idx - 1)->getType();
7314 } else if (FDisConst != NewFDisConst) {
7315 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7316 << NewFDisConst << FD->getSourceRange().getEnd();
7318 SemaRef.Diag(FD->getLocation(),
7319 IsMember ? diag::note_member_def_close_match
7320 : diag::note_local_decl_close_match);
7325 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7326 switch (D.getDeclSpec().getStorageClassSpec()) {
7327 default: llvm_unreachable("Unknown storage class!");
7328 case DeclSpec::SCS_auto:
7329 case DeclSpec::SCS_register:
7330 case DeclSpec::SCS_mutable:
7331 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7332 diag::err_typecheck_sclass_func);
7335 case DeclSpec::SCS_unspecified: break;
7336 case DeclSpec::SCS_extern:
7337 if (D.getDeclSpec().isExternInLinkageSpec())
7340 case DeclSpec::SCS_static: {
7341 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7343 // The declaration of an identifier for a function that has
7344 // block scope shall have no explicit storage-class specifier
7345 // other than extern
7346 // See also (C++ [dcl.stc]p4).
7347 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7348 diag::err_static_block_func);
7353 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7356 // No explicit storage class has already been returned
7360 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7361 DeclContext *DC, QualType &R,
7362 TypeSourceInfo *TInfo,
7364 bool &IsVirtualOkay) {
7365 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7366 DeclarationName Name = NameInfo.getName();
7368 FunctionDecl *NewFD = nullptr;
7369 bool isInline = D.getDeclSpec().isInlineSpecified();
7371 if (!SemaRef.getLangOpts().CPlusPlus) {
7372 // Determine whether the function was written with a
7373 // prototype. This true when:
7374 // - there is a prototype in the declarator, or
7375 // - the type R of the function is some kind of typedef or other reference
7376 // to a type name (which eventually refers to a function type).
7378 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7379 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7381 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7382 D.getLocStart(), NameInfo, R,
7383 TInfo, SC, isInline,
7384 HasPrototype, false);
7385 if (D.isInvalidType())
7386 NewFD->setInvalidDecl();
7391 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7392 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7394 // Check that the return type is not an abstract class type.
7395 // For record types, this is done by the AbstractClassUsageDiagnoser once
7396 // the class has been completely parsed.
7397 if (!DC->isRecord() &&
7398 SemaRef.RequireNonAbstractType(
7399 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7400 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7403 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7404 // This is a C++ constructor declaration.
7405 assert(DC->isRecord() &&
7406 "Constructors can only be declared in a member context");
7408 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7409 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7410 D.getLocStart(), NameInfo,
7411 R, TInfo, isExplicit, isInline,
7412 /*isImplicitlyDeclared=*/false,
7415 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7416 // This is a C++ destructor declaration.
7417 if (DC->isRecord()) {
7418 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7419 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7420 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7421 SemaRef.Context, Record,
7423 NameInfo, R, TInfo, isInline,
7424 /*isImplicitlyDeclared=*/false);
7426 // If the class is complete, then we now create the implicit exception
7427 // specification. If the class is incomplete or dependent, we can't do
7429 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7430 Record->getDefinition() && !Record->isBeingDefined() &&
7431 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7432 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7435 IsVirtualOkay = true;
7439 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7442 // Create a FunctionDecl to satisfy the function definition parsing
7444 return FunctionDecl::Create(SemaRef.Context, DC,
7446 D.getIdentifierLoc(), Name, R, TInfo,
7448 /*hasPrototype=*/true, isConstexpr);
7451 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7452 if (!DC->isRecord()) {
7453 SemaRef.Diag(D.getIdentifierLoc(),
7454 diag::err_conv_function_not_member);
7458 SemaRef.CheckConversionDeclarator(D, R, SC);
7459 IsVirtualOkay = true;
7460 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7461 D.getLocStart(), NameInfo,
7462 R, TInfo, isInline, isExplicit,
7463 isConstexpr, SourceLocation());
7465 } else if (DC->isRecord()) {
7466 // If the name of the function is the same as the name of the record,
7467 // then this must be an invalid constructor that has a return type.
7468 // (The parser checks for a return type and makes the declarator a
7469 // constructor if it has no return type).
7470 if (Name.getAsIdentifierInfo() &&
7471 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7472 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7473 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7474 << SourceRange(D.getIdentifierLoc());
7478 // This is a C++ method declaration.
7479 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7480 cast<CXXRecordDecl>(DC),
7481 D.getLocStart(), NameInfo, R,
7482 TInfo, SC, isInline,
7483 isConstexpr, SourceLocation());
7484 IsVirtualOkay = !Ret->isStatic();
7488 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7489 if (!isFriend && SemaRef.CurContext->isRecord())
7492 // Determine whether the function was written with a
7493 // prototype. This true when:
7494 // - we're in C++ (where every function has a prototype),
7495 return FunctionDecl::Create(SemaRef.Context, DC,
7497 NameInfo, R, TInfo, SC, isInline,
7498 true/*HasPrototype*/, isConstexpr);
7502 enum OpenCLParamType {
7506 PrivatePtrKernelParam,
7511 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7512 if (PT->isPointerType()) {
7513 QualType PointeeType = PT->getPointeeType();
7514 if (PointeeType->isPointerType())
7515 return PtrPtrKernelParam;
7516 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7520 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7521 // be used as builtin types.
7523 if (PT->isImageType())
7524 return PtrKernelParam;
7526 if (PT->isBooleanType())
7527 return InvalidKernelParam;
7530 return InvalidKernelParam;
7532 if (PT->isHalfType())
7533 return InvalidKernelParam;
7535 if (PT->isRecordType())
7536 return RecordKernelParam;
7538 return ValidKernelParam;
7541 static void checkIsValidOpenCLKernelParameter(
7545 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7546 QualType PT = Param->getType();
7548 // Cache the valid types we encounter to avoid rechecking structs that are
7550 if (ValidTypes.count(PT.getTypePtr()))
7553 switch (getOpenCLKernelParameterType(PT)) {
7554 case PtrPtrKernelParam:
7555 // OpenCL v1.2 s6.9.a:
7556 // A kernel function argument cannot be declared as a
7557 // pointer to a pointer type.
7558 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7562 case PrivatePtrKernelParam:
7563 // OpenCL v1.2 s6.9.a:
7564 // A kernel function argument cannot be declared as a
7565 // pointer to the private address space.
7566 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7570 // OpenCL v1.2 s6.9.k:
7571 // Arguments to kernel functions in a program cannot be declared with the
7572 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7573 // uintptr_t or a struct and/or union that contain fields declared to be
7574 // one of these built-in scalar types.
7576 case InvalidKernelParam:
7577 // OpenCL v1.2 s6.8 n:
7578 // A kernel function argument cannot be declared
7580 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7584 case PtrKernelParam:
7585 case ValidKernelParam:
7586 ValidTypes.insert(PT.getTypePtr());
7589 case RecordKernelParam:
7593 // Track nested structs we will inspect
7594 SmallVector<const Decl *, 4> VisitStack;
7596 // Track where we are in the nested structs. Items will migrate from
7597 // VisitStack to HistoryStack as we do the DFS for bad field.
7598 SmallVector<const FieldDecl *, 4> HistoryStack;
7599 HistoryStack.push_back(nullptr);
7601 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7602 VisitStack.push_back(PD);
7604 assert(VisitStack.back() && "First decl null?");
7607 const Decl *Next = VisitStack.pop_back_val();
7609 assert(!HistoryStack.empty());
7610 // Found a marker, we have gone up a level
7611 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7612 ValidTypes.insert(Hist->getType().getTypePtr());
7617 // Adds everything except the original parameter declaration (which is not a
7618 // field itself) to the history stack.
7619 const RecordDecl *RD;
7620 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7621 HistoryStack.push_back(Field);
7622 RD = Field->getType()->castAs<RecordType>()->getDecl();
7624 RD = cast<RecordDecl>(Next);
7627 // Add a null marker so we know when we've gone back up a level
7628 VisitStack.push_back(nullptr);
7630 for (const auto *FD : RD->fields()) {
7631 QualType QT = FD->getType();
7633 if (ValidTypes.count(QT.getTypePtr()))
7636 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7637 if (ParamType == ValidKernelParam)
7640 if (ParamType == RecordKernelParam) {
7641 VisitStack.push_back(FD);
7645 // OpenCL v1.2 s6.9.p:
7646 // Arguments to kernel functions that are declared to be a struct or union
7647 // do not allow OpenCL objects to be passed as elements of the struct or
7649 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7650 ParamType == PrivatePtrKernelParam) {
7651 S.Diag(Param->getLocation(),
7652 diag::err_record_with_pointers_kernel_param)
7653 << PT->isUnionType()
7656 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7659 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7660 << PD->getDeclName();
7662 // We have an error, now let's go back up through history and show where
7663 // the offending field came from
7664 for (ArrayRef<const FieldDecl *>::const_iterator
7665 I = HistoryStack.begin() + 1,
7666 E = HistoryStack.end();
7668 const FieldDecl *OuterField = *I;
7669 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7670 << OuterField->getType();
7673 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7674 << QT->isPointerType()
7679 } while (!VisitStack.empty());
7683 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7684 TypeSourceInfo *TInfo, LookupResult &Previous,
7685 MultiTemplateParamsArg TemplateParamLists,
7687 QualType R = TInfo->getType();
7689 assert(R.getTypePtr()->isFunctionType());
7691 // TODO: consider using NameInfo for diagnostic.
7692 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7693 DeclarationName Name = NameInfo.getName();
7694 StorageClass SC = getFunctionStorageClass(*this, D);
7696 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7697 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7698 diag::err_invalid_thread)
7699 << DeclSpec::getSpecifierName(TSCS);
7701 if (D.isFirstDeclarationOfMember())
7702 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7703 D.getIdentifierLoc());
7705 bool isFriend = false;
7706 FunctionTemplateDecl *FunctionTemplate = nullptr;
7707 bool isExplicitSpecialization = false;
7708 bool isFunctionTemplateSpecialization = false;
7710 bool isDependentClassScopeExplicitSpecialization = false;
7711 bool HasExplicitTemplateArgs = false;
7712 TemplateArgumentListInfo TemplateArgs;
7714 bool isVirtualOkay = false;
7716 DeclContext *OriginalDC = DC;
7717 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7719 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7721 if (!NewFD) return nullptr;
7723 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7724 NewFD->setTopLevelDeclInObjCContainer();
7726 // Set the lexical context. If this is a function-scope declaration, or has a
7727 // C++ scope specifier, or is the object of a friend declaration, the lexical
7728 // context will be different from the semantic context.
7729 NewFD->setLexicalDeclContext(CurContext);
7731 if (IsLocalExternDecl)
7732 NewFD->setLocalExternDecl();
7734 if (getLangOpts().CPlusPlus) {
7735 bool isInline = D.getDeclSpec().isInlineSpecified();
7736 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7737 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7738 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7739 bool isConcept = D.getDeclSpec().isConceptSpecified();
7740 isFriend = D.getDeclSpec().isFriendSpecified();
7741 if (isFriend && !isInline && D.isFunctionDefinition()) {
7742 // C++ [class.friend]p5
7743 // A function can be defined in a friend declaration of a
7744 // class . . . . Such a function is implicitly inline.
7745 NewFD->setImplicitlyInline();
7748 // If this is a method defined in an __interface, and is not a constructor
7749 // or an overloaded operator, then set the pure flag (isVirtual will already
7751 if (const CXXRecordDecl *Parent =
7752 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7753 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7754 NewFD->setPure(true);
7756 // C++ [class.union]p2
7757 // A union can have member functions, but not virtual functions.
7758 if (isVirtual && Parent->isUnion())
7759 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7762 SetNestedNameSpecifier(NewFD, D);
7763 isExplicitSpecialization = false;
7764 isFunctionTemplateSpecialization = false;
7765 if (D.isInvalidType())
7766 NewFD->setInvalidDecl();
7768 // Match up the template parameter lists with the scope specifier, then
7769 // determine whether we have a template or a template specialization.
7770 bool Invalid = false;
7771 if (TemplateParameterList *TemplateParams =
7772 MatchTemplateParametersToScopeSpecifier(
7773 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7774 D.getCXXScopeSpec(),
7775 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7776 ? D.getName().TemplateId
7778 TemplateParamLists, isFriend, isExplicitSpecialization,
7780 if (TemplateParams->size() > 0) {
7781 // This is a function template
7783 // Check that we can declare a template here.
7784 if (CheckTemplateDeclScope(S, TemplateParams))
7785 NewFD->setInvalidDecl();
7787 // A destructor cannot be a template.
7788 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7789 Diag(NewFD->getLocation(), diag::err_destructor_template);
7790 NewFD->setInvalidDecl();
7793 // If we're adding a template to a dependent context, we may need to
7794 // rebuilding some of the types used within the template parameter list,
7795 // now that we know what the current instantiation is.
7796 if (DC->isDependentContext()) {
7797 ContextRAII SavedContext(*this, DC);
7798 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7802 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7803 NewFD->getLocation(),
7804 Name, TemplateParams,
7806 FunctionTemplate->setLexicalDeclContext(CurContext);
7807 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7809 // For source fidelity, store the other template param lists.
7810 if (TemplateParamLists.size() > 1) {
7811 NewFD->setTemplateParameterListsInfo(Context,
7812 TemplateParamLists.drop_back(1));
7815 // This is a function template specialization.
7816 isFunctionTemplateSpecialization = true;
7817 // For source fidelity, store all the template param lists.
7818 if (TemplateParamLists.size() > 0)
7819 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7821 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7823 // We want to remove the "template<>", found here.
7824 SourceRange RemoveRange = TemplateParams->getSourceRange();
7826 // If we remove the template<> and the name is not a
7827 // template-id, we're actually silently creating a problem:
7828 // the friend declaration will refer to an untemplated decl,
7829 // and clearly the user wants a template specialization. So
7830 // we need to insert '<>' after the name.
7831 SourceLocation InsertLoc;
7832 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7833 InsertLoc = D.getName().getSourceRange().getEnd();
7834 InsertLoc = getLocForEndOfToken(InsertLoc);
7837 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7838 << Name << RemoveRange
7839 << FixItHint::CreateRemoval(RemoveRange)
7840 << FixItHint::CreateInsertion(InsertLoc, "<>");
7845 // All template param lists were matched against the scope specifier:
7846 // this is NOT (an explicit specialization of) a template.
7847 if (TemplateParamLists.size() > 0)
7848 // For source fidelity, store all the template param lists.
7849 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7853 NewFD->setInvalidDecl();
7854 if (FunctionTemplate)
7855 FunctionTemplate->setInvalidDecl();
7858 // C++ [dcl.fct.spec]p5:
7859 // The virtual specifier shall only be used in declarations of
7860 // nonstatic class member functions that appear within a
7861 // member-specification of a class declaration; see 10.3.
7863 if (isVirtual && !NewFD->isInvalidDecl()) {
7864 if (!isVirtualOkay) {
7865 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7866 diag::err_virtual_non_function);
7867 } else if (!CurContext->isRecord()) {
7868 // 'virtual' was specified outside of the class.
7869 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7870 diag::err_virtual_out_of_class)
7871 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7872 } else if (NewFD->getDescribedFunctionTemplate()) {
7873 // C++ [temp.mem]p3:
7874 // A member function template shall not be virtual.
7875 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7876 diag::err_virtual_member_function_template)
7877 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7879 // Okay: Add virtual to the method.
7880 NewFD->setVirtualAsWritten(true);
7883 if (getLangOpts().CPlusPlus14 &&
7884 NewFD->getReturnType()->isUndeducedType())
7885 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7888 if (getLangOpts().CPlusPlus14 &&
7889 (NewFD->isDependentContext() ||
7890 (isFriend && CurContext->isDependentContext())) &&
7891 NewFD->getReturnType()->isUndeducedType()) {
7892 // If the function template is referenced directly (for instance, as a
7893 // member of the current instantiation), pretend it has a dependent type.
7894 // This is not really justified by the standard, but is the only sane
7896 // FIXME: For a friend function, we have not marked the function as being
7897 // a friend yet, so 'isDependentContext' on the FD doesn't work.
7898 const FunctionProtoType *FPT =
7899 NewFD->getType()->castAs<FunctionProtoType>();
7901 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7902 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7903 FPT->getExtProtoInfo()));
7906 // C++ [dcl.fct.spec]p3:
7907 // The inline specifier shall not appear on a block scope function
7909 if (isInline && !NewFD->isInvalidDecl()) {
7910 if (CurContext->isFunctionOrMethod()) {
7911 // 'inline' is not allowed on block scope function declaration.
7912 Diag(D.getDeclSpec().getInlineSpecLoc(),
7913 diag::err_inline_declaration_block_scope) << Name
7914 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7918 // C++ [dcl.fct.spec]p6:
7919 // The explicit specifier shall be used only in the declaration of a
7920 // constructor or conversion function within its class definition;
7921 // see 12.3.1 and 12.3.2.
7922 if (isExplicit && !NewFD->isInvalidDecl()) {
7923 if (!CurContext->isRecord()) {
7924 // 'explicit' was specified outside of the class.
7925 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7926 diag::err_explicit_out_of_class)
7927 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7928 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7929 !isa<CXXConversionDecl>(NewFD)) {
7930 // 'explicit' was specified on a function that wasn't a constructor
7931 // or conversion function.
7932 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7933 diag::err_explicit_non_ctor_or_conv_function)
7934 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7939 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7940 // are implicitly inline.
7941 NewFD->setImplicitlyInline();
7943 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7944 // be either constructors or to return a literal type. Therefore,
7945 // destructors cannot be declared constexpr.
7946 if (isa<CXXDestructorDecl>(NewFD))
7947 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7951 // This is a function concept.
7952 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7955 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7956 // applied only to the definition of a function template [...]
7957 if (!D.isFunctionDefinition()) {
7958 Diag(D.getDeclSpec().getConceptSpecLoc(),
7959 diag::err_function_concept_not_defined);
7960 NewFD->setInvalidDecl();
7963 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7964 // have no exception-specification and is treated as if it were specified
7965 // with noexcept(true) (15.4). [...]
7966 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7967 if (FPT->hasExceptionSpec()) {
7969 if (D.isFunctionDeclarator())
7970 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7971 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7972 << FixItHint::CreateRemoval(Range);
7973 NewFD->setInvalidDecl();
7975 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7978 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7979 // following restrictions:
7980 // - The declared return type shall have the type bool.
7981 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7982 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7983 NewFD->setInvalidDecl();
7986 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7987 // following restrictions:
7988 // - The declaration's parameter list shall be equivalent to an empty
7990 if (FPT->getNumParams() > 0 || FPT->isVariadic())
7991 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7994 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7995 // implicity defined to be a constexpr declaration (implicitly inline)
7996 NewFD->setImplicitlyInline();
7998 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7999 // be declared with the thread_local, inline, friend, or constexpr
8000 // specifiers, [...]
8002 Diag(D.getDeclSpec().getInlineSpecLoc(),
8003 diag::err_concept_decl_invalid_specifiers)
8005 NewFD->setInvalidDecl(true);
8009 Diag(D.getDeclSpec().getFriendSpecLoc(),
8010 diag::err_concept_decl_invalid_specifiers)
8012 NewFD->setInvalidDecl(true);
8016 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8017 diag::err_concept_decl_invalid_specifiers)
8019 NewFD->setInvalidDecl(true);
8022 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8023 // applied only to the definition of a function template or variable
8024 // template, declared in namespace scope.
8025 if (isFunctionTemplateSpecialization) {
8026 Diag(D.getDeclSpec().getConceptSpecLoc(),
8027 diag::err_concept_specified_specialization) << 1;
8028 NewFD->setInvalidDecl(true);
8033 // If __module_private__ was specified, mark the function accordingly.
8034 if (D.getDeclSpec().isModulePrivateSpecified()) {
8035 if (isFunctionTemplateSpecialization) {
8036 SourceLocation ModulePrivateLoc
8037 = D.getDeclSpec().getModulePrivateSpecLoc();
8038 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8040 << FixItHint::CreateRemoval(ModulePrivateLoc);
8042 NewFD->setModulePrivate();
8043 if (FunctionTemplate)
8044 FunctionTemplate->setModulePrivate();
8049 if (FunctionTemplate) {
8050 FunctionTemplate->setObjectOfFriendDecl();
8051 FunctionTemplate->setAccess(AS_public);
8053 NewFD->setObjectOfFriendDecl();
8054 NewFD->setAccess(AS_public);
8057 // If a function is defined as defaulted or deleted, mark it as such now.
8058 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8059 // definition kind to FDK_Definition.
8060 switch (D.getFunctionDefinitionKind()) {
8061 case FDK_Declaration:
8062 case FDK_Definition:
8066 NewFD->setDefaulted();
8070 NewFD->setDeletedAsWritten();
8074 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8075 D.isFunctionDefinition()) {
8076 // C++ [class.mfct]p2:
8077 // A member function may be defined (8.4) in its class definition, in
8078 // which case it is an inline member function (7.1.2)
8079 NewFD->setImplicitlyInline();
8082 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8083 !CurContext->isRecord()) {
8084 // C++ [class.static]p1:
8085 // A data or function member of a class may be declared static
8086 // in a class definition, in which case it is a static member of
8089 // Complain about the 'static' specifier if it's on an out-of-line
8090 // member function definition.
8091 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8092 diag::err_static_out_of_line)
8093 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8096 // C++11 [except.spec]p15:
8097 // A deallocation function with no exception-specification is treated
8098 // as if it were specified with noexcept(true).
8099 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8100 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8101 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8102 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8103 NewFD->setType(Context.getFunctionType(
8104 FPT->getReturnType(), FPT->getParamTypes(),
8105 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8108 // Filter out previous declarations that don't match the scope.
8109 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8110 D.getCXXScopeSpec().isNotEmpty() ||
8111 isExplicitSpecialization ||
8112 isFunctionTemplateSpecialization);
8114 // Handle GNU asm-label extension (encoded as an attribute).
8115 if (Expr *E = (Expr*) D.getAsmLabel()) {
8116 // The parser guarantees this is a string.
8117 StringLiteral *SE = cast<StringLiteral>(E);
8118 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8119 SE->getString(), 0));
8120 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8121 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8122 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8123 if (I != ExtnameUndeclaredIdentifiers.end()) {
8124 if (isDeclExternC(NewFD)) {
8125 NewFD->addAttr(I->second);
8126 ExtnameUndeclaredIdentifiers.erase(I);
8128 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8129 << /*Variable*/0 << NewFD;
8133 // Copy the parameter declarations from the declarator D to the function
8134 // declaration NewFD, if they are available. First scavenge them into Params.
8135 SmallVector<ParmVarDecl*, 16> Params;
8136 if (D.isFunctionDeclarator()) {
8137 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8139 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8140 // function that takes no arguments, not a function that takes a
8141 // single void argument.
8142 // We let through "const void" here because Sema::GetTypeForDeclarator
8143 // already checks for that case.
8144 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8145 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8146 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8147 assert(Param->getDeclContext() != NewFD && "Was set before ?");
8148 Param->setDeclContext(NewFD);
8149 Params.push_back(Param);
8151 if (Param->isInvalidDecl())
8152 NewFD->setInvalidDecl();
8155 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8156 // When we're declaring a function with a typedef, typeof, etc as in the
8157 // following example, we'll need to synthesize (unnamed)
8158 // parameters for use in the declaration.
8161 // typedef void fn(int);
8165 // Synthesize a parameter for each argument type.
8166 for (const auto &AI : FT->param_types()) {
8167 ParmVarDecl *Param =
8168 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8169 Param->setScopeInfo(0, Params.size());
8170 Params.push_back(Param);
8173 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8174 "Should not need args for typedef of non-prototype fn");
8177 // Finally, we know we have the right number of parameters, install them.
8178 NewFD->setParams(Params);
8180 // Find all anonymous symbols defined during the declaration of this function
8181 // and add to NewFD. This lets us track decls such 'enum Y' in:
8183 // void f(enum Y {AA} x) {}
8185 // which would otherwise incorrectly end up in the translation unit scope.
8186 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8187 DeclsInPrototypeScope.clear();
8189 if (D.getDeclSpec().isNoreturnSpecified())
8191 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8194 // Functions returning a variably modified type violate C99 6.7.5.2p2
8195 // because all functions have linkage.
8196 if (!NewFD->isInvalidDecl() &&
8197 NewFD->getReturnType()->isVariablyModifiedType()) {
8198 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8199 NewFD->setInvalidDecl();
8202 // Apply an implicit SectionAttr if #pragma code_seg is active.
8203 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8204 !NewFD->hasAttr<SectionAttr>()) {
8206 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8207 CodeSegStack.CurrentValue->getString(),
8208 CodeSegStack.CurrentPragmaLocation));
8209 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8210 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8211 ASTContext::PSF_Read,
8213 NewFD->dropAttr<SectionAttr>();
8216 // Handle attributes.
8217 ProcessDeclAttributes(S, NewFD, D);
8219 if (getLangOpts().CUDA)
8220 maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8222 if (getLangOpts().OpenCL) {
8223 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8224 // type declaration will generate a compilation error.
8225 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8226 if (AddressSpace == LangAS::opencl_local ||
8227 AddressSpace == LangAS::opencl_global ||
8228 AddressSpace == LangAS::opencl_constant) {
8229 Diag(NewFD->getLocation(),
8230 diag::err_opencl_return_value_with_address_space);
8231 NewFD->setInvalidDecl();
8235 if (!getLangOpts().CPlusPlus) {
8236 // Perform semantic checking on the function declaration.
8237 bool isExplicitSpecialization=false;
8238 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8239 CheckMain(NewFD, D.getDeclSpec());
8241 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8242 CheckMSVCRTEntryPoint(NewFD);
8244 if (!NewFD->isInvalidDecl())
8245 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8246 isExplicitSpecialization));
8247 else if (!Previous.empty())
8248 // Recover gracefully from an invalid redeclaration.
8249 D.setRedeclaration(true);
8250 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8251 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8252 "previous declaration set still overloaded");
8254 // Diagnose no-prototype function declarations with calling conventions that
8255 // don't support variadic calls. Only do this in C and do it after merging
8256 // possibly prototyped redeclarations.
8257 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8258 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8259 CallingConv CC = FT->getExtInfo().getCC();
8260 if (!supportsVariadicCall(CC)) {
8261 // Windows system headers sometimes accidentally use stdcall without
8262 // (void) parameters, so we relax this to a warning.
8264 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8265 Diag(NewFD->getLocation(), DiagID)
8266 << FunctionType::getNameForCallConv(CC);
8270 // C++11 [replacement.functions]p3:
8271 // The program's definitions shall not be specified as inline.
8273 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8275 // Suppress the diagnostic if the function is __attribute__((used)), since
8276 // that forces an external definition to be emitted.
8277 if (D.getDeclSpec().isInlineSpecified() &&
8278 NewFD->isReplaceableGlobalAllocationFunction() &&
8279 !NewFD->hasAttr<UsedAttr>())
8280 Diag(D.getDeclSpec().getInlineSpecLoc(),
8281 diag::ext_operator_new_delete_declared_inline)
8282 << NewFD->getDeclName();
8284 // If the declarator is a template-id, translate the parser's template
8285 // argument list into our AST format.
8286 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8287 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8288 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8289 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8290 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8291 TemplateId->NumArgs);
8292 translateTemplateArguments(TemplateArgsPtr,
8295 HasExplicitTemplateArgs = true;
8297 if (NewFD->isInvalidDecl()) {
8298 HasExplicitTemplateArgs = false;
8299 } else if (FunctionTemplate) {
8300 // Function template with explicit template arguments.
8301 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8302 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8304 HasExplicitTemplateArgs = false;
8306 assert((isFunctionTemplateSpecialization ||
8307 D.getDeclSpec().isFriendSpecified()) &&
8308 "should have a 'template<>' for this decl");
8309 // "friend void foo<>(int);" is an implicit specialization decl.
8310 isFunctionTemplateSpecialization = true;
8312 } else if (isFriend && isFunctionTemplateSpecialization) {
8313 // This combination is only possible in a recovery case; the user
8314 // wrote something like:
8315 // template <> friend void foo(int);
8316 // which we're recovering from as if the user had written:
8317 // friend void foo<>(int);
8318 // Go ahead and fake up a template id.
8319 HasExplicitTemplateArgs = true;
8320 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8321 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8324 // If it's a friend (and only if it's a friend), it's possible
8325 // that either the specialized function type or the specialized
8326 // template is dependent, and therefore matching will fail. In
8327 // this case, don't check the specialization yet.
8328 bool InstantiationDependent = false;
8329 if (isFunctionTemplateSpecialization && isFriend &&
8330 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8331 TemplateSpecializationType::anyDependentTemplateArguments(
8333 InstantiationDependent))) {
8334 assert(HasExplicitTemplateArgs &&
8335 "friend function specialization without template args");
8336 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8338 NewFD->setInvalidDecl();
8339 } else if (isFunctionTemplateSpecialization) {
8340 if (CurContext->isDependentContext() && CurContext->isRecord()
8342 isDependentClassScopeExplicitSpecialization = true;
8343 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8344 diag::ext_function_specialization_in_class :
8345 diag::err_function_specialization_in_class)
8346 << NewFD->getDeclName();
8347 } else if (CheckFunctionTemplateSpecialization(NewFD,
8348 (HasExplicitTemplateArgs ? &TemplateArgs
8351 NewFD->setInvalidDecl();
8354 // A storage-class-specifier shall not be specified in an explicit
8355 // specialization (14.7.3)
8356 FunctionTemplateSpecializationInfo *Info =
8357 NewFD->getTemplateSpecializationInfo();
8358 if (Info && SC != SC_None) {
8359 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8360 Diag(NewFD->getLocation(),
8361 diag::err_explicit_specialization_inconsistent_storage_class)
8363 << FixItHint::CreateRemoval(
8364 D.getDeclSpec().getStorageClassSpecLoc());
8367 Diag(NewFD->getLocation(),
8368 diag::ext_explicit_specialization_storage_class)
8369 << FixItHint::CreateRemoval(
8370 D.getDeclSpec().getStorageClassSpecLoc());
8372 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8373 if (CheckMemberSpecialization(NewFD, Previous))
8374 NewFD->setInvalidDecl();
8377 // Perform semantic checking on the function declaration.
8378 if (!isDependentClassScopeExplicitSpecialization) {
8379 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8380 CheckMain(NewFD, D.getDeclSpec());
8382 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8383 CheckMSVCRTEntryPoint(NewFD);
8385 if (!NewFD->isInvalidDecl())
8386 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8387 isExplicitSpecialization));
8388 else if (!Previous.empty())
8389 // Recover gracefully from an invalid redeclaration.
8390 D.setRedeclaration(true);
8393 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8394 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8395 "previous declaration set still overloaded");
8397 NamedDecl *PrincipalDecl = (FunctionTemplate
8398 ? cast<NamedDecl>(FunctionTemplate)
8401 if (isFriend && D.isRedeclaration()) {
8402 AccessSpecifier Access = AS_public;
8403 if (!NewFD->isInvalidDecl())
8404 Access = NewFD->getPreviousDecl()->getAccess();
8406 NewFD->setAccess(Access);
8407 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8410 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8411 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8412 PrincipalDecl->setNonMemberOperator();
8414 // If we have a function template, check the template parameter
8415 // list. This will check and merge default template arguments.
8416 if (FunctionTemplate) {
8417 FunctionTemplateDecl *PrevTemplate =
8418 FunctionTemplate->getPreviousDecl();
8419 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8420 PrevTemplate ? PrevTemplate->getTemplateParameters()
8422 D.getDeclSpec().isFriendSpecified()
8423 ? (D.isFunctionDefinition()
8424 ? TPC_FriendFunctionTemplateDefinition
8425 : TPC_FriendFunctionTemplate)
8426 : (D.getCXXScopeSpec().isSet() &&
8427 DC && DC->isRecord() &&
8428 DC->isDependentContext())
8429 ? TPC_ClassTemplateMember
8430 : TPC_FunctionTemplate);
8433 if (NewFD->isInvalidDecl()) {
8434 // Ignore all the rest of this.
8435 } else if (!D.isRedeclaration()) {
8436 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8438 // Fake up an access specifier if it's supposed to be a class member.
8439 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8440 NewFD->setAccess(AS_public);
8442 // Qualified decls generally require a previous declaration.
8443 if (D.getCXXScopeSpec().isSet()) {
8444 // ...with the major exception of templated-scope or
8445 // dependent-scope friend declarations.
8447 // TODO: we currently also suppress this check in dependent
8448 // contexts because (1) the parameter depth will be off when
8449 // matching friend templates and (2) we might actually be
8450 // selecting a friend based on a dependent factor. But there
8451 // are situations where these conditions don't apply and we
8452 // can actually do this check immediately.
8454 (TemplateParamLists.size() ||
8455 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8456 CurContext->isDependentContext())) {
8459 // The user tried to provide an out-of-line definition for a
8460 // function that is a member of a class or namespace, but there
8461 // was no such member function declared (C++ [class.mfct]p2,
8462 // C++ [namespace.memdef]p2). For example:
8468 // void X::f() { } // ill-formed
8470 // Complain about this problem, and attempt to suggest close
8471 // matches (e.g., those that differ only in cv-qualifiers and
8472 // whether the parameter types are references).
8474 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8475 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8476 AddToScope = ExtraArgs.AddToScope;
8481 // Unqualified local friend declarations are required to resolve
8483 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8484 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8485 *this, Previous, NewFD, ExtraArgs, true, S)) {
8486 AddToScope = ExtraArgs.AddToScope;
8490 } else if (!D.isFunctionDefinition() &&
8491 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8492 !isFriend && !isFunctionTemplateSpecialization &&
8493 !isExplicitSpecialization) {
8494 // An out-of-line member function declaration must also be a
8495 // definition (C++ [class.mfct]p2).
8496 // Note that this is not the case for explicit specializations of
8497 // function templates or member functions of class templates, per
8498 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8499 // extension for compatibility with old SWIG code which likes to
8501 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8502 << D.getCXXScopeSpec().getRange();
8506 ProcessPragmaWeak(S, NewFD);
8507 checkAttributesAfterMerging(*this, *NewFD);
8509 AddKnownFunctionAttributes(NewFD);
8511 if (NewFD->hasAttr<OverloadableAttr>() &&
8512 !NewFD->getType()->getAs<FunctionProtoType>()) {
8513 Diag(NewFD->getLocation(),
8514 diag::err_attribute_overloadable_no_prototype)
8517 // Turn this into a variadic function with no parameters.
8518 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8519 FunctionProtoType::ExtProtoInfo EPI(
8520 Context.getDefaultCallingConvention(true, false));
8521 EPI.Variadic = true;
8522 EPI.ExtInfo = FT->getExtInfo();
8524 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8528 // If there's a #pragma GCC visibility in scope, and this isn't a class
8529 // member, set the visibility of this function.
8530 if (!DC->isRecord() && NewFD->isExternallyVisible())
8531 AddPushedVisibilityAttribute(NewFD);
8533 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8534 // marking the function.
8535 AddCFAuditedAttribute(NewFD);
8537 // If this is a function definition, check if we have to apply optnone due to
8539 if(D.isFunctionDefinition())
8540 AddRangeBasedOptnone(NewFD);
8542 // If this is the first declaration of an extern C variable, update
8543 // the map of such variables.
8544 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8545 isIncompleteDeclExternC(*this, NewFD))
8546 RegisterLocallyScopedExternCDecl(NewFD, S);
8548 // Set this FunctionDecl's range up to the right paren.
8549 NewFD->setRangeEnd(D.getSourceRange().getEnd());
8551 if (D.isRedeclaration() && !Previous.empty()) {
8552 checkDLLAttributeRedeclaration(
8553 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8554 isExplicitSpecialization || isFunctionTemplateSpecialization,
8555 D.isFunctionDefinition());
8558 if (getLangOpts().CUDA) {
8559 IdentifierInfo *II = NewFD->getIdentifier();
8560 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8561 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8562 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8563 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8565 Context.setcudaConfigureCallDecl(NewFD);
8568 // Variadic functions, other than a *declaration* of printf, are not allowed
8569 // in device-side CUDA code, unless someone passed
8570 // -fcuda-allow-variadic-functions.
8571 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8572 (NewFD->hasAttr<CUDADeviceAttr>() ||
8573 NewFD->hasAttr<CUDAGlobalAttr>()) &&
8574 !(II && II->isStr("printf") && NewFD->isExternC() &&
8575 !D.isFunctionDefinition())) {
8576 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8580 if (getLangOpts().CPlusPlus) {
8581 if (FunctionTemplate) {
8582 if (NewFD->isInvalidDecl())
8583 FunctionTemplate->setInvalidDecl();
8584 return FunctionTemplate;
8588 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8589 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8590 if ((getLangOpts().OpenCLVersion >= 120)
8591 && (SC == SC_Static)) {
8592 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8596 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8597 if (!NewFD->getReturnType()->isVoidType()) {
8598 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8599 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8600 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8605 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8606 for (auto Param : NewFD->parameters())
8607 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8609 for (const ParmVarDecl *Param : NewFD->parameters()) {
8610 QualType PT = Param->getType();
8612 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8614 if (getLangOpts().OpenCLVersion >= 200) {
8615 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8616 QualType ElemTy = PipeTy->getElementType();
8617 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8618 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8625 MarkUnusedFileScopedDecl(NewFD);
8627 // Here we have an function template explicit specialization at class scope.
8628 // The actually specialization will be postponed to template instatiation
8629 // time via the ClassScopeFunctionSpecializationDecl node.
8630 if (isDependentClassScopeExplicitSpecialization) {
8631 ClassScopeFunctionSpecializationDecl *NewSpec =
8632 ClassScopeFunctionSpecializationDecl::Create(
8633 Context, CurContext, SourceLocation(),
8634 cast<CXXMethodDecl>(NewFD),
8635 HasExplicitTemplateArgs, TemplateArgs);
8636 CurContext->addDecl(NewSpec);
8643 /// \brief Perform semantic checking of a new function declaration.
8645 /// Performs semantic analysis of the new function declaration
8646 /// NewFD. This routine performs all semantic checking that does not
8647 /// require the actual declarator involved in the declaration, and is
8648 /// used both for the declaration of functions as they are parsed
8649 /// (called via ActOnDeclarator) and for the declaration of functions
8650 /// that have been instantiated via C++ template instantiation (called
8651 /// via InstantiateDecl).
8653 /// \param IsExplicitSpecialization whether this new function declaration is
8654 /// an explicit specialization of the previous declaration.
8656 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8658 /// \returns true if the function declaration is a redeclaration.
8659 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8660 LookupResult &Previous,
8661 bool IsExplicitSpecialization) {
8662 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8663 "Variably modified return types are not handled here");
8665 // Determine whether the type of this function should be merged with
8666 // a previous visible declaration. This never happens for functions in C++,
8667 // and always happens in C if the previous declaration was visible.
8668 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8669 !Previous.isShadowed();
8671 bool Redeclaration = false;
8672 NamedDecl *OldDecl = nullptr;
8674 // Merge or overload the declaration with an existing declaration of
8675 // the same name, if appropriate.
8676 if (!Previous.empty()) {
8677 // Determine whether NewFD is an overload of PrevDecl or
8678 // a declaration that requires merging. If it's an overload,
8679 // there's no more work to do here; we'll just add the new
8680 // function to the scope.
8681 if (!AllowOverloadingOfFunction(Previous, Context)) {
8682 NamedDecl *Candidate = Previous.getRepresentativeDecl();
8683 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8684 Redeclaration = true;
8685 OldDecl = Candidate;
8688 switch (CheckOverload(S, NewFD, Previous, OldDecl,
8689 /*NewIsUsingDecl*/ false)) {
8691 Redeclaration = true;
8694 case Ovl_NonFunction:
8695 Redeclaration = true;
8699 Redeclaration = false;
8703 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8704 // If a function name is overloadable in C, then every function
8705 // with that name must be marked "overloadable".
8706 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8707 << Redeclaration << NewFD;
8708 NamedDecl *OverloadedDecl = nullptr;
8710 OverloadedDecl = OldDecl;
8711 else if (!Previous.empty())
8712 OverloadedDecl = Previous.getRepresentativeDecl();
8714 Diag(OverloadedDecl->getLocation(),
8715 diag::note_attribute_overloadable_prev_overload);
8716 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8721 // Check for a previous extern "C" declaration with this name.
8722 if (!Redeclaration &&
8723 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8724 if (!Previous.empty()) {
8725 // This is an extern "C" declaration with the same name as a previous
8726 // declaration, and thus redeclares that entity...
8727 Redeclaration = true;
8728 OldDecl = Previous.getFoundDecl();
8729 MergeTypeWithPrevious = false;
8731 // ... except in the presence of __attribute__((overloadable)).
8732 if (OldDecl->hasAttr<OverloadableAttr>()) {
8733 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8734 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8735 << Redeclaration << NewFD;
8736 Diag(Previous.getFoundDecl()->getLocation(),
8737 diag::note_attribute_overloadable_prev_overload);
8738 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8740 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8741 Redeclaration = false;
8748 // C++11 [dcl.constexpr]p8:
8749 // A constexpr specifier for a non-static member function that is not
8750 // a constructor declares that member function to be const.
8752 // This needs to be delayed until we know whether this is an out-of-line
8753 // definition of a static member function.
8755 // This rule is not present in C++1y, so we produce a backwards
8756 // compatibility warning whenever it happens in C++11.
8757 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8758 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8759 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8760 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8761 CXXMethodDecl *OldMD = nullptr;
8763 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8764 if (!OldMD || !OldMD->isStatic()) {
8765 const FunctionProtoType *FPT =
8766 MD->getType()->castAs<FunctionProtoType>();
8767 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8768 EPI.TypeQuals |= Qualifiers::Const;
8769 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8770 FPT->getParamTypes(), EPI));
8772 // Warn that we did this, if we're not performing template instantiation.
8773 // In that case, we'll have warned already when the template was defined.
8774 if (ActiveTemplateInstantiations.empty()) {
8775 SourceLocation AddConstLoc;
8776 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8777 .IgnoreParens().getAs<FunctionTypeLoc>())
8778 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8780 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8781 << FixItHint::CreateInsertion(AddConstLoc, " const");
8786 if (Redeclaration) {
8787 // NewFD and OldDecl represent declarations that need to be
8789 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8790 NewFD->setInvalidDecl();
8791 return Redeclaration;
8795 Previous.addDecl(OldDecl);
8797 if (FunctionTemplateDecl *OldTemplateDecl
8798 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8799 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8800 FunctionTemplateDecl *NewTemplateDecl
8801 = NewFD->getDescribedFunctionTemplate();
8802 assert(NewTemplateDecl && "Template/non-template mismatch");
8803 if (CXXMethodDecl *Method
8804 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8805 Method->setAccess(OldTemplateDecl->getAccess());
8806 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8809 // If this is an explicit specialization of a member that is a function
8810 // template, mark it as a member specialization.
8811 if (IsExplicitSpecialization &&
8812 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8813 NewTemplateDecl->setMemberSpecialization();
8814 assert(OldTemplateDecl->isMemberSpecialization());
8815 // Explicit specializations of a member template do not inherit deleted
8816 // status from the parent member template that they are specializing.
8817 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8818 FunctionDecl *const OldTemplatedDecl =
8819 OldTemplateDecl->getTemplatedDecl();
8820 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8821 OldTemplatedDecl->setDeletedAsWritten(false);
8826 // This needs to happen first so that 'inline' propagates.
8827 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8829 if (isa<CXXMethodDecl>(NewFD))
8830 NewFD->setAccess(OldDecl->getAccess());
8834 // Semantic checking for this function declaration (in isolation).
8836 if (getLangOpts().CPlusPlus) {
8837 // C++-specific checks.
8838 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8839 CheckConstructor(Constructor);
8840 } else if (CXXDestructorDecl *Destructor =
8841 dyn_cast<CXXDestructorDecl>(NewFD)) {
8842 CXXRecordDecl *Record = Destructor->getParent();
8843 QualType ClassType = Context.getTypeDeclType(Record);
8845 // FIXME: Shouldn't we be able to perform this check even when the class
8846 // type is dependent? Both gcc and edg can handle that.
8847 if (!ClassType->isDependentType()) {
8848 DeclarationName Name
8849 = Context.DeclarationNames.getCXXDestructorName(
8850 Context.getCanonicalType(ClassType));
8851 if (NewFD->getDeclName() != Name) {
8852 Diag(NewFD->getLocation(), diag::err_destructor_name);
8853 NewFD->setInvalidDecl();
8854 return Redeclaration;
8857 } else if (CXXConversionDecl *Conversion
8858 = dyn_cast<CXXConversionDecl>(NewFD)) {
8859 ActOnConversionDeclarator(Conversion);
8862 // Find any virtual functions that this function overrides.
8863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8864 if (!Method->isFunctionTemplateSpecialization() &&
8865 !Method->getDescribedFunctionTemplate() &&
8866 Method->isCanonicalDecl()) {
8867 if (AddOverriddenMethods(Method->getParent(), Method)) {
8868 // If the function was marked as "static", we have a problem.
8869 if (NewFD->getStorageClass() == SC_Static) {
8870 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8875 if (Method->isStatic())
8876 checkThisInStaticMemberFunctionType(Method);
8879 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8880 if (NewFD->isOverloadedOperator() &&
8881 CheckOverloadedOperatorDeclaration(NewFD)) {
8882 NewFD->setInvalidDecl();
8883 return Redeclaration;
8886 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8887 if (NewFD->getLiteralIdentifier() &&
8888 CheckLiteralOperatorDeclaration(NewFD)) {
8889 NewFD->setInvalidDecl();
8890 return Redeclaration;
8893 // In C++, check default arguments now that we have merged decls. Unless
8894 // the lexical context is the class, because in this case this is done
8895 // during delayed parsing anyway.
8896 if (!CurContext->isRecord())
8897 CheckCXXDefaultArguments(NewFD);
8899 // If this function declares a builtin function, check the type of this
8900 // declaration against the expected type for the builtin.
8901 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8902 ASTContext::GetBuiltinTypeError Error;
8903 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8904 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8905 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8906 // The type of this function differs from the type of the builtin,
8907 // so forget about the builtin entirely.
8908 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8912 // If this function is declared as being extern "C", then check to see if
8913 // the function returns a UDT (class, struct, or union type) that is not C
8914 // compatible, and if it does, warn the user.
8915 // But, issue any diagnostic on the first declaration only.
8916 if (Previous.empty() && NewFD->isExternC()) {
8917 QualType R = NewFD->getReturnType();
8918 if (R->isIncompleteType() && !R->isVoidType())
8919 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8921 else if (!R.isPODType(Context) && !R->isVoidType() &&
8922 !R->isObjCObjectPointerType())
8923 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8926 return Redeclaration;
8929 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8930 // C++11 [basic.start.main]p3:
8931 // A program that [...] declares main to be inline, static or
8932 // constexpr is ill-formed.
8933 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8934 // appear in a declaration of main.
8935 // static main is not an error under C99, but we should warn about it.
8936 // We accept _Noreturn main as an extension.
8937 if (FD->getStorageClass() == SC_Static)
8938 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8939 ? diag::err_static_main : diag::warn_static_main)
8940 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8941 if (FD->isInlineSpecified())
8942 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8943 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8944 if (DS.isNoreturnSpecified()) {
8945 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8946 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8947 Diag(NoreturnLoc, diag::ext_noreturn_main);
8948 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8949 << FixItHint::CreateRemoval(NoreturnRange);
8951 if (FD->isConstexpr()) {
8952 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8953 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8954 FD->setConstexpr(false);
8957 if (getLangOpts().OpenCL) {
8958 Diag(FD->getLocation(), diag::err_opencl_no_main)
8959 << FD->hasAttr<OpenCLKernelAttr>();
8960 FD->setInvalidDecl();
8964 QualType T = FD->getType();
8965 assert(T->isFunctionType() && "function decl is not of function type");
8966 const FunctionType* FT = T->castAs<FunctionType>();
8968 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8969 // In C with GNU extensions we allow main() to have non-integer return
8970 // type, but we should warn about the extension, and we disable the
8971 // implicit-return-zero rule.
8973 // GCC in C mode accepts qualified 'int'.
8974 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8975 FD->setHasImplicitReturnZero(true);
8977 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8978 SourceRange RTRange = FD->getReturnTypeSourceRange();
8979 if (RTRange.isValid())
8980 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8981 << FixItHint::CreateReplacement(RTRange, "int");
8984 // In C and C++, main magically returns 0 if you fall off the end;
8985 // set the flag which tells us that.
8986 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8988 // All the standards say that main() should return 'int'.
8989 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8990 FD->setHasImplicitReturnZero(true);
8992 // Otherwise, this is just a flat-out error.
8993 SourceRange RTRange = FD->getReturnTypeSourceRange();
8994 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8995 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8997 FD->setInvalidDecl(true);
9001 // Treat protoless main() as nullary.
9002 if (isa<FunctionNoProtoType>(FT)) return;
9004 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9005 unsigned nparams = FTP->getNumParams();
9006 assert(FD->getNumParams() == nparams);
9008 bool HasExtraParameters = (nparams > 3);
9010 if (FTP->isVariadic()) {
9011 Diag(FD->getLocation(), diag::ext_variadic_main);
9012 // FIXME: if we had information about the location of the ellipsis, we
9013 // could add a FixIt hint to remove it as a parameter.
9016 // Darwin passes an undocumented fourth argument of type char**. If
9017 // other platforms start sprouting these, the logic below will start
9019 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9020 HasExtraParameters = false;
9022 if (HasExtraParameters) {
9023 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9024 FD->setInvalidDecl(true);
9028 // FIXME: a lot of the following diagnostics would be improved
9029 // if we had some location information about types.
9032 Context.getPointerType(Context.getPointerType(Context.CharTy));
9033 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9035 for (unsigned i = 0; i < nparams; ++i) {
9036 QualType AT = FTP->getParamType(i);
9038 bool mismatch = true;
9040 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9042 else if (Expected[i] == CharPP) {
9043 // As an extension, the following forms are okay:
9045 // char const * const *
9048 QualifierCollector qs;
9049 const PointerType* PT;
9050 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9051 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9052 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9055 mismatch = !qs.empty();
9060 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9061 // TODO: suggest replacing given type with expected type
9062 FD->setInvalidDecl(true);
9066 if (nparams == 1 && !FD->isInvalidDecl()) {
9067 Diag(FD->getLocation(), diag::warn_main_one_arg);
9070 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9071 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9072 FD->setInvalidDecl();
9076 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9077 QualType T = FD->getType();
9078 assert(T->isFunctionType() && "function decl is not of function type");
9079 const FunctionType *FT = T->castAs<FunctionType>();
9081 // Set an implicit return of 'zero' if the function can return some integral,
9082 // enumeration, pointer or nullptr type.
9083 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9084 FT->getReturnType()->isAnyPointerType() ||
9085 FT->getReturnType()->isNullPtrType())
9086 // DllMain is exempt because a return value of zero means it failed.
9087 if (FD->getName() != "DllMain")
9088 FD->setHasImplicitReturnZero(true);
9090 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9091 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9092 FD->setInvalidDecl();
9096 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9097 // FIXME: Need strict checking. In C89, we need to check for
9098 // any assignment, increment, decrement, function-calls, or
9099 // commas outside of a sizeof. In C99, it's the same list,
9100 // except that the aforementioned are allowed in unevaluated
9101 // expressions. Everything else falls under the
9102 // "may accept other forms of constant expressions" exception.
9103 // (We never end up here for C++, so the constant expression
9104 // rules there don't matter.)
9105 const Expr *Culprit;
9106 if (Init->isConstantInitializer(Context, false, &Culprit))
9108 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9109 << Culprit->getSourceRange();
9114 // Visits an initialization expression to see if OrigDecl is evaluated in
9115 // its own initialization and throws a warning if it does.
9116 class SelfReferenceChecker
9117 : public EvaluatedExprVisitor<SelfReferenceChecker> {
9122 bool isReferenceType;
9125 llvm::SmallVector<unsigned, 4> InitFieldIndex;
9128 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9130 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9131 S(S), OrigDecl(OrigDecl) {
9133 isRecordType = false;
9134 isReferenceType = false;
9136 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9137 isPODType = VD->getType().isPODType(S.Context);
9138 isRecordType = VD->getType()->isRecordType();
9139 isReferenceType = VD->getType()->isReferenceType();
9143 // For most expressions, just call the visitor. For initializer lists,
9144 // track the index of the field being initialized since fields are
9145 // initialized in order allowing use of previously initialized fields.
9146 void CheckExpr(Expr *E) {
9147 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9153 // Track and increment the index here.
9155 InitFieldIndex.push_back(0);
9156 for (auto Child : InitList->children()) {
9157 CheckExpr(cast<Expr>(Child));
9158 ++InitFieldIndex.back();
9160 InitFieldIndex.pop_back();
9163 // Returns true if MemberExpr is checked and no futher checking is needed.
9164 // Returns false if additional checking is required.
9165 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9166 llvm::SmallVector<FieldDecl*, 4> Fields;
9168 bool ReferenceField = false;
9170 // Get the field memebers used.
9171 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9172 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9175 Fields.push_back(FD);
9176 if (FD->getType()->isReferenceType())
9177 ReferenceField = true;
9178 Base = ME->getBase()->IgnoreParenImpCasts();
9181 // Keep checking only if the base Decl is the same.
9182 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9183 if (!DRE || DRE->getDecl() != OrigDecl)
9186 // A reference field can be bound to an unininitialized field.
9187 if (CheckReference && !ReferenceField)
9190 // Convert FieldDecls to their index number.
9191 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9192 for (const FieldDecl *I : llvm::reverse(Fields))
9193 UsedFieldIndex.push_back(I->getFieldIndex());
9195 // See if a warning is needed by checking the first difference in index
9196 // numbers. If field being used has index less than the field being
9197 // initialized, then the use is safe.
9198 for (auto UsedIter = UsedFieldIndex.begin(),
9199 UsedEnd = UsedFieldIndex.end(),
9200 OrigIter = InitFieldIndex.begin(),
9201 OrigEnd = InitFieldIndex.end();
9202 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9203 if (*UsedIter < *OrigIter)
9205 if (*UsedIter > *OrigIter)
9209 // TODO: Add a different warning which will print the field names.
9210 HandleDeclRefExpr(DRE);
9214 // For most expressions, the cast is directly above the DeclRefExpr.
9215 // For conditional operators, the cast can be outside the conditional
9216 // operator if both expressions are DeclRefExpr's.
9217 void HandleValue(Expr *E) {
9218 E = E->IgnoreParens();
9219 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9220 HandleDeclRefExpr(DRE);
9224 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9225 Visit(CO->getCond());
9226 HandleValue(CO->getTrueExpr());
9227 HandleValue(CO->getFalseExpr());
9231 if (BinaryConditionalOperator *BCO =
9232 dyn_cast<BinaryConditionalOperator>(E)) {
9233 Visit(BCO->getCond());
9234 HandleValue(BCO->getFalseExpr());
9238 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9239 HandleValue(OVE->getSourceExpr());
9243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9244 if (BO->getOpcode() == BO_Comma) {
9245 Visit(BO->getLHS());
9246 HandleValue(BO->getRHS());
9251 if (isa<MemberExpr>(E)) {
9253 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9254 false /*CheckReference*/))
9258 Expr *Base = E->IgnoreParenImpCasts();
9259 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9260 // Check for static member variables and don't warn on them.
9261 if (!isa<FieldDecl>(ME->getMemberDecl()))
9263 Base = ME->getBase()->IgnoreParenImpCasts();
9265 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9266 HandleDeclRefExpr(DRE);
9273 // Reference types not handled in HandleValue are handled here since all
9274 // uses of references are bad, not just r-value uses.
9275 void VisitDeclRefExpr(DeclRefExpr *E) {
9276 if (isReferenceType)
9277 HandleDeclRefExpr(E);
9280 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9281 if (E->getCastKind() == CK_LValueToRValue) {
9282 HandleValue(E->getSubExpr());
9286 Inherited::VisitImplicitCastExpr(E);
9289 void VisitMemberExpr(MemberExpr *E) {
9291 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9295 // Don't warn on arrays since they can be treated as pointers.
9296 if (E->getType()->canDecayToPointerType()) return;
9298 // Warn when a non-static method call is followed by non-static member
9299 // field accesses, which is followed by a DeclRefExpr.
9300 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9301 bool Warn = (MD && !MD->isStatic());
9302 Expr *Base = E->getBase()->IgnoreParenImpCasts();
9303 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9304 if (!isa<FieldDecl>(ME->getMemberDecl()))
9306 Base = ME->getBase()->IgnoreParenImpCasts();
9309 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9311 HandleDeclRefExpr(DRE);
9315 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9316 // Visit that expression.
9320 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9321 Expr *Callee = E->getCallee();
9323 if (isa<UnresolvedLookupExpr>(Callee))
9324 return Inherited::VisitCXXOperatorCallExpr(E);
9327 for (auto Arg: E->arguments())
9328 HandleValue(Arg->IgnoreParenImpCasts());
9331 void VisitUnaryOperator(UnaryOperator *E) {
9332 // For POD record types, addresses of its own members are well-defined.
9333 if (E->getOpcode() == UO_AddrOf && isRecordType &&
9334 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9336 HandleValue(E->getSubExpr());
9340 if (E->isIncrementDecrementOp()) {
9341 HandleValue(E->getSubExpr());
9345 Inherited::VisitUnaryOperator(E);
9348 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9350 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9351 if (E->getConstructor()->isCopyConstructor()) {
9352 Expr *ArgExpr = E->getArg(0);
9353 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9354 if (ILE->getNumInits() == 1)
9355 ArgExpr = ILE->getInit(0);
9356 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9357 if (ICE->getCastKind() == CK_NoOp)
9358 ArgExpr = ICE->getSubExpr();
9359 HandleValue(ArgExpr);
9362 Inherited::VisitCXXConstructExpr(E);
9365 void VisitCallExpr(CallExpr *E) {
9366 // Treat std::move as a use.
9367 if (E->getNumArgs() == 1) {
9368 if (FunctionDecl *FD = E->getDirectCallee()) {
9369 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9370 FD->getIdentifier()->isStr("move")) {
9371 HandleValue(E->getArg(0));
9377 Inherited::VisitCallExpr(E);
9380 void VisitBinaryOperator(BinaryOperator *E) {
9381 if (E->isCompoundAssignmentOp()) {
9382 HandleValue(E->getLHS());
9387 Inherited::VisitBinaryOperator(E);
9390 // A custom visitor for BinaryConditionalOperator is needed because the
9391 // regular visitor would check the condition and true expression separately
9392 // but both point to the same place giving duplicate diagnostics.
9393 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9394 Visit(E->getCond());
9395 Visit(E->getFalseExpr());
9398 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9399 Decl* ReferenceDecl = DRE->getDecl();
9400 if (OrigDecl != ReferenceDecl) return;
9402 if (isReferenceType) {
9403 diag = diag::warn_uninit_self_reference_in_reference_init;
9404 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9405 diag = diag::warn_static_self_reference_in_init;
9406 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9407 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9408 DRE->getDecl()->getType()->isRecordType()) {
9409 diag = diag::warn_uninit_self_reference_in_init;
9411 // Local variables will be handled by the CFG analysis.
9415 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9417 << DRE->getNameInfo().getName()
9418 << OrigDecl->getLocation()
9419 << DRE->getSourceRange());
9423 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9424 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9426 // Parameters arguments are occassionially constructed with itself,
9427 // for instance, in recursive functions. Skip them.
9428 if (isa<ParmVarDecl>(OrigDecl))
9431 E = E->IgnoreParens();
9433 // Skip checking T a = a where T is not a record or reference type.
9434 // Doing so is a way to silence uninitialized warnings.
9435 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9436 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9437 if (ICE->getCastKind() == CK_LValueToRValue)
9438 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9439 if (DRE->getDecl() == OrigDecl)
9442 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9444 } // end anonymous namespace
9446 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9447 DeclarationName Name, QualType Type,
9448 TypeSourceInfo *TSI,
9449 SourceRange Range, bool DirectInit,
9451 bool IsInitCapture = !VDecl;
9452 assert((!VDecl || !VDecl->isInitCapture()) &&
9453 "init captures are expected to be deduced prior to initialization");
9455 // FIXME: Deduction for a decomposition declaration does weird things if the
9456 // initializer is an array.
9458 ArrayRef<Expr *> DeduceInits = Init;
9460 if (auto *PL = dyn_cast<ParenListExpr>(Init))
9461 DeduceInits = PL->exprs();
9462 else if (auto *IL = dyn_cast<InitListExpr>(Init))
9463 DeduceInits = IL->inits();
9466 // Deduction only works if we have exactly one source expression.
9467 if (DeduceInits.empty()) {
9468 // It isn't possible to write this directly, but it is possible to
9469 // end up in this situation with "auto x(some_pack...);"
9470 Diag(Init->getLocStart(), IsInitCapture
9471 ? diag::err_init_capture_no_expression
9472 : diag::err_auto_var_init_no_expression)
9473 << Name << Type << Range;
9477 if (DeduceInits.size() > 1) {
9478 Diag(DeduceInits[1]->getLocStart(),
9479 IsInitCapture ? diag::err_init_capture_multiple_expressions
9480 : diag::err_auto_var_init_multiple_expressions)
9481 << Name << Type << Range;
9485 Expr *DeduceInit = DeduceInits[0];
9486 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9487 Diag(Init->getLocStart(), IsInitCapture
9488 ? diag::err_init_capture_paren_braces
9489 : diag::err_auto_var_init_paren_braces)
9490 << isa<InitListExpr>(Init) << Name << Type << Range;
9494 // Expressions default to 'id' when we're in a debugger.
9495 bool DefaultedAnyToId = false;
9496 if (getLangOpts().DebuggerCastResultToId &&
9497 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9498 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9499 if (Result.isInvalid()) {
9502 Init = Result.get();
9503 DefaultedAnyToId = true;
9506 QualType DeducedType;
9507 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9509 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9510 else if (isa<InitListExpr>(Init))
9511 Diag(Range.getBegin(),
9512 diag::err_init_capture_deduction_failure_from_init_list)
9514 << (DeduceInit->getType().isNull() ? TSI->getType()
9515 : DeduceInit->getType())
9516 << DeduceInit->getSourceRange();
9518 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9519 << Name << TSI->getType()
9520 << (DeduceInit->getType().isNull() ? TSI->getType()
9521 : DeduceInit->getType())
9522 << DeduceInit->getSourceRange();
9525 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9526 // 'id' instead of a specific object type prevents most of our usual
9528 // We only want to warn outside of template instantiations, though:
9529 // inside a template, the 'id' could have come from a parameter.
9530 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9531 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9532 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9533 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9539 /// AddInitializerToDecl - Adds the initializer Init to the
9540 /// declaration dcl. If DirectInit is true, this is C++ direct
9541 /// initialization rather than copy initialization.
9542 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9543 bool DirectInit, bool TypeMayContainAuto) {
9544 // If there is no declaration, there was an error parsing it. Just ignore
9546 if (!RealDecl || RealDecl->isInvalidDecl()) {
9547 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9552 // Pure-specifiers are handled in ActOnPureSpecifier.
9553 Diag(Method->getLocation(), diag::err_member_function_initialization)
9554 << Method->getDeclName() << Init->getSourceRange();
9555 Method->setInvalidDecl();
9559 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9561 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9562 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9563 RealDecl->setInvalidDecl();
9567 // C++1z [dcl.dcl]p1 grammar implies that a parenthesized initializer is not
9569 if (isa<DecompositionDecl>(VDecl) && DirectInit && isa<ParenListExpr>(Init))
9570 Diag(VDecl->getLocation(), diag::err_decomp_decl_paren_init) << VDecl;
9572 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9573 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9574 // Attempt typo correction early so that the type of the init expression can
9575 // be deduced based on the chosen correction if the original init contains a
9577 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9578 if (!Res.isUsable()) {
9579 RealDecl->setInvalidDecl();
9584 QualType DeducedType = deduceVarTypeFromInitializer(
9585 VDecl, VDecl->getDeclName(), VDecl->getType(),
9586 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9587 if (DeducedType.isNull()) {
9588 RealDecl->setInvalidDecl();
9592 VDecl->setType(DeducedType);
9593 assert(VDecl->isLinkageValid());
9595 // In ARC, infer lifetime.
9596 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9597 VDecl->setInvalidDecl();
9599 // If this is a redeclaration, check that the type we just deduced matches
9600 // the previously declared type.
9601 if (VarDecl *Old = VDecl->getPreviousDecl()) {
9602 // We never need to merge the type, because we cannot form an incomplete
9603 // array of auto, nor deduce such a type.
9604 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9607 // Check the deduced type is valid for a variable declaration.
9608 CheckVariableDeclarationType(VDecl);
9609 if (VDecl->isInvalidDecl())
9613 // dllimport cannot be used on variable definitions.
9614 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9615 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9616 VDecl->setInvalidDecl();
9620 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9621 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9622 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9623 VDecl->setInvalidDecl();
9627 if (!VDecl->getType()->isDependentType()) {
9628 // A definition must end up with a complete type, which means it must be
9629 // complete with the restriction that an array type might be completed by
9630 // the initializer; note that later code assumes this restriction.
9631 QualType BaseDeclType = VDecl->getType();
9632 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9633 BaseDeclType = Array->getElementType();
9634 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9635 diag::err_typecheck_decl_incomplete_type)) {
9636 RealDecl->setInvalidDecl();
9640 // The variable can not have an abstract class type.
9641 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9642 diag::err_abstract_type_in_decl,
9643 AbstractVariableType))
9644 VDecl->setInvalidDecl();
9648 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9649 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine())) {
9650 NamedDecl *Hidden = nullptr;
9651 if (!hasVisibleDefinition(Def, &Hidden) &&
9652 (VDecl->getFormalLinkage() == InternalLinkage ||
9653 VDecl->getDescribedVarTemplate() ||
9654 VDecl->getNumTemplateParameterLists() ||
9655 VDecl->getDeclContext()->isDependentContext())) {
9656 // The previous definition is hidden, and multiple definitions are
9657 // permitted (in separate TUs). Form another definition of it.
9659 Diag(VDecl->getLocation(), diag::err_redefinition)
9660 << VDecl->getDeclName();
9661 Diag(Def->getLocation(), diag::note_previous_definition);
9662 VDecl->setInvalidDecl();
9667 if (getLangOpts().CPlusPlus) {
9668 // C++ [class.static.data]p4
9669 // If a static data member is of const integral or const
9670 // enumeration type, its declaration in the class definition can
9671 // specify a constant-initializer which shall be an integral
9672 // constant expression (5.19). In that case, the member can appear
9673 // in integral constant expressions. The member shall still be
9674 // defined in a namespace scope if it is used in the program and the
9675 // namespace scope definition shall not contain an initializer.
9677 // We already performed a redefinition check above, but for static
9678 // data members we also need to check whether there was an in-class
9679 // declaration with an initializer.
9680 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9681 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9682 << VDecl->getDeclName();
9683 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9684 diag::note_previous_initializer)
9689 if (VDecl->hasLocalStorage())
9690 getCurFunction()->setHasBranchProtectedScope();
9692 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9693 VDecl->setInvalidDecl();
9698 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9699 // a kernel function cannot be initialized."
9700 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9701 Diag(VDecl->getLocation(), diag::err_local_cant_init);
9702 VDecl->setInvalidDecl();
9706 // Get the decls type and save a reference for later, since
9707 // CheckInitializerTypes may change it.
9708 QualType DclT = VDecl->getType(), SavT = DclT;
9710 // Expressions default to 'id' when we're in a debugger
9711 // and we are assigning it to a variable of Objective-C pointer type.
9712 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9713 Init->getType() == Context.UnknownAnyTy) {
9714 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9715 if (Result.isInvalid()) {
9716 VDecl->setInvalidDecl();
9719 Init = Result.get();
9722 // Perform the initialization.
9723 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9724 if (!VDecl->isInvalidDecl()) {
9725 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9726 InitializationKind Kind =
9729 ? InitializationKind::CreateDirect(VDecl->getLocation(),
9730 Init->getLocStart(),
9732 : InitializationKind::CreateDirectList(VDecl->getLocation())
9733 : InitializationKind::CreateCopy(VDecl->getLocation(),
9734 Init->getLocStart());
9736 MultiExprArg Args = Init;
9738 Args = MultiExprArg(CXXDirectInit->getExprs(),
9739 CXXDirectInit->getNumExprs());
9741 // Try to correct any TypoExprs in the initialization arguments.
9742 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9743 ExprResult Res = CorrectDelayedTyposInExpr(
9744 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9745 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9746 return Init.Failed() ? ExprError() : E;
9748 if (Res.isInvalid()) {
9749 VDecl->setInvalidDecl();
9750 } else if (Res.get() != Args[Idx]) {
9751 Args[Idx] = Res.get();
9754 if (VDecl->isInvalidDecl())
9757 InitializationSequence InitSeq(*this, Entity, Kind, Args,
9758 /*TopLevelOfInitList=*/false,
9759 /*TreatUnavailableAsInvalid=*/false);
9760 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9761 if (Result.isInvalid()) {
9762 VDecl->setInvalidDecl();
9766 Init = Result.getAs<Expr>();
9769 // Check for self-references within variable initializers.
9770 // Variables declared within a function/method body (except for references)
9771 // are handled by a dataflow analysis.
9772 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9773 VDecl->getType()->isReferenceType()) {
9774 CheckSelfReference(*this, RealDecl, Init, DirectInit);
9777 // If the type changed, it means we had an incomplete type that was
9778 // completed by the initializer. For example:
9779 // int ary[] = { 1, 3, 5 };
9780 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9781 if (!VDecl->isInvalidDecl() && (DclT != SavT))
9782 VDecl->setType(DclT);
9784 if (!VDecl->isInvalidDecl()) {
9785 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9787 if (VDecl->hasAttr<BlocksAttr>())
9788 checkRetainCycles(VDecl, Init);
9790 // It is safe to assign a weak reference into a strong variable.
9791 // Although this code can still have problems:
9792 // id x = self.weakProp;
9793 // id y = self.weakProp;
9794 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9795 // paths through the function. This should be revisited if
9796 // -Wrepeated-use-of-weak is made flow-sensitive.
9797 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9798 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9799 Init->getLocStart()))
9800 getCurFunction()->markSafeWeakUse(Init);
9803 // The initialization is usually a full-expression.
9805 // FIXME: If this is a braced initialization of an aggregate, it is not
9806 // an expression, and each individual field initializer is a separate
9807 // full-expression. For instance, in:
9809 // struct Temp { ~Temp(); };
9810 // struct S { S(Temp); };
9811 // struct T { S a, b; } t = { Temp(), Temp() }
9813 // we should destroy the first Temp before constructing the second.
9814 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9816 VDecl->isConstexpr());
9817 if (Result.isInvalid()) {
9818 VDecl->setInvalidDecl();
9821 Init = Result.get();
9823 // Attach the initializer to the decl.
9824 VDecl->setInit(Init);
9826 if (VDecl->isLocalVarDecl()) {
9827 // C99 6.7.8p4: All the expressions in an initializer for an object that has
9828 // static storage duration shall be constant expressions or string literals.
9829 // C++ does not have this restriction.
9830 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9831 const Expr *Culprit;
9832 if (VDecl->getStorageClass() == SC_Static)
9833 CheckForConstantInitializer(Init, DclT);
9834 // C89 is stricter than C99 for non-static aggregate types.
9835 // C89 6.5.7p3: All the expressions [...] in an initializer list
9836 // for an object that has aggregate or union type shall be
9837 // constant expressions.
9838 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9839 isa<InitListExpr>(Init) &&
9840 !Init->isConstantInitializer(Context, false, &Culprit))
9841 Diag(Culprit->getExprLoc(),
9842 diag::ext_aggregate_init_not_constant)
9843 << Culprit->getSourceRange();
9845 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
9846 VDecl->getLexicalDeclContext()->isRecord()) {
9847 // This is an in-class initialization for a static data member, e.g.,
9850 // static const int value = 17;
9853 // C++ [class.mem]p4:
9854 // A member-declarator can contain a constant-initializer only
9855 // if it declares a static member (9.4) of const integral or
9856 // const enumeration type, see 9.4.2.
9858 // C++11 [class.static.data]p3:
9859 // If a non-volatile non-inline const static data member is of integral
9860 // or enumeration type, its declaration in the class definition can
9861 // specify a brace-or-equal-initializer in which every initalizer-clause
9862 // that is an assignment-expression is a constant expression. A static
9863 // data member of literal type can be declared in the class definition
9864 // with the constexpr specifier; if so, its declaration shall specify a
9865 // brace-or-equal-initializer in which every initializer-clause that is
9866 // an assignment-expression is a constant expression.
9868 // Do nothing on dependent types.
9869 if (DclT->isDependentType()) {
9871 // Allow any 'static constexpr' members, whether or not they are of literal
9872 // type. We separately check that every constexpr variable is of literal
9874 } else if (VDecl->isConstexpr()) {
9876 // Require constness.
9877 } else if (!DclT.isConstQualified()) {
9878 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9879 << Init->getSourceRange();
9880 VDecl->setInvalidDecl();
9882 // We allow integer constant expressions in all cases.
9883 } else if (DclT->isIntegralOrEnumerationType()) {
9884 // Check whether the expression is a constant expression.
9886 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9887 // In C++11, a non-constexpr const static data member with an
9888 // in-class initializer cannot be volatile.
9889 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9890 else if (Init->isValueDependent())
9891 ; // Nothing to check.
9892 else if (Init->isIntegerConstantExpr(Context, &Loc))
9893 ; // Ok, it's an ICE!
9894 else if (Init->isEvaluatable(Context)) {
9895 // If we can constant fold the initializer through heroics, accept it,
9896 // but report this as a use of an extension for -pedantic.
9897 Diag(Loc, diag::ext_in_class_initializer_non_constant)
9898 << Init->getSourceRange();
9900 // Otherwise, this is some crazy unknown case. Report the issue at the
9901 // location provided by the isIntegerConstantExpr failed check.
9902 Diag(Loc, diag::err_in_class_initializer_non_constant)
9903 << Init->getSourceRange();
9904 VDecl->setInvalidDecl();
9907 // We allow foldable floating-point constants as an extension.
9908 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9909 // In C++98, this is a GNU extension. In C++11, it is not, but we support
9910 // it anyway and provide a fixit to add the 'constexpr'.
9911 if (getLangOpts().CPlusPlus11) {
9912 Diag(VDecl->getLocation(),
9913 diag::ext_in_class_initializer_float_type_cxx11)
9914 << DclT << Init->getSourceRange();
9915 Diag(VDecl->getLocStart(),
9916 diag::note_in_class_initializer_float_type_cxx11)
9917 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9919 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9920 << DclT << Init->getSourceRange();
9922 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9923 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9924 << Init->getSourceRange();
9925 VDecl->setInvalidDecl();
9929 // Suggest adding 'constexpr' in C++11 for literal types.
9930 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9931 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9932 << DclT << Init->getSourceRange()
9933 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9934 VDecl->setConstexpr(true);
9937 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9938 << DclT << Init->getSourceRange();
9939 VDecl->setInvalidDecl();
9941 } else if (VDecl->isFileVarDecl()) {
9942 // In C, extern is typically used to avoid tentative definitions when
9943 // declaring variables in headers, but adding an intializer makes it a
9944 // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
9945 // In C++, extern is often used to give implictly static const variables
9946 // external linkage, so don't warn in that case. If selectany is present,
9947 // this might be header code intended for C and C++ inclusion, so apply the
9949 if (VDecl->getStorageClass() == SC_Extern &&
9950 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
9951 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
9952 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
9953 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9954 Diag(VDecl->getLocation(), diag::warn_extern_init);
9956 // C99 6.7.8p4. All file scoped initializers need to be constant.
9957 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9958 CheckForConstantInitializer(Init, DclT);
9961 // We will represent direct-initialization similarly to copy-initialization:
9962 // int x(1); -as-> int x = 1;
9963 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9965 // Clients that want to distinguish between the two forms, can check for
9966 // direct initializer using VarDecl::getInitStyle().
9967 // A major benefit is that clients that don't particularly care about which
9968 // exactly form was it (like the CodeGen) can handle both cases without
9969 // special case code.
9972 // The form of initialization (using parentheses or '=') is generally
9973 // insignificant, but does matter when the entity being initialized has a
9975 if (CXXDirectInit) {
9976 assert(DirectInit && "Call-style initializer must be direct init.");
9977 VDecl->setInitStyle(VarDecl::CallInit);
9978 } else if (DirectInit) {
9979 // This must be list-initialization. No other way is direct-initialization.
9980 VDecl->setInitStyle(VarDecl::ListInit);
9983 CheckCompleteVariableDeclaration(VDecl);
9986 /// ActOnInitializerError - Given that there was an error parsing an
9987 /// initializer for the given declaration, try to return to some form
9989 void Sema::ActOnInitializerError(Decl *D) {
9990 // Our main concern here is re-establishing invariants like "a
9991 // variable's type is either dependent or complete".
9992 if (!D || D->isInvalidDecl()) return;
9994 VarDecl *VD = dyn_cast<VarDecl>(D);
9997 // Bindings are not usable if we can't make sense of the initializer.
9998 if (auto *DD = dyn_cast<DecompositionDecl>(D))
9999 for (auto *BD : DD->bindings())
10000 BD->setInvalidDecl();
10002 // Auto types are meaningless if we can't make sense of the initializer.
10003 if (ParsingInitForAutoVars.count(D)) {
10004 D->setInvalidDecl();
10008 QualType Ty = VD->getType();
10009 if (Ty->isDependentType()) return;
10011 // Require a complete type.
10012 if (RequireCompleteType(VD->getLocation(),
10013 Context.getBaseElementType(Ty),
10014 diag::err_typecheck_decl_incomplete_type)) {
10015 VD->setInvalidDecl();
10019 // Require a non-abstract type.
10020 if (RequireNonAbstractType(VD->getLocation(), Ty,
10021 diag::err_abstract_type_in_decl,
10022 AbstractVariableType)) {
10023 VD->setInvalidDecl();
10027 // Don't bother complaining about constructors or destructors,
10031 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
10032 bool TypeMayContainAuto) {
10033 // If there is no declaration, there was an error parsing it. Just ignore it.
10037 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10038 QualType Type = Var->getType();
10040 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10041 if (isa<DecompositionDecl>(RealDecl)) {
10042 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10043 Var->setInvalidDecl();
10047 // C++11 [dcl.spec.auto]p3
10048 if (TypeMayContainAuto && Type->getContainedAutoType()) {
10049 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10050 << Var->getDeclName() << Type;
10051 Var->setInvalidDecl();
10055 // C++11 [class.static.data]p3: A static data member can be declared with
10056 // the constexpr specifier; if so, its declaration shall specify
10057 // a brace-or-equal-initializer.
10058 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10059 // the definition of a variable [...] or the declaration of a static data
10061 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
10062 if (Var->isStaticDataMember()) {
10063 // C++1z removes the relevant rule; the in-class declaration is always
10064 // a definition there.
10065 if (!getLangOpts().CPlusPlus1z) {
10066 Diag(Var->getLocation(),
10067 diag::err_constexpr_static_mem_var_requires_init)
10068 << Var->getDeclName();
10069 Var->setInvalidDecl();
10073 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10074 Var->setInvalidDecl();
10079 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
10080 // definition having the concept specifier is called a variable concept. A
10081 // concept definition refers to [...] a variable concept and its initializer.
10082 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10083 if (VTD->isConcept()) {
10084 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10085 Var->setInvalidDecl();
10090 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10092 if (!Var->isInvalidDecl() &&
10093 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10094 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10095 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10096 Var->setInvalidDecl();
10100 switch (Var->isThisDeclarationADefinition()) {
10101 case VarDecl::Definition:
10102 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10105 // We have an out-of-line definition of a static data member
10106 // that has an in-class initializer, so we type-check this like
10111 case VarDecl::DeclarationOnly:
10112 // It's only a declaration.
10114 // Block scope. C99 6.7p7: If an identifier for an object is
10115 // declared with no linkage (C99 6.2.2p6), the type for the
10116 // object shall be complete.
10117 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10118 !Var->hasLinkage() && !Var->isInvalidDecl() &&
10119 RequireCompleteType(Var->getLocation(), Type,
10120 diag::err_typecheck_decl_incomplete_type))
10121 Var->setInvalidDecl();
10123 // Make sure that the type is not abstract.
10124 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10125 RequireNonAbstractType(Var->getLocation(), Type,
10126 diag::err_abstract_type_in_decl,
10127 AbstractVariableType))
10128 Var->setInvalidDecl();
10129 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10130 Var->getStorageClass() == SC_PrivateExtern) {
10131 Diag(Var->getLocation(), diag::warn_private_extern);
10132 Diag(Var->getLocation(), diag::note_private_extern);
10137 case VarDecl::TentativeDefinition:
10138 // File scope. C99 6.9.2p2: A declaration of an identifier for an
10139 // object that has file scope without an initializer, and without a
10140 // storage-class specifier or with the storage-class specifier "static",
10141 // constitutes a tentative definition. Note: A tentative definition with
10142 // external linkage is valid (C99 6.2.2p5).
10143 if (!Var->isInvalidDecl()) {
10144 if (const IncompleteArrayType *ArrayT
10145 = Context.getAsIncompleteArrayType(Type)) {
10146 if (RequireCompleteType(Var->getLocation(),
10147 ArrayT->getElementType(),
10148 diag::err_illegal_decl_array_incomplete_type))
10149 Var->setInvalidDecl();
10150 } else if (Var->getStorageClass() == SC_Static) {
10151 // C99 6.9.2p3: If the declaration of an identifier for an object is
10152 // a tentative definition and has internal linkage (C99 6.2.2p3), the
10153 // declared type shall not be an incomplete type.
10154 // NOTE: code such as the following
10155 // static struct s;
10156 // struct s { int a; };
10157 // is accepted by gcc. Hence here we issue a warning instead of
10158 // an error and we do not invalidate the static declaration.
10159 // NOTE: to avoid multiple warnings, only check the first declaration.
10160 if (Var->isFirstDecl())
10161 RequireCompleteType(Var->getLocation(), Type,
10162 diag::ext_typecheck_decl_incomplete_type);
10166 // Record the tentative definition; we're done.
10167 if (!Var->isInvalidDecl())
10168 TentativeDefinitions.push_back(Var);
10172 // Provide a specific diagnostic for uninitialized variable
10173 // definitions with incomplete array type.
10174 if (Type->isIncompleteArrayType()) {
10175 Diag(Var->getLocation(),
10176 diag::err_typecheck_incomplete_array_needs_initializer);
10177 Var->setInvalidDecl();
10181 // Provide a specific diagnostic for uninitialized variable
10182 // definitions with reference type.
10183 if (Type->isReferenceType()) {
10184 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10185 << Var->getDeclName()
10186 << SourceRange(Var->getLocation(), Var->getLocation());
10187 Var->setInvalidDecl();
10191 // Do not attempt to type-check the default initializer for a
10192 // variable with dependent type.
10193 if (Type->isDependentType())
10196 if (Var->isInvalidDecl())
10199 if (!Var->hasAttr<AliasAttr>()) {
10200 if (RequireCompleteType(Var->getLocation(),
10201 Context.getBaseElementType(Type),
10202 diag::err_typecheck_decl_incomplete_type)) {
10203 Var->setInvalidDecl();
10210 // The variable can not have an abstract class type.
10211 if (RequireNonAbstractType(Var->getLocation(), Type,
10212 diag::err_abstract_type_in_decl,
10213 AbstractVariableType)) {
10214 Var->setInvalidDecl();
10218 // Check for jumps past the implicit initializer. C++0x
10219 // clarifies that this applies to a "variable with automatic
10220 // storage duration", not a "local variable".
10221 // C++11 [stmt.dcl]p3
10222 // A program that jumps from a point where a variable with automatic
10223 // storage duration is not in scope to a point where it is in scope is
10224 // ill-formed unless the variable has scalar type, class type with a
10225 // trivial default constructor and a trivial destructor, a cv-qualified
10226 // version of one of these types, or an array of one of the preceding
10227 // types and is declared without an initializer.
10228 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10229 if (const RecordType *Record
10230 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10231 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10232 // Mark the function for further checking even if the looser rules of
10233 // C++11 do not require such checks, so that we can diagnose
10234 // incompatibilities with C++98.
10235 if (!CXXRecord->isPOD())
10236 getCurFunction()->setHasBranchProtectedScope();
10240 // C++03 [dcl.init]p9:
10241 // If no initializer is specified for an object, and the
10242 // object is of (possibly cv-qualified) non-POD class type (or
10243 // array thereof), the object shall be default-initialized; if
10244 // the object is of const-qualified type, the underlying class
10245 // type shall have a user-declared default
10246 // constructor. Otherwise, if no initializer is specified for
10247 // a non- static object, the object and its subobjects, if
10248 // any, have an indeterminate initial value); if the object
10249 // or any of its subobjects are of const-qualified type, the
10250 // program is ill-formed.
10251 // C++0x [dcl.init]p11:
10252 // If no initializer is specified for an object, the object is
10253 // default-initialized; [...].
10254 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10255 InitializationKind Kind
10256 = InitializationKind::CreateDefault(Var->getLocation());
10258 InitializationSequence InitSeq(*this, Entity, Kind, None);
10259 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10260 if (Init.isInvalid())
10261 Var->setInvalidDecl();
10262 else if (Init.get()) {
10263 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10264 // This is important for template substitution.
10265 Var->setInitStyle(VarDecl::CallInit);
10268 CheckCompleteVariableDeclaration(Var);
10272 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10273 // If there is no declaration, there was an error parsing it. Ignore it.
10277 VarDecl *VD = dyn_cast<VarDecl>(D);
10279 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10280 D->setInvalidDecl();
10284 VD->setCXXForRangeDecl(true);
10286 // for-range-declaration cannot be given a storage class specifier.
10288 switch (VD->getStorageClass()) {
10297 case SC_PrivateExtern:
10308 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10309 << VD->getDeclName() << Error;
10310 D->setInvalidDecl();
10315 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10316 IdentifierInfo *Ident,
10317 ParsedAttributes &Attrs,
10318 SourceLocation AttrEnd) {
10319 // C++1y [stmt.iter]p1:
10320 // A range-based for statement of the form
10321 // for ( for-range-identifier : for-range-initializer ) statement
10322 // is equivalent to
10323 // for ( auto&& for-range-identifier : for-range-initializer ) statement
10324 DeclSpec DS(Attrs.getPool().getFactory());
10326 const char *PrevSpec;
10328 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10329 getPrintingPolicy());
10331 Declarator D(DS, Declarator::ForContext);
10332 D.SetIdentifier(Ident, IdentLoc);
10333 D.takeAttributes(Attrs, AttrEnd);
10335 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10336 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10337 EmptyAttrs, IdentLoc);
10338 Decl *Var = ActOnDeclarator(S, D);
10339 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10340 FinalizeDeclaration(Var);
10341 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10342 AttrEnd.isValid() ? AttrEnd : IdentLoc);
10345 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10346 if (var->isInvalidDecl()) return;
10348 if (getLangOpts().OpenCL) {
10349 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10351 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10353 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10355 var->setInvalidDecl();
10360 // In Objective-C, don't allow jumps past the implicit initialization of a
10361 // local retaining variable.
10362 if (getLangOpts().ObjC1 &&
10363 var->hasLocalStorage()) {
10364 switch (var->getType().getObjCLifetime()) {
10365 case Qualifiers::OCL_None:
10366 case Qualifiers::OCL_ExplicitNone:
10367 case Qualifiers::OCL_Autoreleasing:
10370 case Qualifiers::OCL_Weak:
10371 case Qualifiers::OCL_Strong:
10372 getCurFunction()->setHasBranchProtectedScope();
10377 // Warn about externally-visible variables being defined without a
10378 // prior declaration. We only want to do this for global
10379 // declarations, but we also specifically need to avoid doing it for
10380 // class members because the linkage of an anonymous class can
10381 // change if it's later given a typedef name.
10382 if (var->isThisDeclarationADefinition() &&
10383 var->getDeclContext()->getRedeclContext()->isFileContext() &&
10384 var->isExternallyVisible() && var->hasLinkage() &&
10385 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10386 var->getLocation())) {
10387 // Find a previous declaration that's not a definition.
10388 VarDecl *prev = var->getPreviousDecl();
10389 while (prev && prev->isThisDeclarationADefinition())
10390 prev = prev->getPreviousDecl();
10393 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10396 if (var->getTLSKind() == VarDecl::TLS_Static) {
10397 const Expr *Culprit;
10398 if (var->getType().isDestructedType()) {
10399 // GNU C++98 edits for __thread, [basic.start.term]p3:
10400 // The type of an object with thread storage duration shall not
10401 // have a non-trivial destructor.
10402 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10403 if (getLangOpts().CPlusPlus11)
10404 Diag(var->getLocation(), diag::note_use_thread_local);
10405 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10406 !var->getInit()->isConstantInitializer(
10407 Context, var->getType()->isReferenceType(), &Culprit)) {
10408 // GNU C++98 edits for __thread, [basic.start.init]p4:
10409 // An object of thread storage duration shall not require dynamic
10411 // FIXME: Need strict checking here.
10412 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10413 << Culprit->getSourceRange();
10414 if (getLangOpts().CPlusPlus11)
10415 Diag(var->getLocation(), diag::note_use_thread_local);
10419 // Apply section attributes and pragmas to global variables.
10420 bool GlobalStorage = var->hasGlobalStorage();
10421 if (GlobalStorage && var->isThisDeclarationADefinition() &&
10422 ActiveTemplateInstantiations.empty()) {
10423 PragmaStack<StringLiteral *> *Stack = nullptr;
10424 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10425 if (var->getType().isConstQualified())
10426 Stack = &ConstSegStack;
10427 else if (!var->getInit()) {
10428 Stack = &BSSSegStack;
10429 SectionFlags |= ASTContext::PSF_Write;
10431 Stack = &DataSegStack;
10432 SectionFlags |= ASTContext::PSF_Write;
10434 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10435 var->addAttr(SectionAttr::CreateImplicit(
10436 Context, SectionAttr::Declspec_allocate,
10437 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10439 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10440 if (UnifySection(SA->getName(), SectionFlags, var))
10441 var->dropAttr<SectionAttr>();
10443 // Apply the init_seg attribute if this has an initializer. If the
10444 // initializer turns out to not be dynamic, we'll end up ignoring this
10446 if (CurInitSeg && var->getInit())
10447 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10451 // All the following checks are C++ only.
10452 if (!getLangOpts().CPlusPlus) return;
10454 if (auto *DD = dyn_cast<DecompositionDecl>(var))
10455 CheckCompleteDecompositionDeclaration(DD);
10457 QualType type = var->getType();
10458 if (type->isDependentType()) return;
10460 // __block variables might require us to capture a copy-initializer.
10461 if (var->hasAttr<BlocksAttr>()) {
10462 // It's currently invalid to ever have a __block variable with an
10463 // array type; should we diagnose that here?
10465 // Regardless, we don't want to ignore array nesting when
10466 // constructing this copy.
10467 if (type->isStructureOrClassType()) {
10468 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10469 SourceLocation poi = var->getLocation();
10470 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10472 = PerformMoveOrCopyInitialization(
10473 InitializedEntity::InitializeBlock(poi, type, false),
10474 var, var->getType(), varRef, /*AllowNRVO=*/true);
10475 if (!result.isInvalid()) {
10476 result = MaybeCreateExprWithCleanups(result);
10477 Expr *init = result.getAs<Expr>();
10478 Context.setBlockVarCopyInits(var, init);
10483 Expr *Init = var->getInit();
10484 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10485 QualType baseType = Context.getBaseElementType(type);
10487 if (!var->getDeclContext()->isDependentContext() &&
10488 Init && !Init->isValueDependent()) {
10489 if (IsGlobal && !var->isConstexpr() &&
10490 !getDiagnostics().isIgnored(diag::warn_global_constructor,
10491 var->getLocation())) {
10492 // Warn about globals which don't have a constant initializer. Don't
10493 // warn about globals with a non-trivial destructor because we already
10494 // warned about them.
10495 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10496 if (!(RD && !RD->hasTrivialDestructor()) &&
10497 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10498 Diag(var->getLocation(), diag::warn_global_constructor)
10499 << Init->getSourceRange();
10502 if (var->isConstexpr()) {
10503 SmallVector<PartialDiagnosticAt, 8> Notes;
10504 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10505 SourceLocation DiagLoc = var->getLocation();
10506 // If the note doesn't add any useful information other than a source
10507 // location, fold it into the primary diagnostic.
10508 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10509 diag::note_invalid_subexpr_in_const_expr) {
10510 DiagLoc = Notes[0].first;
10513 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10514 << var << Init->getSourceRange();
10515 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10516 Diag(Notes[I].first, Notes[I].second);
10518 } else if (var->isUsableInConstantExpressions(Context)) {
10519 // Check whether the initializer of a const variable of integral or
10520 // enumeration type is an ICE now, since we can't tell whether it was
10521 // initialized by a constant expression if we check later.
10522 var->checkInitIsICE();
10526 // Require the destructor.
10527 if (const RecordType *recordType = baseType->getAs<RecordType>())
10528 FinalizeVarWithDestructor(var, recordType);
10530 // If this variable must be emitted, add it as an initializer for the current
10532 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10533 Context.addModuleInitializer(ModuleScopes.back().Module, var);
10536 /// \brief Determines if a variable's alignment is dependent.
10537 static bool hasDependentAlignment(VarDecl *VD) {
10538 if (VD->getType()->isDependentType())
10540 for (auto *I : VD->specific_attrs<AlignedAttr>())
10541 if (I->isAlignmentDependent())
10546 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10547 /// any semantic actions necessary after any initializer has been attached.
10549 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10550 // Note that we are no longer parsing the initializer for this declaration.
10551 ParsingInitForAutoVars.erase(ThisDecl);
10553 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10557 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10558 for (auto *BD : DD->bindings()) {
10559 if (ThisDecl->isInvalidDecl())
10560 BD->setInvalidDecl();
10561 FinalizeDeclaration(BD);
10565 checkAttributesAfterMerging(*this, *VD);
10567 // Perform TLS alignment check here after attributes attached to the variable
10568 // which may affect the alignment have been processed. Only perform the check
10569 // if the target has a maximum TLS alignment (zero means no constraints).
10570 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10571 // Protect the check so that it's not performed on dependent types and
10572 // dependent alignments (we can't determine the alignment in that case).
10573 if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10574 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10575 if (Context.getDeclAlign(VD) > MaxAlignChars) {
10576 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10577 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10578 << (unsigned)MaxAlignChars.getQuantity();
10583 if (VD->isStaticLocal()) {
10584 if (FunctionDecl *FD =
10585 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10586 // Static locals inherit dll attributes from their function.
10587 if (Attr *A = getDLLAttr(FD)) {
10588 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10589 NewAttr->setInherited(true);
10590 VD->addAttr(NewAttr);
10592 // CUDA E.2.9.4: Within the body of a __device__ or __global__
10593 // function, only __shared__ variables may be declared with
10594 // static storage class.
10595 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10596 (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10597 !VD->hasAttr<CUDASharedAttr>()) {
10598 Diag(VD->getLocation(), diag::err_device_static_local_var);
10599 VD->setInvalidDecl();
10604 // Perform check for initializers of device-side global variables.
10605 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10606 // 7.5). We must also apply the same checks to all __shared__
10607 // variables whether they are local or not. CUDA also allows
10608 // constant initializers for __constant__ and __device__ variables.
10609 if (getLangOpts().CUDA) {
10610 const Expr *Init = VD->getInit();
10611 if (Init && VD->hasGlobalStorage()) {
10612 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10613 VD->hasAttr<CUDASharedAttr>()) {
10614 assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10615 bool AllowedInit = false;
10616 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10618 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10619 // We'll allow constant initializers even if it's a non-empty
10620 // constructor according to CUDA rules. This deviates from NVCC,
10621 // but allows us to handle things like constexpr constructors.
10622 if (!AllowedInit &&
10623 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10624 AllowedInit = VD->getInit()->isConstantInitializer(
10625 Context, VD->getType()->isReferenceType());
10627 // Also make sure that destructor, if there is one, is empty.
10629 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10631 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10633 if (!AllowedInit) {
10634 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10635 ? diag::err_shared_var_init
10636 : diag::err_dynamic_var_init)
10637 << Init->getSourceRange();
10638 VD->setInvalidDecl();
10641 // This is a host-side global variable. Check that the initializer is
10642 // callable from the host side.
10643 const FunctionDecl *InitFn = nullptr;
10644 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10645 InitFn = CE->getConstructor();
10646 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10647 InitFn = CE->getDirectCallee();
10650 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10651 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10652 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10653 << InitFnTarget << InitFn;
10654 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10655 VD->setInvalidDecl();
10662 // Grab the dllimport or dllexport attribute off of the VarDecl.
10663 const InheritableAttr *DLLAttr = getDLLAttr(VD);
10665 // Imported static data members cannot be defined out-of-line.
10666 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10667 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10668 VD->isThisDeclarationADefinition()) {
10669 // We allow definitions of dllimport class template static data members
10671 CXXRecordDecl *Context =
10672 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10673 bool IsClassTemplateMember =
10674 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10675 Context->getDescribedClassTemplate();
10677 Diag(VD->getLocation(),
10678 IsClassTemplateMember
10679 ? diag::warn_attribute_dllimport_static_field_definition
10680 : diag::err_attribute_dllimport_static_field_definition);
10681 Diag(IA->getLocation(), diag::note_attribute);
10682 if (!IsClassTemplateMember)
10683 VD->setInvalidDecl();
10687 // dllimport/dllexport variables cannot be thread local, their TLS index
10688 // isn't exported with the variable.
10689 if (DLLAttr && VD->getTLSKind()) {
10690 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10691 if (F && getDLLAttr(F)) {
10692 assert(VD->isStaticLocal());
10693 // But if this is a static local in a dlimport/dllexport function, the
10694 // function will never be inlined, which means the var would never be
10695 // imported, so having it marked import/export is safe.
10697 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10699 VD->setInvalidDecl();
10703 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10704 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10705 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10706 VD->dropAttr<UsedAttr>();
10710 const DeclContext *DC = VD->getDeclContext();
10711 // If there's a #pragma GCC visibility in scope, and this isn't a class
10712 // member, set the visibility of this variable.
10713 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10714 AddPushedVisibilityAttribute(VD);
10716 // FIXME: Warn on unused templates.
10717 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10718 !isa<VarTemplatePartialSpecializationDecl>(VD))
10719 MarkUnusedFileScopedDecl(VD);
10721 // Now we have parsed the initializer and can update the table of magic
10723 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10724 !VD->getType()->isIntegralOrEnumerationType())
10727 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10728 const Expr *MagicValueExpr = VD->getInit();
10729 if (!MagicValueExpr) {
10732 llvm::APSInt MagicValueInt;
10733 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10734 Diag(I->getRange().getBegin(),
10735 diag::err_type_tag_for_datatype_not_ice)
10736 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10739 if (MagicValueInt.getActiveBits() > 64) {
10740 Diag(I->getRange().getBegin(),
10741 diag::err_type_tag_for_datatype_too_large)
10742 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10745 uint64_t MagicValue = MagicValueInt.getZExtValue();
10746 RegisterTypeTagForDatatype(I->getArgumentKind(),
10748 I->getMatchingCType(),
10749 I->getLayoutCompatible(),
10750 I->getMustBeNull());
10754 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10755 ArrayRef<Decl *> Group) {
10756 SmallVector<Decl*, 8> Decls;
10758 if (DS.isTypeSpecOwned())
10759 Decls.push_back(DS.getRepAsDecl());
10761 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10762 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
10763 bool DiagnosedMultipleDecomps = false;
10765 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10766 if (Decl *D = Group[i]) {
10767 auto *DD = dyn_cast<DeclaratorDecl>(D);
10768 if (DD && !FirstDeclaratorInGroup)
10769 FirstDeclaratorInGroup = DD;
10771 auto *Decomp = dyn_cast<DecompositionDecl>(D);
10772 if (Decomp && !FirstDecompDeclaratorInGroup)
10773 FirstDecompDeclaratorInGroup = Decomp;
10775 // A decomposition declaration cannot be combined with any other
10776 // declaration in the same group.
10777 auto *OtherDD = FirstDeclaratorInGroup;
10778 if (OtherDD == FirstDecompDeclaratorInGroup)
10780 if (OtherDD && FirstDecompDeclaratorInGroup &&
10781 OtherDD != FirstDecompDeclaratorInGroup &&
10782 !DiagnosedMultipleDecomps) {
10783 Diag(FirstDecompDeclaratorInGroup->getLocation(),
10784 diag::err_decomp_decl_not_alone)
10785 << OtherDD->getSourceRange();
10786 DiagnosedMultipleDecomps = true;
10789 Decls.push_back(D);
10793 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10794 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10795 handleTagNumbering(Tag, S);
10796 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10797 getLangOpts().CPlusPlus)
10798 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10802 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10805 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10806 /// group, performing any necessary semantic checking.
10807 Sema::DeclGroupPtrTy
10808 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10809 bool TypeMayContainAuto) {
10810 // C++0x [dcl.spec.auto]p7:
10811 // If the type deduced for the template parameter U is not the same in each
10812 // deduction, the program is ill-formed.
10813 // FIXME: When initializer-list support is added, a distinction is needed
10814 // between the deduced type U and the deduced type which 'auto' stands for.
10815 // auto a = 0, b = { 1, 2, 3 };
10816 // is legal because the deduced type U is 'int' in both cases.
10817 if (TypeMayContainAuto && Group.size() > 1) {
10819 CanQualType DeducedCanon;
10820 VarDecl *DeducedDecl = nullptr;
10821 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10822 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10823 AutoType *AT = D->getType()->getContainedAutoType();
10824 // Don't reissue diagnostics when instantiating a template.
10825 if (AT && D->isInvalidDecl())
10827 QualType U = AT ? AT->getDeducedType() : QualType();
10829 CanQualType UCanon = Context.getCanonicalType(U);
10830 if (Deduced.isNull()) {
10832 DeducedCanon = UCanon;
10834 } else if (DeducedCanon != UCanon) {
10835 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10836 diag::err_auto_different_deductions)
10837 << (unsigned)AT->getKeyword()
10838 << Deduced << DeducedDecl->getDeclName()
10839 << U << D->getDeclName()
10840 << DeducedDecl->getInit()->getSourceRange()
10841 << D->getInit()->getSourceRange();
10842 D->setInvalidDecl();
10850 ActOnDocumentableDecls(Group);
10852 return DeclGroupPtrTy::make(
10853 DeclGroupRef::Create(Context, Group.data(), Group.size()));
10856 void Sema::ActOnDocumentableDecl(Decl *D) {
10857 ActOnDocumentableDecls(D);
10860 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10861 // Don't parse the comment if Doxygen diagnostics are ignored.
10862 if (Group.empty() || !Group[0])
10865 if (Diags.isIgnored(diag::warn_doc_param_not_found,
10866 Group[0]->getLocation()) &&
10867 Diags.isIgnored(diag::warn_unknown_comment_command_name,
10868 Group[0]->getLocation()))
10871 if (Group.size() >= 2) {
10872 // This is a decl group. Normally it will contain only declarations
10873 // produced from declarator list. But in case we have any definitions or
10874 // additional declaration references:
10875 // 'typedef struct S {} S;'
10876 // 'typedef struct S *S;'
10878 // FinalizeDeclaratorGroup adds these as separate declarations.
10879 Decl *MaybeTagDecl = Group[0];
10880 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10881 Group = Group.slice(1);
10885 // See if there are any new comments that are not attached to a decl.
10886 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10887 if (!Comments.empty() &&
10888 !Comments.back()->isAttached()) {
10889 // There is at least one comment that not attached to a decl.
10890 // Maybe it should be attached to one of these decls?
10892 // Note that this way we pick up not only comments that precede the
10893 // declaration, but also comments that *follow* the declaration -- thanks to
10894 // the lookahead in the lexer: we've consumed the semicolon and looked
10895 // ahead through comments.
10896 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10897 Context.getCommentForDecl(Group[i], &PP);
10901 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10902 /// to introduce parameters into function prototype scope.
10903 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10904 const DeclSpec &DS = D.getDeclSpec();
10906 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10908 // C++03 [dcl.stc]p2 also permits 'auto'.
10909 StorageClass SC = SC_None;
10910 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10912 } else if (getLangOpts().CPlusPlus &&
10913 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10915 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10916 Diag(DS.getStorageClassSpecLoc(),
10917 diag::err_invalid_storage_class_in_func_decl);
10918 D.getMutableDeclSpec().ClearStorageClassSpecs();
10921 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10922 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10923 << DeclSpec::getSpecifierName(TSCS);
10924 if (DS.isInlineSpecified())
10925 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
10926 << getLangOpts().CPlusPlus1z;
10927 if (DS.isConstexprSpecified())
10928 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10930 if (DS.isConceptSpecified())
10931 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10933 DiagnoseFunctionSpecifiers(DS);
10935 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10936 QualType parmDeclType = TInfo->getType();
10938 if (getLangOpts().CPlusPlus) {
10939 // Check that there are no default arguments inside the type of this
10941 CheckExtraCXXDefaultArguments(D);
10943 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10944 if (D.getCXXScopeSpec().isSet()) {
10945 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10946 << D.getCXXScopeSpec().getRange();
10947 D.getCXXScopeSpec().clear();
10951 // Ensure we have a valid name
10952 IdentifierInfo *II = nullptr;
10954 II = D.getIdentifier();
10956 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10957 << GetNameForDeclarator(D).getName();
10958 D.setInvalidType(true);
10962 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10964 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10967 if (R.isSingleResult()) {
10968 NamedDecl *PrevDecl = R.getFoundDecl();
10969 if (PrevDecl->isTemplateParameter()) {
10970 // Maybe we will complain about the shadowed template parameter.
10971 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10972 // Just pretend that we didn't see the previous declaration.
10973 PrevDecl = nullptr;
10974 } else if (S->isDeclScope(PrevDecl)) {
10975 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10976 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10978 // Recover by removing the name
10980 D.SetIdentifier(nullptr, D.getIdentifierLoc());
10981 D.setInvalidType(true);
10986 // Temporarily put parameter variables in the translation unit, not
10987 // the enclosing context. This prevents them from accidentally
10988 // looking like class members in C++.
10989 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10991 D.getIdentifierLoc(), II,
10992 parmDeclType, TInfo,
10995 if (D.isInvalidType())
10996 New->setInvalidDecl();
10998 assert(S->isFunctionPrototypeScope());
10999 assert(S->getFunctionPrototypeDepth() >= 1);
11000 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11001 S->getNextFunctionPrototypeIndex());
11003 // Add the parameter declaration into this scope.
11006 IdResolver.AddDecl(New);
11008 ProcessDeclAttributes(S, New, D);
11010 if (D.getDeclSpec().isModulePrivateSpecified())
11011 Diag(New->getLocation(), diag::err_module_private_local)
11012 << 1 << New->getDeclName()
11013 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11014 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11016 if (New->hasAttr<BlocksAttr>()) {
11017 Diag(New->getLocation(), diag::err_block_on_nonlocal);
11022 /// \brief Synthesizes a variable for a parameter arising from a
11024 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11025 SourceLocation Loc,
11027 /* FIXME: setting StartLoc == Loc.
11028 Would it be worth to modify callers so as to provide proper source
11029 location for the unnamed parameters, embedding the parameter's type? */
11030 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11031 T, Context.getTrivialTypeSourceInfo(T, Loc),
11033 Param->setImplicit();
11037 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11038 // Don't diagnose unused-parameter errors in template instantiations; we
11039 // will already have done so in the template itself.
11040 if (!ActiveTemplateInstantiations.empty())
11043 for (const ParmVarDecl *Parameter : Parameters) {
11044 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11045 !Parameter->hasAttr<UnusedAttr>()) {
11046 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11047 << Parameter->getDeclName();
11052 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11053 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11054 if (LangOpts.NumLargeByValueCopy == 0) // No check.
11057 // Warn if the return value is pass-by-value and larger than the specified
11059 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11060 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11061 if (Size > LangOpts.NumLargeByValueCopy)
11062 Diag(D->getLocation(), diag::warn_return_value_size)
11063 << D->getDeclName() << Size;
11066 // Warn if any parameter is pass-by-value and larger than the specified
11068 for (const ParmVarDecl *Parameter : Parameters) {
11069 QualType T = Parameter->getType();
11070 if (T->isDependentType() || !T.isPODType(Context))
11072 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11073 if (Size > LangOpts.NumLargeByValueCopy)
11074 Diag(Parameter->getLocation(), diag::warn_parameter_size)
11075 << Parameter->getDeclName() << Size;
11079 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11080 SourceLocation NameLoc, IdentifierInfo *Name,
11081 QualType T, TypeSourceInfo *TSInfo,
11083 // In ARC, infer a lifetime qualifier for appropriate parameter types.
11084 if (getLangOpts().ObjCAutoRefCount &&
11085 T.getObjCLifetime() == Qualifiers::OCL_None &&
11086 T->isObjCLifetimeType()) {
11088 Qualifiers::ObjCLifetime lifetime;
11090 // Special cases for arrays:
11091 // - if it's const, use __unsafe_unretained
11092 // - otherwise, it's an error
11093 if (T->isArrayType()) {
11094 if (!T.isConstQualified()) {
11095 DelayedDiagnostics.add(
11096 sema::DelayedDiagnostic::makeForbiddenType(
11097 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11099 lifetime = Qualifiers::OCL_ExplicitNone;
11101 lifetime = T->getObjCARCImplicitLifetime();
11103 T = Context.getLifetimeQualifiedType(T, lifetime);
11106 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11107 Context.getAdjustedParameterType(T),
11108 TSInfo, SC, nullptr);
11110 // Parameters can not be abstract class types.
11111 // For record types, this is done by the AbstractClassUsageDiagnoser once
11112 // the class has been completely parsed.
11113 if (!CurContext->isRecord() &&
11114 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11115 AbstractParamType))
11116 New->setInvalidDecl();
11118 // Parameter declarators cannot be interface types. All ObjC objects are
11119 // passed by reference.
11120 if (T->isObjCObjectType()) {
11121 SourceLocation TypeEndLoc =
11122 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11124 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11125 << FixItHint::CreateInsertion(TypeEndLoc, "*");
11126 T = Context.getObjCObjectPointerType(T);
11130 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11131 // duration shall not be qualified by an address-space qualifier."
11132 // Since all parameters have automatic store duration, they can not have
11133 // an address space.
11134 if (T.getAddressSpace() != 0) {
11135 // OpenCL allows function arguments declared to be an array of a type
11136 // to be qualified with an address space.
11137 if (!(getLangOpts().OpenCL && T->isArrayType())) {
11138 Diag(NameLoc, diag::err_arg_with_address_space);
11139 New->setInvalidDecl();
11146 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11147 SourceLocation LocAfterDecls) {
11148 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11150 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11151 // for a K&R function.
11152 if (!FTI.hasPrototype) {
11153 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11155 if (FTI.Params[i].Param == nullptr) {
11156 SmallString<256> Code;
11157 llvm::raw_svector_ostream(Code)
11158 << " int " << FTI.Params[i].Ident->getName() << ";\n";
11159 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11160 << FTI.Params[i].Ident
11161 << FixItHint::CreateInsertion(LocAfterDecls, Code);
11163 // Implicitly declare the argument as type 'int' for lack of a better
11165 AttributeFactory attrs;
11166 DeclSpec DS(attrs);
11167 const char* PrevSpec; // unused
11168 unsigned DiagID; // unused
11169 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11170 DiagID, Context.getPrintingPolicy());
11171 // Use the identifier location for the type source range.
11172 DS.SetRangeStart(FTI.Params[i].IdentLoc);
11173 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11174 Declarator ParamD(DS, Declarator::KNRTypeListContext);
11175 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11176 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11183 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11184 MultiTemplateParamsArg TemplateParameterLists,
11185 SkipBodyInfo *SkipBody) {
11186 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11187 assert(D.isFunctionDeclarator() && "Not a function declarator!");
11188 Scope *ParentScope = FnBodyScope->getParent();
11190 D.setFunctionDefinitionKind(FDK_Definition);
11191 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11192 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11195 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11196 Consumer.HandleInlineFunctionDefinition(D);
11199 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11200 const FunctionDecl*& PossibleZeroParamPrototype) {
11201 // Don't warn about invalid declarations.
11202 if (FD->isInvalidDecl())
11205 // Or declarations that aren't global.
11206 if (!FD->isGlobal())
11209 // Don't warn about C++ member functions.
11210 if (isa<CXXMethodDecl>(FD))
11213 // Don't warn about 'main'.
11217 // Don't warn about inline functions.
11218 if (FD->isInlined())
11221 // Don't warn about function templates.
11222 if (FD->getDescribedFunctionTemplate())
11225 // Don't warn about function template specializations.
11226 if (FD->isFunctionTemplateSpecialization())
11229 // Don't warn for OpenCL kernels.
11230 if (FD->hasAttr<OpenCLKernelAttr>())
11233 // Don't warn on explicitly deleted functions.
11234 if (FD->isDeleted())
11237 bool MissingPrototype = true;
11238 for (const FunctionDecl *Prev = FD->getPreviousDecl();
11239 Prev; Prev = Prev->getPreviousDecl()) {
11240 // Ignore any declarations that occur in function or method
11241 // scope, because they aren't visible from the header.
11242 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11245 MissingPrototype = !Prev->getType()->isFunctionProtoType();
11246 if (FD->getNumParams() == 0)
11247 PossibleZeroParamPrototype = Prev;
11251 return MissingPrototype;
11255 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11256 const FunctionDecl *EffectiveDefinition,
11257 SkipBodyInfo *SkipBody) {
11258 // Don't complain if we're in GNU89 mode and the previous definition
11259 // was an extern inline function.
11260 const FunctionDecl *Definition = EffectiveDefinition;
11262 if (!FD->isDefined(Definition))
11265 if (canRedefineFunction(Definition, getLangOpts()))
11268 // If we don't have a visible definition of the function, and it's inline or
11269 // a template, skip the new definition.
11270 if (SkipBody && !hasVisibleDefinition(Definition) &&
11271 (Definition->getFormalLinkage() == InternalLinkage ||
11272 Definition->isInlined() ||
11273 Definition->getDescribedFunctionTemplate() ||
11274 Definition->getNumTemplateParameterLists())) {
11275 SkipBody->ShouldSkip = true;
11276 if (auto *TD = Definition->getDescribedFunctionTemplate())
11277 makeMergedDefinitionVisible(TD, FD->getLocation());
11278 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11279 FD->getLocation());
11283 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11284 Definition->getStorageClass() == SC_Extern)
11285 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11286 << FD->getDeclName() << getLangOpts().CPlusPlus;
11288 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11290 Diag(Definition->getLocation(), diag::note_previous_definition);
11291 FD->setInvalidDecl();
11294 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11296 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11298 LambdaScopeInfo *LSI = S.PushLambdaScope();
11299 LSI->CallOperator = CallOperator;
11300 LSI->Lambda = LambdaClass;
11301 LSI->ReturnType = CallOperator->getReturnType();
11302 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11304 if (LCD == LCD_None)
11305 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11306 else if (LCD == LCD_ByCopy)
11307 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11308 else if (LCD == LCD_ByRef)
11309 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11310 DeclarationNameInfo DNI = CallOperator->getNameInfo();
11312 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11313 LSI->Mutable = !CallOperator->isConst();
11315 // Add the captures to the LSI so they can be noted as already
11316 // captured within tryCaptureVar.
11317 auto I = LambdaClass->field_begin();
11318 for (const auto &C : LambdaClass->captures()) {
11319 if (C.capturesVariable()) {
11320 VarDecl *VD = C.getCapturedVar();
11321 if (VD->isInitCapture())
11322 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11323 QualType CaptureType = VD->getType();
11324 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11325 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11326 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11327 /*EllipsisLoc*/C.isPackExpansion()
11328 ? C.getEllipsisLoc() : SourceLocation(),
11329 CaptureType, /*Expr*/ nullptr);
11331 } else if (C.capturesThis()) {
11332 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11334 C.getCaptureKind() == LCK_StarThis);
11336 LSI->addVLATypeCapture(C.getLocation(), I->getType());
11342 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11343 SkipBodyInfo *SkipBody) {
11344 // Clear the last template instantiation error context.
11345 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11349 FunctionDecl *FD = nullptr;
11351 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11352 FD = FunTmpl->getTemplatedDecl();
11354 FD = cast<FunctionDecl>(D);
11356 // See if this is a redefinition.
11357 if (!FD->isLateTemplateParsed()) {
11358 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11360 // If we're skipping the body, we're done. Don't enter the scope.
11361 if (SkipBody && SkipBody->ShouldSkip)
11365 // If we are instantiating a generic lambda call operator, push
11366 // a LambdaScopeInfo onto the function stack. But use the information
11367 // that's already been calculated (ActOnLambdaExpr) to prime the current
11368 // LambdaScopeInfo.
11369 // When the template operator is being specialized, the LambdaScopeInfo,
11370 // has to be properly restored so that tryCaptureVariable doesn't try
11371 // and capture any new variables. In addition when calculating potential
11372 // captures during transformation of nested lambdas, it is necessary to
11373 // have the LSI properly restored.
11374 if (isGenericLambdaCallOperatorSpecialization(FD)) {
11375 assert(ActiveTemplateInstantiations.size() &&
11376 "There should be an active template instantiation on the stack "
11377 "when instantiating a generic lambda!");
11378 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11381 // Enter a new function scope
11382 PushFunctionScope();
11384 // Builtin functions cannot be defined.
11385 if (unsigned BuiltinID = FD->getBuiltinID()) {
11386 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11387 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11388 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11389 FD->setInvalidDecl();
11393 // The return type of a function definition must be complete
11394 // (C99 6.9.1p3, C++ [dcl.fct]p6).
11395 QualType ResultType = FD->getReturnType();
11396 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11397 !FD->isInvalidDecl() &&
11398 RequireCompleteType(FD->getLocation(), ResultType,
11399 diag::err_func_def_incomplete_result))
11400 FD->setInvalidDecl();
11403 PushDeclContext(FnBodyScope, FD);
11405 // Check the validity of our function parameters
11406 CheckParmsForFunctionDef(FD->parameters(),
11407 /*CheckParameterNames=*/true);
11409 // Introduce our parameters into the function scope
11410 for (auto Param : FD->parameters()) {
11411 Param->setOwningFunction(FD);
11413 // If this has an identifier, add it to the scope stack.
11414 if (Param->getIdentifier() && FnBodyScope) {
11415 CheckShadow(FnBodyScope, Param);
11417 PushOnScopeChains(Param, FnBodyScope);
11421 // If we had any tags defined in the function prototype,
11422 // introduce them into the function scope.
11424 for (ArrayRef<NamedDecl *>::iterator
11425 I = FD->getDeclsInPrototypeScope().begin(),
11426 E = FD->getDeclsInPrototypeScope().end();
11430 // Some of these decls (like enums) may have been pinned to the
11431 // translation unit for lack of a real context earlier. If so, remove
11432 // from the translation unit and reattach to the current context.
11433 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11434 // Is the decl actually in the context?
11435 if (Context.getTranslationUnitDecl()->containsDecl(D))
11436 Context.getTranslationUnitDecl()->removeDecl(D);
11437 // Either way, reassign the lexical decl context to our FunctionDecl.
11438 D->setLexicalDeclContext(CurContext);
11441 // If the decl has a non-null name, make accessible in the current scope.
11442 if (!D->getName().empty())
11443 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11445 // Similarly, dive into enums and fish their constants out, making them
11446 // accessible in this scope.
11447 if (auto *ED = dyn_cast<EnumDecl>(D)) {
11448 for (auto *EI : ED->enumerators())
11449 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11454 // Ensure that the function's exception specification is instantiated.
11455 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11456 ResolveExceptionSpec(D->getLocation(), FPT);
11458 // dllimport cannot be applied to non-inline function definitions.
11459 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11460 !FD->isTemplateInstantiation()) {
11461 assert(!FD->hasAttr<DLLExportAttr>());
11462 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11463 FD->setInvalidDecl();
11466 // We want to attach documentation to original Decl (which might be
11467 // a function template).
11468 ActOnDocumentableDecl(D);
11469 if (getCurLexicalContext()->isObjCContainer() &&
11470 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11471 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11472 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11477 /// \brief Given the set of return statements within a function body,
11478 /// compute the variables that are subject to the named return value
11481 /// Each of the variables that is subject to the named return value
11482 /// optimization will be marked as NRVO variables in the AST, and any
11483 /// return statement that has a marked NRVO variable as its NRVO candidate can
11484 /// use the named return value optimization.
11486 /// This function applies a very simplistic algorithm for NRVO: if every return
11487 /// statement in the scope of a variable has the same NRVO candidate, that
11488 /// candidate is an NRVO variable.
11489 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11490 ReturnStmt **Returns = Scope->Returns.data();
11492 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11493 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11494 if (!NRVOCandidate->isNRVOVariable())
11495 Returns[I]->setNRVOCandidate(nullptr);
11500 bool Sema::canDelayFunctionBody(const Declarator &D) {
11501 // We can't delay parsing the body of a constexpr function template (yet).
11502 if (D.getDeclSpec().isConstexprSpecified())
11505 // We can't delay parsing the body of a function template with a deduced
11506 // return type (yet).
11507 if (D.getDeclSpec().containsPlaceholderType()) {
11508 // If the placeholder introduces a non-deduced trailing return type,
11509 // we can still delay parsing it.
11510 if (D.getNumTypeObjects()) {
11511 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11512 if (Outer.Kind == DeclaratorChunk::Function &&
11513 Outer.Fun.hasTrailingReturnType()) {
11514 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11515 return Ty.isNull() || !Ty->isUndeducedType();
11524 bool Sema::canSkipFunctionBody(Decl *D) {
11525 // We cannot skip the body of a function (or function template) which is
11526 // constexpr, since we may need to evaluate its body in order to parse the
11527 // rest of the file.
11528 // We cannot skip the body of a function with an undeduced return type,
11529 // because any callers of that function need to know the type.
11530 if (const FunctionDecl *FD = D->getAsFunction())
11531 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11533 return Consumer.shouldSkipFunctionBody(D);
11536 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11537 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11538 FD->setHasSkippedBody();
11539 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11540 MD->setHasSkippedBody();
11544 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11545 return ActOnFinishFunctionBody(D, BodyArg, false);
11548 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11549 bool IsInstantiation) {
11550 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11552 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11553 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11555 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11556 CheckCompletedCoroutineBody(FD, Body);
11561 if (getLangOpts().CPlusPlus14) {
11562 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11563 FD->getReturnType()->isUndeducedType()) {
11564 // If the function has a deduced result type but contains no 'return'
11565 // statements, the result type as written must be exactly 'auto', and
11566 // the deduced result type is 'void'.
11567 if (!FD->getReturnType()->getAs<AutoType>()) {
11568 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11569 << FD->getReturnType();
11570 FD->setInvalidDecl();
11572 // Substitute 'void' for the 'auto' in the type.
11573 TypeLoc ResultType = getReturnTypeLoc(FD);
11574 Context.adjustDeducedFunctionResultType(
11575 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11578 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11579 // In C++11, we don't use 'auto' deduction rules for lambda call
11580 // operators because we don't support return type deduction.
11581 auto *LSI = getCurLambda();
11582 if (LSI->HasImplicitReturnType) {
11583 deduceClosureReturnType(*LSI);
11585 // C++11 [expr.prim.lambda]p4:
11586 // [...] if there are no return statements in the compound-statement
11587 // [the deduced type is] the type void
11589 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11591 // Update the return type to the deduced type.
11592 const FunctionProtoType *Proto =
11593 FD->getType()->getAs<FunctionProtoType>();
11594 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11595 Proto->getExtProtoInfo()));
11599 // The only way to be included in UndefinedButUsed is if there is an
11600 // ODR use before the definition. Avoid the expensive map lookup if this
11601 // is the first declaration.
11602 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11603 if (!FD->isExternallyVisible())
11604 UndefinedButUsed.erase(FD);
11605 else if (FD->isInlined() &&
11606 !LangOpts.GNUInline &&
11607 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11608 UndefinedButUsed.erase(FD);
11611 // If the function implicitly returns zero (like 'main') or is naked,
11612 // don't complain about missing return statements.
11613 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11614 WP.disableCheckFallThrough();
11616 // MSVC permits the use of pure specifier (=0) on function definition,
11617 // defined at class scope, warn about this non-standard construct.
11618 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11619 Diag(FD->getLocation(), diag::ext_pure_function_definition);
11621 if (!FD->isInvalidDecl()) {
11622 // Don't diagnose unused parameters of defaulted or deleted functions.
11623 if (!FD->isDeleted() && !FD->isDefaulted())
11624 DiagnoseUnusedParameters(FD->parameters());
11625 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11626 FD->getReturnType(), FD);
11628 // If this is a structor, we need a vtable.
11629 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11630 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11631 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11632 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11634 // Try to apply the named return value optimization. We have to check
11635 // if we can do this here because lambdas keep return statements around
11636 // to deduce an implicit return type.
11637 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11638 !FD->isDependentContext())
11639 computeNRVO(Body, getCurFunction());
11642 // GNU warning -Wmissing-prototypes:
11643 // Warn if a global function is defined without a previous
11644 // prototype declaration. This warning is issued even if the
11645 // definition itself provides a prototype. The aim is to detect
11646 // global functions that fail to be declared in header files.
11647 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11648 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11649 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11651 if (PossibleZeroParamPrototype) {
11652 // We found a declaration that is not a prototype,
11653 // but that could be a zero-parameter prototype
11654 if (TypeSourceInfo *TI =
11655 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11656 TypeLoc TL = TI->getTypeLoc();
11657 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11658 Diag(PossibleZeroParamPrototype->getLocation(),
11659 diag::note_declaration_not_a_prototype)
11660 << PossibleZeroParamPrototype
11661 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11666 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11667 const CXXMethodDecl *KeyFunction;
11668 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11670 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11671 MD == KeyFunction->getCanonicalDecl()) {
11672 // Update the key-function state if necessary for this ABI.
11673 if (FD->isInlined() &&
11674 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11675 Context.setNonKeyFunction(MD);
11677 // If the newly-chosen key function is already defined, then we
11678 // need to mark the vtable as used retroactively.
11679 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11680 const FunctionDecl *Definition;
11681 if (KeyFunction && KeyFunction->isDefined(Definition))
11682 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11684 // We just defined they key function; mark the vtable as used.
11685 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11690 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11691 "Function parsing confused");
11692 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11693 assert(MD == getCurMethodDecl() && "Method parsing confused");
11695 if (!MD->isInvalidDecl()) {
11696 DiagnoseUnusedParameters(MD->parameters());
11697 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11698 MD->getReturnType(), MD);
11701 computeNRVO(Body, getCurFunction());
11703 if (getCurFunction()->ObjCShouldCallSuper) {
11704 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11705 << MD->getSelector().getAsString();
11706 getCurFunction()->ObjCShouldCallSuper = false;
11708 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11709 const ObjCMethodDecl *InitMethod = nullptr;
11710 bool isDesignated =
11711 MD->isDesignatedInitializerForTheInterface(&InitMethod);
11712 assert(isDesignated && InitMethod);
11713 (void)isDesignated;
11715 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11716 auto IFace = MD->getClassInterface();
11719 auto SuperD = IFace->getSuperClass();
11722 return SuperD->getIdentifier() ==
11723 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11725 // Don't issue this warning for unavailable inits or direct subclasses
11727 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11728 Diag(MD->getLocation(),
11729 diag::warn_objc_designated_init_missing_super_call);
11730 Diag(InitMethod->getLocation(),
11731 diag::note_objc_designated_init_marked_here);
11733 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11735 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11736 // Don't issue this warning for unavaialable inits.
11737 if (!MD->isUnavailable())
11738 Diag(MD->getLocation(),
11739 diag::warn_objc_secondary_init_missing_init_call);
11740 getCurFunction()->ObjCWarnForNoInitDelegation = false;
11746 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
11747 DiagnoseUnguardedAvailabilityViolations(dcl);
11749 assert(!getCurFunction()->ObjCShouldCallSuper &&
11750 "This should only be set for ObjC methods, which should have been "
11751 "handled in the block above.");
11753 // Verify and clean out per-function state.
11754 if (Body && (!FD || !FD->isDefaulted())) {
11755 // C++ constructors that have function-try-blocks can't have return
11756 // statements in the handlers of that block. (C++ [except.handle]p14)
11758 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11759 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11761 // Verify that gotos and switch cases don't jump into scopes illegally.
11762 if (getCurFunction()->NeedsScopeChecking() &&
11763 !PP.isCodeCompletionEnabled())
11764 DiagnoseInvalidJumps(Body);
11766 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11767 if (!Destructor->getParent()->isDependentType())
11768 CheckDestructor(Destructor);
11770 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11771 Destructor->getParent());
11774 // If any errors have occurred, clear out any temporaries that may have
11775 // been leftover. This ensures that these temporaries won't be picked up for
11776 // deletion in some later function.
11777 if (getDiagnostics().hasErrorOccurred() ||
11778 getDiagnostics().getSuppressAllDiagnostics()) {
11779 DiscardCleanupsInEvaluationContext();
11781 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11782 !isa<FunctionTemplateDecl>(dcl)) {
11783 // Since the body is valid, issue any analysis-based warnings that are
11785 ActivePolicy = &WP;
11788 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11789 (!CheckConstexprFunctionDecl(FD) ||
11790 !CheckConstexprFunctionBody(FD, Body)))
11791 FD->setInvalidDecl();
11793 if (FD && FD->hasAttr<NakedAttr>()) {
11794 for (const Stmt *S : Body->children()) {
11795 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11796 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11797 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11798 FD->setInvalidDecl();
11804 assert(ExprCleanupObjects.size() ==
11805 ExprEvalContexts.back().NumCleanupObjects &&
11806 "Leftover temporaries in function");
11807 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
11808 assert(MaybeODRUseExprs.empty() &&
11809 "Leftover expressions for odr-use checking");
11812 if (!IsInstantiation)
11815 PopFunctionScopeInfo(ActivePolicy, dcl);
11816 // If any errors have occurred, clear out any temporaries that may have
11817 // been leftover. This ensures that these temporaries won't be picked up for
11818 // deletion in some later function.
11819 if (getDiagnostics().hasErrorOccurred()) {
11820 DiscardCleanupsInEvaluationContext();
11826 /// When we finish delayed parsing of an attribute, we must attach it to the
11828 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11829 ParsedAttributes &Attrs) {
11830 // Always attach attributes to the underlying decl.
11831 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11832 D = TD->getTemplatedDecl();
11833 ProcessDeclAttributeList(S, D, Attrs.getList());
11835 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11836 if (Method->isStatic())
11837 checkThisInStaticMemberFunctionAttributes(Method);
11840 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11841 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11842 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11843 IdentifierInfo &II, Scope *S) {
11844 // Before we produce a declaration for an implicitly defined
11845 // function, see whether there was a locally-scoped declaration of
11846 // this name as a function or variable. If so, use that
11847 // (non-visible) declaration, and complain about it.
11848 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11849 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11850 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11851 return ExternCPrev;
11854 // Extension in C99. Legal in C90, but warn about it.
11856 if (II.getName().startswith("__builtin_"))
11857 diag_id = diag::warn_builtin_unknown;
11858 else if (getLangOpts().C99)
11859 diag_id = diag::ext_implicit_function_decl;
11861 diag_id = diag::warn_implicit_function_decl;
11862 Diag(Loc, diag_id) << &II;
11864 // Because typo correction is expensive, only do it if the implicit
11865 // function declaration is going to be treated as an error.
11866 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11867 TypoCorrection Corrected;
11869 (Corrected = CorrectTypo(
11870 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11871 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11872 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11873 /*ErrorRecovery*/false);
11876 // Set a Declarator for the implicit definition: int foo();
11878 AttributeFactory attrFactory;
11879 DeclSpec DS(attrFactory);
11881 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11882 Context.getPrintingPolicy());
11883 (void)Error; // Silence warning.
11884 assert(!Error && "Error setting up implicit decl!");
11885 SourceLocation NoLoc;
11886 Declarator D(DS, Declarator::BlockContext);
11887 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11888 /*IsAmbiguous=*/false,
11889 /*LParenLoc=*/NoLoc,
11890 /*Params=*/nullptr,
11892 /*EllipsisLoc=*/NoLoc,
11893 /*RParenLoc=*/NoLoc,
11895 /*RefQualifierIsLvalueRef=*/true,
11896 /*RefQualifierLoc=*/NoLoc,
11897 /*ConstQualifierLoc=*/NoLoc,
11898 /*VolatileQualifierLoc=*/NoLoc,
11899 /*RestrictQualifierLoc=*/NoLoc,
11900 /*MutableLoc=*/NoLoc,
11902 /*ESpecRange=*/SourceRange(),
11903 /*Exceptions=*/nullptr,
11904 /*ExceptionRanges=*/nullptr,
11905 /*NumExceptions=*/0,
11906 /*NoexceptExpr=*/nullptr,
11907 /*ExceptionSpecTokens=*/nullptr,
11909 DS.getAttributes(),
11911 D.SetIdentifier(&II, Loc);
11913 // Insert this function into translation-unit scope.
11915 DeclContext *PrevDC = CurContext;
11916 CurContext = Context.getTranslationUnitDecl();
11918 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11921 CurContext = PrevDC;
11923 AddKnownFunctionAttributes(FD);
11928 /// \brief Adds any function attributes that we know a priori based on
11929 /// the declaration of this function.
11931 /// These attributes can apply both to implicitly-declared builtins
11932 /// (like __builtin___printf_chk) or to library-declared functions
11933 /// like NSLog or printf.
11935 /// We need to check for duplicate attributes both here and where user-written
11936 /// attributes are applied to declarations.
11937 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11938 if (FD->isInvalidDecl())
11941 // If this is a built-in function, map its builtin attributes to
11942 // actual attributes.
11943 if (unsigned BuiltinID = FD->getBuiltinID()) {
11944 // Handle printf-formatting attributes.
11945 unsigned FormatIdx;
11947 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11948 if (!FD->hasAttr<FormatAttr>()) {
11949 const char *fmt = "printf";
11950 unsigned int NumParams = FD->getNumParams();
11951 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11952 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11954 FD->addAttr(FormatAttr::CreateImplicit(Context,
11955 &Context.Idents.get(fmt),
11957 HasVAListArg ? 0 : FormatIdx+2,
11958 FD->getLocation()));
11961 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11963 if (!FD->hasAttr<FormatAttr>())
11964 FD->addAttr(FormatAttr::CreateImplicit(Context,
11965 &Context.Idents.get("scanf"),
11967 HasVAListArg ? 0 : FormatIdx+2,
11968 FD->getLocation()));
11971 // Mark const if we don't care about errno and that is the only
11972 // thing preventing the function from being const. This allows
11973 // IRgen to use LLVM intrinsics for such functions.
11974 if (!getLangOpts().MathErrno &&
11975 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11976 if (!FD->hasAttr<ConstAttr>())
11977 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11980 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11981 !FD->hasAttr<ReturnsTwiceAttr>())
11982 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11983 FD->getLocation()));
11984 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11985 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11986 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11987 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11988 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11989 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11990 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11991 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11992 // Add the appropriate attribute, depending on the CUDA compilation mode
11993 // and which target the builtin belongs to. For example, during host
11994 // compilation, aux builtins are __device__, while the rest are __host__.
11995 if (getLangOpts().CUDAIsDevice !=
11996 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11997 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11999 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12003 // If C++ exceptions are enabled but we are told extern "C" functions cannot
12004 // throw, add an implicit nothrow attribute to any extern "C" function we come
12006 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12007 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12008 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12009 if (!FPT || FPT->getExceptionSpecType() == EST_None)
12010 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12013 IdentifierInfo *Name = FD->getIdentifier();
12016 if ((!getLangOpts().CPlusPlus &&
12017 FD->getDeclContext()->isTranslationUnit()) ||
12018 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12019 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12020 LinkageSpecDecl::lang_c)) {
12021 // Okay: this could be a libc/libm/Objective-C function we know
12026 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12027 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12028 // target-specific builtins, perhaps?
12029 if (!FD->hasAttr<FormatAttr>())
12030 FD->addAttr(FormatAttr::CreateImplicit(Context,
12031 &Context.Idents.get("printf"), 2,
12032 Name->isStr("vasprintf") ? 0 : 3,
12033 FD->getLocation()));
12036 if (Name->isStr("__CFStringMakeConstantString")) {
12037 // We already have a __builtin___CFStringMakeConstantString,
12038 // but builds that use -fno-constant-cfstrings don't go through that.
12039 if (!FD->hasAttr<FormatArgAttr>())
12040 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12041 FD->getLocation()));
12045 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12046 TypeSourceInfo *TInfo) {
12047 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12048 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12051 assert(D.isInvalidType() && "no declarator info for valid type");
12052 TInfo = Context.getTrivialTypeSourceInfo(T);
12055 // Scope manipulation handled by caller.
12056 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12058 D.getIdentifierLoc(),
12062 // Bail out immediately if we have an invalid declaration.
12063 if (D.isInvalidType()) {
12064 NewTD->setInvalidDecl();
12068 if (D.getDeclSpec().isModulePrivateSpecified()) {
12069 if (CurContext->isFunctionOrMethod())
12070 Diag(NewTD->getLocation(), diag::err_module_private_local)
12071 << 2 << NewTD->getDeclName()
12072 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12073 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12075 NewTD->setModulePrivate();
12078 // C++ [dcl.typedef]p8:
12079 // If the typedef declaration defines an unnamed class (or
12080 // enum), the first typedef-name declared by the declaration
12081 // to be that class type (or enum type) is used to denote the
12082 // class type (or enum type) for linkage purposes only.
12083 // We need to check whether the type was declared in the declaration.
12084 switch (D.getDeclSpec().getTypeSpecType()) {
12087 case TST_interface:
12090 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12091 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12102 /// \brief Check that this is a valid underlying type for an enum declaration.
12103 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12104 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12105 QualType T = TI->getType();
12107 if (T->isDependentType())
12110 if (const BuiltinType *BT = T->getAs<BuiltinType>())
12111 if (BT->isInteger())
12114 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12118 /// Check whether this is a valid redeclaration of a previous enumeration.
12119 /// \return true if the redeclaration was invalid.
12120 bool Sema::CheckEnumRedeclaration(
12121 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12122 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12123 bool IsFixed = !EnumUnderlyingTy.isNull();
12125 if (IsScoped != Prev->isScoped()) {
12126 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12127 << Prev->isScoped();
12128 Diag(Prev->getLocation(), diag::note_previous_declaration);
12132 if (IsFixed && Prev->isFixed()) {
12133 if (!EnumUnderlyingTy->isDependentType() &&
12134 !Prev->getIntegerType()->isDependentType() &&
12135 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12136 Prev->getIntegerType())) {
12137 // TODO: Highlight the underlying type of the redeclaration.
12138 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12139 << EnumUnderlyingTy << Prev->getIntegerType();
12140 Diag(Prev->getLocation(), diag::note_previous_declaration)
12141 << Prev->getIntegerTypeRange();
12144 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12146 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12148 } else if (IsFixed != Prev->isFixed()) {
12149 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12150 << Prev->isFixed();
12151 Diag(Prev->getLocation(), diag::note_previous_declaration);
12158 /// \brief Get diagnostic %select index for tag kind for
12159 /// redeclaration diagnostic message.
12160 /// WARNING: Indexes apply to particular diagnostics only!
12162 /// \returns diagnostic %select index.
12163 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12165 case TTK_Struct: return 0;
12166 case TTK_Interface: return 1;
12167 case TTK_Class: return 2;
12168 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12172 /// \brief Determine if tag kind is a class-key compatible with
12173 /// class for redeclaration (class, struct, or __interface).
12175 /// \returns true iff the tag kind is compatible.
12176 static bool isClassCompatTagKind(TagTypeKind Tag)
12178 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12181 /// \brief Determine whether a tag with a given kind is acceptable
12182 /// as a redeclaration of the given tag declaration.
12184 /// \returns true if the new tag kind is acceptable, false otherwise.
12185 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12186 TagTypeKind NewTag, bool isDefinition,
12187 SourceLocation NewTagLoc,
12188 const IdentifierInfo *Name) {
12189 // C++ [dcl.type.elab]p3:
12190 // The class-key or enum keyword present in the
12191 // elaborated-type-specifier shall agree in kind with the
12192 // declaration to which the name in the elaborated-type-specifier
12193 // refers. This rule also applies to the form of
12194 // elaborated-type-specifier that declares a class-name or
12195 // friend class since it can be construed as referring to the
12196 // definition of the class. Thus, in any
12197 // elaborated-type-specifier, the enum keyword shall be used to
12198 // refer to an enumeration (7.2), the union class-key shall be
12199 // used to refer to a union (clause 9), and either the class or
12200 // struct class-key shall be used to refer to a class (clause 9)
12201 // declared using the class or struct class-key.
12202 TagTypeKind OldTag = Previous->getTagKind();
12203 if (!isDefinition || !isClassCompatTagKind(NewTag))
12204 if (OldTag == NewTag)
12207 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12208 // Warn about the struct/class tag mismatch.
12209 bool isTemplate = false;
12210 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12211 isTemplate = Record->getDescribedClassTemplate();
12213 if (!ActiveTemplateInstantiations.empty()) {
12214 // In a template instantiation, do not offer fix-its for tag mismatches
12215 // since they usually mess up the template instead of fixing the problem.
12216 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12217 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12218 << getRedeclDiagFromTagKind(OldTag);
12222 if (isDefinition) {
12223 // On definitions, check previous tags and issue a fix-it for each
12224 // one that doesn't match the current tag.
12225 if (Previous->getDefinition()) {
12226 // Don't suggest fix-its for redefinitions.
12230 bool previousMismatch = false;
12231 for (auto I : Previous->redecls()) {
12232 if (I->getTagKind() != NewTag) {
12233 if (!previousMismatch) {
12234 previousMismatch = true;
12235 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12236 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12237 << getRedeclDiagFromTagKind(I->getTagKind());
12239 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12240 << getRedeclDiagFromTagKind(NewTag)
12241 << FixItHint::CreateReplacement(I->getInnerLocStart(),
12242 TypeWithKeyword::getTagTypeKindName(NewTag));
12248 // Check for a previous definition. If current tag and definition
12249 // are same type, do nothing. If no definition, but disagree with
12250 // with previous tag type, give a warning, but no fix-it.
12251 const TagDecl *Redecl = Previous->getDefinition() ?
12252 Previous->getDefinition() : Previous;
12253 if (Redecl->getTagKind() == NewTag) {
12257 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12258 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12259 << getRedeclDiagFromTagKind(OldTag);
12260 Diag(Redecl->getLocation(), diag::note_previous_use);
12262 // If there is a previous definition, suggest a fix-it.
12263 if (Previous->getDefinition()) {
12264 Diag(NewTagLoc, diag::note_struct_class_suggestion)
12265 << getRedeclDiagFromTagKind(Redecl->getTagKind())
12266 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12267 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12275 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12276 /// from an outer enclosing namespace or file scope inside a friend declaration.
12277 /// This should provide the commented out code in the following snippet:
12281 /// struct Y { friend struct /*N::*/ X; };
12284 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12285 SourceLocation NameLoc) {
12286 // While the decl is in a namespace, do repeated lookup of that name and see
12287 // if we get the same namespace back. If we do not, continue until
12288 // translation unit scope, at which point we have a fully qualified NNS.
12289 SmallVector<IdentifierInfo *, 4> Namespaces;
12290 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12291 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12292 // This tag should be declared in a namespace, which can only be enclosed by
12293 // other namespaces. Bail if there's an anonymous namespace in the chain.
12294 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12295 if (!Namespace || Namespace->isAnonymousNamespace())
12296 return FixItHint();
12297 IdentifierInfo *II = Namespace->getIdentifier();
12298 Namespaces.push_back(II);
12299 NamedDecl *Lookup = SemaRef.LookupSingleName(
12300 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12301 if (Lookup == Namespace)
12305 // Once we have all the namespaces, reverse them to go outermost first, and
12307 SmallString<64> Insertion;
12308 llvm::raw_svector_ostream OS(Insertion);
12309 if (DC->isTranslationUnit())
12311 std::reverse(Namespaces.begin(), Namespaces.end());
12312 for (auto *II : Namespaces)
12313 OS << II->getName() << "::";
12314 return FixItHint::CreateInsertion(NameLoc, Insertion);
12317 /// \brief Determine whether a tag originally declared in context \p OldDC can
12318 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12319 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12320 /// using-declaration).
12321 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12322 DeclContext *NewDC) {
12323 OldDC = OldDC->getRedeclContext();
12324 NewDC = NewDC->getRedeclContext();
12326 if (OldDC->Equals(NewDC))
12329 // In MSVC mode, we allow a redeclaration if the contexts are related (either
12330 // encloses the other).
12331 if (S.getLangOpts().MSVCCompat &&
12332 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12338 /// Find the DeclContext in which a tag is implicitly declared if we see an
12339 /// elaborated type specifier in the specified context, and lookup finds
12341 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12342 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12343 DC = DC->getParent();
12347 /// Find the Scope in which a tag is implicitly declared if we see an
12348 /// elaborated type specifier in the specified context, and lookup finds
12350 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12351 while (S->isClassScope() ||
12352 (LangOpts.CPlusPlus &&
12353 S->isFunctionPrototypeScope()) ||
12354 ((S->getFlags() & Scope::DeclScope) == 0) ||
12355 (S->getEntity() && S->getEntity()->isTransparentContext()))
12356 S = S->getParent();
12360 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
12361 /// former case, Name will be non-null. In the later case, Name will be null.
12362 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12363 /// reference/declaration/definition of a tag.
12365 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12366 /// trailing-type-specifier) other than one in an alias-declaration.
12368 /// \param SkipBody If non-null, will be set to indicate if the caller should
12369 /// skip the definition of this tag and treat it as if it were a declaration.
12370 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12371 SourceLocation KWLoc, CXXScopeSpec &SS,
12372 IdentifierInfo *Name, SourceLocation NameLoc,
12373 AttributeList *Attr, AccessSpecifier AS,
12374 SourceLocation ModulePrivateLoc,
12375 MultiTemplateParamsArg TemplateParameterLists,
12376 bool &OwnedDecl, bool &IsDependent,
12377 SourceLocation ScopedEnumKWLoc,
12378 bool ScopedEnumUsesClassTag,
12379 TypeResult UnderlyingType,
12380 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12381 // If this is not a definition, it must have a name.
12382 IdentifierInfo *OrigName = Name;
12383 assert((Name != nullptr || TUK == TUK_Definition) &&
12384 "Nameless record must be a definition!");
12385 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12388 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12389 bool ScopedEnum = ScopedEnumKWLoc.isValid();
12391 // FIXME: Check explicit specializations more carefully.
12392 bool isExplicitSpecialization = false;
12393 bool Invalid = false;
12395 // We only need to do this matching if we have template parameters
12396 // or a scope specifier, which also conveniently avoids this work
12397 // for non-C++ cases.
12398 if (TemplateParameterLists.size() > 0 ||
12399 (SS.isNotEmpty() && TUK != TUK_Reference)) {
12400 if (TemplateParameterList *TemplateParams =
12401 MatchTemplateParametersToScopeSpecifier(
12402 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12403 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12404 if (Kind == TTK_Enum) {
12405 Diag(KWLoc, diag::err_enum_template);
12409 if (TemplateParams->size() > 0) {
12410 // This is a declaration or definition of a class template (which may
12411 // be a member of another template).
12417 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12418 SS, Name, NameLoc, Attr,
12419 TemplateParams, AS,
12421 /*FriendLoc*/SourceLocation(),
12422 TemplateParameterLists.size()-1,
12423 TemplateParameterLists.data(),
12425 return Result.get();
12427 // The "template<>" header is extraneous.
12428 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12429 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12430 isExplicitSpecialization = true;
12435 // Figure out the underlying type if this a enum declaration. We need to do
12436 // this early, because it's needed to detect if this is an incompatible
12438 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12439 bool EnumUnderlyingIsImplicit = false;
12441 if (Kind == TTK_Enum) {
12442 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12443 // No underlying type explicitly specified, or we failed to parse the
12444 // type, default to int.
12445 EnumUnderlying = Context.IntTy.getTypePtr();
12446 else if (UnderlyingType.get()) {
12447 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12448 // integral type; any cv-qualification is ignored.
12449 TypeSourceInfo *TI = nullptr;
12450 GetTypeFromParser(UnderlyingType.get(), &TI);
12451 EnumUnderlying = TI;
12453 if (CheckEnumUnderlyingType(TI))
12454 // Recover by falling back to int.
12455 EnumUnderlying = Context.IntTy.getTypePtr();
12457 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12458 UPPC_FixedUnderlyingType))
12459 EnumUnderlying = Context.IntTy.getTypePtr();
12461 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12462 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12463 // Microsoft enums are always of int type.
12464 EnumUnderlying = Context.IntTy.getTypePtr();
12465 EnumUnderlyingIsImplicit = true;
12470 DeclContext *SearchDC = CurContext;
12471 DeclContext *DC = CurContext;
12472 bool isStdBadAlloc = false;
12474 RedeclarationKind Redecl = ForRedeclaration;
12475 if (TUK == TUK_Friend || TUK == TUK_Reference)
12476 Redecl = NotForRedeclaration;
12478 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12479 if (Name && SS.isNotEmpty()) {
12480 // We have a nested-name tag ('struct foo::bar').
12482 // Check for invalid 'foo::'.
12483 if (SS.isInvalid()) {
12485 goto CreateNewDecl;
12488 // If this is a friend or a reference to a class in a dependent
12489 // context, don't try to make a decl for it.
12490 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12491 DC = computeDeclContext(SS, false);
12493 IsDependent = true;
12497 DC = computeDeclContext(SS, true);
12499 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12505 if (RequireCompleteDeclContext(SS, DC))
12509 // Look-up name inside 'foo::'.
12510 LookupQualifiedName(Previous, DC);
12512 if (Previous.isAmbiguous())
12515 if (Previous.empty()) {
12516 // Name lookup did not find anything. However, if the
12517 // nested-name-specifier refers to the current instantiation,
12518 // and that current instantiation has any dependent base
12519 // classes, we might find something at instantiation time: treat
12520 // this as a dependent elaborated-type-specifier.
12521 // But this only makes any sense for reference-like lookups.
12522 if (Previous.wasNotFoundInCurrentInstantiation() &&
12523 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12524 IsDependent = true;
12528 // A tag 'foo::bar' must already exist.
12529 Diag(NameLoc, diag::err_not_tag_in_scope)
12530 << Kind << Name << DC << SS.getRange();
12533 goto CreateNewDecl;
12536 // C++14 [class.mem]p14:
12537 // If T is the name of a class, then each of the following shall have a
12538 // name different from T:
12539 // -- every member of class T that is itself a type
12540 if (TUK != TUK_Reference && TUK != TUK_Friend &&
12541 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12544 // If this is a named struct, check to see if there was a previous forward
12545 // declaration or definition.
12546 // FIXME: We're looking into outer scopes here, even when we
12547 // shouldn't be. Doing so can result in ambiguities that we
12548 // shouldn't be diagnosing.
12549 LookupName(Previous, S);
12551 // When declaring or defining a tag, ignore ambiguities introduced
12552 // by types using'ed into this scope.
12553 if (Previous.isAmbiguous() &&
12554 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12555 LookupResult::Filter F = Previous.makeFilter();
12556 while (F.hasNext()) {
12557 NamedDecl *ND = F.next();
12558 if (!ND->getDeclContext()->getRedeclContext()->Equals(
12559 SearchDC->getRedeclContext()))
12565 // C++11 [namespace.memdef]p3:
12566 // If the name in a friend declaration is neither qualified nor
12567 // a template-id and the declaration is a function or an
12568 // elaborated-type-specifier, the lookup to determine whether
12569 // the entity has been previously declared shall not consider
12570 // any scopes outside the innermost enclosing namespace.
12572 // MSVC doesn't implement the above rule for types, so a friend tag
12573 // declaration may be a redeclaration of a type declared in an enclosing
12574 // scope. They do implement this rule for friend functions.
12576 // Does it matter that this should be by scope instead of by
12577 // semantic context?
12578 if (!Previous.empty() && TUK == TUK_Friend) {
12579 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12580 LookupResult::Filter F = Previous.makeFilter();
12581 bool FriendSawTagOutsideEnclosingNamespace = false;
12582 while (F.hasNext()) {
12583 NamedDecl *ND = F.next();
12584 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12585 if (DC->isFileContext() &&
12586 !EnclosingNS->Encloses(ND->getDeclContext())) {
12587 if (getLangOpts().MSVCCompat)
12588 FriendSawTagOutsideEnclosingNamespace = true;
12595 // Diagnose this MSVC extension in the easy case where lookup would have
12596 // unambiguously found something outside the enclosing namespace.
12597 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12598 NamedDecl *ND = Previous.getFoundDecl();
12599 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12600 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12604 // Note: there used to be some attempt at recovery here.
12605 if (Previous.isAmbiguous())
12608 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12609 // FIXME: This makes sure that we ignore the contexts associated
12610 // with C structs, unions, and enums when looking for a matching
12611 // tag declaration or definition. See the similar lookup tweak
12612 // in Sema::LookupName; is there a better way to deal with this?
12613 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12614 SearchDC = SearchDC->getParent();
12618 if (Previous.isSingleResult() &&
12619 Previous.getFoundDecl()->isTemplateParameter()) {
12620 // Maybe we will complain about the shadowed template parameter.
12621 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12622 // Just pretend that we didn't see the previous declaration.
12626 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12627 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12628 // This is a declaration of or a reference to "std::bad_alloc".
12629 isStdBadAlloc = true;
12631 if (Previous.empty() && StdBadAlloc) {
12632 // std::bad_alloc has been implicitly declared (but made invisible to
12633 // name lookup). Fill in this implicit declaration as the previous
12634 // declaration, so that the declarations get chained appropriately.
12635 Previous.addDecl(getStdBadAlloc());
12639 // If we didn't find a previous declaration, and this is a reference
12640 // (or friend reference), move to the correct scope. In C++, we
12641 // also need to do a redeclaration lookup there, just in case
12642 // there's a shadow friend decl.
12643 if (Name && Previous.empty() &&
12644 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12645 if (Invalid) goto CreateNewDecl;
12646 assert(SS.isEmpty());
12648 if (TUK == TUK_Reference) {
12649 // C++ [basic.scope.pdecl]p5:
12650 // -- for an elaborated-type-specifier of the form
12652 // class-key identifier
12654 // if the elaborated-type-specifier is used in the
12655 // decl-specifier-seq or parameter-declaration-clause of a
12656 // function defined in namespace scope, the identifier is
12657 // declared as a class-name in the namespace that contains
12658 // the declaration; otherwise, except as a friend
12659 // declaration, the identifier is declared in the smallest
12660 // non-class, non-function-prototype scope that contains the
12663 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12664 // C structs and unions.
12666 // It is an error in C++ to declare (rather than define) an enum
12667 // type, including via an elaborated type specifier. We'll
12668 // diagnose that later; for now, declare the enum in the same
12669 // scope as we would have picked for any other tag type.
12671 // GNU C also supports this behavior as part of its incomplete
12672 // enum types extension, while GNU C++ does not.
12674 // Find the context where we'll be declaring the tag.
12675 // FIXME: We would like to maintain the current DeclContext as the
12676 // lexical context,
12677 SearchDC = getTagInjectionContext(SearchDC);
12679 // Find the scope where we'll be declaring the tag.
12680 S = getTagInjectionScope(S, getLangOpts());
12682 assert(TUK == TUK_Friend);
12683 // C++ [namespace.memdef]p3:
12684 // If a friend declaration in a non-local class first declares a
12685 // class or function, the friend class or function is a member of
12686 // the innermost enclosing namespace.
12687 SearchDC = SearchDC->getEnclosingNamespaceContext();
12690 // In C++, we need to do a redeclaration lookup to properly
12691 // diagnose some problems.
12692 // FIXME: redeclaration lookup is also used (with and without C++) to find a
12693 // hidden declaration so that we don't get ambiguity errors when using a
12694 // type declared by an elaborated-type-specifier. In C that is not correct
12695 // and we should instead merge compatible types found by lookup.
12696 if (getLangOpts().CPlusPlus) {
12697 Previous.setRedeclarationKind(ForRedeclaration);
12698 LookupQualifiedName(Previous, SearchDC);
12700 Previous.setRedeclarationKind(ForRedeclaration);
12701 LookupName(Previous, S);
12705 // If we have a known previous declaration to use, then use it.
12706 if (Previous.empty() && SkipBody && SkipBody->Previous)
12707 Previous.addDecl(SkipBody->Previous);
12709 if (!Previous.empty()) {
12710 NamedDecl *PrevDecl = Previous.getFoundDecl();
12711 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12713 // It's okay to have a tag decl in the same scope as a typedef
12714 // which hides a tag decl in the same scope. Finding this
12715 // insanity with a redeclaration lookup can only actually happen
12718 // This is also okay for elaborated-type-specifiers, which is
12719 // technically forbidden by the current standard but which is
12720 // okay according to the likely resolution of an open issue;
12721 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12722 if (getLangOpts().CPlusPlus) {
12723 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12724 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12725 TagDecl *Tag = TT->getDecl();
12726 if (Tag->getDeclName() == Name &&
12727 Tag->getDeclContext()->getRedeclContext()
12728 ->Equals(TD->getDeclContext()->getRedeclContext())) {
12731 Previous.addDecl(Tag);
12732 Previous.resolveKind();
12738 // If this is a redeclaration of a using shadow declaration, it must
12739 // declare a tag in the same context. In MSVC mode, we allow a
12740 // redefinition if either context is within the other.
12741 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12742 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12743 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12744 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12745 !(OldTag && isAcceptableTagRedeclContext(
12746 *this, OldTag->getDeclContext(), SearchDC))) {
12747 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12748 Diag(Shadow->getTargetDecl()->getLocation(),
12749 diag::note_using_decl_target);
12750 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12752 // Recover by ignoring the old declaration.
12754 goto CreateNewDecl;
12758 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12759 // If this is a use of a previous tag, or if the tag is already declared
12760 // in the same scope (so that the definition/declaration completes or
12761 // rementions the tag), reuse the decl.
12762 if (TUK == TUK_Reference || TUK == TUK_Friend ||
12763 isDeclInScope(DirectPrevDecl, SearchDC, S,
12764 SS.isNotEmpty() || isExplicitSpecialization)) {
12765 // Make sure that this wasn't declared as an enum and now used as a
12766 // struct or something similar.
12767 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12768 TUK == TUK_Definition, KWLoc,
12770 bool SafeToContinue
12771 = (PrevTagDecl->getTagKind() != TTK_Enum &&
12773 if (SafeToContinue)
12774 Diag(KWLoc, diag::err_use_with_wrong_tag)
12776 << FixItHint::CreateReplacement(SourceRange(KWLoc),
12777 PrevTagDecl->getKindName());
12779 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12780 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12782 if (SafeToContinue)
12783 Kind = PrevTagDecl->getTagKind();
12785 // Recover by making this an anonymous redefinition.
12792 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12793 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12795 // If this is an elaborated-type-specifier for a scoped enumeration,
12796 // the 'class' keyword is not necessary and not permitted.
12797 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12799 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12800 << PrevEnum->isScoped()
12801 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12802 return PrevTagDecl;
12805 QualType EnumUnderlyingTy;
12806 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12807 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12808 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12809 EnumUnderlyingTy = QualType(T, 0);
12811 // All conflicts with previous declarations are recovered by
12812 // returning the previous declaration, unless this is a definition,
12813 // in which case we want the caller to bail out.
12814 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12815 ScopedEnum, EnumUnderlyingTy,
12816 EnumUnderlyingIsImplicit, PrevEnum))
12817 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12820 // C++11 [class.mem]p1:
12821 // A member shall not be declared twice in the member-specification,
12822 // except that a nested class or member class template can be declared
12823 // and then later defined.
12824 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12825 S->isDeclScope(PrevDecl)) {
12826 Diag(NameLoc, diag::ext_member_redeclared);
12827 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12831 // If this is a use, just return the declaration we found, unless
12832 // we have attributes.
12833 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12835 // FIXME: Diagnose these attributes. For now, we create a new
12836 // declaration to hold them.
12837 } else if (TUK == TUK_Reference &&
12838 (PrevTagDecl->getFriendObjectKind() ==
12839 Decl::FOK_Undeclared ||
12840 PP.getModuleContainingLocation(
12841 PrevDecl->getLocation()) !=
12842 PP.getModuleContainingLocation(KWLoc)) &&
12844 // This declaration is a reference to an existing entity, but
12845 // has different visibility from that entity: it either makes
12846 // a friend visible or it makes a type visible in a new module.
12847 // In either case, create a new declaration. We only do this if
12848 // the declaration would have meant the same thing if no prior
12849 // declaration were found, that is, if it was found in the same
12850 // scope where we would have injected a declaration.
12851 if (!getTagInjectionContext(CurContext)->getRedeclContext()
12852 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12853 return PrevTagDecl;
12854 // This is in the injected scope, create a new declaration in
12856 S = getTagInjectionScope(S, getLangOpts());
12858 return PrevTagDecl;
12862 // Diagnose attempts to redefine a tag.
12863 if (TUK == TUK_Definition) {
12864 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12865 // If we're defining a specialization and the previous definition
12866 // is from an implicit instantiation, don't emit an error
12867 // here; we'll catch this in the general case below.
12868 bool IsExplicitSpecializationAfterInstantiation = false;
12869 if (isExplicitSpecialization) {
12870 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12871 IsExplicitSpecializationAfterInstantiation =
12872 RD->getTemplateSpecializationKind() !=
12873 TSK_ExplicitSpecialization;
12874 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12875 IsExplicitSpecializationAfterInstantiation =
12876 ED->getTemplateSpecializationKind() !=
12877 TSK_ExplicitSpecialization;
12880 NamedDecl *Hidden = nullptr;
12881 if (SkipBody && getLangOpts().CPlusPlus &&
12882 !hasVisibleDefinition(Def, &Hidden)) {
12883 // There is a definition of this tag, but it is not visible. We
12884 // explicitly make use of C++'s one definition rule here, and
12885 // assume that this definition is identical to the hidden one
12886 // we already have. Make the existing definition visible and
12887 // use it in place of this one.
12888 SkipBody->ShouldSkip = true;
12889 makeMergedDefinitionVisible(Hidden, KWLoc);
12891 } else if (!IsExplicitSpecializationAfterInstantiation) {
12892 // A redeclaration in function prototype scope in C isn't
12893 // visible elsewhere, so merely issue a warning.
12894 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12895 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12897 Diag(NameLoc, diag::err_redefinition) << Name;
12898 Diag(Def->getLocation(), diag::note_previous_definition);
12899 // If this is a redefinition, recover by making this
12900 // struct be anonymous, which will make any later
12901 // references get the previous definition.
12907 // If the type is currently being defined, complain
12908 // about a nested redefinition.
12909 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12910 if (TD->isBeingDefined()) {
12911 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12912 Diag(PrevTagDecl->getLocation(),
12913 diag::note_previous_definition);
12920 // Okay, this is definition of a previously declared or referenced
12921 // tag. We're going to create a new Decl for it.
12924 // Okay, we're going to make a redeclaration. If this is some kind
12925 // of reference, make sure we build the redeclaration in the same DC
12926 // as the original, and ignore the current access specifier.
12927 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12928 SearchDC = PrevTagDecl->getDeclContext();
12932 // If we get here we have (another) forward declaration or we
12933 // have a definition. Just create a new decl.
12936 // If we get here, this is a definition of a new tag type in a nested
12937 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12938 // new decl/type. We set PrevDecl to NULL so that the entities
12939 // have distinct types.
12942 // If we get here, we're going to create a new Decl. If PrevDecl
12943 // is non-NULL, it's a definition of the tag declared by
12944 // PrevDecl. If it's NULL, we have a new definition.
12946 // Otherwise, PrevDecl is not a tag, but was found with tag
12947 // lookup. This is only actually possible in C++, where a few
12948 // things like templates still live in the tag namespace.
12950 // Use a better diagnostic if an elaborated-type-specifier
12951 // found the wrong kind of type on the first
12952 // (non-redeclaration) lookup.
12953 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12954 !Previous.isForRedeclaration()) {
12956 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12957 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12958 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12959 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12960 Diag(PrevDecl->getLocation(), diag::note_declared_at);
12963 // Otherwise, only diagnose if the declaration is in scope.
12964 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12965 SS.isNotEmpty() || isExplicitSpecialization)) {
12968 // Diagnose implicit declarations introduced by elaborated types.
12969 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12971 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12972 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12973 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12974 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12975 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12978 // Otherwise it's a declaration. Call out a particularly common
12980 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12982 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12983 Diag(NameLoc, diag::err_tag_definition_of_typedef)
12984 << Name << Kind << TND->getUnderlyingType();
12985 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12988 // Otherwise, diagnose.
12990 // The tag name clashes with something else in the target scope,
12991 // issue an error and recover by making this tag be anonymous.
12992 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12993 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12998 // The existing declaration isn't relevant to us; we're in a
12999 // new scope, so clear out the previous declaration.
13006 TagDecl *PrevDecl = nullptr;
13007 if (Previous.isSingleResult())
13008 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13010 // If there is an identifier, use the location of the identifier as the
13011 // location of the decl, otherwise use the location of the struct/union
13013 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13015 // Otherwise, create a new declaration. If there is a previous
13016 // declaration of the same entity, the two will be linked via
13020 bool IsForwardReference = false;
13021 if (Kind == TTK_Enum) {
13022 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13023 // enum X { A, B, C } D; D should chain to X.
13024 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13025 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13026 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13027 // If this is an undefined enum, warn.
13028 if (TUK != TUK_Definition && !Invalid) {
13030 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13031 cast<EnumDecl>(New)->isFixed()) {
13032 // C++0x: 7.2p2: opaque-enum-declaration.
13033 // Conflicts are diagnosed above. Do nothing.
13035 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13036 Diag(Loc, diag::ext_forward_ref_enum_def)
13038 Diag(Def->getLocation(), diag::note_previous_definition);
13040 unsigned DiagID = diag::ext_forward_ref_enum;
13041 if (getLangOpts().MSVCCompat)
13042 DiagID = diag::ext_ms_forward_ref_enum;
13043 else if (getLangOpts().CPlusPlus)
13044 DiagID = diag::err_forward_ref_enum;
13047 // If this is a forward-declared reference to an enumeration, make a
13048 // note of it; we won't actually be introducing the declaration into
13049 // the declaration context.
13050 if (TUK == TUK_Reference)
13051 IsForwardReference = true;
13055 if (EnumUnderlying) {
13056 EnumDecl *ED = cast<EnumDecl>(New);
13057 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13058 ED->setIntegerTypeSourceInfo(TI);
13060 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13061 ED->setPromotionType(ED->getIntegerType());
13064 // struct/union/class
13066 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13067 // struct X { int A; } D; D should chain to X.
13068 if (getLangOpts().CPlusPlus) {
13069 // FIXME: Look for a way to use RecordDecl for simple structs.
13070 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13071 cast_or_null<CXXRecordDecl>(PrevDecl));
13073 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13074 StdBadAlloc = cast<CXXRecordDecl>(New);
13076 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13077 cast_or_null<RecordDecl>(PrevDecl));
13080 // C++11 [dcl.type]p3:
13081 // A type-specifier-seq shall not define a class or enumeration [...].
13082 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13083 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13084 << Context.getTagDeclType(New);
13088 // Maybe add qualifier info.
13089 if (SS.isNotEmpty()) {
13091 // If this is either a declaration or a definition, check the
13092 // nested-name-specifier against the current context. We don't do this
13093 // for explicit specializations, because they have similar checking
13094 // (with more specific diagnostics) in the call to
13095 // CheckMemberSpecialization, below.
13096 if (!isExplicitSpecialization &&
13097 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13098 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13101 New->setQualifierInfo(SS.getWithLocInContext(Context));
13102 if (TemplateParameterLists.size() > 0) {
13103 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13110 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13111 // Add alignment attributes if necessary; these attributes are checked when
13112 // the ASTContext lays out the structure.
13114 // It is important for implementing the correct semantics that this
13115 // happen here (in act on tag decl). The #pragma pack stack is
13116 // maintained as a result of parser callbacks which can occur at
13117 // many points during the parsing of a struct declaration (because
13118 // the #pragma tokens are effectively skipped over during the
13119 // parsing of the struct).
13120 if (TUK == TUK_Definition) {
13121 AddAlignmentAttributesForRecord(RD);
13122 AddMsStructLayoutForRecord(RD);
13126 if (ModulePrivateLoc.isValid()) {
13127 if (isExplicitSpecialization)
13128 Diag(New->getLocation(), diag::err_module_private_specialization)
13130 << FixItHint::CreateRemoval(ModulePrivateLoc);
13131 // __module_private__ does not apply to local classes. However, we only
13132 // diagnose this as an error when the declaration specifiers are
13133 // freestanding. Here, we just ignore the __module_private__.
13134 else if (!SearchDC->isFunctionOrMethod())
13135 New->setModulePrivate();
13138 // If this is a specialization of a member class (of a class template),
13139 // check the specialization.
13140 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13143 // If we're declaring or defining a tag in function prototype scope in C,
13144 // note that this type can only be used within the function and add it to
13145 // the list of decls to inject into the function definition scope.
13146 if ((Name || Kind == TTK_Enum) &&
13147 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13148 if (getLangOpts().CPlusPlus) {
13149 // C++ [dcl.fct]p6:
13150 // Types shall not be defined in return or parameter types.
13151 if (TUK == TUK_Definition && !IsTypeSpecifier) {
13152 Diag(Loc, diag::err_type_defined_in_param_type)
13156 } else if (!PrevDecl) {
13157 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13159 DeclsInPrototypeScope.push_back(New);
13163 New->setInvalidDecl();
13166 ProcessDeclAttributeList(S, New, Attr);
13168 // Set the lexical context. If the tag has a C++ scope specifier, the
13169 // lexical context will be different from the semantic context.
13170 New->setLexicalDeclContext(CurContext);
13172 // Mark this as a friend decl if applicable.
13173 // In Microsoft mode, a friend declaration also acts as a forward
13174 // declaration so we always pass true to setObjectOfFriendDecl to make
13175 // the tag name visible.
13176 if (TUK == TUK_Friend)
13177 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13179 // Set the access specifier.
13180 if (!Invalid && SearchDC->isRecord())
13181 SetMemberAccessSpecifier(New, PrevDecl, AS);
13183 if (TUK == TUK_Definition)
13184 New->startDefinition();
13186 // If this has an identifier, add it to the scope stack.
13187 if (TUK == TUK_Friend) {
13188 // We might be replacing an existing declaration in the lookup tables;
13189 // if so, borrow its access specifier.
13191 New->setAccess(PrevDecl->getAccess());
13193 DeclContext *DC = New->getDeclContext()->getRedeclContext();
13194 DC->makeDeclVisibleInContext(New);
13195 if (Name) // can be null along some error paths
13196 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13197 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13199 S = getNonFieldDeclScope(S);
13200 PushOnScopeChains(New, S, !IsForwardReference);
13201 if (IsForwardReference)
13202 SearchDC->makeDeclVisibleInContext(New);
13204 CurContext->addDecl(New);
13207 // If this is the C FILE type, notify the AST context.
13208 if (IdentifierInfo *II = New->getIdentifier())
13209 if (!New->isInvalidDecl() &&
13210 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13212 Context.setFILEDecl(New);
13215 mergeDeclAttributes(New, PrevDecl);
13217 // If there's a #pragma GCC visibility in scope, set the visibility of this
13219 AddPushedVisibilityAttribute(New);
13222 // In C++, don't return an invalid declaration. We can't recover well from
13223 // the cases where we make the type anonymous.
13224 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13227 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13228 AdjustDeclIfTemplate(TagD);
13229 TagDecl *Tag = cast<TagDecl>(TagD);
13231 // Enter the tag context.
13232 PushDeclContext(S, Tag);
13234 ActOnDocumentableDecl(TagD);
13236 // If there's a #pragma GCC visibility in scope, set the visibility of this
13238 AddPushedVisibilityAttribute(Tag);
13241 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13242 assert(isa<ObjCContainerDecl>(IDecl) &&
13243 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13244 DeclContext *OCD = cast<DeclContext>(IDecl);
13245 assert(getContainingDC(OCD) == CurContext &&
13246 "The next DeclContext should be lexically contained in the current one.");
13251 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13252 SourceLocation FinalLoc,
13253 bool IsFinalSpelledSealed,
13254 SourceLocation LBraceLoc) {
13255 AdjustDeclIfTemplate(TagD);
13256 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13258 FieldCollector->StartClass();
13260 if (!Record->getIdentifier())
13263 if (FinalLoc.isValid())
13264 Record->addAttr(new (Context)
13265 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13268 // [...] The class-name is also inserted into the scope of the
13269 // class itself; this is known as the injected-class-name. For
13270 // purposes of access checking, the injected-class-name is treated
13271 // as if it were a public member name.
13272 CXXRecordDecl *InjectedClassName
13273 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13274 Record->getLocStart(), Record->getLocation(),
13275 Record->getIdentifier(),
13276 /*PrevDecl=*/nullptr,
13277 /*DelayTypeCreation=*/true);
13278 Context.getTypeDeclType(InjectedClassName, Record);
13279 InjectedClassName->setImplicit();
13280 InjectedClassName->setAccess(AS_public);
13281 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13282 InjectedClassName->setDescribedClassTemplate(Template);
13283 PushOnScopeChains(InjectedClassName, S);
13284 assert(InjectedClassName->isInjectedClassName() &&
13285 "Broken injected-class-name");
13288 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13289 SourceRange BraceRange) {
13290 AdjustDeclIfTemplate(TagD);
13291 TagDecl *Tag = cast<TagDecl>(TagD);
13292 Tag->setBraceRange(BraceRange);
13294 // Make sure we "complete" the definition even it is invalid.
13295 if (Tag->isBeingDefined()) {
13296 assert(Tag->isInvalidDecl() && "We should already have completed it");
13297 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13298 RD->completeDefinition();
13301 if (isa<CXXRecordDecl>(Tag))
13302 FieldCollector->FinishClass();
13304 // Exit this scope of this tag's definition.
13307 if (getCurLexicalContext()->isObjCContainer() &&
13308 Tag->getDeclContext()->isFileContext())
13309 Tag->setTopLevelDeclInObjCContainer();
13311 // Notify the consumer that we've defined a tag.
13312 if (!Tag->isInvalidDecl())
13313 Consumer.HandleTagDeclDefinition(Tag);
13316 void Sema::ActOnObjCContainerFinishDefinition() {
13317 // Exit this scope of this interface definition.
13321 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13322 assert(DC == CurContext && "Mismatch of container contexts");
13323 OriginalLexicalContext = DC;
13324 ActOnObjCContainerFinishDefinition();
13327 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13328 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13329 OriginalLexicalContext = nullptr;
13332 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13333 AdjustDeclIfTemplate(TagD);
13334 TagDecl *Tag = cast<TagDecl>(TagD);
13335 Tag->setInvalidDecl();
13337 // Make sure we "complete" the definition even it is invalid.
13338 if (Tag->isBeingDefined()) {
13339 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13340 RD->completeDefinition();
13343 // We're undoing ActOnTagStartDefinition here, not
13344 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13345 // the FieldCollector.
13350 // Note that FieldName may be null for anonymous bitfields.
13351 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13352 IdentifierInfo *FieldName,
13353 QualType FieldTy, bool IsMsStruct,
13354 Expr *BitWidth, bool *ZeroWidth) {
13355 // Default to true; that shouldn't confuse checks for emptiness
13359 // C99 6.7.2.1p4 - verify the field type.
13360 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13361 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13362 // Handle incomplete types with specific error.
13363 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13364 return ExprError();
13366 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13367 << FieldName << FieldTy << BitWidth->getSourceRange();
13368 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13369 << FieldTy << BitWidth->getSourceRange();
13370 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13371 UPPC_BitFieldWidth))
13372 return ExprError();
13374 // If the bit-width is type- or value-dependent, don't try to check
13376 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13379 llvm::APSInt Value;
13380 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13381 if (ICE.isInvalid())
13383 BitWidth = ICE.get();
13385 if (Value != 0 && ZeroWidth)
13386 *ZeroWidth = false;
13388 // Zero-width bitfield is ok for anonymous field.
13389 if (Value == 0 && FieldName)
13390 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13392 if (Value.isSigned() && Value.isNegative()) {
13394 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13395 << FieldName << Value.toString(10);
13396 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13397 << Value.toString(10);
13400 if (!FieldTy->isDependentType()) {
13401 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13402 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13403 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13405 // Over-wide bitfields are an error in C or when using the MSVC bitfield
13407 bool CStdConstraintViolation =
13408 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13409 bool MSBitfieldViolation =
13410 Value.ugt(TypeStorageSize) &&
13411 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13412 if (CStdConstraintViolation || MSBitfieldViolation) {
13413 unsigned DiagWidth =
13414 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13416 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13417 << FieldName << (unsigned)Value.getZExtValue()
13418 << !CStdConstraintViolation << DiagWidth;
13420 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13421 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13425 // Warn on types where the user might conceivably expect to get all
13426 // specified bits as value bits: that's all integral types other than
13428 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13430 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13431 << FieldName << (unsigned)Value.getZExtValue()
13432 << (unsigned)TypeWidth;
13434 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13435 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13442 /// ActOnField - Each field of a C struct/union is passed into this in order
13443 /// to create a FieldDecl object for it.
13444 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13445 Declarator &D, Expr *BitfieldWidth) {
13446 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13447 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13448 /*InitStyle=*/ICIS_NoInit, AS_public);
13452 /// HandleField - Analyze a field of a C struct or a C++ data member.
13454 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13455 SourceLocation DeclStart,
13456 Declarator &D, Expr *BitWidth,
13457 InClassInitStyle InitStyle,
13458 AccessSpecifier AS) {
13459 if (D.isDecompositionDeclarator()) {
13460 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13461 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13462 << Decomp.getSourceRange();
13466 IdentifierInfo *II = D.getIdentifier();
13467 SourceLocation Loc = DeclStart;
13468 if (II) Loc = D.getIdentifierLoc();
13470 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13471 QualType T = TInfo->getType();
13472 if (getLangOpts().CPlusPlus) {
13473 CheckExtraCXXDefaultArguments(D);
13475 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13476 UPPC_DataMemberType)) {
13477 D.setInvalidType();
13479 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13483 // TR 18037 does not allow fields to be declared with address spaces.
13484 if (T.getQualifiers().hasAddressSpace()) {
13485 Diag(Loc, diag::err_field_with_address_space);
13486 D.setInvalidType();
13489 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13490 // used as structure or union field: image, sampler, event or block types.
13491 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13492 T->isSamplerT() || T->isBlockPointerType())) {
13493 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13494 D.setInvalidType();
13497 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13499 if (D.getDeclSpec().isInlineSpecified())
13500 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13501 << getLangOpts().CPlusPlus1z;
13502 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13503 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13504 diag::err_invalid_thread)
13505 << DeclSpec::getSpecifierName(TSCS);
13507 // Check to see if this name was declared as a member previously
13508 NamedDecl *PrevDecl = nullptr;
13509 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13510 LookupName(Previous, S);
13511 switch (Previous.getResultKind()) {
13512 case LookupResult::Found:
13513 case LookupResult::FoundUnresolvedValue:
13514 PrevDecl = Previous.getAsSingle<NamedDecl>();
13517 case LookupResult::FoundOverloaded:
13518 PrevDecl = Previous.getRepresentativeDecl();
13521 case LookupResult::NotFound:
13522 case LookupResult::NotFoundInCurrentInstantiation:
13523 case LookupResult::Ambiguous:
13526 Previous.suppressDiagnostics();
13528 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13529 // Maybe we will complain about the shadowed template parameter.
13530 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13531 // Just pretend that we didn't see the previous declaration.
13532 PrevDecl = nullptr;
13535 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13536 PrevDecl = nullptr;
13539 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13540 SourceLocation TSSL = D.getLocStart();
13542 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13543 TSSL, AS, PrevDecl, &D);
13545 if (NewFD->isInvalidDecl())
13546 Record->setInvalidDecl();
13548 if (D.getDeclSpec().isModulePrivateSpecified())
13549 NewFD->setModulePrivate();
13551 if (NewFD->isInvalidDecl() && PrevDecl) {
13552 // Don't introduce NewFD into scope; there's already something
13553 // with the same name in the same scope.
13555 PushOnScopeChains(NewFD, S);
13557 Record->addDecl(NewFD);
13562 /// \brief Build a new FieldDecl and check its well-formedness.
13564 /// This routine builds a new FieldDecl given the fields name, type,
13565 /// record, etc. \p PrevDecl should refer to any previous declaration
13566 /// with the same name and in the same scope as the field to be
13569 /// \returns a new FieldDecl.
13571 /// \todo The Declarator argument is a hack. It will be removed once
13572 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13573 TypeSourceInfo *TInfo,
13574 RecordDecl *Record, SourceLocation Loc,
13575 bool Mutable, Expr *BitWidth,
13576 InClassInitStyle InitStyle,
13577 SourceLocation TSSL,
13578 AccessSpecifier AS, NamedDecl *PrevDecl,
13580 IdentifierInfo *II = Name.getAsIdentifierInfo();
13581 bool InvalidDecl = false;
13582 if (D) InvalidDecl = D->isInvalidType();
13584 // If we receive a broken type, recover by assuming 'int' and
13585 // marking this declaration as invalid.
13587 InvalidDecl = true;
13591 QualType EltTy = Context.getBaseElementType(T);
13592 if (!EltTy->isDependentType()) {
13593 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13594 // Fields of incomplete type force their record to be invalid.
13595 Record->setInvalidDecl();
13596 InvalidDecl = true;
13599 EltTy->isIncompleteType(&Def);
13600 if (Def && Def->isInvalidDecl()) {
13601 Record->setInvalidDecl();
13602 InvalidDecl = true;
13607 // OpenCL v1.2 s6.9.c: bitfields are not supported.
13608 if (BitWidth && getLangOpts().OpenCL) {
13609 Diag(Loc, diag::err_opencl_bitfields);
13610 InvalidDecl = true;
13613 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13614 // than a variably modified type.
13615 if (!InvalidDecl && T->isVariablyModifiedType()) {
13616 bool SizeIsNegative;
13617 llvm::APSInt Oversized;
13619 TypeSourceInfo *FixedTInfo =
13620 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13624 Diag(Loc, diag::warn_illegal_constant_array_size);
13625 TInfo = FixedTInfo;
13626 T = FixedTInfo->getType();
13628 if (SizeIsNegative)
13629 Diag(Loc, diag::err_typecheck_negative_array_size);
13630 else if (Oversized.getBoolValue())
13631 Diag(Loc, diag::err_array_too_large)
13632 << Oversized.toString(10);
13634 Diag(Loc, diag::err_typecheck_field_variable_size);
13635 InvalidDecl = true;
13639 // Fields can not have abstract class types
13640 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13641 diag::err_abstract_type_in_decl,
13642 AbstractFieldType))
13643 InvalidDecl = true;
13645 bool ZeroWidth = false;
13647 BitWidth = nullptr;
13648 // If this is declared as a bit-field, check the bit-field.
13650 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13653 InvalidDecl = true;
13654 BitWidth = nullptr;
13659 // Check that 'mutable' is consistent with the type of the declaration.
13660 if (!InvalidDecl && Mutable) {
13661 unsigned DiagID = 0;
13662 if (T->isReferenceType())
13663 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13664 : diag::err_mutable_reference;
13665 else if (T.isConstQualified())
13666 DiagID = diag::err_mutable_const;
13669 SourceLocation ErrLoc = Loc;
13670 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13671 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13672 Diag(ErrLoc, DiagID);
13673 if (DiagID != diag::ext_mutable_reference) {
13675 InvalidDecl = true;
13680 // C++11 [class.union]p8 (DR1460):
13681 // At most one variant member of a union may have a
13682 // brace-or-equal-initializer.
13683 if (InitStyle != ICIS_NoInit)
13684 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13686 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13687 BitWidth, Mutable, InitStyle);
13689 NewFD->setInvalidDecl();
13691 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13692 Diag(Loc, diag::err_duplicate_member) << II;
13693 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13694 NewFD->setInvalidDecl();
13697 if (!InvalidDecl && getLangOpts().CPlusPlus) {
13698 if (Record->isUnion()) {
13699 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13700 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13701 if (RDecl->getDefinition()) {
13702 // C++ [class.union]p1: An object of a class with a non-trivial
13703 // constructor, a non-trivial copy constructor, a non-trivial
13704 // destructor, or a non-trivial copy assignment operator
13705 // cannot be a member of a union, nor can an array of such
13707 if (CheckNontrivialField(NewFD))
13708 NewFD->setInvalidDecl();
13712 // C++ [class.union]p1: If a union contains a member of reference type,
13713 // the program is ill-formed, except when compiling with MSVC extensions
13715 if (EltTy->isReferenceType()) {
13716 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13717 diag::ext_union_member_of_reference_type :
13718 diag::err_union_member_of_reference_type)
13719 << NewFD->getDeclName() << EltTy;
13720 if (!getLangOpts().MicrosoftExt)
13721 NewFD->setInvalidDecl();
13726 // FIXME: We need to pass in the attributes given an AST
13727 // representation, not a parser representation.
13729 // FIXME: The current scope is almost... but not entirely... correct here.
13730 ProcessDeclAttributes(getCurScope(), NewFD, *D);
13732 if (NewFD->hasAttrs())
13733 CheckAlignasUnderalignment(NewFD);
13736 // In auto-retain/release, infer strong retension for fields of
13737 // retainable type.
13738 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13739 NewFD->setInvalidDecl();
13741 if (T.isObjCGCWeak())
13742 Diag(Loc, diag::warn_attribute_weak_on_field);
13744 NewFD->setAccess(AS);
13748 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13750 assert(getLangOpts().CPlusPlus && "valid check only for C++");
13752 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13755 QualType EltTy = Context.getBaseElementType(FD->getType());
13756 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13757 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13758 if (RDecl->getDefinition()) {
13759 // We check for copy constructors before constructors
13760 // because otherwise we'll never get complaints about
13761 // copy constructors.
13763 CXXSpecialMember member = CXXInvalid;
13764 // We're required to check for any non-trivial constructors. Since the
13765 // implicit default constructor is suppressed if there are any
13766 // user-declared constructors, we just need to check that there is a
13767 // trivial default constructor and a trivial copy constructor. (We don't
13768 // worry about move constructors here, since this is a C++98 check.)
13769 if (RDecl->hasNonTrivialCopyConstructor())
13770 member = CXXCopyConstructor;
13771 else if (!RDecl->hasTrivialDefaultConstructor())
13772 member = CXXDefaultConstructor;
13773 else if (RDecl->hasNonTrivialCopyAssignment())
13774 member = CXXCopyAssignment;
13775 else if (RDecl->hasNonTrivialDestructor())
13776 member = CXXDestructor;
13778 if (member != CXXInvalid) {
13779 if (!getLangOpts().CPlusPlus11 &&
13780 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13781 // Objective-C++ ARC: it is an error to have a non-trivial field of
13782 // a union. However, system headers in Objective-C programs
13783 // occasionally have Objective-C lifetime objects within unions,
13784 // and rather than cause the program to fail, we make those
13785 // members unavailable.
13786 SourceLocation Loc = FD->getLocation();
13787 if (getSourceManager().isInSystemHeader(Loc)) {
13788 if (!FD->hasAttr<UnavailableAttr>())
13789 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13790 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13795 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13796 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13797 diag::err_illegal_union_or_anon_struct_member)
13798 << FD->getParent()->isUnion() << FD->getDeclName() << member;
13799 DiagnoseNontrivial(RDecl, member);
13800 return !getLangOpts().CPlusPlus11;
13808 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13809 /// AST enum value.
13810 static ObjCIvarDecl::AccessControl
13811 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13812 switch (ivarVisibility) {
13813 default: llvm_unreachable("Unknown visitibility kind");
13814 case tok::objc_private: return ObjCIvarDecl::Private;
13815 case tok::objc_public: return ObjCIvarDecl::Public;
13816 case tok::objc_protected: return ObjCIvarDecl::Protected;
13817 case tok::objc_package: return ObjCIvarDecl::Package;
13821 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13822 /// in order to create an IvarDecl object for it.
13823 Decl *Sema::ActOnIvar(Scope *S,
13824 SourceLocation DeclStart,
13825 Declarator &D, Expr *BitfieldWidth,
13826 tok::ObjCKeywordKind Visibility) {
13828 IdentifierInfo *II = D.getIdentifier();
13829 Expr *BitWidth = (Expr*)BitfieldWidth;
13830 SourceLocation Loc = DeclStart;
13831 if (II) Loc = D.getIdentifierLoc();
13833 // FIXME: Unnamed fields can be handled in various different ways, for
13834 // example, unnamed unions inject all members into the struct namespace!
13836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13837 QualType T = TInfo->getType();
13840 // 6.7.2.1p3, 6.7.2.1p4
13841 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13843 D.setInvalidType();
13850 if (T->isReferenceType()) {
13851 Diag(Loc, diag::err_ivar_reference_type);
13852 D.setInvalidType();
13854 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13855 // than a variably modified type.
13856 else if (T->isVariablyModifiedType()) {
13857 Diag(Loc, diag::err_typecheck_ivar_variable_size);
13858 D.setInvalidType();
13861 // Get the visibility (access control) for this ivar.
13862 ObjCIvarDecl::AccessControl ac =
13863 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13864 : ObjCIvarDecl::None;
13865 // Must set ivar's DeclContext to its enclosing interface.
13866 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13867 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13869 ObjCContainerDecl *EnclosingContext;
13870 if (ObjCImplementationDecl *IMPDecl =
13871 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13872 if (LangOpts.ObjCRuntime.isFragile()) {
13873 // Case of ivar declared in an implementation. Context is that of its class.
13874 EnclosingContext = IMPDecl->getClassInterface();
13875 assert(EnclosingContext && "Implementation has no class interface!");
13878 EnclosingContext = EnclosingDecl;
13880 if (ObjCCategoryDecl *CDecl =
13881 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13882 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13883 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13887 EnclosingContext = EnclosingDecl;
13890 // Construct the decl.
13891 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13892 DeclStart, Loc, II, T,
13893 TInfo, ac, (Expr *)BitfieldWidth);
13896 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13898 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13899 && !isa<TagDecl>(PrevDecl)) {
13900 Diag(Loc, diag::err_duplicate_member) << II;
13901 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13902 NewID->setInvalidDecl();
13906 // Process attributes attached to the ivar.
13907 ProcessDeclAttributes(S, NewID, D);
13909 if (D.isInvalidType())
13910 NewID->setInvalidDecl();
13912 // In ARC, infer 'retaining' for ivars of retainable type.
13913 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13914 NewID->setInvalidDecl();
13916 if (D.getDeclSpec().isModulePrivateSpecified())
13917 NewID->setModulePrivate();
13920 // FIXME: When interfaces are DeclContexts, we'll need to add
13921 // these to the interface.
13923 IdResolver.AddDecl(NewID);
13926 if (LangOpts.ObjCRuntime.isNonFragile() &&
13927 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13928 Diag(Loc, diag::warn_ivars_in_interface);
13933 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13934 /// class and class extensions. For every class \@interface and class
13935 /// extension \@interface, if the last ivar is a bitfield of any type,
13936 /// then add an implicit `char :0` ivar to the end of that interface.
13937 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13938 SmallVectorImpl<Decl *> &AllIvarDecls) {
13939 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13942 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13943 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13945 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13947 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13949 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13950 if (!CD->IsClassExtension())
13953 // No need to add this to end of @implementation.
13957 // All conditions are met. Add a new bitfield to the tail end of ivars.
13958 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13959 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13961 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13962 DeclLoc, DeclLoc, nullptr,
13964 Context.getTrivialTypeSourceInfo(Context.CharTy,
13966 ObjCIvarDecl::Private, BW,
13968 AllIvarDecls.push_back(Ivar);
13971 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13972 ArrayRef<Decl *> Fields, SourceLocation LBrac,
13973 SourceLocation RBrac, AttributeList *Attr) {
13974 assert(EnclosingDecl && "missing record or interface decl");
13976 // If this is an Objective-C @implementation or category and we have
13977 // new fields here we should reset the layout of the interface since
13978 // it will now change.
13979 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13980 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13981 switch (DC->getKind()) {
13983 case Decl::ObjCCategory:
13984 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13986 case Decl::ObjCImplementation:
13988 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13993 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13995 // Start counting up the number of named members; make sure to include
13996 // members of anonymous structs and unions in the total.
13997 unsigned NumNamedMembers = 0;
13999 for (const auto *I : Record->decls()) {
14000 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14001 if (IFD->getDeclName())
14006 // Verify that all the fields are okay.
14007 SmallVector<FieldDecl*, 32> RecFields;
14009 bool ARCErrReported = false;
14010 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14012 FieldDecl *FD = cast<FieldDecl>(*i);
14014 // Get the type for the field.
14015 const Type *FDTy = FD->getType().getTypePtr();
14017 if (!FD->isAnonymousStructOrUnion()) {
14018 // Remember all fields written by the user.
14019 RecFields.push_back(FD);
14022 // If the field is already invalid for some reason, don't emit more
14023 // diagnostics about it.
14024 if (FD->isInvalidDecl()) {
14025 EnclosingDecl->setInvalidDecl();
14030 // A structure or union shall not contain a member with
14031 // incomplete or function type (hence, a structure shall not
14032 // contain an instance of itself, but may contain a pointer to
14033 // an instance of itself), except that the last member of a
14034 // structure with more than one named member may have incomplete
14035 // array type; such a structure (and any union containing,
14036 // possibly recursively, a member that is such a structure)
14037 // shall not be a member of a structure or an element of an
14039 if (FDTy->isFunctionType()) {
14040 // Field declared as a function.
14041 Diag(FD->getLocation(), diag::err_field_declared_as_function)
14042 << FD->getDeclName();
14043 FD->setInvalidDecl();
14044 EnclosingDecl->setInvalidDecl();
14046 } else if (FDTy->isIncompleteArrayType() && Record &&
14047 ((i + 1 == Fields.end() && !Record->isUnion()) ||
14048 ((getLangOpts().MicrosoftExt ||
14049 getLangOpts().CPlusPlus) &&
14050 (i + 1 == Fields.end() || Record->isUnion())))) {
14051 // Flexible array member.
14052 // Microsoft and g++ is more permissive regarding flexible array.
14053 // It will accept flexible array in union and also
14054 // as the sole element of a struct/class.
14055 unsigned DiagID = 0;
14056 if (Record->isUnion())
14057 DiagID = getLangOpts().MicrosoftExt
14058 ? diag::ext_flexible_array_union_ms
14059 : getLangOpts().CPlusPlus
14060 ? diag::ext_flexible_array_union_gnu
14061 : diag::err_flexible_array_union;
14062 else if (NumNamedMembers < 1)
14063 DiagID = getLangOpts().MicrosoftExt
14064 ? diag::ext_flexible_array_empty_aggregate_ms
14065 : getLangOpts().CPlusPlus
14066 ? diag::ext_flexible_array_empty_aggregate_gnu
14067 : diag::err_flexible_array_empty_aggregate;
14070 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14071 << Record->getTagKind();
14072 // While the layout of types that contain virtual bases is not specified
14073 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14074 // virtual bases after the derived members. This would make a flexible
14075 // array member declared at the end of an object not adjacent to the end
14077 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14078 if (RD->getNumVBases() != 0)
14079 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14080 << FD->getDeclName() << Record->getTagKind();
14081 if (!getLangOpts().C99)
14082 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14083 << FD->getDeclName() << Record->getTagKind();
14085 // If the element type has a non-trivial destructor, we would not
14086 // implicitly destroy the elements, so disallow it for now.
14088 // FIXME: GCC allows this. We should probably either implicitly delete
14089 // the destructor of the containing class, or just allow this.
14090 QualType BaseElem = Context.getBaseElementType(FD->getType());
14091 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14092 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14093 << FD->getDeclName() << FD->getType();
14094 FD->setInvalidDecl();
14095 EnclosingDecl->setInvalidDecl();
14098 // Okay, we have a legal flexible array member at the end of the struct.
14099 Record->setHasFlexibleArrayMember(true);
14100 } else if (!FDTy->isDependentType() &&
14101 RequireCompleteType(FD->getLocation(), FD->getType(),
14102 diag::err_field_incomplete)) {
14104 FD->setInvalidDecl();
14105 EnclosingDecl->setInvalidDecl();
14107 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14108 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14109 // A type which contains a flexible array member is considered to be a
14110 // flexible array member.
14111 Record->setHasFlexibleArrayMember(true);
14112 if (!Record->isUnion()) {
14113 // If this is a struct/class and this is not the last element, reject
14114 // it. Note that GCC supports variable sized arrays in the middle of
14116 if (i + 1 != Fields.end())
14117 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14118 << FD->getDeclName() << FD->getType();
14120 // We support flexible arrays at the end of structs in
14121 // other structs as an extension.
14122 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14123 << FD->getDeclName();
14127 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14128 RequireNonAbstractType(FD->getLocation(), FD->getType(),
14129 diag::err_abstract_type_in_decl,
14130 AbstractIvarType)) {
14131 // Ivars can not have abstract class types
14132 FD->setInvalidDecl();
14134 if (Record && FDTTy->getDecl()->hasObjectMember())
14135 Record->setHasObjectMember(true);
14136 if (Record && FDTTy->getDecl()->hasVolatileMember())
14137 Record->setHasVolatileMember(true);
14138 } else if (FDTy->isObjCObjectType()) {
14139 /// A field cannot be an Objective-c object
14140 Diag(FD->getLocation(), diag::err_statically_allocated_object)
14141 << FixItHint::CreateInsertion(FD->getLocation(), "*");
14142 QualType T = Context.getObjCObjectPointerType(FD->getType());
14144 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14145 (!getLangOpts().CPlusPlus || Record->isUnion())) {
14146 // It's an error in ARC if a field has lifetime.
14147 // We don't want to report this in a system header, though,
14148 // so we just make the field unavailable.
14149 // FIXME: that's really not sufficient; we need to make the type
14150 // itself invalid to, say, initialize or copy.
14151 QualType T = FD->getType();
14152 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14153 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14154 SourceLocation loc = FD->getLocation();
14155 if (getSourceManager().isInSystemHeader(loc)) {
14156 if (!FD->hasAttr<UnavailableAttr>()) {
14157 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14158 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14161 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14162 << T->isBlockPointerType() << Record->getTagKind();
14164 ARCErrReported = true;
14166 } else if (getLangOpts().ObjC1 &&
14167 getLangOpts().getGC() != LangOptions::NonGC &&
14168 Record && !Record->hasObjectMember()) {
14169 if (FD->getType()->isObjCObjectPointerType() ||
14170 FD->getType().isObjCGCStrong())
14171 Record->setHasObjectMember(true);
14172 else if (Context.getAsArrayType(FD->getType())) {
14173 QualType BaseType = Context.getBaseElementType(FD->getType());
14174 if (BaseType->isRecordType() &&
14175 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14176 Record->setHasObjectMember(true);
14177 else if (BaseType->isObjCObjectPointerType() ||
14178 BaseType.isObjCGCStrong())
14179 Record->setHasObjectMember(true);
14182 if (Record && FD->getType().isVolatileQualified())
14183 Record->setHasVolatileMember(true);
14184 // Keep track of the number of named members.
14185 if (FD->getIdentifier())
14189 // Okay, we successfully defined 'Record'.
14191 bool Completed = false;
14192 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14193 if (!CXXRecord->isInvalidDecl()) {
14194 // Set access bits correctly on the directly-declared conversions.
14195 for (CXXRecordDecl::conversion_iterator
14196 I = CXXRecord->conversion_begin(),
14197 E = CXXRecord->conversion_end(); I != E; ++I)
14198 I.setAccess((*I)->getAccess());
14201 if (!CXXRecord->isDependentType()) {
14202 if (CXXRecord->hasUserDeclaredDestructor()) {
14203 // Adjust user-defined destructor exception spec.
14204 if (getLangOpts().CPlusPlus11)
14205 AdjustDestructorExceptionSpec(CXXRecord,
14206 CXXRecord->getDestructor());
14209 if (!CXXRecord->isInvalidDecl()) {
14210 // Add any implicitly-declared members to this class.
14211 AddImplicitlyDeclaredMembersToClass(CXXRecord);
14213 // If we have virtual base classes, we may end up finding multiple
14214 // final overriders for a given virtual function. Check for this
14216 if (CXXRecord->getNumVBases()) {
14217 CXXFinalOverriderMap FinalOverriders;
14218 CXXRecord->getFinalOverriders(FinalOverriders);
14220 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14221 MEnd = FinalOverriders.end();
14223 for (OverridingMethods::iterator SO = M->second.begin(),
14224 SOEnd = M->second.end();
14225 SO != SOEnd; ++SO) {
14226 assert(SO->second.size() > 0 &&
14227 "Virtual function without overridding functions?");
14228 if (SO->second.size() == 1)
14231 // C++ [class.virtual]p2:
14232 // In a derived class, if a virtual member function of a base
14233 // class subobject has more than one final overrider the
14234 // program is ill-formed.
14235 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14236 << (const NamedDecl *)M->first << Record;
14237 Diag(M->first->getLocation(),
14238 diag::note_overridden_virtual_function);
14239 for (OverridingMethods::overriding_iterator
14240 OM = SO->second.begin(),
14241 OMEnd = SO->second.end();
14243 Diag(OM->Method->getLocation(), diag::note_final_overrider)
14244 << (const NamedDecl *)M->first << OM->Method->getParent();
14246 Record->setInvalidDecl();
14249 CXXRecord->completeDefinition(&FinalOverriders);
14257 Record->completeDefinition();
14259 if (Record->hasAttrs()) {
14260 CheckAlignasUnderalignment(Record);
14262 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14263 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14264 IA->getRange(), IA->getBestCase(),
14265 IA->getSemanticSpelling());
14268 // Check if the structure/union declaration is a type that can have zero
14269 // size in C. For C this is a language extension, for C++ it may cause
14270 // compatibility problems.
14271 bool CheckForZeroSize;
14272 if (!getLangOpts().CPlusPlus) {
14273 CheckForZeroSize = true;
14275 // For C++ filter out types that cannot be referenced in C code.
14276 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14278 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14279 !CXXRecord->isDependentType() &&
14280 CXXRecord->isCLike();
14282 if (CheckForZeroSize) {
14283 bool ZeroSize = true;
14284 bool IsEmpty = true;
14285 unsigned NonBitFields = 0;
14286 for (RecordDecl::field_iterator I = Record->field_begin(),
14287 E = Record->field_end();
14288 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14290 if (I->isUnnamedBitfield()) {
14291 if (I->getBitWidthValue(Context) > 0)
14295 QualType FieldType = I->getType();
14296 if (FieldType->isIncompleteType() ||
14297 !Context.getTypeSizeInChars(FieldType).isZero())
14302 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14303 // allowed in C++, but warn if its declaration is inside
14304 // extern "C" block.
14306 Diag(RecLoc, getLangOpts().CPlusPlus ?
14307 diag::warn_zero_size_struct_union_in_extern_c :
14308 diag::warn_zero_size_struct_union_compat)
14309 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14312 // Structs without named members are extension in C (C99 6.7.2.1p7),
14313 // but are accepted by GCC.
14314 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14315 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14316 diag::ext_no_named_members_in_struct_union)
14317 << Record->isUnion();
14321 ObjCIvarDecl **ClsFields =
14322 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14323 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14324 ID->setEndOfDefinitionLoc(RBrac);
14325 // Add ivar's to class's DeclContext.
14326 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14327 ClsFields[i]->setLexicalDeclContext(ID);
14328 ID->addDecl(ClsFields[i]);
14330 // Must enforce the rule that ivars in the base classes may not be
14332 if (ID->getSuperClass())
14333 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14334 } else if (ObjCImplementationDecl *IMPDecl =
14335 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14336 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14337 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14338 // Ivar declared in @implementation never belongs to the implementation.
14339 // Only it is in implementation's lexical context.
14340 ClsFields[I]->setLexicalDeclContext(IMPDecl);
14341 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14342 IMPDecl->setIvarLBraceLoc(LBrac);
14343 IMPDecl->setIvarRBraceLoc(RBrac);
14344 } else if (ObjCCategoryDecl *CDecl =
14345 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14346 // case of ivars in class extension; all other cases have been
14347 // reported as errors elsewhere.
14348 // FIXME. Class extension does not have a LocEnd field.
14349 // CDecl->setLocEnd(RBrac);
14350 // Add ivar's to class extension's DeclContext.
14351 // Diagnose redeclaration of private ivars.
14352 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14353 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14355 if (const ObjCIvarDecl *ClsIvar =
14356 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14357 Diag(ClsFields[i]->getLocation(),
14358 diag::err_duplicate_ivar_declaration);
14359 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14362 for (const auto *Ext : IDecl->known_extensions()) {
14363 if (const ObjCIvarDecl *ClsExtIvar
14364 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14365 Diag(ClsFields[i]->getLocation(),
14366 diag::err_duplicate_ivar_declaration);
14367 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14372 ClsFields[i]->setLexicalDeclContext(CDecl);
14373 CDecl->addDecl(ClsFields[i]);
14375 CDecl->setIvarLBraceLoc(LBrac);
14376 CDecl->setIvarRBraceLoc(RBrac);
14381 ProcessDeclAttributeList(S, Record, Attr);
14384 /// \brief Determine whether the given integral value is representable within
14385 /// the given type T.
14386 static bool isRepresentableIntegerValue(ASTContext &Context,
14387 llvm::APSInt &Value,
14389 assert(T->isIntegralType(Context) && "Integral type required!");
14390 unsigned BitWidth = Context.getIntWidth(T);
14392 if (Value.isUnsigned() || Value.isNonNegative()) {
14393 if (T->isSignedIntegerOrEnumerationType())
14395 return Value.getActiveBits() <= BitWidth;
14397 return Value.getMinSignedBits() <= BitWidth;
14400 // \brief Given an integral type, return the next larger integral type
14401 // (or a NULL type of no such type exists).
14402 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14403 // FIXME: Int128/UInt128 support, which also needs to be introduced into
14404 // enum checking below.
14405 assert(T->isIntegralType(Context) && "Integral type required!");
14406 const unsigned NumTypes = 4;
14407 QualType SignedIntegralTypes[NumTypes] = {
14408 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14410 QualType UnsignedIntegralTypes[NumTypes] = {
14411 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14412 Context.UnsignedLongLongTy
14415 unsigned BitWidth = Context.getTypeSize(T);
14416 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14417 : UnsignedIntegralTypes;
14418 for (unsigned I = 0; I != NumTypes; ++I)
14419 if (Context.getTypeSize(Types[I]) > BitWidth)
14425 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14426 EnumConstantDecl *LastEnumConst,
14427 SourceLocation IdLoc,
14428 IdentifierInfo *Id,
14430 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14431 llvm::APSInt EnumVal(IntWidth);
14434 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14438 Val = DefaultLvalueConversion(Val).get();
14441 if (Enum->isDependentType() || Val->isTypeDependent())
14442 EltTy = Context.DependentTy;
14444 SourceLocation ExpLoc;
14445 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14446 !getLangOpts().MSVCCompat) {
14447 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14448 // constant-expression in the enumerator-definition shall be a converted
14449 // constant expression of the underlying type.
14450 EltTy = Enum->getIntegerType();
14451 ExprResult Converted =
14452 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14454 if (Converted.isInvalid())
14457 Val = Converted.get();
14458 } else if (!Val->isValueDependent() &&
14459 !(Val = VerifyIntegerConstantExpression(Val,
14460 &EnumVal).get())) {
14461 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14463 if (Enum->isFixed()) {
14464 EltTy = Enum->getIntegerType();
14466 // In Obj-C and Microsoft mode, require the enumeration value to be
14467 // representable in the underlying type of the enumeration. In C++11,
14468 // we perform a non-narrowing conversion as part of converted constant
14469 // expression checking.
14470 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14471 if (getLangOpts().MSVCCompat) {
14472 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14473 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14475 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14477 Val = ImpCastExprToType(Val, EltTy,
14478 EltTy->isBooleanType() ?
14479 CK_IntegralToBoolean : CK_IntegralCast)
14481 } else if (getLangOpts().CPlusPlus) {
14482 // C++11 [dcl.enum]p5:
14483 // If the underlying type is not fixed, the type of each enumerator
14484 // is the type of its initializing value:
14485 // - If an initializer is specified for an enumerator, the
14486 // initializing value has the same type as the expression.
14487 EltTy = Val->getType();
14490 // The expression that defines the value of an enumeration constant
14491 // shall be an integer constant expression that has a value
14492 // representable as an int.
14494 // Complain if the value is not representable in an int.
14495 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14496 Diag(IdLoc, diag::ext_enum_value_not_int)
14497 << EnumVal.toString(10) << Val->getSourceRange()
14498 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14499 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14500 // Force the type of the expression to 'int'.
14501 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14503 EltTy = Val->getType();
14510 if (Enum->isDependentType())
14511 EltTy = Context.DependentTy;
14512 else if (!LastEnumConst) {
14513 // C++0x [dcl.enum]p5:
14514 // If the underlying type is not fixed, the type of each enumerator
14515 // is the type of its initializing value:
14516 // - If no initializer is specified for the first enumerator, the
14517 // initializing value has an unspecified integral type.
14519 // GCC uses 'int' for its unspecified integral type, as does
14521 if (Enum->isFixed()) {
14522 EltTy = Enum->getIntegerType();
14525 EltTy = Context.IntTy;
14528 // Assign the last value + 1.
14529 EnumVal = LastEnumConst->getInitVal();
14531 EltTy = LastEnumConst->getType();
14533 // Check for overflow on increment.
14534 if (EnumVal < LastEnumConst->getInitVal()) {
14535 // C++0x [dcl.enum]p5:
14536 // If the underlying type is not fixed, the type of each enumerator
14537 // is the type of its initializing value:
14539 // - Otherwise the type of the initializing value is the same as
14540 // the type of the initializing value of the preceding enumerator
14541 // unless the incremented value is not representable in that type,
14542 // in which case the type is an unspecified integral type
14543 // sufficient to contain the incremented value. If no such type
14544 // exists, the program is ill-formed.
14545 QualType T = getNextLargerIntegralType(Context, EltTy);
14546 if (T.isNull() || Enum->isFixed()) {
14547 // There is no integral type larger enough to represent this
14548 // value. Complain, then allow the value to wrap around.
14549 EnumVal = LastEnumConst->getInitVal();
14550 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14552 if (Enum->isFixed())
14553 // When the underlying type is fixed, this is ill-formed.
14554 Diag(IdLoc, diag::err_enumerator_wrapped)
14555 << EnumVal.toString(10)
14558 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14559 << EnumVal.toString(10);
14564 // Retrieve the last enumerator's value, extent that type to the
14565 // type that is supposed to be large enough to represent the incremented
14566 // value, then increment.
14567 EnumVal = LastEnumConst->getInitVal();
14568 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14569 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14572 // If we're not in C++, diagnose the overflow of enumerator values,
14573 // which in C99 means that the enumerator value is not representable in
14574 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14575 // permits enumerator values that are representable in some larger
14577 if (!getLangOpts().CPlusPlus && !T.isNull())
14578 Diag(IdLoc, diag::warn_enum_value_overflow);
14579 } else if (!getLangOpts().CPlusPlus &&
14580 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14581 // Enforce C99 6.7.2.2p2 even when we compute the next value.
14582 Diag(IdLoc, diag::ext_enum_value_not_int)
14583 << EnumVal.toString(10) << 1;
14588 if (!EltTy->isDependentType()) {
14589 // Make the enumerator value match the signedness and size of the
14590 // enumerator's type.
14591 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14592 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14595 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14599 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14600 SourceLocation IILoc) {
14601 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14602 !getLangOpts().CPlusPlus)
14603 return SkipBodyInfo();
14605 // We have an anonymous enum definition. Look up the first enumerator to
14606 // determine if we should merge the definition with an existing one and
14608 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14610 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14612 return SkipBodyInfo();
14614 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14616 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14618 Skip.Previous = Hidden;
14622 return SkipBodyInfo();
14625 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14626 SourceLocation IdLoc, IdentifierInfo *Id,
14627 AttributeList *Attr,
14628 SourceLocation EqualLoc, Expr *Val) {
14629 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14630 EnumConstantDecl *LastEnumConst =
14631 cast_or_null<EnumConstantDecl>(lastEnumConst);
14633 // The scope passed in may not be a decl scope. Zip up the scope tree until
14634 // we find one that is.
14635 S = getNonFieldDeclScope(S);
14637 // Verify that there isn't already something declared with this name in this
14639 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14641 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14642 // Maybe we will complain about the shadowed template parameter.
14643 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14644 // Just pretend that we didn't see the previous declaration.
14645 PrevDecl = nullptr;
14648 // C++ [class.mem]p15:
14649 // If T is the name of a class, then each of the following shall have a name
14650 // different from T:
14651 // - every enumerator of every member of class T that is an unscoped
14653 if (!TheEnumDecl->isScoped())
14654 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14655 DeclarationNameInfo(Id, IdLoc));
14657 EnumConstantDecl *New =
14658 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14663 // When in C++, we may get a TagDecl with the same name; in this case the
14664 // enum constant will 'hide' the tag.
14665 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14666 "Received TagDecl when not in C++!");
14667 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14668 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14669 if (isa<EnumConstantDecl>(PrevDecl))
14670 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14672 Diag(IdLoc, diag::err_redefinition) << Id;
14673 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14678 // Process attributes.
14679 if (Attr) ProcessDeclAttributeList(S, New, Attr);
14681 // Register this decl in the current scope stack.
14682 New->setAccess(TheEnumDecl->getAccess());
14683 PushOnScopeChains(New, S);
14685 ActOnDocumentableDecl(New);
14690 // Returns true when the enum initial expression does not trigger the
14691 // duplicate enum warning. A few common cases are exempted as follows:
14692 // Element2 = Element1
14693 // Element2 = Element1 + 1
14694 // Element2 = Element1 - 1
14695 // Where Element2 and Element1 are from the same enum.
14696 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14697 Expr *InitExpr = ECD->getInitExpr();
14700 InitExpr = InitExpr->IgnoreImpCasts();
14702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14703 if (!BO->isAdditiveOp())
14705 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14708 if (IL->getValue() != 1)
14711 InitExpr = BO->getLHS();
14714 // This checks if the elements are from the same enum.
14715 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14719 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14723 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14733 bool isTombstoneOrEmptyKey;
14734 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14735 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14738 static DupKey GetDupKey(const llvm::APSInt& Val) {
14739 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14743 struct DenseMapInfoDupKey {
14744 static DupKey getEmptyKey() { return DupKey(0, true); }
14745 static DupKey getTombstoneKey() { return DupKey(1, true); }
14746 static unsigned getHashValue(const DupKey Key) {
14747 return (unsigned)(Key.val * 37);
14749 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14750 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14751 LHS.val == RHS.val;
14754 } // end anonymous namespace
14756 // Emits a warning when an element is implicitly set a value that
14757 // a previous element has already been set to.
14758 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14760 QualType EnumType) {
14761 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14763 // Avoid anonymous enums
14764 if (!Enum->getIdentifier())
14767 // Only check for small enums.
14768 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14771 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14772 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14774 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14775 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14778 DuplicatesVector DupVector;
14779 ValueToVectorMap EnumMap;
14781 // Populate the EnumMap with all values represented by enum constants without
14783 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14784 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14786 // Null EnumConstantDecl means a previous diagnostic has been emitted for
14787 // this constant. Skip this enum since it may be ill-formed.
14792 if (ECD->getInitExpr())
14795 DupKey Key = GetDupKey(ECD->getInitVal());
14796 DeclOrVector &Entry = EnumMap[Key];
14798 // First time encountering this value.
14799 if (Entry.isNull())
14803 // Create vectors for any values that has duplicates.
14804 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14805 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14806 if (!ValidDuplicateEnum(ECD, Enum))
14809 DupKey Key = GetDupKey(ECD->getInitVal());
14811 DeclOrVector& Entry = EnumMap[Key];
14812 if (Entry.isNull())
14815 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14816 // Ensure constants are different.
14820 // Create new vector and push values onto it.
14821 ECDVector *Vec = new ECDVector();
14823 Vec->push_back(ECD);
14825 // Update entry to point to the duplicates vector.
14828 // Store the vector somewhere we can consult later for quick emission of
14830 DupVector.push_back(Vec);
14834 ECDVector *Vec = Entry.get<ECDVector*>();
14835 // Make sure constants are not added more than once.
14836 if (*Vec->begin() == ECD)
14839 Vec->push_back(ECD);
14842 // Emit diagnostics.
14843 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14844 DupVectorEnd = DupVector.end();
14845 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14846 ECDVector *Vec = *DupVectorIter;
14847 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14849 // Emit warning for one enum constant.
14850 ECDVector::iterator I = Vec->begin();
14851 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14852 << (*I)->getName() << (*I)->getInitVal().toString(10)
14853 << (*I)->getSourceRange();
14856 // Emit one note for each of the remaining enum constants with
14858 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14859 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14860 << (*I)->getName() << (*I)->getInitVal().toString(10)
14861 << (*I)->getSourceRange();
14866 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14867 bool AllowMask) const {
14868 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14869 assert(ED->isCompleteDefinition() && "expected enum definition");
14871 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14872 llvm::APInt &FlagBits = R.first->second;
14875 for (auto *E : ED->enumerators()) {
14876 const auto &EVal = E->getInitVal();
14877 // Only single-bit enumerators introduce new flag values.
14878 if (EVal.isPowerOf2())
14879 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14883 // A value is in a flag enum if either its bits are a subset of the enum's
14884 // flag bits (the first condition) or we are allowing masks and the same is
14885 // true of its complement (the second condition). When masks are allowed, we
14886 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14888 // While it's true that any value could be used as a mask, the assumption is
14889 // that a mask will have all of the insignificant bits set. Anything else is
14890 // likely a logic error.
14891 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14892 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14895 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
14897 ArrayRef<Decl *> Elements,
14898 Scope *S, AttributeList *Attr) {
14899 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14900 QualType EnumType = Context.getTypeDeclType(Enum);
14903 ProcessDeclAttributeList(S, Enum, Attr);
14905 if (Enum->isDependentType()) {
14906 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14907 EnumConstantDecl *ECD =
14908 cast_or_null<EnumConstantDecl>(Elements[i]);
14909 if (!ECD) continue;
14911 ECD->setType(EnumType);
14914 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14918 // TODO: If the result value doesn't fit in an int, it must be a long or long
14919 // long value. ISO C does not support this, but GCC does as an extension,
14921 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14922 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14923 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14925 // Verify that all the values are okay, compute the size of the values, and
14926 // reverse the list.
14927 unsigned NumNegativeBits = 0;
14928 unsigned NumPositiveBits = 0;
14930 // Keep track of whether all elements have type int.
14931 bool AllElementsInt = true;
14933 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14934 EnumConstantDecl *ECD =
14935 cast_or_null<EnumConstantDecl>(Elements[i]);
14936 if (!ECD) continue; // Already issued a diagnostic.
14938 const llvm::APSInt &InitVal = ECD->getInitVal();
14940 // Keep track of the size of positive and negative values.
14941 if (InitVal.isUnsigned() || InitVal.isNonNegative())
14942 NumPositiveBits = std::max(NumPositiveBits,
14943 (unsigned)InitVal.getActiveBits());
14945 NumNegativeBits = std::max(NumNegativeBits,
14946 (unsigned)InitVal.getMinSignedBits());
14948 // Keep track of whether every enum element has type int (very commmon).
14949 if (AllElementsInt)
14950 AllElementsInt = ECD->getType() == Context.IntTy;
14953 // Figure out the type that should be used for this enum.
14955 unsigned BestWidth;
14957 // C++0x N3000 [conv.prom]p3:
14958 // An rvalue of an unscoped enumeration type whose underlying
14959 // type is not fixed can be converted to an rvalue of the first
14960 // of the following types that can represent all the values of
14961 // the enumeration: int, unsigned int, long int, unsigned long
14962 // int, long long int, or unsigned long long int.
14964 // An identifier declared as an enumeration constant has type int.
14965 // The C99 rule is modified by a gcc extension
14966 QualType BestPromotionType;
14968 bool Packed = Enum->hasAttr<PackedAttr>();
14969 // -fshort-enums is the equivalent to specifying the packed attribute on all
14970 // enum definitions.
14971 if (LangOpts.ShortEnums)
14974 if (Enum->isFixed()) {
14975 BestType = Enum->getIntegerType();
14976 if (BestType->isPromotableIntegerType())
14977 BestPromotionType = Context.getPromotedIntegerType(BestType);
14979 BestPromotionType = BestType;
14981 BestWidth = Context.getIntWidth(BestType);
14983 else if (NumNegativeBits) {
14984 // If there is a negative value, figure out the smallest integer type (of
14985 // int/long/longlong) that fits.
14986 // If it's packed, check also if it fits a char or a short.
14987 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14988 BestType = Context.SignedCharTy;
14989 BestWidth = CharWidth;
14990 } else if (Packed && NumNegativeBits <= ShortWidth &&
14991 NumPositiveBits < ShortWidth) {
14992 BestType = Context.ShortTy;
14993 BestWidth = ShortWidth;
14994 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14995 BestType = Context.IntTy;
14996 BestWidth = IntWidth;
14998 BestWidth = Context.getTargetInfo().getLongWidth();
15000 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15001 BestType = Context.LongTy;
15003 BestWidth = Context.getTargetInfo().getLongLongWidth();
15005 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15006 Diag(Enum->getLocation(), diag::ext_enum_too_large);
15007 BestType = Context.LongLongTy;
15010 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15012 // If there is no negative value, figure out the smallest type that fits
15013 // all of the enumerator values.
15014 // If it's packed, check also if it fits a char or a short.
15015 if (Packed && NumPositiveBits <= CharWidth) {
15016 BestType = Context.UnsignedCharTy;
15017 BestPromotionType = Context.IntTy;
15018 BestWidth = CharWidth;
15019 } else if (Packed && NumPositiveBits <= ShortWidth) {
15020 BestType = Context.UnsignedShortTy;
15021 BestPromotionType = Context.IntTy;
15022 BestWidth = ShortWidth;
15023 } else if (NumPositiveBits <= IntWidth) {
15024 BestType = Context.UnsignedIntTy;
15025 BestWidth = IntWidth;
15027 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15028 ? Context.UnsignedIntTy : Context.IntTy;
15029 } else if (NumPositiveBits <=
15030 (BestWidth = Context.getTargetInfo().getLongWidth())) {
15031 BestType = Context.UnsignedLongTy;
15033 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15034 ? Context.UnsignedLongTy : Context.LongTy;
15036 BestWidth = Context.getTargetInfo().getLongLongWidth();
15037 assert(NumPositiveBits <= BestWidth &&
15038 "How could an initializer get larger than ULL?");
15039 BestType = Context.UnsignedLongLongTy;
15041 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15042 ? Context.UnsignedLongLongTy : Context.LongLongTy;
15046 // Loop over all of the enumerator constants, changing their types to match
15047 // the type of the enum if needed.
15048 for (auto *D : Elements) {
15049 auto *ECD = cast_or_null<EnumConstantDecl>(D);
15050 if (!ECD) continue; // Already issued a diagnostic.
15052 // Standard C says the enumerators have int type, but we allow, as an
15053 // extension, the enumerators to be larger than int size. If each
15054 // enumerator value fits in an int, type it as an int, otherwise type it the
15055 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
15056 // that X has type 'int', not 'unsigned'.
15058 // Determine whether the value fits into an int.
15059 llvm::APSInt InitVal = ECD->getInitVal();
15061 // If it fits into an integer type, force it. Otherwise force it to match
15062 // the enum decl type.
15066 if (!getLangOpts().CPlusPlus &&
15067 !Enum->isFixed() &&
15068 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15069 NewTy = Context.IntTy;
15070 NewWidth = IntWidth;
15072 } else if (ECD->getType() == BestType) {
15073 // Already the right type!
15074 if (getLangOpts().CPlusPlus)
15075 // C++ [dcl.enum]p4: Following the closing brace of an
15076 // enum-specifier, each enumerator has the type of its
15078 ECD->setType(EnumType);
15082 NewWidth = BestWidth;
15083 NewSign = BestType->isSignedIntegerOrEnumerationType();
15086 // Adjust the APSInt value.
15087 InitVal = InitVal.extOrTrunc(NewWidth);
15088 InitVal.setIsSigned(NewSign);
15089 ECD->setInitVal(InitVal);
15091 // Adjust the Expr initializer and type.
15092 if (ECD->getInitExpr() &&
15093 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15094 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15096 ECD->getInitExpr(),
15097 /*base paths*/ nullptr,
15099 if (getLangOpts().CPlusPlus)
15100 // C++ [dcl.enum]p4: Following the closing brace of an
15101 // enum-specifier, each enumerator has the type of its
15103 ECD->setType(EnumType);
15105 ECD->setType(NewTy);
15108 Enum->completeDefinition(BestType, BestPromotionType,
15109 NumPositiveBits, NumNegativeBits);
15111 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15113 if (Enum->hasAttr<FlagEnumAttr>()) {
15114 for (Decl *D : Elements) {
15115 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15116 if (!ECD) continue; // Already issued a diagnostic.
15118 llvm::APSInt InitVal = ECD->getInitVal();
15119 if (InitVal != 0 && !InitVal.isPowerOf2() &&
15120 !IsValueInFlagEnum(Enum, InitVal, true))
15121 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15126 // Now that the enum type is defined, ensure it's not been underaligned.
15127 if (Enum->hasAttrs())
15128 CheckAlignasUnderalignment(Enum);
15131 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15132 SourceLocation StartLoc,
15133 SourceLocation EndLoc) {
15134 StringLiteral *AsmString = cast<StringLiteral>(expr);
15136 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15137 AsmString, StartLoc,
15139 CurContext->addDecl(New);
15143 static void checkModuleImportContext(Sema &S, Module *M,
15144 SourceLocation ImportLoc, DeclContext *DC,
15145 bool FromInclude = false) {
15146 SourceLocation ExternCLoc;
15148 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15149 switch (LSD->getLanguage()) {
15150 case LinkageSpecDecl::lang_c:
15151 if (ExternCLoc.isInvalid())
15152 ExternCLoc = LSD->getLocStart();
15154 case LinkageSpecDecl::lang_cxx:
15157 DC = LSD->getParent();
15160 while (isa<LinkageSpecDecl>(DC))
15161 DC = DC->getParent();
15163 if (!isa<TranslationUnitDecl>(DC)) {
15164 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15165 ? diag::ext_module_import_not_at_top_level_noop
15166 : diag::err_module_import_not_at_top_level_fatal)
15167 << M->getFullModuleName() << DC;
15168 S.Diag(cast<Decl>(DC)->getLocStart(),
15169 diag::note_module_import_not_at_top_level) << DC;
15170 } else if (!M->IsExternC && ExternCLoc.isValid()) {
15171 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15172 << M->getFullModuleName();
15173 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15177 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15178 return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15181 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15182 ModuleDeclKind MDK,
15183 ModuleIdPath Path) {
15184 // 'module implementation' requires that we are not compiling a module of any
15185 // kind. 'module' and 'module partition' require that we are compiling a
15186 // module inteface (not a module map).
15187 auto CMK = getLangOpts().getCompilingModule();
15188 if (MDK == ModuleDeclKind::Implementation
15189 ? CMK != LangOptions::CMK_None
15190 : CMK != LangOptions::CMK_ModuleInterface) {
15191 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15196 // FIXME: Create a ModuleDecl and return it.
15198 // FIXME: Most of this work should be done by the preprocessor rather than
15199 // here, in case we look ahead across something where the current
15200 // module matters (eg a #include).
15202 // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15203 // hierarchical module map modules, the dots here are just another character
15204 // that can appear in a module name. Flatten down to the actual module name.
15205 std::string ModuleName;
15206 for (auto &Piece : Path) {
15207 if (!ModuleName.empty())
15209 ModuleName += Piece.first->getName();
15212 // If a module name was explicitly specified on the command line, it must be
15214 if (!getLangOpts().CurrentModule.empty() &&
15215 getLangOpts().CurrentModule != ModuleName) {
15216 Diag(Path.front().second, diag::err_current_module_name_mismatch)
15217 << SourceRange(Path.front().second, Path.back().second)
15218 << getLangOpts().CurrentModule;
15221 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15223 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15226 case ModuleDeclKind::Module: {
15227 // FIXME: Check we're not in a submodule.
15229 // We can't have imported a definition of this module or parsed a module
15230 // map defining it already.
15231 if (auto *M = Map.findModule(ModuleName)) {
15232 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15233 if (M->DefinitionLoc.isValid())
15234 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15235 else if (const auto *FE = M->getASTFile())
15236 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15241 // Create a Module for the module that we're defining.
15242 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15243 assert(Mod && "module creation should not fail");
15245 // Enter the semantic scope of the module.
15246 ActOnModuleBegin(ModuleLoc, Mod);
15250 case ModuleDeclKind::Partition:
15251 // FIXME: Check we are in a submodule of the named module.
15254 case ModuleDeclKind::Implementation:
15255 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15256 PP.getIdentifierInfo(ModuleName), Path[0].second);
15258 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15259 if (Import.isInvalid())
15261 return ConvertDeclToDeclGroup(Import.get());
15264 llvm_unreachable("unexpected module decl kind");
15267 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15268 SourceLocation ImportLoc,
15269 ModuleIdPath Path) {
15271 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15272 /*IsIncludeDirective=*/false);
15276 VisibleModules.setVisible(Mod, ImportLoc);
15278 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15280 // FIXME: we should support importing a submodule within a different submodule
15281 // of the same top-level module. Until we do, make it an error rather than
15282 // silently ignoring the import.
15283 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15284 // warn on a redundant import of the current module?
15285 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15286 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15287 Diag(ImportLoc, getLangOpts().isCompilingModule()
15288 ? diag::err_module_self_import
15289 : diag::err_module_import_in_implementation)
15290 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15292 SmallVector<SourceLocation, 2> IdentifierLocs;
15293 Module *ModCheck = Mod;
15294 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15295 // If we've run out of module parents, just drop the remaining identifiers.
15296 // We need the length to be consistent.
15299 ModCheck = ModCheck->Parent;
15301 IdentifierLocs.push_back(Path[I].second);
15304 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15305 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15306 Mod, IdentifierLocs);
15307 if (!ModuleScopes.empty())
15308 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15309 TU->addDecl(Import);
15313 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15314 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15315 BuildModuleInclude(DirectiveLoc, Mod);
15318 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15319 // Determine whether we're in the #include buffer for a module. The #includes
15320 // in that buffer do not qualify as module imports; they're just an
15321 // implementation detail of us building the module.
15323 // FIXME: Should we even get ActOnModuleInclude calls for those?
15324 bool IsInModuleIncludes =
15325 TUKind == TU_Module &&
15326 getSourceManager().isWrittenInMainFile(DirectiveLoc);
15328 bool ShouldAddImport = !IsInModuleIncludes;
15330 // If this module import was due to an inclusion directive, create an
15331 // implicit import declaration to capture it in the AST.
15332 if (ShouldAddImport) {
15333 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15334 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15337 if (!ModuleScopes.empty())
15338 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15339 TU->addDecl(ImportD);
15340 Consumer.HandleImplicitImportDecl(ImportD);
15343 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15344 VisibleModules.setVisible(Mod, DirectiveLoc);
15347 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15348 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15350 ModuleScopes.push_back({});
15351 ModuleScopes.back().Module = Mod;
15352 if (getLangOpts().ModulesLocalVisibility)
15353 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15355 VisibleModules.setVisible(Mod, DirectiveLoc);
15358 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15359 checkModuleImportContext(*this, Mod, EofLoc, CurContext);
15361 if (getLangOpts().ModulesLocalVisibility) {
15362 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15363 // Leaving a module hides namespace names, so our visible namespace cache
15364 // is now out of date.
15365 VisibleNamespaceCache.clear();
15368 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15369 "left the wrong module scope");
15370 ModuleScopes.pop_back();
15372 // We got to the end of processing a #include of a local module. Create an
15373 // ImportDecl as we would for an imported module.
15374 FileID File = getSourceManager().getFileID(EofLoc);
15375 assert(File != getSourceManager().getMainFileID() &&
15376 "end of submodule in main source file");
15377 SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15378 BuildModuleInclude(DirectiveLoc, Mod);
15381 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15383 // Bail if we're not allowed to implicitly import a module here.
15384 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15387 // Create the implicit import declaration.
15388 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15389 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15391 TU->addDecl(ImportD);
15392 Consumer.HandleImplicitImportDecl(ImportD);
15394 // Make the module visible.
15395 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15396 VisibleModules.setVisible(Mod, Loc);
15399 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15400 IdentifierInfo* AliasName,
15401 SourceLocation PragmaLoc,
15402 SourceLocation NameLoc,
15403 SourceLocation AliasNameLoc) {
15404 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15405 LookupOrdinaryName);
15406 AsmLabelAttr *Attr =
15407 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15409 // If a declaration that:
15410 // 1) declares a function or a variable
15411 // 2) has external linkage
15412 // already exists, add a label attribute to it.
15413 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15414 if (isDeclExternC(PrevDecl))
15415 PrevDecl->addAttr(Attr);
15417 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15418 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15419 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15421 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15424 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15425 SourceLocation PragmaLoc,
15426 SourceLocation NameLoc) {
15427 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15430 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15432 (void)WeakUndeclaredIdentifiers.insert(
15433 std::pair<IdentifierInfo*,WeakInfo>
15434 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15438 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15439 IdentifierInfo* AliasName,
15440 SourceLocation PragmaLoc,
15441 SourceLocation NameLoc,
15442 SourceLocation AliasNameLoc) {
15443 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15444 LookupOrdinaryName);
15445 WeakInfo W = WeakInfo(Name, NameLoc);
15447 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15448 if (!PrevDecl->hasAttr<AliasAttr>())
15449 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15450 DeclApplyPragmaWeak(TUScope, ND, W);
15452 (void)WeakUndeclaredIdentifiers.insert(
15453 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15457 Decl *Sema::getObjCDeclContext() const {
15458 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15461 AvailabilityResult Sema::getCurContextAvailability() const {
15462 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15464 return AR_Available;
15466 // If we are within an Objective-C method, we should consult
15467 // both the availability of the method as well as the
15468 // enclosing class. If the class is (say) deprecated,
15469 // the entire method is considered deprecated from the
15470 // purpose of checking if the current context is deprecated.
15471 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15472 AvailabilityResult R = MD->getAvailability();
15473 if (R != AR_Available)
15475 D = MD->getClassInterface();
15477 // If we are within an Objective-c @implementation, it
15478 // gets the same availability context as the @interface.
15479 else if (const ObjCImplementationDecl *ID =
15480 dyn_cast<ObjCImplementationDecl>(D)) {
15481 D = ID->getClassInterface();
15483 // Recover from user error.
15484 return D ? D->getAvailability() : AR_Available;