1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
50 using namespace clang;
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 Decl *Group[2] = { OwnedType, Ptr };
56 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
59 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
67 bool AllowTemplates=false)
68 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
69 AllowClassTemplates(AllowTemplates) {
70 WantExpressionKeywords = false;
71 WantCXXNamedCasts = false;
72 WantRemainingKeywords = false;
75 bool ValidateCandidate(const TypoCorrection &candidate) override {
76 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
77 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
78 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
79 return (IsType || AllowedTemplate) &&
80 (AllowInvalidDecl || !ND->isInvalidDecl());
82 return !WantClassName && candidate.isKeyword();
86 bool AllowInvalidDecl;
88 bool AllowClassTemplates;
93 /// \brief Determine whether the token kind starts a simple-type-specifier.
94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96 // FIXME: Take into account the current language when deciding whether a
97 // token kind is a valid type specifier
100 case tok::kw___int64:
101 case tok::kw___int128:
103 case tok::kw_unsigned:
110 case tok::kw_wchar_t:
112 case tok::kw___underlying_type:
113 case tok::kw___auto_type:
116 case tok::annot_typename:
117 case tok::kw_char16_t:
118 case tok::kw_char32_t:
120 case tok::annot_decltype:
121 case tok::kw_decltype:
122 return getLangOpts().CPlusPlus;
132 enum class UnqualifiedTypeNameLookupResult {
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145 SourceLocation NameLoc,
146 const CXXRecordDecl *RD) {
147 if (!RD->hasDefinition())
148 return UnqualifiedTypeNameLookupResult::NotFound;
149 // Look for type decls in base classes.
150 UnqualifiedTypeNameLookupResult FoundTypeDecl =
151 UnqualifiedTypeNameLookupResult::NotFound;
152 for (const auto &Base : RD->bases()) {
153 const CXXRecordDecl *BaseRD = nullptr;
154 if (auto *BaseTT = Base.getType()->getAs<TagType>())
155 BaseRD = BaseTT->getAsCXXRecordDecl();
156 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157 // Look for type decls in dependent base classes that have known primary
159 if (!TST || !TST->isDependentType())
161 auto *TD = TST->getTemplateName().getAsTemplateDecl();
164 auto *BasePrimaryTemplate =
165 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166 if (!BasePrimaryTemplate)
168 BaseRD = BasePrimaryTemplate;
171 for (NamedDecl *ND : BaseRD->lookup(&II)) {
172 if (!isa<TypeDecl>(ND))
173 return UnqualifiedTypeNameLookupResult::FoundNonType;
174 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
176 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178 case UnqualifiedTypeNameLookupResult::FoundNonType:
179 return UnqualifiedTypeNameLookupResult::FoundNonType;
180 case UnqualifiedTypeNameLookupResult::FoundType:
181 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183 case UnqualifiedTypeNameLookupResult::NotFound:
190 return FoundTypeDecl;
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194 const IdentifierInfo &II,
195 SourceLocation NameLoc) {
196 // Lookup in the parent class template context, if any.
197 const CXXRecordDecl *RD = nullptr;
198 UnqualifiedTypeNameLookupResult FoundTypeDecl =
199 UnqualifiedTypeNameLookupResult::NotFound;
200 for (DeclContext *DC = S.CurContext;
201 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202 DC = DC->getParent()) {
203 // Look for type decls in dependent base classes that have known primary
205 RD = dyn_cast<CXXRecordDecl>(DC);
206 if (RD && RD->getDescribedClassTemplate())
207 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
209 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
212 // We found some types in dependent base classes. Recover as if the user
213 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
214 // lookup during template instantiation.
215 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
217 ASTContext &Context = S.Context;
218 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219 cast<Type>(Context.getRecordType(RD)));
220 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
223 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225 TypeLocBuilder Builder;
226 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227 DepTL.setNameLoc(NameLoc);
228 DepTL.setElaboratedKeywordLoc(SourceLocation());
229 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242 Scope *S, CXXScopeSpec *SS,
243 bool isClassName, bool HasTrailingDot,
244 ParsedType ObjectTypePtr,
245 bool IsCtorOrDtorName,
246 bool WantNontrivialTypeSourceInfo,
247 IdentifierInfo **CorrectedII) {
248 // Determine where we will perform name lookup.
249 DeclContext *LookupCtx = nullptr;
251 QualType ObjectType = ObjectTypePtr.get();
252 if (ObjectType->isRecordType())
253 LookupCtx = computeDeclContext(ObjectType);
254 } else if (SS && SS->isNotEmpty()) {
255 LookupCtx = computeDeclContext(*SS, false);
258 if (isDependentScopeSpecifier(*SS)) {
260 // A qualified-id that refers to a type and in which the
261 // nested-name-specifier depends on a template-parameter (14.6.2)
262 // shall be prefixed by the keyword typename to indicate that the
263 // qualified-id denotes a type, forming an
264 // elaborated-type-specifier (7.1.5.3).
266 // We therefore do not perform any name lookup if the result would
267 // refer to a member of an unknown specialization.
268 if (!isClassName && !IsCtorOrDtorName)
271 // We know from the grammar that this name refers to a type,
272 // so build a dependent node to describe the type.
273 if (WantNontrivialTypeSourceInfo)
274 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
276 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
279 return ParsedType::make(T);
285 if (!LookupCtx->isDependentContext() &&
286 RequireCompleteDeclContext(*SS, LookupCtx))
290 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291 // lookup for class-names.
292 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
294 LookupResult Result(*this, &II, NameLoc, Kind);
296 // Perform "qualified" name lookup into the declaration context we
297 // computed, which is either the type of the base of a member access
298 // expression or the declaration context associated with a prior
299 // nested-name-specifier.
300 LookupQualifiedName(Result, LookupCtx);
302 if (ObjectTypePtr && Result.empty()) {
303 // C++ [basic.lookup.classref]p3:
304 // If the unqualified-id is ~type-name, the type-name is looked up
305 // in the context of the entire postfix-expression. If the type T of
306 // the object expression is of a class type C, the type-name is also
307 // looked up in the scope of class C. At least one of the lookups shall
308 // find a name that refers to (possibly cv-qualified) T.
309 LookupName(Result, S);
312 // Perform unqualified name lookup.
313 LookupName(Result, S);
315 // For unqualified lookup in a class template in MSVC mode, look into
316 // dependent base classes where the primary class template is known.
317 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318 if (ParsedType TypeInBase =
319 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
324 NamedDecl *IIDecl = nullptr;
325 switch (Result.getResultKind()) {
326 case LookupResult::NotFound:
327 case LookupResult::NotFoundInCurrentInstantiation:
329 TypoCorrection Correction = CorrectTypo(
330 Result.getLookupNameInfo(), Kind, S, SS,
331 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
333 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
335 bool MemberOfUnknownSpecialization;
336 UnqualifiedId TemplateName;
337 TemplateName.setIdentifier(NewII, NameLoc);
338 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339 CXXScopeSpec NewSS, *NewSSPtr = SS;
341 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
344 if (Correction && (NNS || NewII != &II) &&
345 // Ignore a correction to a template type as the to-be-corrected
346 // identifier is not a template (typo correction for template names
347 // is handled elsewhere).
348 !(getLangOpts().CPlusPlus && NewSSPtr &&
349 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350 false, Template, MemberOfUnknownSpecialization))) {
351 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352 isClassName, HasTrailingDot, ObjectTypePtr,
354 WantNontrivialTypeSourceInfo);
356 diagnoseTypo(Correction,
357 PDiag(diag::err_unknown_type_or_class_name_suggest)
358 << Result.getLookupName() << isClassName);
360 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361 *CorrectedII = NewII;
366 // If typo correction failed or was not performed, fall through
367 case LookupResult::FoundOverloaded:
368 case LookupResult::FoundUnresolvedValue:
369 Result.suppressDiagnostics();
372 case LookupResult::Ambiguous:
373 // Recover from type-hiding ambiguities by hiding the type. We'll
374 // do the lookup again when looking for an object, and we can
375 // diagnose the error then. If we don't do this, then the error
376 // about hiding the type will be immediately followed by an error
377 // that only makes sense if the identifier was treated like a type.
378 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379 Result.suppressDiagnostics();
383 // Look to see if we have a type anywhere in the list of results.
384 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385 Res != ResEnd; ++Res) {
386 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
388 (*Res)->getLocation().getRawEncoding() <
389 IIDecl->getLocation().getRawEncoding())
395 // None of the entities we found is a type, so there is no way
396 // to even assume that the result is a type. In this case, don't
397 // complain about the ambiguity. The parser will either try to
398 // perform this lookup again (e.g., as an object name), which
399 // will produce the ambiguity, or will complain that it expected
401 Result.suppressDiagnostics();
405 // We found a type within the ambiguous lookup; diagnose the
406 // ambiguity and then return that type. This might be the right
407 // answer, or it might not be, but it suppresses any attempt to
408 // perform the name lookup again.
411 case LookupResult::Found:
412 IIDecl = Result.getFoundDecl();
416 assert(IIDecl && "Didn't find decl");
419 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420 DiagnoseUseOfDecl(IIDecl, NameLoc);
422 T = Context.getTypeDeclType(TD);
423 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
425 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426 // constructor or destructor name (in such a case, the scope specifier
427 // will be attached to the enclosing Expr or Decl node).
428 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429 if (WantNontrivialTypeSourceInfo) {
430 // Construct a type with type-source information.
431 TypeLocBuilder Builder;
432 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
434 T = getElaboratedType(ETK_None, *SS, T);
435 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436 ElabTL.setElaboratedKeywordLoc(SourceLocation());
437 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
440 T = getElaboratedType(ETK_None, *SS, T);
443 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
446 T = Context.getObjCInterfaceType(IDecl);
450 // If it's not plausibly a type, suppress diagnostics.
451 Result.suppressDiagnostics();
454 return ParsedType::make(T);
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460 for (;; DC = DC->getLookupParent()) {
461 DC = DC->getPrimaryContext();
462 auto *ND = dyn_cast<NamespaceDecl>(DC);
463 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464 return NestedNameSpecifier::Create(Context, nullptr, ND);
465 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467 RD->getTypeForDecl());
468 else if (isa<TranslationUnitDecl>(DC))
469 return NestedNameSpecifier::GlobalSpecifier(Context);
471 llvm_unreachable("something isn't in TU scope?");
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475 SourceLocation NameLoc) {
476 // Accepting an undeclared identifier as a default argument for a template
477 // type parameter is a Microsoft extension.
478 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
480 // Build a fake DependentNameType that will perform lookup into CurContext at
481 // instantiation time. The name specifier isn't dependent, so template
482 // instantiation won't transform it. It will retry the lookup, however.
483 NestedNameSpecifier *NNS =
484 synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
487 // Build type location information. We synthesized the qualifier, so we have
488 // to build a fake NestedNameSpecifierLoc.
489 NestedNameSpecifierLocBuilder NNSLocBuilder;
490 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
493 TypeLocBuilder Builder;
494 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495 DepTL.setNameLoc(NameLoc);
496 DepTL.setElaboratedKeywordLoc(SourceLocation());
497 DepTL.setQualifierLoc(QualifierLoc);
498 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo"). If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507 // Do a tag name lookup in this scope.
508 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509 LookupName(R, S, false);
510 R.suppressDiagnostics();
511 if (R.getResultKind() == LookupResult::Found)
512 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513 switch (TD->getTagKind()) {
514 case TTK_Struct: return DeclSpec::TST_struct;
515 case TTK_Interface: return DeclSpec::TST_interface;
516 case TTK_Union: return DeclSpec::TST_union;
517 case TTK_Class: return DeclSpec::TST_class;
518 case TTK_Enum: return DeclSpec::TST_enum;
522 return DeclSpec::TST_unspecified;
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
530 /// template<class T> class A {
532 /// typedef int TYPE;
534 /// template<class T> class B : public A<T> {
536 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540 if (CurContext->isRecord()) {
541 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
544 const Type *Ty = SS->getScopeRep()->getAsType();
546 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547 for (const auto &Base : RD->bases())
548 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
550 return S->isFunctionPrototypeScope();
552 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556 SourceLocation IILoc,
559 ParsedType &SuggestedType,
560 bool AllowClassTemplates) {
561 // We don't have anything to suggest (yet).
562 SuggestedType = ParsedType();
564 // There may have been a typo in the name of the type. Look up typo
565 // results, in case we have something that we can suggest.
566 if (TypoCorrection Corrected =
567 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568 llvm::make_unique<TypeNameValidatorCCC>(
569 false, false, AllowClassTemplates),
570 CTK_ErrorRecovery)) {
571 if (Corrected.isKeyword()) {
572 // We corrected to a keyword.
573 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574 II = Corrected.getCorrectionAsIdentifierInfo();
576 // We found a similarly-named type or interface; suggest that.
577 if (!SS || !SS->isSet()) {
578 diagnoseTypo(Corrected,
579 PDiag(diag::err_unknown_typename_suggest) << II);
580 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583 II->getName().equals(CorrectedStr);
584 diagnoseTypo(Corrected,
585 PDiag(diag::err_unknown_nested_typename_suggest)
586 << II << DC << DroppedSpecifier << SS->getRange());
588 llvm_unreachable("could not have corrected a typo here");
592 if (Corrected.getCorrectionSpecifier())
593 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
595 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
598 /*IsCtorOrDtorName=*/false,
599 /*NonTrivialTypeSourceInfo=*/true);
604 if (getLangOpts().CPlusPlus) {
605 // See if II is a class template that the user forgot to pass arguments to.
607 Name.setIdentifier(II, IILoc);
608 CXXScopeSpec EmptySS;
609 TemplateTy TemplateResult;
610 bool MemberOfUnknownSpecialization;
611 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612 Name, ParsedType(), true, TemplateResult,
613 MemberOfUnknownSpecialization) == TNK_Type_template) {
614 TemplateName TplName = TemplateResult.get();
615 Diag(IILoc, diag::err_template_missing_args) << TplName;
616 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618 << TplDecl->getTemplateParameters()->getSourceRange();
624 // FIXME: Should we move the logic that tries to recover from a missing tag
625 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
627 if (!SS || (!SS->isSet() && !SS->isInvalid()))
628 Diag(IILoc, diag::err_unknown_typename) << II;
629 else if (DeclContext *DC = computeDeclContext(*SS, false))
630 Diag(IILoc, diag::err_typename_nested_not_found)
631 << II << DC << SS->getRange();
632 else if (isDependentScopeSpecifier(*SS)) {
633 unsigned DiagID = diag::err_typename_missing;
634 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635 DiagID = diag::ext_typename_missing;
637 Diag(SS->getRange().getBegin(), DiagID)
638 << SS->getScopeRep() << II->getName()
639 << SourceRange(SS->getRange().getBegin(), IILoc)
640 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641 SuggestedType = ActOnTypenameType(S, SourceLocation(),
642 *SS, *II, IILoc).get();
644 assert(SS && SS->isInvalid() &&
645 "Invalid scope specifier has already been diagnosed");
649 /// \brief Determine whether the given result set contains either a type name
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653 NextToken.is(tok::less);
655 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
659 if (CheckTemplate && isa<TemplateDecl>(*I))
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667 Scope *S, CXXScopeSpec &SS,
668 IdentifierInfo *&Name,
669 SourceLocation NameLoc) {
670 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671 SemaRef.LookupParsedName(R, S, &SS);
672 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673 StringRef FixItTagName;
674 switch (Tag->getTagKind()) {
676 FixItTagName = "class ";
680 FixItTagName = "enum ";
684 FixItTagName = "struct ";
688 FixItTagName = "__interface ";
692 FixItTagName = "union ";
696 StringRef TagName = FixItTagName.drop_back();
697 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
701 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
703 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
706 // Replace lookup results with just the tag decl.
707 Result.clear(Sema::LookupTagName);
708 SemaRef.LookupParsedName(Result, S, &SS);
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717 QualType T, SourceLocation NameLoc) {
718 ASTContext &Context = S.Context;
720 TypeLocBuilder Builder;
721 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
723 T = S.getElaboratedType(ETK_None, SS, T);
724 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725 ElabTL.setElaboratedKeywordLoc(SourceLocation());
726 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732 SourceLocation NameLoc, const Token &NextToken,
733 bool IsAddressOfOperand,
734 std::unique_ptr<CorrectionCandidateCallback> CCC) {
735 DeclarationNameInfo NameInfo(Name, NameLoc);
736 ObjCMethodDecl *CurMethod = getCurMethodDecl();
738 if (NextToken.is(tok::coloncolon)) {
739 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740 QualType(), false, SS, nullptr, false);
743 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744 LookupParsedName(Result, S, &SS, !CurMethod);
746 // For unqualified lookup in a class template in MSVC mode, look into
747 // dependent base classes where the primary class template is known.
748 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749 if (ParsedType TypeInBase =
750 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
754 // Perform lookup for Objective-C instance variables (including automatically
755 // synthesized instance variables), if we're in an Objective-C method.
756 // FIXME: This lookup really, really needs to be folded in to the normal
757 // unqualified lookup mechanism.
758 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760 if (E.get() || E.isInvalid())
764 bool SecondTry = false;
765 bool IsFilteredTemplateName = false;
768 switch (Result.getResultKind()) {
769 case LookupResult::NotFound:
770 // If an unqualified-id is followed by a '(', then we have a function
772 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773 // In C++, this is an ADL-only call.
775 if (getLangOpts().CPlusPlus)
776 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
779 // If the expression that precedes the parenthesized argument list in a
780 // function call consists solely of an identifier, and if no
781 // declaration is visible for this identifier, the identifier is
782 // implicitly declared exactly as if, in the innermost block containing
783 // the function call, the declaration
785 // extern int identifier ();
789 // We also allow this in C99 as an extension.
790 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
792 Result.resolveKind();
793 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
797 // In C, we first see whether there is a tag type by the same name, in
798 // which case it's likely that the user just forgot to write "enum",
799 // "struct", or "union".
800 if (!getLangOpts().CPlusPlus && !SecondTry &&
801 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
805 // Perform typo correction to determine if there is another name that is
806 // close to this name.
807 if (!SecondTry && CCC) {
809 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810 Result.getLookupKind(), S,
812 CTK_ErrorRecovery)) {
813 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814 unsigned QualifiedDiag = diag::err_no_member_suggest;
816 NamedDecl *FirstDecl = Corrected.getFoundDecl();
817 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
818 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
819 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
820 UnqualifiedDiag = diag::err_no_template_suggest;
821 QualifiedDiag = diag::err_no_member_template_suggest;
822 } else if (UnderlyingFirstDecl &&
823 (isa<TypeDecl>(UnderlyingFirstDecl) ||
824 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
825 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
826 UnqualifiedDiag = diag::err_unknown_typename_suggest;
827 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
831 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
832 } else {// FIXME: is this even reachable? Test it.
833 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
834 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
835 Name->getName().equals(CorrectedStr);
836 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
837 << Name << computeDeclContext(SS, false)
838 << DroppedSpecifier << SS.getRange());
841 // Update the name, so that the caller has the new name.
842 Name = Corrected.getCorrectionAsIdentifierInfo();
844 // Typo correction corrected to a keyword.
845 if (Corrected.isKeyword())
848 // Also update the LookupResult...
849 // FIXME: This should probably go away at some point
851 Result.setLookupName(Corrected.getCorrection());
853 Result.addDecl(FirstDecl);
855 // If we found an Objective-C instance variable, let
856 // LookupInObjCMethod build the appropriate expression to
857 // reference the ivar.
858 // FIXME: This is a gross hack.
859 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
869 // We failed to correct; just fall through and let the parser deal with it.
870 Result.suppressDiagnostics();
871 return NameClassification::Unknown();
873 case LookupResult::NotFoundInCurrentInstantiation: {
874 // We performed name lookup into the current instantiation, and there were
875 // dependent bases, so we treat this result the same way as any other
876 // dependent nested-name-specifier.
879 // A name used in a template declaration or definition and that is
880 // dependent on a template-parameter is assumed not to name a type
881 // unless the applicable name lookup finds a type name or the name is
882 // qualified by the keyword typename.
884 // FIXME: If the next token is '<', we might want to ask the parser to
885 // perform some heroics to see if we actually have a
886 // template-argument-list, which would indicate a missing 'template'
888 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
889 NameInfo, IsAddressOfOperand,
890 /*TemplateArgs=*/nullptr);
893 case LookupResult::Found:
894 case LookupResult::FoundOverloaded:
895 case LookupResult::FoundUnresolvedValue:
898 case LookupResult::Ambiguous:
899 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
900 hasAnyAcceptableTemplateNames(Result)) {
901 // C++ [temp.local]p3:
902 // A lookup that finds an injected-class-name (10.2) can result in an
903 // ambiguity in certain cases (for example, if it is found in more than
904 // one base class). If all of the injected-class-names that are found
905 // refer to specializations of the same class template, and if the name
906 // is followed by a template-argument-list, the reference refers to the
907 // class template itself and not a specialization thereof, and is not
910 // This filtering can make an ambiguous result into an unambiguous one,
911 // so try again after filtering out template names.
912 FilterAcceptableTemplateNames(Result);
913 if (!Result.isAmbiguous()) {
914 IsFilteredTemplateName = true;
919 // Diagnose the ambiguity and return an error.
920 return NameClassification::Error();
923 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
924 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
925 // C++ [temp.names]p3:
926 // After name lookup (3.4) finds that a name is a template-name or that
927 // an operator-function-id or a literal- operator-id refers to a set of
928 // overloaded functions any member of which is a function template if
929 // this is followed by a <, the < is always taken as the delimiter of a
930 // template-argument-list and never as the less-than operator.
931 if (!IsFilteredTemplateName)
932 FilterAcceptableTemplateNames(Result);
934 if (!Result.empty()) {
935 bool IsFunctionTemplate;
937 TemplateName Template;
938 if (Result.end() - Result.begin() > 1) {
939 IsFunctionTemplate = true;
940 Template = Context.getOverloadedTemplateName(Result.begin(),
944 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
945 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
946 IsVarTemplate = isa<VarTemplateDecl>(TD);
948 if (SS.isSet() && !SS.isInvalid())
949 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
950 /*TemplateKeyword=*/false,
953 Template = TemplateName(TD);
956 if (IsFunctionTemplate) {
957 // Function templates always go through overload resolution, at which
958 // point we'll perform the various checks (e.g., accessibility) we need
959 // to based on which function we selected.
960 Result.suppressDiagnostics();
962 return NameClassification::FunctionTemplate(Template);
965 return IsVarTemplate ? NameClassification::VarTemplate(Template)
966 : NameClassification::TypeTemplate(Template);
970 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
971 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
972 DiagnoseUseOfDecl(Type, NameLoc);
973 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
974 QualType T = Context.getTypeDeclType(Type);
976 return buildNestedType(*this, SS, T, NameLoc);
977 return ParsedType::make(T);
980 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982 // FIXME: It's unfortunate that we don't have a Type node for handling this.
983 if (ObjCCompatibleAliasDecl *Alias =
984 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
985 Class = Alias->getClassInterface();
989 DiagnoseUseOfDecl(Class, NameLoc);
991 if (NextToken.is(tok::period)) {
992 // Interface. <something> is parsed as a property reference expression.
993 // Just return "unknown" as a fall-through for now.
994 Result.suppressDiagnostics();
995 return NameClassification::Unknown();
998 QualType T = Context.getObjCInterfaceType(Class);
999 return ParsedType::make(T);
1002 // We can have a type template here if we're classifying a template argument.
1003 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1004 return NameClassification::TypeTemplate(
1005 TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 // Check for a tag type hidden by a non-type decl in a few cases where it
1008 // seems likely a type is wanted instead of the non-type that was found.
1009 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1010 if ((NextToken.is(tok::identifier) ||
1012 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1013 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1014 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1015 DiagnoseUseOfDecl(Type, NameLoc);
1016 QualType T = Context.getTypeDeclType(Type);
1017 if (SS.isNotEmpty())
1018 return buildNestedType(*this, SS, T, NameLoc);
1019 return ParsedType::make(T);
1022 if (FirstDecl->isCXXClassMember())
1023 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1026 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1027 return BuildDeclarationNameExpr(SS, Result, ADL);
1030 // Determines the context to return to after temporarily entering a
1031 // context. This depends in an unnecessarily complicated way on the
1032 // exact ordering of callbacks from the parser.
1033 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 // Functions defined inline within classes aren't parsed until we've
1036 // finished parsing the top-level class, so the top-level class is
1037 // the context we'll need to return to.
1038 // A Lambda call operator whose parent is a class must not be treated
1039 // as an inline member function. A Lambda can be used legally
1040 // either as an in-class member initializer or a default argument. These
1041 // are parsed once the class has been marked complete and so the containing
1042 // context would be the nested class (when the lambda is defined in one);
1043 // If the class is not complete, then the lambda is being used in an
1044 // ill-formed fashion (such as to specify the width of a bit-field, or
1045 // in an array-bound) - in which case we still want to return the
1046 // lexically containing DC (which could be a nested class).
1047 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1048 DC = DC->getLexicalParent();
1050 // A function not defined within a class will always return to its
1052 if (!isa<CXXRecordDecl>(DC))
1055 // A C++ inline method/friend is parsed *after* the topmost class
1056 // it was declared in is fully parsed ("complete"); the topmost
1057 // class is the context we need to return to.
1058 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1061 // Return the declaration context of the topmost class the inline method is
1066 return DC->getLexicalParent();
1069 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1070 assert(getContainingDC(DC) == CurContext &&
1071 "The next DeclContext should be lexically contained in the current one.");
1076 void Sema::PopDeclContext() {
1077 assert(CurContext && "DeclContext imbalance!");
1079 CurContext = getContainingDC(CurContext);
1080 assert(CurContext && "Popped translation unit!");
1083 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085 // Unlike PushDeclContext, the context to which we return is not necessarily
1086 // the containing DC of TD, because the new context will be some pre-existing
1087 // TagDecl definition instead of a fresh one.
1088 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1089 CurContext = cast<TagDecl>(D)->getDefinition();
1090 assert(CurContext && "skipping definition of undefined tag");
1091 // Start lookups from the parent of the current context; we don't want to look
1092 // into the pre-existing complete definition.
1093 S->setEntity(CurContext->getLookupParent());
1097 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1098 CurContext = static_cast<decltype(CurContext)>(Context);
1101 /// EnterDeclaratorContext - Used when we must lookup names in the context
1102 /// of a declarator's nested name specifier.
1104 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1105 // C++0x [basic.lookup.unqual]p13:
1106 // A name used in the definition of a static data member of class
1107 // X (after the qualified-id of the static member) is looked up as
1108 // if the name was used in a member function of X.
1109 // C++0x [basic.lookup.unqual]p14:
1110 // If a variable member of a namespace is defined outside of the
1111 // scope of its namespace then any name used in the definition of
1112 // the variable member (after the declarator-id) is looked up as
1113 // if the definition of the variable member occurred in its
1115 // Both of these imply that we should push a scope whose context
1116 // is the semantic context of the declaration. We can't use
1117 // PushDeclContext here because that context is not necessarily
1118 // lexically contained in the current context. Fortunately,
1119 // the containing scope should have the appropriate information.
1121 assert(!S->getEntity() && "scope already has entity");
1124 Scope *Ancestor = S->getParent();
1125 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1126 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1133 void Sema::ExitDeclaratorContext(Scope *S) {
1134 assert(S->getEntity() == CurContext && "Context imbalance!");
1136 // Switch back to the lexical context. The safety of this is
1137 // enforced by an assert in EnterDeclaratorContext.
1138 Scope *Ancestor = S->getParent();
1139 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1140 CurContext = Ancestor->getEntity();
1142 // We don't need to do anything with the scope, which is going to
1147 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1148 // We assume that the caller has already called
1149 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1150 FunctionDecl *FD = D->getAsFunction();
1154 // Same implementation as PushDeclContext, but enters the context
1155 // from the lexical parent, rather than the top-level class.
1156 assert(CurContext == FD->getLexicalParent() &&
1157 "The next DeclContext should be lexically contained in the current one.");
1159 S->setEntity(CurContext);
1161 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1162 ParmVarDecl *Param = FD->getParamDecl(P);
1163 // If the parameter has an identifier, then add it to the scope
1164 if (Param->getIdentifier()) {
1166 IdResolver.AddDecl(Param);
1172 void Sema::ActOnExitFunctionContext() {
1173 // Same implementation as PopDeclContext, but returns to the lexical parent,
1174 // rather than the top-level class.
1175 assert(CurContext && "DeclContext imbalance!");
1176 CurContext = CurContext->getLexicalParent();
1177 assert(CurContext && "Popped translation unit!");
1181 /// \brief Determine whether we allow overloading of the function
1182 /// PrevDecl with another declaration.
1184 /// This routine determines whether overloading is possible, not
1185 /// whether some new function is actually an overload. It will return
1186 /// true in C++ (where we can always provide overloads) or, as an
1187 /// extension, in C when the previous function is already an
1188 /// overloaded function declaration or has the "overloadable"
1190 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1191 ASTContext &Context) {
1192 if (Context.getLangOpts().CPlusPlus)
1195 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1198 return (Previous.getResultKind() == LookupResult::Found
1199 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1202 /// Add this decl to the scope shadowed decl chains.
1203 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1204 // Move up the scope chain until we find the nearest enclosing
1205 // non-transparent context. The declaration will be introduced into this
1207 while (S->getEntity() && S->getEntity()->isTransparentContext())
1210 // Add scoped declarations into their context, so that they can be
1211 // found later. Declarations without a context won't be inserted
1212 // into any context.
1214 CurContext->addDecl(D);
1216 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1217 // are function-local declarations.
1218 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1219 !D->getDeclContext()->getRedeclContext()->Equals(
1220 D->getLexicalDeclContext()->getRedeclContext()) &&
1221 !D->getLexicalDeclContext()->isFunctionOrMethod())
1224 // Template instantiations should also not be pushed into scope.
1225 if (isa<FunctionDecl>(D) &&
1226 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1229 // If this replaces anything in the current scope,
1230 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1231 IEnd = IdResolver.end();
1232 for (; I != IEnd; ++I) {
1233 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1235 IdResolver.RemoveDecl(*I);
1237 // Should only need to replace one decl.
1244 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1245 // Implicitly-generated labels may end up getting generated in an order that
1246 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1247 // the label at the appropriate place in the identifier chain.
1248 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1249 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1250 if (IDC == CurContext) {
1251 if (!S->isDeclScope(*I))
1253 } else if (IDC->Encloses(CurContext))
1257 IdResolver.InsertDeclAfter(I, D);
1259 IdResolver.AddDecl(D);
1263 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1264 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1265 TUScope->AddDecl(D);
1268 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1269 bool AllowInlineNamespace) {
1270 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1273 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1274 DeclContext *TargetDC = DC->getPrimaryContext();
1276 if (DeclContext *ScopeDC = S->getEntity())
1277 if (ScopeDC->getPrimaryContext() == TargetDC)
1279 } while ((S = S->getParent()));
1284 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1288 /// Filters out lookup results that don't fall within the given scope
1289 /// as determined by isDeclInScope.
1290 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1291 bool ConsiderLinkage,
1292 bool AllowInlineNamespace) {
1293 LookupResult::Filter F = R.makeFilter();
1294 while (F.hasNext()) {
1295 NamedDecl *D = F.next();
1297 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1300 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1309 static bool isUsingDecl(NamedDecl *D) {
1310 return isa<UsingShadowDecl>(D) ||
1311 isa<UnresolvedUsingTypenameDecl>(D) ||
1312 isa<UnresolvedUsingValueDecl>(D);
1315 /// Removes using shadow declarations from the lookup results.
1316 static void RemoveUsingDecls(LookupResult &R) {
1317 LookupResult::Filter F = R.makeFilter();
1319 if (isUsingDecl(F.next()))
1325 /// \brief Check for this common pattern:
1328 /// S(const S&); // DO NOT IMPLEMENT
1329 /// void operator=(const S&); // DO NOT IMPLEMENT
1332 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1333 // FIXME: Should check for private access too but access is set after we get
1335 if (D->doesThisDeclarationHaveABody())
1338 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1339 return CD->isCopyConstructor();
1340 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1341 return Method->isCopyAssignmentOperator();
1345 // We need this to handle
1348 // void *foo() { return 0; }
1351 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1352 // for example. If 'A', foo will have external linkage. If we have '*A',
1353 // foo will have no linkage. Since we can't know until we get to the end
1354 // of the typedef, this function finds out if D might have non-external linkage.
1355 // Callers should verify at the end of the TU if it D has external linkage or
1357 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1358 const DeclContext *DC = D->getDeclContext();
1359 while (!DC->isTranslationUnit()) {
1360 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1361 if (!RD->hasNameForLinkage())
1364 DC = DC->getParent();
1367 return !D->isExternallyVisible();
1370 // FIXME: This needs to be refactored; some other isInMainFile users want
1372 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1373 if (S.TUKind != TU_Complete)
1375 return S.SourceMgr.isInMainFile(Loc);
1378 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1381 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1384 // Ignore all entities declared within templates, and out-of-line definitions
1385 // of members of class templates.
1386 if (D->getDeclContext()->isDependentContext() ||
1387 D->getLexicalDeclContext()->isDependentContext())
1390 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1391 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1394 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1395 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1398 // 'static inline' functions are defined in headers; don't warn.
1399 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1403 if (FD->doesThisDeclarationHaveABody() &&
1404 Context.DeclMustBeEmitted(FD))
1406 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1407 // Constants and utility variables are defined in headers with internal
1408 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1410 if (!isMainFileLoc(*this, VD->getLocation()))
1413 if (Context.DeclMustBeEmitted(VD))
1416 if (VD->isStaticDataMember() &&
1417 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1423 // Only warn for unused decls internal to the translation unit.
1424 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1425 // for inline functions defined in the main source file, for instance.
1426 return mightHaveNonExternalLinkage(D);
1429 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1433 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1434 const FunctionDecl *First = FD->getFirstDecl();
1435 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1436 return; // First should already be in the vector.
1439 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1440 const VarDecl *First = VD->getFirstDecl();
1441 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1442 return; // First should already be in the vector.
1445 if (ShouldWarnIfUnusedFileScopedDecl(D))
1446 UnusedFileScopedDecls.push_back(D);
1449 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1450 if (D->isInvalidDecl())
1453 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1454 D->hasAttr<ObjCPreciseLifetimeAttr>())
1457 if (isa<LabelDecl>(D))
1460 // Except for labels, we only care about unused decls that are local to
1462 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1463 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1464 // For dependent types, the diagnostic is deferred.
1466 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1467 if (!WithinFunction)
1470 if (isa<TypedefNameDecl>(D))
1473 // White-list anything that isn't a local variable.
1474 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1477 // Types of valid local variables should be complete, so this should succeed.
1478 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1480 // White-list anything with an __attribute__((unused)) type.
1481 QualType Ty = VD->getType();
1483 // Only look at the outermost level of typedef.
1484 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1485 if (TT->getDecl()->hasAttr<UnusedAttr>())
1489 // If we failed to complete the type for some reason, or if the type is
1490 // dependent, don't diagnose the variable.
1491 if (Ty->isIncompleteType() || Ty->isDependentType())
1494 if (const TagType *TT = Ty->getAs<TagType>()) {
1495 const TagDecl *Tag = TT->getDecl();
1496 if (Tag->hasAttr<UnusedAttr>())
1499 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1500 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1503 if (const Expr *Init = VD->getInit()) {
1504 if (const ExprWithCleanups *Cleanups =
1505 dyn_cast<ExprWithCleanups>(Init))
1506 Init = Cleanups->getSubExpr();
1507 const CXXConstructExpr *Construct =
1508 dyn_cast<CXXConstructExpr>(Init);
1509 if (Construct && !Construct->isElidable()) {
1510 CXXConstructorDecl *CD = Construct->getConstructor();
1511 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1518 // TODO: __attribute__((unused)) templates?
1524 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1526 if (isa<LabelDecl>(D)) {
1527 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1528 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1529 if (AfterColon.isInvalid())
1531 Hint = FixItHint::CreateRemoval(CharSourceRange::
1532 getCharRange(D->getLocStart(), AfterColon));
1537 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1538 if (D->getTypeForDecl()->isDependentType())
1541 for (auto *TmpD : D->decls()) {
1542 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1543 DiagnoseUnusedDecl(T);
1544 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1545 DiagnoseUnusedNestedTypedefs(R);
1549 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1550 /// unless they are marked attr(unused).
1551 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1552 if (!ShouldDiagnoseUnusedDecl(D))
1555 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1556 // typedefs can be referenced later on, so the diagnostics are emitted
1557 // at end-of-translation-unit.
1558 UnusedLocalTypedefNameCandidates.insert(TD);
1563 GenerateFixForUnusedDecl(D, Context, Hint);
1566 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1567 DiagID = diag::warn_unused_exception_param;
1568 else if (isa<LabelDecl>(D))
1569 DiagID = diag::warn_unused_label;
1571 DiagID = diag::warn_unused_variable;
1573 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1576 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1577 // Verify that we have no forward references left. If so, there was a goto
1578 // or address of a label taken, but no definition of it. Label fwd
1579 // definitions are indicated with a null substmt which is also not a resolved
1580 // MS inline assembly label name.
1581 bool Diagnose = false;
1582 if (L->isMSAsmLabel())
1583 Diagnose = !L->isResolvedMSAsmLabel();
1585 Diagnose = L->getStmt() == nullptr;
1587 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1590 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1591 S->mergeNRVOIntoParent();
1593 if (S->decl_empty()) return;
1594 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1595 "Scope shouldn't contain decls!");
1597 for (auto *TmpD : S->decls()) {
1598 assert(TmpD && "This decl didn't get pushed??");
1600 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1601 NamedDecl *D = cast<NamedDecl>(TmpD);
1603 if (!D->getDeclName()) continue;
1605 // Diagnose unused variables in this scope.
1606 if (!S->hasUnrecoverableErrorOccurred()) {
1607 DiagnoseUnusedDecl(D);
1608 if (const auto *RD = dyn_cast<RecordDecl>(D))
1609 DiagnoseUnusedNestedTypedefs(RD);
1612 // If this was a forward reference to a label, verify it was defined.
1613 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1614 CheckPoppedLabel(LD, *this);
1616 // Remove this name from our lexical scope.
1617 IdResolver.RemoveDecl(D);
1621 /// \brief Look for an Objective-C class in the translation unit.
1623 /// \param Id The name of the Objective-C class we're looking for. If
1624 /// typo-correction fixes this name, the Id will be updated
1625 /// to the fixed name.
1627 /// \param IdLoc The location of the name in the translation unit.
1629 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1630 /// if there is no class with the given name.
1632 /// \returns The declaration of the named Objective-C class, or NULL if the
1633 /// class could not be found.
1634 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1635 SourceLocation IdLoc,
1636 bool DoTypoCorrection) {
1637 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1638 // creation from this context.
1639 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1641 if (!IDecl && DoTypoCorrection) {
1642 // Perform typo correction at the given location, but only if we
1643 // find an Objective-C class name.
1644 if (TypoCorrection C = CorrectTypo(
1645 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1646 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1647 CTK_ErrorRecovery)) {
1648 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1649 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1650 Id = IDecl->getIdentifier();
1653 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1654 // This routine must always return a class definition, if any.
1655 if (Def && Def->getDefinition())
1656 Def = Def->getDefinition();
1660 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1661 /// from S, where a non-field would be declared. This routine copes
1662 /// with the difference between C and C++ scoping rules in structs and
1663 /// unions. For example, the following code is well-formed in C but
1664 /// ill-formed in C++:
1670 /// void test_S6() {
1675 /// For the declaration of BAR, this routine will return a different
1676 /// scope. The scope S will be the scope of the unnamed enumeration
1677 /// within S6. In C++, this routine will return the scope associated
1678 /// with S6, because the enumeration's scope is a transparent
1679 /// context but structures can contain non-field names. In C, this
1680 /// routine will return the translation unit scope, since the
1681 /// enumeration's scope is a transparent context and structures cannot
1682 /// contain non-field names.
1683 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1684 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1685 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1686 (S->isClassScope() && !getLangOpts().CPlusPlus))
1691 /// \brief Looks up the declaration of "struct objc_super" and
1692 /// saves it for later use in building builtin declaration of
1693 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1694 /// pre-existing declaration exists no action takes place.
1695 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1696 IdentifierInfo *II) {
1697 if (!II->isStr("objc_msgSendSuper"))
1699 ASTContext &Context = ThisSema.Context;
1701 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1702 SourceLocation(), Sema::LookupTagName);
1703 ThisSema.LookupName(Result, S);
1704 if (Result.getResultKind() == LookupResult::Found)
1705 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1706 Context.setObjCSuperType(Context.getTagDeclType(TD));
1709 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1711 case ASTContext::GE_None:
1713 case ASTContext::GE_Missing_stdio:
1715 case ASTContext::GE_Missing_setjmp:
1717 case ASTContext::GE_Missing_ucontext:
1718 return "ucontext.h";
1720 llvm_unreachable("unhandled error kind");
1723 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1724 /// file scope. lazily create a decl for it. ForRedeclaration is true
1725 /// if we're creating this built-in in anticipation of redeclaring the
1727 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1728 Scope *S, bool ForRedeclaration,
1729 SourceLocation Loc) {
1730 LookupPredefedObjCSuperType(*this, S, II);
1732 ASTContext::GetBuiltinTypeError Error;
1733 QualType R = Context.GetBuiltinType(ID, Error);
1735 if (ForRedeclaration)
1736 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1737 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1741 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1742 Diag(Loc, diag::ext_implicit_lib_function_decl)
1743 << Context.BuiltinInfo.getName(ID) << R;
1744 if (Context.BuiltinInfo.getHeaderName(ID) &&
1745 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1746 Diag(Loc, diag::note_include_header_or_declare)
1747 << Context.BuiltinInfo.getHeaderName(ID)
1748 << Context.BuiltinInfo.getName(ID);
1751 DeclContext *Parent = Context.getTranslationUnitDecl();
1752 if (getLangOpts().CPlusPlus) {
1753 LinkageSpecDecl *CLinkageDecl =
1754 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1755 LinkageSpecDecl::lang_c, false);
1756 CLinkageDecl->setImplicit();
1757 Parent->addDecl(CLinkageDecl);
1758 Parent = CLinkageDecl;
1761 FunctionDecl *New = FunctionDecl::Create(Context,
1763 Loc, Loc, II, R, /*TInfo=*/nullptr,
1766 R->isFunctionProtoType());
1769 // Create Decl objects for each parameter, adding them to the
1771 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1772 SmallVector<ParmVarDecl*, 16> Params;
1773 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1776 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778 parm->setScopeInfo(0, i);
1779 Params.push_back(parm);
1781 New->setParams(Params);
1784 AddKnownFunctionAttributes(New);
1785 RegisterLocallyScopedExternCDecl(New, S);
1787 // TUScope is the translation-unit scope to insert this function into.
1788 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1789 // relate Scopes to DeclContexts, and probably eliminate CurContext
1790 // entirely, but we're not there yet.
1791 DeclContext *SavedContext = CurContext;
1792 CurContext = Parent;
1793 PushOnScopeChains(New, TUScope);
1794 CurContext = SavedContext;
1798 /// Typedef declarations don't have linkage, but they still denote the same
1799 /// entity if their types are the same.
1800 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1802 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1803 TypedefNameDecl *Decl,
1804 LookupResult &Previous) {
1805 // This is only interesting when modules are enabled.
1806 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1809 // Empty sets are uninteresting.
1810 if (Previous.empty())
1813 LookupResult::Filter Filter = Previous.makeFilter();
1814 while (Filter.hasNext()) {
1815 NamedDecl *Old = Filter.next();
1817 // Non-hidden declarations are never ignored.
1818 if (S.isVisible(Old))
1821 // Declarations of the same entity are not ignored, even if they have
1822 // different linkages.
1823 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1824 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1825 Decl->getUnderlyingType()))
1828 // If both declarations give a tag declaration a typedef name for linkage
1829 // purposes, then they declare the same entity.
1830 if (S.getLangOpts().CPlusPlus &&
1831 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1832 Decl->getAnonDeclWithTypedefName())
1842 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1844 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1845 OldType = OldTypedef->getUnderlyingType();
1847 OldType = Context.getTypeDeclType(Old);
1848 QualType NewType = New->getUnderlyingType();
1850 if (NewType->isVariablyModifiedType()) {
1851 // Must not redefine a typedef with a variably-modified type.
1852 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1853 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1855 if (Old->getLocation().isValid())
1856 Diag(Old->getLocation(), diag::note_previous_definition);
1857 New->setInvalidDecl();
1861 if (OldType != NewType &&
1862 !OldType->isDependentType() &&
1863 !NewType->isDependentType() &&
1864 !Context.hasSameType(OldType, NewType)) {
1865 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1866 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1867 << Kind << NewType << OldType;
1868 if (Old->getLocation().isValid())
1869 Diag(Old->getLocation(), diag::note_previous_definition);
1870 New->setInvalidDecl();
1876 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1877 /// same name and scope as a previous declaration 'Old'. Figure out
1878 /// how to resolve this situation, merging decls or emitting
1879 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1881 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1882 LookupResult &OldDecls) {
1883 // If the new decl is known invalid already, don't bother doing any
1885 if (New->isInvalidDecl()) return;
1887 // Allow multiple definitions for ObjC built-in typedefs.
1888 // FIXME: Verify the underlying types are equivalent!
1889 if (getLangOpts().ObjC1) {
1890 const IdentifierInfo *TypeID = New->getIdentifier();
1891 switch (TypeID->getLength()) {
1895 if (!TypeID->isStr("id"))
1897 QualType T = New->getUnderlyingType();
1898 if (!T->isPointerType())
1900 if (!T->isVoidPointerType()) {
1901 QualType PT = T->getAs<PointerType>()->getPointeeType();
1902 if (!PT->isStructureType())
1905 Context.setObjCIdRedefinitionType(T);
1906 // Install the built-in type for 'id', ignoring the current definition.
1907 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1911 if (!TypeID->isStr("Class"))
1913 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1914 // Install the built-in type for 'Class', ignoring the current definition.
1915 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1918 if (!TypeID->isStr("SEL"))
1920 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1921 // Install the built-in type for 'SEL', ignoring the current definition.
1922 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1925 // Fall through - the typedef name was not a builtin type.
1928 // Verify the old decl was also a type.
1929 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1931 Diag(New->getLocation(), diag::err_redefinition_different_kind)
1932 << New->getDeclName();
1934 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1935 if (OldD->getLocation().isValid())
1936 Diag(OldD->getLocation(), diag::note_previous_definition);
1938 return New->setInvalidDecl();
1941 // If the old declaration is invalid, just give up here.
1942 if (Old->isInvalidDecl())
1943 return New->setInvalidDecl();
1945 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1946 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1947 auto *NewTag = New->getAnonDeclWithTypedefName();
1948 NamedDecl *Hidden = nullptr;
1949 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1950 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1951 !hasVisibleDefinition(OldTag, &Hidden)) {
1952 // There is a definition of this tag, but it is not visible. Use it
1953 // instead of our tag.
1954 New->setTypeForDecl(OldTD->getTypeForDecl());
1955 if (OldTD->isModed())
1956 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1957 OldTD->getUnderlyingType());
1959 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1961 // Make the old tag definition visible.
1962 makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1964 // If this was an unscoped enumeration, yank all of its enumerators
1965 // out of the scope.
1966 if (isa<EnumDecl>(NewTag)) {
1967 Scope *EnumScope = getNonFieldDeclScope(S);
1968 for (auto *D : NewTag->decls()) {
1969 auto *ED = cast<EnumConstantDecl>(D);
1970 assert(EnumScope->isDeclScope(ED));
1971 EnumScope->RemoveDecl(ED);
1972 IdResolver.RemoveDecl(ED);
1973 ED->getLexicalDeclContext()->removeDecl(ED);
1979 // If the typedef types are not identical, reject them in all languages and
1980 // with any extensions enabled.
1981 if (isIncompatibleTypedef(Old, New))
1984 // The types match. Link up the redeclaration chain and merge attributes if
1985 // the old declaration was a typedef.
1986 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1987 New->setPreviousDecl(Typedef);
1988 mergeDeclAttributes(New, Old);
1991 if (getLangOpts().MicrosoftExt)
1994 if (getLangOpts().CPlusPlus) {
1995 // C++ [dcl.typedef]p2:
1996 // In a given non-class scope, a typedef specifier can be used to
1997 // redefine the name of any type declared in that scope to refer
1998 // to the type to which it already refers.
1999 if (!isa<CXXRecordDecl>(CurContext))
2002 // C++0x [dcl.typedef]p4:
2003 // In a given class scope, a typedef specifier can be used to redefine
2004 // any class-name declared in that scope that is not also a typedef-name
2005 // to refer to the type to which it already refers.
2007 // This wording came in via DR424, which was a correction to the
2008 // wording in DR56, which accidentally banned code like:
2011 // typedef struct A { } A;
2014 // in the C++03 standard. We implement the C++0x semantics, which
2015 // allow the above but disallow
2022 // since that was the intent of DR56.
2023 if (!isa<TypedefNameDecl>(Old))
2026 Diag(New->getLocation(), diag::err_redefinition)
2027 << New->getDeclName();
2028 Diag(Old->getLocation(), diag::note_previous_definition);
2029 return New->setInvalidDecl();
2032 // Modules always permit redefinition of typedefs, as does C11.
2033 if (getLangOpts().Modules || getLangOpts().C11)
2036 // If we have a redefinition of a typedef in C, emit a warning. This warning
2037 // is normally mapped to an error, but can be controlled with
2038 // -Wtypedef-redefinition. If either the original or the redefinition is
2039 // in a system header, don't emit this for compatibility with GCC.
2040 if (getDiagnostics().getSuppressSystemWarnings() &&
2041 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2042 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2045 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2046 << New->getDeclName();
2047 Diag(Old->getLocation(), diag::note_previous_definition);
2050 /// DeclhasAttr - returns true if decl Declaration already has the target
2052 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2053 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2054 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2055 for (const auto *i : D->attrs())
2056 if (i->getKind() == A->getKind()) {
2058 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2062 // FIXME: Don't hardcode this check
2063 if (OA && isa<OwnershipAttr>(i))
2064 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2071 static bool isAttributeTargetADefinition(Decl *D) {
2072 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2073 return VD->isThisDeclarationADefinition();
2074 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2075 return TD->isCompleteDefinition() || TD->isBeingDefined();
2079 /// Merge alignment attributes from \p Old to \p New, taking into account the
2080 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2082 /// \return \c true if any attributes were added to \p New.
2083 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2084 // Look for alignas attributes on Old, and pick out whichever attribute
2085 // specifies the strictest alignment requirement.
2086 AlignedAttr *OldAlignasAttr = nullptr;
2087 AlignedAttr *OldStrictestAlignAttr = nullptr;
2088 unsigned OldAlign = 0;
2089 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2090 // FIXME: We have no way of representing inherited dependent alignments
2092 // template<int A, int B> struct alignas(A) X;
2093 // template<int A, int B> struct alignas(B) X {};
2094 // For now, we just ignore any alignas attributes which are not on the
2095 // definition in such a case.
2096 if (I->isAlignmentDependent())
2102 unsigned Align = I->getAlignment(S.Context);
2103 if (Align > OldAlign) {
2105 OldStrictestAlignAttr = I;
2109 // Look for alignas attributes on New.
2110 AlignedAttr *NewAlignasAttr = nullptr;
2111 unsigned NewAlign = 0;
2112 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2113 if (I->isAlignmentDependent())
2119 unsigned Align = I->getAlignment(S.Context);
2120 if (Align > NewAlign)
2124 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2125 // Both declarations have 'alignas' attributes. We require them to match.
2126 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2127 // fall short. (If two declarations both have alignas, they must both match
2128 // every definition, and so must match each other if there is a definition.)
2130 // If either declaration only contains 'alignas(0)' specifiers, then it
2131 // specifies the natural alignment for the type.
2132 if (OldAlign == 0 || NewAlign == 0) {
2134 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2137 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2140 OldAlign = S.Context.getTypeAlign(Ty);
2142 NewAlign = S.Context.getTypeAlign(Ty);
2145 if (OldAlign != NewAlign) {
2146 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2147 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2148 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2149 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2153 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2154 // C++11 [dcl.align]p6:
2155 // if any declaration of an entity has an alignment-specifier,
2156 // every defining declaration of that entity shall specify an
2157 // equivalent alignment.
2159 // If the definition of an object does not have an alignment
2160 // specifier, any other declaration of that object shall also
2161 // have no alignment specifier.
2162 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2164 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2168 bool AnyAdded = false;
2170 // Ensure we have an attribute representing the strictest alignment.
2171 if (OldAlign > NewAlign) {
2172 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2173 Clone->setInherited(true);
2174 New->addAttr(Clone);
2178 // Ensure we have an alignas attribute if the old declaration had one.
2179 if (OldAlignasAttr && !NewAlignasAttr &&
2180 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2181 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2182 Clone->setInherited(true);
2183 New->addAttr(Clone);
2190 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2191 const InheritableAttr *Attr,
2192 Sema::AvailabilityMergeKind AMK) {
2193 InheritableAttr *NewAttr = nullptr;
2194 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2195 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2196 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2197 AA->getIntroduced(), AA->getDeprecated(),
2198 AA->getObsoleted(), AA->getUnavailable(),
2199 AA->getMessage(), AMK,
2200 AttrSpellingListIndex);
2201 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2202 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2203 AttrSpellingListIndex);
2204 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2205 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2206 AttrSpellingListIndex);
2207 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2208 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2209 AttrSpellingListIndex);
2210 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2211 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2212 AttrSpellingListIndex);
2213 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2214 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2215 FA->getFormatIdx(), FA->getFirstArg(),
2216 AttrSpellingListIndex);
2217 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2218 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2219 AttrSpellingListIndex);
2220 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2221 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2222 AttrSpellingListIndex,
2223 IA->getSemanticSpelling());
2224 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2225 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2226 &S.Context.Idents.get(AA->getSpelling()),
2227 AttrSpellingListIndex);
2228 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2229 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2230 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2231 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2232 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2233 NewAttr = S.mergeInternalLinkageAttr(
2234 D, InternalLinkageA->getRange(),
2235 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2236 AttrSpellingListIndex);
2237 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2238 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2239 &S.Context.Idents.get(CommonA->getSpelling()),
2240 AttrSpellingListIndex);
2241 else if (isa<AlignedAttr>(Attr))
2242 // AlignedAttrs are handled separately, because we need to handle all
2243 // such attributes on a declaration at the same time.
2245 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2246 (AMK == Sema::AMK_Override ||
2247 AMK == Sema::AMK_ProtocolImplementation))
2249 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2250 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2253 NewAttr->setInherited(true);
2254 D->addAttr(NewAttr);
2261 static const Decl *getDefinition(const Decl *D) {
2262 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2263 return TD->getDefinition();
2264 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2265 const VarDecl *Def = VD->getDefinition();
2268 return VD->getActingDefinition();
2270 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2271 const FunctionDecl* Def;
2272 if (FD->isDefined(Def))
2278 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2279 for (const auto *Attribute : D->attrs())
2280 if (Attribute->getKind() == Kind)
2285 /// checkNewAttributesAfterDef - If we already have a definition, check that
2286 /// there are no new attributes in this declaration.
2287 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2288 if (!New->hasAttrs())
2291 const Decl *Def = getDefinition(Old);
2292 if (!Def || Def == New)
2295 AttrVec &NewAttributes = New->getAttrs();
2296 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2297 const Attr *NewAttribute = NewAttributes[I];
2299 if (isa<AliasAttr>(NewAttribute)) {
2300 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2301 Sema::SkipBodyInfo SkipBody;
2302 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2304 // If we're skipping this definition, drop the "alias" attribute.
2305 if (SkipBody.ShouldSkip) {
2306 NewAttributes.erase(NewAttributes.begin() + I);
2311 VarDecl *VD = cast<VarDecl>(New);
2312 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2313 VarDecl::TentativeDefinition
2314 ? diag::err_alias_after_tentative
2315 : diag::err_redefinition;
2316 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2317 S.Diag(Def->getLocation(), diag::note_previous_definition);
2318 VD->setInvalidDecl();
2324 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2325 // Tentative definitions are only interesting for the alias check above.
2326 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2332 if (hasAttribute(Def, NewAttribute->getKind())) {
2334 continue; // regular attr merging will take care of validating this.
2337 if (isa<C11NoReturnAttr>(NewAttribute)) {
2338 // C's _Noreturn is allowed to be added to a function after it is defined.
2341 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2342 if (AA->isAlignas()) {
2343 // C++11 [dcl.align]p6:
2344 // if any declaration of an entity has an alignment-specifier,
2345 // every defining declaration of that entity shall specify an
2346 // equivalent alignment.
2348 // If the definition of an object does not have an alignment
2349 // specifier, any other declaration of that object shall also
2350 // have no alignment specifier.
2351 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2353 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2355 NewAttributes.erase(NewAttributes.begin() + I);
2361 S.Diag(NewAttribute->getLocation(),
2362 diag::warn_attribute_precede_definition);
2363 S.Diag(Def->getLocation(), diag::note_previous_definition);
2364 NewAttributes.erase(NewAttributes.begin() + I);
2369 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2370 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2371 AvailabilityMergeKind AMK) {
2372 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2373 UsedAttr *NewAttr = OldAttr->clone(Context);
2374 NewAttr->setInherited(true);
2375 New->addAttr(NewAttr);
2378 if (!Old->hasAttrs() && !New->hasAttrs())
2381 // Attributes declared post-definition are currently ignored.
2382 checkNewAttributesAfterDef(*this, New, Old);
2384 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2385 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2386 if (OldA->getLabel() != NewA->getLabel()) {
2387 // This redeclaration changes __asm__ label.
2388 Diag(New->getLocation(), diag::err_different_asm_label);
2389 Diag(OldA->getLocation(), diag::note_previous_declaration);
2391 } else if (Old->isUsed()) {
2392 // This redeclaration adds an __asm__ label to a declaration that has
2393 // already been ODR-used.
2394 Diag(New->getLocation(), diag::err_late_asm_label_name)
2395 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2399 if (!Old->hasAttrs())
2402 bool foundAny = New->hasAttrs();
2404 // Ensure that any moving of objects within the allocated map is done before
2406 if (!foundAny) New->setAttrs(AttrVec());
2408 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2409 // Ignore deprecated/unavailable/availability attributes if requested.
2410 AvailabilityMergeKind LocalAMK = AMK_None;
2411 if (isa<DeprecatedAttr>(I) ||
2412 isa<UnavailableAttr>(I) ||
2413 isa<AvailabilityAttr>(I)) {
2418 case AMK_Redeclaration:
2420 case AMK_ProtocolImplementation:
2427 if (isa<UsedAttr>(I))
2430 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2434 if (mergeAlignedAttrs(*this, New, Old))
2437 if (!foundAny) New->dropAttrs();
2440 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2442 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2443 const ParmVarDecl *oldDecl,
2445 // C++11 [dcl.attr.depend]p2:
2446 // The first declaration of a function shall specify the
2447 // carries_dependency attribute for its declarator-id if any declaration
2448 // of the function specifies the carries_dependency attribute.
2449 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2450 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2451 S.Diag(CDA->getLocation(),
2452 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2453 // Find the first declaration of the parameter.
2454 // FIXME: Should we build redeclaration chains for function parameters?
2455 const FunctionDecl *FirstFD =
2456 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2457 const ParmVarDecl *FirstVD =
2458 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2459 S.Diag(FirstVD->getLocation(),
2460 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2463 if (!oldDecl->hasAttrs())
2466 bool foundAny = newDecl->hasAttrs();
2468 // Ensure that any moving of objects within the allocated map is
2469 // done before we process them.
2470 if (!foundAny) newDecl->setAttrs(AttrVec());
2472 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2473 if (!DeclHasAttr(newDecl, I)) {
2474 InheritableAttr *newAttr =
2475 cast<InheritableParamAttr>(I->clone(S.Context));
2476 newAttr->setInherited(true);
2477 newDecl->addAttr(newAttr);
2482 if (!foundAny) newDecl->dropAttrs();
2485 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2486 const ParmVarDecl *OldParam,
2488 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2489 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2490 if (*Oldnullability != *Newnullability) {
2491 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2492 << DiagNullabilityKind(
2494 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2496 << DiagNullabilityKind(
2498 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2500 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2503 QualType NewT = NewParam->getType();
2504 NewT = S.Context.getAttributedType(
2505 AttributedType::getNullabilityAttrKind(*Oldnullability),
2507 NewParam->setType(NewT);
2514 /// Used in MergeFunctionDecl to keep track of function parameters in
2516 struct GNUCompatibleParamWarning {
2517 ParmVarDecl *OldParm;
2518 ParmVarDecl *NewParm;
2519 QualType PromotedType;
2524 /// getSpecialMember - get the special member enum for a method.
2525 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2526 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2527 if (Ctor->isDefaultConstructor())
2528 return Sema::CXXDefaultConstructor;
2530 if (Ctor->isCopyConstructor())
2531 return Sema::CXXCopyConstructor;
2533 if (Ctor->isMoveConstructor())
2534 return Sema::CXXMoveConstructor;
2535 } else if (isa<CXXDestructorDecl>(MD)) {
2536 return Sema::CXXDestructor;
2537 } else if (MD->isCopyAssignmentOperator()) {
2538 return Sema::CXXCopyAssignment;
2539 } else if (MD->isMoveAssignmentOperator()) {
2540 return Sema::CXXMoveAssignment;
2543 return Sema::CXXInvalid;
2546 // Determine whether the previous declaration was a definition, implicit
2547 // declaration, or a declaration.
2548 template <typename T>
2549 static std::pair<diag::kind, SourceLocation>
2550 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2551 diag::kind PrevDiag;
2552 SourceLocation OldLocation = Old->getLocation();
2553 if (Old->isThisDeclarationADefinition())
2554 PrevDiag = diag::note_previous_definition;
2555 else if (Old->isImplicit()) {
2556 PrevDiag = diag::note_previous_implicit_declaration;
2557 if (OldLocation.isInvalid())
2558 OldLocation = New->getLocation();
2560 PrevDiag = diag::note_previous_declaration;
2561 return std::make_pair(PrevDiag, OldLocation);
2564 /// canRedefineFunction - checks if a function can be redefined. Currently,
2565 /// only extern inline functions can be redefined, and even then only in
2567 static bool canRedefineFunction(const FunctionDecl *FD,
2568 const LangOptions& LangOpts) {
2569 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2570 !LangOpts.CPlusPlus &&
2571 FD->isInlineSpecified() &&
2572 FD->getStorageClass() == SC_Extern);
2575 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2576 const AttributedType *AT = T->getAs<AttributedType>();
2577 while (AT && !AT->isCallingConv())
2578 AT = AT->getModifiedType()->getAs<AttributedType>();
2582 template <typename T>
2583 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2584 const DeclContext *DC = Old->getDeclContext();
2588 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2589 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2591 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2596 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2597 static bool isExternC(VarTemplateDecl *) { return false; }
2599 /// \brief Check whether a redeclaration of an entity introduced by a
2600 /// using-declaration is valid, given that we know it's not an overload
2601 /// (nor a hidden tag declaration).
2602 template<typename ExpectedDecl>
2603 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2604 ExpectedDecl *New) {
2605 // C++11 [basic.scope.declarative]p4:
2606 // Given a set of declarations in a single declarative region, each of
2607 // which specifies the same unqualified name,
2608 // -- they shall all refer to the same entity, or all refer to functions
2609 // and function templates; or
2610 // -- exactly one declaration shall declare a class name or enumeration
2611 // name that is not a typedef name and the other declarations shall all
2612 // refer to the same variable or enumerator, or all refer to functions
2613 // and function templates; in this case the class name or enumeration
2614 // name is hidden (3.3.10).
2616 // C++11 [namespace.udecl]p14:
2617 // If a function declaration in namespace scope or block scope has the
2618 // same name and the same parameter-type-list as a function introduced
2619 // by a using-declaration, and the declarations do not declare the same
2620 // function, the program is ill-formed.
2622 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2624 !Old->getDeclContext()->getRedeclContext()->Equals(
2625 New->getDeclContext()->getRedeclContext()) &&
2626 !(isExternC(Old) && isExternC(New)))
2630 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2631 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2632 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2638 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2639 const FunctionDecl *B) {
2640 assert(A->getNumParams() == B->getNumParams());
2642 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2643 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2644 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2647 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2650 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2653 /// MergeFunctionDecl - We just parsed a function 'New' from
2654 /// declarator D which has the same name and scope as a previous
2655 /// declaration 'Old'. Figure out how to resolve this situation,
2656 /// merging decls or emitting diagnostics as appropriate.
2658 /// In C++, New and Old must be declarations that are not
2659 /// overloaded. Use IsOverload to determine whether New and Old are
2660 /// overloaded, and to select the Old declaration that New should be
2663 /// Returns true if there was an error, false otherwise.
2664 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2665 Scope *S, bool MergeTypeWithOld) {
2666 // Verify the old decl was also a function.
2667 FunctionDecl *Old = OldD->getAsFunction();
2669 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2670 if (New->getFriendObjectKind()) {
2671 Diag(New->getLocation(), diag::err_using_decl_friend);
2672 Diag(Shadow->getTargetDecl()->getLocation(),
2673 diag::note_using_decl_target);
2674 Diag(Shadow->getUsingDecl()->getLocation(),
2675 diag::note_using_decl) << 0;
2679 // Check whether the two declarations might declare the same function.
2680 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2682 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2684 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2685 << New->getDeclName();
2686 Diag(OldD->getLocation(), diag::note_previous_definition);
2691 // If the old declaration is invalid, just give up here.
2692 if (Old->isInvalidDecl())
2695 diag::kind PrevDiag;
2696 SourceLocation OldLocation;
2697 std::tie(PrevDiag, OldLocation) =
2698 getNoteDiagForInvalidRedeclaration(Old, New);
2700 // Don't complain about this if we're in GNU89 mode and the old function
2701 // is an extern inline function.
2702 // Don't complain about specializations. They are not supposed to have
2704 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2705 New->getStorageClass() == SC_Static &&
2706 Old->hasExternalFormalLinkage() &&
2707 !New->getTemplateSpecializationInfo() &&
2708 !canRedefineFunction(Old, getLangOpts())) {
2709 if (getLangOpts().MicrosoftExt) {
2710 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2711 Diag(OldLocation, PrevDiag);
2713 Diag(New->getLocation(), diag::err_static_non_static) << New;
2714 Diag(OldLocation, PrevDiag);
2719 if (New->hasAttr<InternalLinkageAttr>() &&
2720 !Old->hasAttr<InternalLinkageAttr>()) {
2721 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2722 << New->getDeclName();
2723 Diag(Old->getLocation(), diag::note_previous_definition);
2724 New->dropAttr<InternalLinkageAttr>();
2727 // If a function is first declared with a calling convention, but is later
2728 // declared or defined without one, all following decls assume the calling
2729 // convention of the first.
2731 // It's OK if a function is first declared without a calling convention,
2732 // but is later declared or defined with the default calling convention.
2734 // To test if either decl has an explicit calling convention, we look for
2735 // AttributedType sugar nodes on the type as written. If they are missing or
2736 // were canonicalized away, we assume the calling convention was implicit.
2738 // Note also that we DO NOT return at this point, because we still have
2739 // other tests to run.
2740 QualType OldQType = Context.getCanonicalType(Old->getType());
2741 QualType NewQType = Context.getCanonicalType(New->getType());
2742 const FunctionType *OldType = cast<FunctionType>(OldQType);
2743 const FunctionType *NewType = cast<FunctionType>(NewQType);
2744 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2745 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2746 bool RequiresAdjustment = false;
2748 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2749 FunctionDecl *First = Old->getFirstDecl();
2750 const FunctionType *FT =
2751 First->getType().getCanonicalType()->castAs<FunctionType>();
2752 FunctionType::ExtInfo FI = FT->getExtInfo();
2753 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2754 if (!NewCCExplicit) {
2755 // Inherit the CC from the previous declaration if it was specified
2756 // there but not here.
2757 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2758 RequiresAdjustment = true;
2760 // Calling conventions aren't compatible, so complain.
2761 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2762 Diag(New->getLocation(), diag::err_cconv_change)
2763 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2765 << (!FirstCCExplicit ? "" :
2766 FunctionType::getNameForCallConv(FI.getCC()));
2768 // Put the note on the first decl, since it is the one that matters.
2769 Diag(First->getLocation(), diag::note_previous_declaration);
2774 // FIXME: diagnose the other way around?
2775 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2776 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2777 RequiresAdjustment = true;
2780 // Merge regparm attribute.
2781 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2782 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2783 if (NewTypeInfo.getHasRegParm()) {
2784 Diag(New->getLocation(), diag::err_regparm_mismatch)
2785 << NewType->getRegParmType()
2786 << OldType->getRegParmType();
2787 Diag(OldLocation, diag::note_previous_declaration);
2791 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2792 RequiresAdjustment = true;
2795 // Merge ns_returns_retained attribute.
2796 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2797 if (NewTypeInfo.getProducesResult()) {
2798 Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2799 Diag(OldLocation, diag::note_previous_declaration);
2803 NewTypeInfo = NewTypeInfo.withProducesResult(true);
2804 RequiresAdjustment = true;
2807 if (RequiresAdjustment) {
2808 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2809 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2810 New->setType(QualType(AdjustedType, 0));
2811 NewQType = Context.getCanonicalType(New->getType());
2812 NewType = cast<FunctionType>(NewQType);
2815 // If this redeclaration makes the function inline, we may need to add it to
2816 // UndefinedButUsed.
2817 if (!Old->isInlined() && New->isInlined() &&
2818 !New->hasAttr<GNUInlineAttr>() &&
2819 !getLangOpts().GNUInline &&
2820 Old->isUsed(false) &&
2821 !Old->isDefined() && !New->isThisDeclarationADefinition())
2822 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2825 // If this redeclaration makes it newly gnu_inline, we don't want to warn
2827 if (New->hasAttr<GNUInlineAttr>() &&
2828 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2829 UndefinedButUsed.erase(Old->getCanonicalDecl());
2832 // If pass_object_size params don't match up perfectly, this isn't a valid
2834 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2835 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2836 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2837 << New->getDeclName();
2838 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2842 if (getLangOpts().CPlusPlus) {
2844 // Certain function declarations cannot be overloaded:
2845 // -- Function declarations that differ only in the return type
2846 // cannot be overloaded.
2848 // Go back to the type source info to compare the declared return types,
2849 // per C++1y [dcl.type.auto]p13:
2850 // Redeclarations or specializations of a function or function template
2851 // with a declared return type that uses a placeholder type shall also
2852 // use that placeholder, not a deduced type.
2853 QualType OldDeclaredReturnType =
2854 (Old->getTypeSourceInfo()
2855 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2856 : OldType)->getReturnType();
2857 QualType NewDeclaredReturnType =
2858 (New->getTypeSourceInfo()
2859 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2860 : NewType)->getReturnType();
2862 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2863 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2864 New->isLocalExternDecl())) {
2865 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2866 OldDeclaredReturnType->isObjCObjectPointerType())
2867 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2868 if (ResQT.isNull()) {
2869 if (New->isCXXClassMember() && New->isOutOfLine())
2870 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2871 << New << New->getReturnTypeSourceRange();
2873 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2874 << New->getReturnTypeSourceRange();
2875 Diag(OldLocation, PrevDiag) << Old << Old->getType()
2876 << Old->getReturnTypeSourceRange();
2883 QualType OldReturnType = OldType->getReturnType();
2884 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2885 if (OldReturnType != NewReturnType) {
2886 // If this function has a deduced return type and has already been
2887 // defined, copy the deduced value from the old declaration.
2888 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2889 if (OldAT && OldAT->isDeduced()) {
2891 SubstAutoType(New->getType(),
2892 OldAT->isDependentType() ? Context.DependentTy
2893 : OldAT->getDeducedType()));
2894 NewQType = Context.getCanonicalType(
2895 SubstAutoType(NewQType,
2896 OldAT->isDependentType() ? Context.DependentTy
2897 : OldAT->getDeducedType()));
2901 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2902 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2903 if (OldMethod && NewMethod) {
2904 // Preserve triviality.
2905 NewMethod->setTrivial(OldMethod->isTrivial());
2907 // MSVC allows explicit template specialization at class scope:
2908 // 2 CXXMethodDecls referring to the same function will be injected.
2909 // We don't want a redeclaration error.
2910 bool IsClassScopeExplicitSpecialization =
2911 OldMethod->isFunctionTemplateSpecialization() &&
2912 NewMethod->isFunctionTemplateSpecialization();
2913 bool isFriend = NewMethod->getFriendObjectKind();
2915 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2916 !IsClassScopeExplicitSpecialization) {
2917 // -- Member function declarations with the same name and the
2918 // same parameter types cannot be overloaded if any of them
2919 // is a static member function declaration.
2920 if (OldMethod->isStatic() != NewMethod->isStatic()) {
2921 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2922 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2926 // C++ [class.mem]p1:
2927 // [...] A member shall not be declared twice in the
2928 // member-specification, except that a nested class or member
2929 // class template can be declared and then later defined.
2930 if (ActiveTemplateInstantiations.empty()) {
2932 if (isa<CXXConstructorDecl>(OldMethod))
2933 NewDiag = diag::err_constructor_redeclared;
2934 else if (isa<CXXDestructorDecl>(NewMethod))
2935 NewDiag = diag::err_destructor_redeclared;
2936 else if (isa<CXXConversionDecl>(NewMethod))
2937 NewDiag = diag::err_conv_function_redeclared;
2939 NewDiag = diag::err_member_redeclared;
2941 Diag(New->getLocation(), NewDiag);
2943 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2944 << New << New->getType();
2946 Diag(OldLocation, PrevDiag) << Old << Old->getType();
2949 // Complain if this is an explicit declaration of a special
2950 // member that was initially declared implicitly.
2952 // As an exception, it's okay to befriend such methods in order
2953 // to permit the implicit constructor/destructor/operator calls.
2954 } else if (OldMethod->isImplicit()) {
2956 NewMethod->setImplicit();
2958 Diag(NewMethod->getLocation(),
2959 diag::err_definition_of_implicitly_declared_member)
2960 << New << getSpecialMember(OldMethod);
2963 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2964 Diag(NewMethod->getLocation(),
2965 diag::err_definition_of_explicitly_defaulted_member)
2966 << getSpecialMember(OldMethod);
2971 // C++11 [dcl.attr.noreturn]p1:
2972 // The first declaration of a function shall specify the noreturn
2973 // attribute if any declaration of that function specifies the noreturn
2975 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2976 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2977 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2978 Diag(Old->getFirstDecl()->getLocation(),
2979 diag::note_noreturn_missing_first_decl);
2982 // C++11 [dcl.attr.depend]p2:
2983 // The first declaration of a function shall specify the
2984 // carries_dependency attribute for its declarator-id if any declaration
2985 // of the function specifies the carries_dependency attribute.
2986 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2987 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2988 Diag(CDA->getLocation(),
2989 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2990 Diag(Old->getFirstDecl()->getLocation(),
2991 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2995 // All declarations for a function shall agree exactly in both the
2996 // return type and the parameter-type-list.
2997 // We also want to respect all the extended bits except noreturn.
2999 // noreturn should now match unless the old type info didn't have it.
3000 QualType OldQTypeForComparison = OldQType;
3001 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3002 assert(OldQType == QualType(OldType, 0));
3003 const FunctionType *OldTypeForComparison
3004 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3005 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3006 assert(OldQTypeForComparison.isCanonical());
3009 if (haveIncompatibleLanguageLinkages(Old, New)) {
3010 // As a special case, retain the language linkage from previous
3011 // declarations of a friend function as an extension.
3013 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3014 // and is useful because there's otherwise no way to specify language
3015 // linkage within class scope.
3017 // Check cautiously as the friend object kind isn't yet complete.
3018 if (New->getFriendObjectKind() != Decl::FOK_None) {
3019 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3020 Diag(OldLocation, PrevDiag);
3022 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3023 Diag(OldLocation, PrevDiag);
3028 if (OldQTypeForComparison == NewQType)
3029 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3031 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3032 New->isLocalExternDecl()) {
3033 // It's OK if we couldn't merge types for a local function declaraton
3034 // if either the old or new type is dependent. We'll merge the types
3035 // when we instantiate the function.
3039 // Fall through for conflicting redeclarations and redefinitions.
3042 // C: Function types need to be compatible, not identical. This handles
3043 // duplicate function decls like "void f(int); void f(enum X);" properly.
3044 if (!getLangOpts().CPlusPlus &&
3045 Context.typesAreCompatible(OldQType, NewQType)) {
3046 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3047 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3048 const FunctionProtoType *OldProto = nullptr;
3049 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3050 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3051 // The old declaration provided a function prototype, but the
3052 // new declaration does not. Merge in the prototype.
3053 assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3054 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3056 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3057 OldProto->getExtProtoInfo());
3058 New->setType(NewQType);
3059 New->setHasInheritedPrototype();
3061 // Synthesize parameters with the same types.
3062 SmallVector<ParmVarDecl*, 16> Params;
3063 for (const auto &ParamType : OldProto->param_types()) {
3064 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3065 SourceLocation(), nullptr,
3066 ParamType, /*TInfo=*/nullptr,
3068 Param->setScopeInfo(0, Params.size());
3069 Param->setImplicit();
3070 Params.push_back(Param);
3073 New->setParams(Params);
3076 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3079 // GNU C permits a K&R definition to follow a prototype declaration
3080 // if the declared types of the parameters in the K&R definition
3081 // match the types in the prototype declaration, even when the
3082 // promoted types of the parameters from the K&R definition differ
3083 // from the types in the prototype. GCC then keeps the types from
3086 // If a variadic prototype is followed by a non-variadic K&R definition,
3087 // the K&R definition becomes variadic. This is sort of an edge case, but
3088 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3090 if (!getLangOpts().CPlusPlus &&
3091 Old->hasPrototype() && !New->hasPrototype() &&
3092 New->getType()->getAs<FunctionProtoType>() &&
3093 Old->getNumParams() == New->getNumParams()) {
3094 SmallVector<QualType, 16> ArgTypes;
3095 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3096 const FunctionProtoType *OldProto
3097 = Old->getType()->getAs<FunctionProtoType>();
3098 const FunctionProtoType *NewProto
3099 = New->getType()->getAs<FunctionProtoType>();
3101 // Determine whether this is the GNU C extension.
3102 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3103 NewProto->getReturnType());
3104 bool LooseCompatible = !MergedReturn.isNull();
3105 for (unsigned Idx = 0, End = Old->getNumParams();
3106 LooseCompatible && Idx != End; ++Idx) {
3107 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3108 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3109 if (Context.typesAreCompatible(OldParm->getType(),
3110 NewProto->getParamType(Idx))) {
3111 ArgTypes.push_back(NewParm->getType());
3112 } else if (Context.typesAreCompatible(OldParm->getType(),
3114 /*CompareUnqualified=*/true)) {
3115 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3116 NewProto->getParamType(Idx) };
3117 Warnings.push_back(Warn);
3118 ArgTypes.push_back(NewParm->getType());
3120 LooseCompatible = false;
3123 if (LooseCompatible) {
3124 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3125 Diag(Warnings[Warn].NewParm->getLocation(),
3126 diag::ext_param_promoted_not_compatible_with_prototype)
3127 << Warnings[Warn].PromotedType
3128 << Warnings[Warn].OldParm->getType();
3129 if (Warnings[Warn].OldParm->getLocation().isValid())
3130 Diag(Warnings[Warn].OldParm->getLocation(),
3131 diag::note_previous_declaration);
3134 if (MergeTypeWithOld)
3135 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3136 OldProto->getExtProtoInfo()));
3137 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3140 // Fall through to diagnose conflicting types.
3143 // A function that has already been declared has been redeclared or
3144 // defined with a different type; show an appropriate diagnostic.
3146 // If the previous declaration was an implicitly-generated builtin
3147 // declaration, then at the very least we should use a specialized note.
3149 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3150 // If it's actually a library-defined builtin function like 'malloc'
3151 // or 'printf', just warn about the incompatible redeclaration.
3152 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3153 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3154 Diag(OldLocation, diag::note_previous_builtin_declaration)
3155 << Old << Old->getType();
3157 // If this is a global redeclaration, just forget hereafter
3158 // about the "builtin-ness" of the function.
3160 // Doing this for local extern declarations is problematic. If
3161 // the builtin declaration remains visible, a second invalid
3162 // local declaration will produce a hard error; if it doesn't
3163 // remain visible, a single bogus local redeclaration (which is
3164 // actually only a warning) could break all the downstream code.
3165 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3166 New->getIdentifier()->revertBuiltin();
3171 PrevDiag = diag::note_previous_builtin_declaration;
3174 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3175 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3179 /// \brief Completes the merge of two function declarations that are
3180 /// known to be compatible.
3182 /// This routine handles the merging of attributes and other
3183 /// properties of function declarations from the old declaration to
3184 /// the new declaration, once we know that New is in fact a
3185 /// redeclaration of Old.
3188 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3189 Scope *S, bool MergeTypeWithOld) {
3190 // Merge the attributes
3191 mergeDeclAttributes(New, Old);
3193 // Merge "pure" flag.
3197 // Merge "used" flag.
3198 if (Old->getMostRecentDecl()->isUsed(false))
3201 // Merge attributes from the parameters. These can mismatch with K&R
3203 if (New->getNumParams() == Old->getNumParams())
3204 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3205 ParmVarDecl *NewParam = New->getParamDecl(i);
3206 ParmVarDecl *OldParam = Old->getParamDecl(i);
3207 mergeParamDeclAttributes(NewParam, OldParam, *this);
3208 mergeParamDeclTypes(NewParam, OldParam, *this);
3211 if (getLangOpts().CPlusPlus)
3212 return MergeCXXFunctionDecl(New, Old, S);
3214 // Merge the function types so the we get the composite types for the return
3215 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3217 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3218 if (!Merged.isNull() && MergeTypeWithOld)
3219 New->setType(Merged);
3225 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3226 ObjCMethodDecl *oldMethod) {
3228 // Merge the attributes, including deprecated/unavailable
3229 AvailabilityMergeKind MergeKind =
3230 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3231 ? AMK_ProtocolImplementation
3232 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3235 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3237 // Merge attributes from the parameters.
3238 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3239 oe = oldMethod->param_end();
3240 for (ObjCMethodDecl::param_iterator
3241 ni = newMethod->param_begin(), ne = newMethod->param_end();
3242 ni != ne && oi != oe; ++ni, ++oi)
3243 mergeParamDeclAttributes(*ni, *oi, *this);
3245 CheckObjCMethodOverride(newMethod, oldMethod);
3248 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3249 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
3250 /// emitting diagnostics as appropriate.
3252 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3253 /// to here in AddInitializerToDecl. We can't check them before the initializer
3255 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3256 bool MergeTypeWithOld) {
3257 if (New->isInvalidDecl() || Old->isInvalidDecl())
3261 if (getLangOpts().CPlusPlus) {
3262 if (New->getType()->isUndeducedType()) {
3263 // We don't know what the new type is until the initializer is attached.
3265 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3266 // These could still be something that needs exception specs checked.
3267 return MergeVarDeclExceptionSpecs(New, Old);
3269 // C++ [basic.link]p10:
3270 // [...] the types specified by all declarations referring to a given
3271 // object or function shall be identical, except that declarations for an
3272 // array object can specify array types that differ by the presence or
3273 // absence of a major array bound (8.3.4).
3274 else if (Old->getType()->isIncompleteArrayType() &&
3275 New->getType()->isArrayType()) {
3276 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3277 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3278 if (Context.hasSameType(OldArray->getElementType(),
3279 NewArray->getElementType()))
3280 MergedT = New->getType();
3281 } else if (Old->getType()->isArrayType() &&
3282 New->getType()->isIncompleteArrayType()) {
3283 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3284 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3285 if (Context.hasSameType(OldArray->getElementType(),
3286 NewArray->getElementType()))
3287 MergedT = Old->getType();
3288 } else if (New->getType()->isObjCObjectPointerType() &&
3289 Old->getType()->isObjCObjectPointerType()) {
3290 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3295 // All declarations that refer to the same object or function shall have
3297 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3299 if (MergedT.isNull()) {
3300 // It's OK if we couldn't merge types if either type is dependent, for a
3301 // block-scope variable. In other cases (static data members of class
3302 // templates, variable templates, ...), we require the types to be
3304 // FIXME: The C++ standard doesn't say anything about this.
3305 if ((New->getType()->isDependentType() ||
3306 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3307 // If the old type was dependent, we can't merge with it, so the new type
3308 // becomes dependent for now. We'll reproduce the original type when we
3309 // instantiate the TypeSourceInfo for the variable.
3310 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3311 New->setType(Context.DependentTy);
3315 // FIXME: Even if this merging succeeds, some other non-visible declaration
3316 // of this variable might have an incompatible type. For instance:
3318 // extern int arr[];
3319 // void f() { extern int arr[2]; }
3320 // void g() { extern int arr[3]; }
3322 // Neither C nor C++ requires a diagnostic for this, but we should still try
3324 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 Diag(OldLocation, PrevDiag);
3334 return New->setInvalidDecl();
3337 // Don't actually update the type on the new declaration if the old
3338 // declaration was an extern declaration in a different scope.
3339 if (MergeTypeWithOld)
3340 New->setType(MergedT);
3343 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3344 LookupResult &Previous) {
3346 // For an identifier with internal or external linkage declared
3347 // in a scope in which a prior declaration of that identifier is
3348 // visible, if the prior declaration specifies internal or
3349 // external linkage, the type of the identifier at the later
3350 // declaration becomes the composite type.
3352 // If the variable isn't visible, we do not merge with its type.
3353 if (Previous.isShadowed())
3356 if (S.getLangOpts().CPlusPlus) {
3357 // C++11 [dcl.array]p3:
3358 // If there is a preceding declaration of the entity in the same
3359 // scope in which the bound was specified, an omitted array bound
3360 // is taken to be the same as in that earlier declaration.
3361 return NewVD->isPreviousDeclInSameBlockScope() ||
3362 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3363 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3365 // If the old declaration was function-local, don't merge with its
3366 // type unless we're in the same function.
3367 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3368 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3372 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3373 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
3374 /// situation, merging decls or emitting diagnostics as appropriate.
3376 /// Tentative definition rules (C99 6.9.2p2) are checked by
3377 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3378 /// definitions here, since the initializer hasn't been attached.
3380 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3381 // If the new decl is already invalid, don't do any other checking.
3382 if (New->isInvalidDecl())
3385 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3388 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3390 // Verify the old decl was also a variable or variable template.
3391 VarDecl *Old = nullptr;
3392 VarTemplateDecl *OldTemplate = nullptr;
3393 if (Previous.isSingleResult()) {
3395 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3396 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3399 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3400 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3401 return New->setInvalidDecl();
3403 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3406 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3407 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3408 return New->setInvalidDecl();
3412 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3413 << New->getDeclName();
3414 Diag(Previous.getRepresentativeDecl()->getLocation(),
3415 diag::note_previous_definition);
3416 return New->setInvalidDecl();
3419 // Ensure the template parameters are compatible.
3421 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3422 OldTemplate->getTemplateParameters(),
3423 /*Complain=*/true, TPL_TemplateMatch))
3424 return New->setInvalidDecl();
3426 // C++ [class.mem]p1:
3427 // A member shall not be declared twice in the member-specification [...]
3429 // Here, we need only consider static data members.
3430 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3431 Diag(New->getLocation(), diag::err_duplicate_member)
3432 << New->getIdentifier();
3433 Diag(Old->getLocation(), diag::note_previous_declaration);
3434 New->setInvalidDecl();
3437 mergeDeclAttributes(New, Old);
3438 // Warn if an already-declared variable is made a weak_import in a subsequent
3440 if (New->hasAttr<WeakImportAttr>() &&
3441 Old->getStorageClass() == SC_None &&
3442 !Old->hasAttr<WeakImportAttr>()) {
3443 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3444 Diag(Old->getLocation(), diag::note_previous_definition);
3445 // Remove weak_import attribute on new declaration.
3446 New->dropAttr<WeakImportAttr>();
3449 if (New->hasAttr<InternalLinkageAttr>() &&
3450 !Old->hasAttr<InternalLinkageAttr>()) {
3451 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3452 << New->getDeclName();
3453 Diag(Old->getLocation(), diag::note_previous_definition);
3454 New->dropAttr<InternalLinkageAttr>();
3458 VarDecl *MostRecent = Old->getMostRecentDecl();
3459 if (MostRecent != Old) {
3460 MergeVarDeclTypes(New, MostRecent,
3461 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3462 if (New->isInvalidDecl())
3466 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3467 if (New->isInvalidDecl())
3470 diag::kind PrevDiag;
3471 SourceLocation OldLocation;
3472 std::tie(PrevDiag, OldLocation) =
3473 getNoteDiagForInvalidRedeclaration(Old, New);
3475 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3476 if (New->getStorageClass() == SC_Static &&
3477 !New->isStaticDataMember() &&
3478 Old->hasExternalFormalLinkage()) {
3479 if (getLangOpts().MicrosoftExt) {
3480 Diag(New->getLocation(), diag::ext_static_non_static)
3481 << New->getDeclName();
3482 Diag(OldLocation, PrevDiag);
3484 Diag(New->getLocation(), diag::err_static_non_static)
3485 << New->getDeclName();
3486 Diag(OldLocation, PrevDiag);
3487 return New->setInvalidDecl();
3491 // For an identifier declared with the storage-class specifier
3492 // extern in a scope in which a prior declaration of that
3493 // identifier is visible,23) if the prior declaration specifies
3494 // internal or external linkage, the linkage of the identifier at
3495 // the later declaration is the same as the linkage specified at
3496 // the prior declaration. If no prior declaration is visible, or
3497 // if the prior declaration specifies no linkage, then the
3498 // identifier has external linkage.
3499 if (New->hasExternalStorage() && Old->hasLinkage())
3501 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3502 !New->isStaticDataMember() &&
3503 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3504 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3505 Diag(OldLocation, PrevDiag);
3506 return New->setInvalidDecl();
3509 // Check if extern is followed by non-extern and vice-versa.
3510 if (New->hasExternalStorage() &&
3511 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3512 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3513 Diag(OldLocation, PrevDiag);
3514 return New->setInvalidDecl();
3516 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3517 !New->hasExternalStorage()) {
3518 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3519 Diag(OldLocation, PrevDiag);
3520 return New->setInvalidDecl();
3523 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3525 // FIXME: The test for external storage here seems wrong? We still
3526 // need to check for mismatches.
3527 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3528 // Don't complain about out-of-line definitions of static members.
3529 !(Old->getLexicalDeclContext()->isRecord() &&
3530 !New->getLexicalDeclContext()->isRecord())) {
3531 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3532 Diag(OldLocation, PrevDiag);
3533 return New->setInvalidDecl();
3536 if (New->getTLSKind() != Old->getTLSKind()) {
3537 if (!Old->getTLSKind()) {
3538 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3539 Diag(OldLocation, PrevDiag);
3540 } else if (!New->getTLSKind()) {
3541 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3542 Diag(OldLocation, PrevDiag);
3544 // Do not allow redeclaration to change the variable between requiring
3545 // static and dynamic initialization.
3546 // FIXME: GCC allows this, but uses the TLS keyword on the first
3547 // declaration to determine the kind. Do we need to be compatible here?
3548 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3549 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3550 Diag(OldLocation, PrevDiag);
3554 // C++ doesn't have tentative definitions, so go right ahead and check here.
3556 if (getLangOpts().CPlusPlus &&
3557 New->isThisDeclarationADefinition() == VarDecl::Definition &&
3558 (Def = Old->getDefinition())) {
3559 NamedDecl *Hidden = nullptr;
3560 if (!hasVisibleDefinition(Def, &Hidden) &&
3561 (New->getFormalLinkage() == InternalLinkage ||
3562 New->getDescribedVarTemplate() ||
3563 New->getNumTemplateParameterLists() ||
3564 New->getDeclContext()->isDependentContext())) {
3565 // The previous definition is hidden, and multiple definitions are
3566 // permitted (in separate TUs). Form another definition of it.
3568 Diag(New->getLocation(), diag::err_redefinition) << New;
3569 Diag(Def->getLocation(), diag::note_previous_definition);
3570 New->setInvalidDecl();
3575 if (haveIncompatibleLanguageLinkages(Old, New)) {
3576 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3577 Diag(OldLocation, PrevDiag);
3578 New->setInvalidDecl();
3582 // Merge "used" flag.
3583 if (Old->getMostRecentDecl()->isUsed(false))
3586 // Keep a chain of previous declarations.
3587 New->setPreviousDecl(Old);
3589 NewTemplate->setPreviousDecl(OldTemplate);
3591 // Inherit access appropriately.
3592 New->setAccess(Old->getAccess());
3594 NewTemplate->setAccess(New->getAccess());
3597 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3598 /// no declarator (e.g. "struct foo;") is parsed.
3599 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3601 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3604 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3605 // disambiguate entities defined in different scopes.
3606 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3608 // We will pick our mangling number depending on which version of MSVC is being
3610 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3611 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3612 ? S->getMSCurManglingNumber()
3613 : S->getMSLastManglingNumber();
3616 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3617 if (!Context.getLangOpts().CPlusPlus)
3620 if (isa<CXXRecordDecl>(Tag->getParent())) {
3621 // If this tag is the direct child of a class, number it if
3623 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3625 MangleNumberingContext &MCtx =
3626 Context.getManglingNumberContext(Tag->getParent());
3627 Context.setManglingNumber(
3628 Tag, MCtx.getManglingNumber(
3629 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3633 // If this tag isn't a direct child of a class, number it if it is local.
3634 Decl *ManglingContextDecl;
3635 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3636 Tag->getDeclContext(), ManglingContextDecl)) {
3637 Context.setManglingNumber(
3638 Tag, MCtx->getManglingNumber(
3639 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3643 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3644 TypedefNameDecl *NewTD) {
3645 if (TagFromDeclSpec->isInvalidDecl())
3648 // Do nothing if the tag already has a name for linkage purposes.
3649 if (TagFromDeclSpec->hasNameForLinkage())
3652 // A well-formed anonymous tag must always be a TUK_Definition.
3653 assert(TagFromDeclSpec->isThisDeclarationADefinition());
3655 // The type must match the tag exactly; no qualifiers allowed.
3656 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3657 Context.getTagDeclType(TagFromDeclSpec))) {
3658 if (getLangOpts().CPlusPlus)
3659 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3663 // If we've already computed linkage for the anonymous tag, then
3664 // adding a typedef name for the anonymous decl can change that
3665 // linkage, which might be a serious problem. Diagnose this as
3666 // unsupported and ignore the typedef name. TODO: we should
3667 // pursue this as a language defect and establish a formal rule
3668 // for how to handle it.
3669 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3670 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3672 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3673 tagLoc = getLocForEndOfToken(tagLoc);
3675 llvm::SmallString<40> textToInsert;
3676 textToInsert += ' ';
3677 textToInsert += NewTD->getIdentifier()->getName();
3678 Diag(tagLoc, diag::note_typedef_changes_linkage)
3679 << FixItHint::CreateInsertion(tagLoc, textToInsert);
3683 // Otherwise, set this is the anon-decl typedef for the tag.
3684 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3687 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3689 case DeclSpec::TST_class:
3691 case DeclSpec::TST_struct:
3693 case DeclSpec::TST_interface:
3695 case DeclSpec::TST_union:
3697 case DeclSpec::TST_enum:
3700 llvm_unreachable("unexpected type specifier");
3704 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3705 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3706 /// parameters to cope with template friend declarations.
3707 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3709 MultiTemplateParamsArg TemplateParams,
3710 bool IsExplicitInstantiation) {
3711 Decl *TagD = nullptr;
3712 TagDecl *Tag = nullptr;
3713 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3714 DS.getTypeSpecType() == DeclSpec::TST_struct ||
3715 DS.getTypeSpecType() == DeclSpec::TST_interface ||
3716 DS.getTypeSpecType() == DeclSpec::TST_union ||
3717 DS.getTypeSpecType() == DeclSpec::TST_enum) {
3718 TagD = DS.getRepAsDecl();
3720 if (!TagD) // We probably had an error
3723 // Note that the above type specs guarantee that the
3724 // type rep is a Decl, whereas in many of the others
3726 if (isa<TagDecl>(TagD))
3727 Tag = cast<TagDecl>(TagD);
3728 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3729 Tag = CTD->getTemplatedDecl();
3733 handleTagNumbering(Tag, S);
3734 Tag->setFreeStanding();
3735 if (Tag->isInvalidDecl())
3739 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3740 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3741 // or incomplete types shall not be restrict-qualified."
3742 if (TypeQuals & DeclSpec::TQ_restrict)
3743 Diag(DS.getRestrictSpecLoc(),
3744 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3745 << DS.getSourceRange();
3748 if (DS.isConstexprSpecified()) {
3749 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3750 // and definitions of functions and variables.
3752 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3753 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3755 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3756 // Don't emit warnings after this error.
3760 if (DS.isConceptSpecified()) {
3761 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3762 // either a function concept and its definition or a variable concept and
3764 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3768 DiagnoseFunctionSpecifiers(DS);
3770 if (DS.isFriendSpecified()) {
3771 // If we're dealing with a decl but not a TagDecl, assume that
3772 // whatever routines created it handled the friendship aspect.
3775 return ActOnFriendTypeDecl(S, DS, TemplateParams);
3778 const CXXScopeSpec &SS = DS.getTypeSpecScope();
3779 bool IsExplicitSpecialization =
3780 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3781 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3782 !IsExplicitInstantiation && !IsExplicitSpecialization &&
3783 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3784 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3785 // nested-name-specifier unless it is an explicit instantiation
3786 // or an explicit specialization.
3788 // FIXME: We allow class template partial specializations here too, per the
3789 // obvious intent of DR1819.
3791 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3792 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3793 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3797 // Track whether this decl-specifier declares anything.
3798 bool DeclaresAnything = true;
3800 // Handle anonymous struct definitions.
3801 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3802 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3803 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3804 if (getLangOpts().CPlusPlus ||
3805 Record->getDeclContext()->isRecord())
3806 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3807 Context.getPrintingPolicy());
3809 DeclaresAnything = false;
3814 // A struct-declaration that does not declare an anonymous structure or
3815 // anonymous union shall contain a struct-declarator-list.
3817 // This rule also existed in C89 and C99; the grammar for struct-declaration
3818 // did not permit a struct-declaration without a struct-declarator-list.
3819 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3820 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3821 // Check for Microsoft C extension: anonymous struct/union member.
3822 // Handle 2 kinds of anonymous struct/union:
3826 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
3827 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
3828 if ((Tag && Tag->getDeclName()) ||
3829 DS.getTypeSpecType() == DeclSpec::TST_typename) {
3830 RecordDecl *Record = nullptr;
3832 Record = dyn_cast<RecordDecl>(Tag);
3833 else if (const RecordType *RT =
3834 DS.getRepAsType().get()->getAsStructureType())
3835 Record = RT->getDecl();
3836 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3837 Record = UT->getDecl();
3839 if (Record && getLangOpts().MicrosoftExt) {
3840 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3841 << Record->isUnion() << DS.getSourceRange();
3842 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3845 DeclaresAnything = false;
3849 // Skip all the checks below if we have a type error.
3850 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3851 (TagD && TagD->isInvalidDecl()))
3854 if (getLangOpts().CPlusPlus &&
3855 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3856 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3857 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3858 !Enum->getIdentifier() && !Enum->isInvalidDecl())
3859 DeclaresAnything = false;
3861 if (!DS.isMissingDeclaratorOk()) {
3862 // Customize diagnostic for a typedef missing a name.
3863 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3864 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3865 << DS.getSourceRange();
3867 DeclaresAnything = false;
3870 if (DS.isModulePrivateSpecified() &&
3871 Tag && Tag->getDeclContext()->isFunctionOrMethod())
3872 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3873 << Tag->getTagKind()
3874 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3876 ActOnDocumentableDecl(TagD);
3879 // A declaration [...] shall declare at least a declarator [...], a tag,
3880 // or the members of an enumeration.
3882 // [If there are no declarators], and except for the declaration of an
3883 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
3884 // names into the program, or shall redeclare a name introduced by a
3885 // previous declaration.
3886 if (!DeclaresAnything) {
3887 // In C, we allow this as a (popular) extension / bug. Don't bother
3888 // producing further diagnostics for redundant qualifiers after this.
3889 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3894 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3895 // init-declarator-list of the declaration shall not be empty.
3896 // C++ [dcl.fct.spec]p1:
3897 // If a cv-qualifier appears in a decl-specifier-seq, the
3898 // init-declarator-list of the declaration shall not be empty.
3900 // Spurious qualifiers here appear to be valid in C.
3901 unsigned DiagID = diag::warn_standalone_specifier;
3902 if (getLangOpts().CPlusPlus)
3903 DiagID = diag::ext_standalone_specifier;
3905 // Note that a linkage-specification sets a storage class, but
3906 // 'extern "C" struct foo;' is actually valid and not theoretically
3908 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3909 if (SCS == DeclSpec::SCS_mutable)
3910 // Since mutable is not a viable storage class specifier in C, there is
3911 // no reason to treat it as an extension. Instead, diagnose as an error.
3912 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3913 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3914 Diag(DS.getStorageClassSpecLoc(), DiagID)
3915 << DeclSpec::getSpecifierName(SCS);
3918 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3919 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3920 << DeclSpec::getSpecifierName(TSCS);
3921 if (DS.getTypeQualifiers()) {
3922 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3923 Diag(DS.getConstSpecLoc(), DiagID) << "const";
3924 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3925 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3926 // Restrict is covered above.
3927 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3928 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3931 // Warn about ignored type attributes, for example:
3932 // __attribute__((aligned)) struct A;
3933 // Attributes should be placed after tag to apply to type declaration.
3934 if (!DS.getAttributes().empty()) {
3935 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3936 if (TypeSpecType == DeclSpec::TST_class ||
3937 TypeSpecType == DeclSpec::TST_struct ||
3938 TypeSpecType == DeclSpec::TST_interface ||
3939 TypeSpecType == DeclSpec::TST_union ||
3940 TypeSpecType == DeclSpec::TST_enum) {
3941 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3942 attrs = attrs->getNext())
3943 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3944 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3951 /// We are trying to inject an anonymous member into the given scope;
3952 /// check if there's an existing declaration that can't be overloaded.
3954 /// \return true if this is a forbidden redeclaration
3955 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3958 DeclarationName Name,
3959 SourceLocation NameLoc,
3961 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3962 Sema::ForRedeclaration);
3963 if (!SemaRef.LookupName(R, S)) return false;
3965 if (R.getAsSingle<TagDecl>())
3968 // Pick a representative declaration.
3969 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3970 assert(PrevDecl && "Expected a non-null Decl");
3972 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3975 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3977 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3982 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3983 /// anonymous struct or union AnonRecord into the owning context Owner
3984 /// and scope S. This routine will be invoked just after we realize
3985 /// that an unnamed union or struct is actually an anonymous union or
3992 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3993 /// // f into the surrounding scope.x
3996 /// This routine is recursive, injecting the names of nested anonymous
3997 /// structs/unions into the owning context and scope as well.
3998 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
4000 RecordDecl *AnonRecord,
4002 SmallVectorImpl<NamedDecl *> &Chaining,
4003 bool MSAnonStruct) {
4004 bool Invalid = false;
4006 // Look every FieldDecl and IndirectFieldDecl with a name.
4007 for (auto *D : AnonRecord->decls()) {
4008 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4009 cast<NamedDecl>(D)->getDeclName()) {
4010 ValueDecl *VD = cast<ValueDecl>(D);
4011 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4013 AnonRecord->isUnion())) {
4014 // C++ [class.union]p2:
4015 // The names of the members of an anonymous union shall be
4016 // distinct from the names of any other entity in the
4017 // scope in which the anonymous union is declared.
4020 // C++ [class.union]p2:
4021 // For the purpose of name lookup, after the anonymous union
4022 // definition, the members of the anonymous union are
4023 // considered to have been defined in the scope in which the
4024 // anonymous union is declared.
4025 unsigned OldChainingSize = Chaining.size();
4026 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4027 Chaining.append(IF->chain_begin(), IF->chain_end());
4029 Chaining.push_back(VD);
4031 assert(Chaining.size() >= 2);
4032 NamedDecl **NamedChain =
4033 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4034 for (unsigned i = 0; i < Chaining.size(); i++)
4035 NamedChain[i] = Chaining[i];
4037 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4038 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4039 VD->getType(), NamedChain, Chaining.size());
4041 for (const auto *Attr : VD->attrs())
4042 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4044 IndirectField->setAccess(AS);
4045 IndirectField->setImplicit();
4046 SemaRef.PushOnScopeChains(IndirectField, S);
4048 // That includes picking up the appropriate access specifier.
4049 if (AS != AS_none) IndirectField->setAccess(AS);
4051 Chaining.resize(OldChainingSize);
4059 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4060 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4061 /// illegal input values are mapped to SC_None.
4063 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4064 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4065 assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4066 "Parser allowed 'typedef' as storage class VarDecl.");
4067 switch (StorageClassSpec) {
4068 case DeclSpec::SCS_unspecified: return SC_None;
4069 case DeclSpec::SCS_extern:
4070 if (DS.isExternInLinkageSpec())
4073 case DeclSpec::SCS_static: return SC_Static;
4074 case DeclSpec::SCS_auto: return SC_Auto;
4075 case DeclSpec::SCS_register: return SC_Register;
4076 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4077 // Illegal SCSs map to None: error reporting is up to the caller.
4078 case DeclSpec::SCS_mutable: // Fall through.
4079 case DeclSpec::SCS_typedef: return SC_None;
4081 llvm_unreachable("unknown storage class specifier");
4084 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4085 assert(Record->hasInClassInitializer());
4087 for (const auto *I : Record->decls()) {
4088 const auto *FD = dyn_cast<FieldDecl>(I);
4089 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4090 FD = IFD->getAnonField();
4091 if (FD && FD->hasInClassInitializer())
4092 return FD->getLocation();
4095 llvm_unreachable("couldn't find in-class initializer");
4098 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4099 SourceLocation DefaultInitLoc) {
4100 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4103 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4104 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4107 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4108 CXXRecordDecl *AnonUnion) {
4109 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4112 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4115 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4116 /// anonymous structure or union. Anonymous unions are a C++ feature
4117 /// (C++ [class.union]) and a C11 feature; anonymous structures
4118 /// are a C11 feature and GNU C++ extension.
4119 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4122 const PrintingPolicy &Policy) {
4123 DeclContext *Owner = Record->getDeclContext();
4125 // Diagnose whether this anonymous struct/union is an extension.
4126 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4127 Diag(Record->getLocation(), diag::ext_anonymous_union);
4128 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4129 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4130 else if (!Record->isUnion() && !getLangOpts().C11)
4131 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4133 // C and C++ require different kinds of checks for anonymous
4135 bool Invalid = false;
4136 if (getLangOpts().CPlusPlus) {
4137 const char *PrevSpec = nullptr;
4139 if (Record->isUnion()) {
4140 // C++ [class.union]p6:
4141 // Anonymous unions declared in a named namespace or in the
4142 // global namespace shall be declared static.
4143 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4144 (isa<TranslationUnitDecl>(Owner) ||
4145 (isa<NamespaceDecl>(Owner) &&
4146 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4147 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4148 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4150 // Recover by adding 'static'.
4151 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4152 PrevSpec, DiagID, Policy);
4154 // C++ [class.union]p6:
4155 // A storage class is not allowed in a declaration of an
4156 // anonymous union in a class scope.
4157 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4158 isa<RecordDecl>(Owner)) {
4159 Diag(DS.getStorageClassSpecLoc(),
4160 diag::err_anonymous_union_with_storage_spec)
4161 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4163 // Recover by removing the storage specifier.
4164 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4166 PrevSpec, DiagID, Context.getPrintingPolicy());
4170 // Ignore const/volatile/restrict qualifiers.
4171 if (DS.getTypeQualifiers()) {
4172 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4173 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4174 << Record->isUnion() << "const"
4175 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4176 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4177 Diag(DS.getVolatileSpecLoc(),
4178 diag::ext_anonymous_struct_union_qualified)
4179 << Record->isUnion() << "volatile"
4180 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4181 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4182 Diag(DS.getRestrictSpecLoc(),
4183 diag::ext_anonymous_struct_union_qualified)
4184 << Record->isUnion() << "restrict"
4185 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4186 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4187 Diag(DS.getAtomicSpecLoc(),
4188 diag::ext_anonymous_struct_union_qualified)
4189 << Record->isUnion() << "_Atomic"
4190 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4192 DS.ClearTypeQualifiers();
4195 // C++ [class.union]p2:
4196 // The member-specification of an anonymous union shall only
4197 // define non-static data members. [Note: nested types and
4198 // functions cannot be declared within an anonymous union. ]
4199 for (auto *Mem : Record->decls()) {
4200 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4201 // C++ [class.union]p3:
4202 // An anonymous union shall not have private or protected
4203 // members (clause 11).
4204 assert(FD->getAccess() != AS_none);
4205 if (FD->getAccess() != AS_public) {
4206 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4207 << Record->isUnion() << (FD->getAccess() == AS_protected);
4211 // C++ [class.union]p1
4212 // An object of a class with a non-trivial constructor, a non-trivial
4213 // copy constructor, a non-trivial destructor, or a non-trivial copy
4214 // assignment operator cannot be a member of a union, nor can an
4215 // array of such objects.
4216 if (CheckNontrivialField(FD))
4218 } else if (Mem->isImplicit()) {
4219 // Any implicit members are fine.
4220 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4221 // This is a type that showed up in an
4222 // elaborated-type-specifier inside the anonymous struct or
4223 // union, but which actually declares a type outside of the
4224 // anonymous struct or union. It's okay.
4225 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4226 if (!MemRecord->isAnonymousStructOrUnion() &&
4227 MemRecord->getDeclName()) {
4228 // Visual C++ allows type definition in anonymous struct or union.
4229 if (getLangOpts().MicrosoftExt)
4230 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4231 << Record->isUnion();
4233 // This is a nested type declaration.
4234 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4235 << Record->isUnion();
4239 // This is an anonymous type definition within another anonymous type.
4240 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4241 // not part of standard C++.
4242 Diag(MemRecord->getLocation(),
4243 diag::ext_anonymous_record_with_anonymous_type)
4244 << Record->isUnion();
4246 } else if (isa<AccessSpecDecl>(Mem)) {
4247 // Any access specifier is fine.
4248 } else if (isa<StaticAssertDecl>(Mem)) {
4249 // In C++1z, static_assert declarations are also fine.
4251 // We have something that isn't a non-static data
4252 // member. Complain about it.
4253 unsigned DK = diag::err_anonymous_record_bad_member;
4254 if (isa<TypeDecl>(Mem))
4255 DK = diag::err_anonymous_record_with_type;
4256 else if (isa<FunctionDecl>(Mem))
4257 DK = diag::err_anonymous_record_with_function;
4258 else if (isa<VarDecl>(Mem))
4259 DK = diag::err_anonymous_record_with_static;
4261 // Visual C++ allows type definition in anonymous struct or union.
4262 if (getLangOpts().MicrosoftExt &&
4263 DK == diag::err_anonymous_record_with_type)
4264 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4265 << Record->isUnion();
4267 Diag(Mem->getLocation(), DK) << Record->isUnion();
4273 // C++11 [class.union]p8 (DR1460):
4274 // At most one variant member of a union may have a
4275 // brace-or-equal-initializer.
4276 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4278 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4279 cast<CXXRecordDecl>(Record));
4282 if (!Record->isUnion() && !Owner->isRecord()) {
4283 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4284 << getLangOpts().CPlusPlus;
4288 // Mock up a declarator.
4289 Declarator Dc(DS, Declarator::MemberContext);
4290 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4291 assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4293 // Create a declaration for this anonymous struct/union.
4294 NamedDecl *Anon = nullptr;
4295 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4296 Anon = FieldDecl::Create(Context, OwningClass,
4298 Record->getLocation(),
4299 /*IdentifierInfo=*/nullptr,
4300 Context.getTypeDeclType(Record),
4302 /*BitWidth=*/nullptr, /*Mutable=*/false,
4303 /*InitStyle=*/ICIS_NoInit);
4304 Anon->setAccess(AS);
4305 if (getLangOpts().CPlusPlus)
4306 FieldCollector->Add(cast<FieldDecl>(Anon));
4308 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4309 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4310 if (SCSpec == DeclSpec::SCS_mutable) {
4311 // mutable can only appear on non-static class members, so it's always
4313 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4318 Anon = VarDecl::Create(Context, Owner,
4320 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4321 Context.getTypeDeclType(Record),
4324 // Default-initialize the implicit variable. This initialization will be
4325 // trivial in almost all cases, except if a union member has an in-class
4327 // union { int n = 0; };
4328 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4330 Anon->setImplicit();
4332 // Mark this as an anonymous struct/union type.
4333 Record->setAnonymousStructOrUnion(true);
4335 // Add the anonymous struct/union object to the current
4336 // context. We'll be referencing this object when we refer to one of
4338 Owner->addDecl(Anon);
4340 // Inject the members of the anonymous struct/union into the owning
4341 // context and into the identifier resolver chain for name lookup
4343 SmallVector<NamedDecl*, 2> Chain;
4344 Chain.push_back(Anon);
4346 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4350 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4351 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4352 Decl *ManglingContextDecl;
4353 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4354 NewVD->getDeclContext(), ManglingContextDecl)) {
4355 Context.setManglingNumber(
4356 NewVD, MCtx->getManglingNumber(
4357 NewVD, getMSManglingNumber(getLangOpts(), S)));
4358 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4364 Anon->setInvalidDecl();
4369 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4370 /// Microsoft C anonymous structure.
4371 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4374 /// struct A { int a; };
4375 /// struct B { struct A; int b; };
4382 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4383 RecordDecl *Record) {
4384 assert(Record && "expected a record!");
4386 // Mock up a declarator.
4387 Declarator Dc(DS, Declarator::TypeNameContext);
4388 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4389 assert(TInfo && "couldn't build declarator info for anonymous struct");
4391 auto *ParentDecl = cast<RecordDecl>(CurContext);
4392 QualType RecTy = Context.getTypeDeclType(Record);
4394 // Create a declaration for this anonymous struct.
4395 NamedDecl *Anon = FieldDecl::Create(Context,
4399 /*IdentifierInfo=*/nullptr,
4402 /*BitWidth=*/nullptr, /*Mutable=*/false,
4403 /*InitStyle=*/ICIS_NoInit);
4404 Anon->setImplicit();
4406 // Add the anonymous struct object to the current context.
4407 CurContext->addDecl(Anon);
4409 // Inject the members of the anonymous struct into the current
4410 // context and into the identifier resolver chain for name lookup
4412 SmallVector<NamedDecl*, 2> Chain;
4413 Chain.push_back(Anon);
4415 RecordDecl *RecordDef = Record->getDefinition();
4416 if (RequireCompleteType(Anon->getLocation(), RecTy,
4417 diag::err_field_incomplete) ||
4418 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4419 AS_none, Chain, true)) {
4420 Anon->setInvalidDecl();
4421 ParentDecl->setInvalidDecl();
4427 /// GetNameForDeclarator - Determine the full declaration name for the
4428 /// given Declarator.
4429 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4430 return GetNameFromUnqualifiedId(D.getName());
4433 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4435 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4436 DeclarationNameInfo NameInfo;
4437 NameInfo.setLoc(Name.StartLocation);
4439 switch (Name.getKind()) {
4441 case UnqualifiedId::IK_ImplicitSelfParam:
4442 case UnqualifiedId::IK_Identifier:
4443 NameInfo.setName(Name.Identifier);
4444 NameInfo.setLoc(Name.StartLocation);
4447 case UnqualifiedId::IK_OperatorFunctionId:
4448 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4449 Name.OperatorFunctionId.Operator));
4450 NameInfo.setLoc(Name.StartLocation);
4451 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4452 = Name.OperatorFunctionId.SymbolLocations[0];
4453 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4454 = Name.EndLocation.getRawEncoding();
4457 case UnqualifiedId::IK_LiteralOperatorId:
4458 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4460 NameInfo.setLoc(Name.StartLocation);
4461 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4464 case UnqualifiedId::IK_ConversionFunctionId: {
4465 TypeSourceInfo *TInfo;
4466 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4468 return DeclarationNameInfo();
4469 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4470 Context.getCanonicalType(Ty)));
4471 NameInfo.setLoc(Name.StartLocation);
4472 NameInfo.setNamedTypeInfo(TInfo);
4476 case UnqualifiedId::IK_ConstructorName: {
4477 TypeSourceInfo *TInfo;
4478 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4480 return DeclarationNameInfo();
4481 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4482 Context.getCanonicalType(Ty)));
4483 NameInfo.setLoc(Name.StartLocation);
4484 NameInfo.setNamedTypeInfo(TInfo);
4488 case UnqualifiedId::IK_ConstructorTemplateId: {
4489 // In well-formed code, we can only have a constructor
4490 // template-id that refers to the current context, so go there
4491 // to find the actual type being constructed.
4492 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4493 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4494 return DeclarationNameInfo();
4496 // Determine the type of the class being constructed.
4497 QualType CurClassType = Context.getTypeDeclType(CurClass);
4499 // FIXME: Check two things: that the template-id names the same type as
4500 // CurClassType, and that the template-id does not occur when the name
4503 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4504 Context.getCanonicalType(CurClassType)));
4505 NameInfo.setLoc(Name.StartLocation);
4506 // FIXME: should we retrieve TypeSourceInfo?
4507 NameInfo.setNamedTypeInfo(nullptr);
4511 case UnqualifiedId::IK_DestructorName: {
4512 TypeSourceInfo *TInfo;
4513 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4515 return DeclarationNameInfo();
4516 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4517 Context.getCanonicalType(Ty)));
4518 NameInfo.setLoc(Name.StartLocation);
4519 NameInfo.setNamedTypeInfo(TInfo);
4523 case UnqualifiedId::IK_TemplateId: {
4524 TemplateName TName = Name.TemplateId->Template.get();
4525 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4526 return Context.getNameForTemplate(TName, TNameLoc);
4529 } // switch (Name.getKind())
4531 llvm_unreachable("Unknown name kind");
4534 static QualType getCoreType(QualType Ty) {
4536 if (Ty->isPointerType() || Ty->isReferenceType())
4537 Ty = Ty->getPointeeType();
4538 else if (Ty->isArrayType())
4539 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4541 return Ty.withoutLocalFastQualifiers();
4545 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4546 /// and Definition have "nearly" matching parameters. This heuristic is
4547 /// used to improve diagnostics in the case where an out-of-line function
4548 /// definition doesn't match any declaration within the class or namespace.
4549 /// Also sets Params to the list of indices to the parameters that differ
4550 /// between the declaration and the definition. If hasSimilarParameters
4551 /// returns true and Params is empty, then all of the parameters match.
4552 static bool hasSimilarParameters(ASTContext &Context,
4553 FunctionDecl *Declaration,
4554 FunctionDecl *Definition,
4555 SmallVectorImpl<unsigned> &Params) {
4557 if (Declaration->param_size() != Definition->param_size())
4559 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4560 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4561 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4563 // The parameter types are identical
4564 if (Context.hasSameType(DefParamTy, DeclParamTy))
4567 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4568 QualType DefParamBaseTy = getCoreType(DefParamTy);
4569 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4570 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4572 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4573 (DeclTyName && DeclTyName == DefTyName))
4574 Params.push_back(Idx);
4575 else // The two parameters aren't even close
4582 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4583 /// declarator needs to be rebuilt in the current instantiation.
4584 /// Any bits of declarator which appear before the name are valid for
4585 /// consideration here. That's specifically the type in the decl spec
4586 /// and the base type in any member-pointer chunks.
4587 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4588 DeclarationName Name) {
4589 // The types we specifically need to rebuild are:
4590 // - typenames, typeofs, and decltypes
4591 // - types which will become injected class names
4592 // Of course, we also need to rebuild any type referencing such a
4593 // type. It's safest to just say "dependent", but we call out a
4596 DeclSpec &DS = D.getMutableDeclSpec();
4597 switch (DS.getTypeSpecType()) {
4598 case DeclSpec::TST_typename:
4599 case DeclSpec::TST_typeofType:
4600 case DeclSpec::TST_underlyingType:
4601 case DeclSpec::TST_atomic: {
4602 // Grab the type from the parser.
4603 TypeSourceInfo *TSI = nullptr;
4604 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4605 if (T.isNull() || !T->isDependentType()) break;
4607 // Make sure there's a type source info. This isn't really much
4608 // of a waste; most dependent types should have type source info
4609 // attached already.
4611 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4613 // Rebuild the type in the current instantiation.
4614 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4615 if (!TSI) return true;
4617 // Store the new type back in the decl spec.
4618 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4619 DS.UpdateTypeRep(LocType);
4623 case DeclSpec::TST_decltype:
4624 case DeclSpec::TST_typeofExpr: {
4625 Expr *E = DS.getRepAsExpr();
4626 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4627 if (Result.isInvalid()) return true;
4628 DS.UpdateExprRep(Result.get());
4633 // Nothing to do for these decl specs.
4637 // It doesn't matter what order we do this in.
4638 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4639 DeclaratorChunk &Chunk = D.getTypeObject(I);
4641 // The only type information in the declarator which can come
4642 // before the declaration name is the base type of a member
4644 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4647 // Rebuild the scope specifier in-place.
4648 CXXScopeSpec &SS = Chunk.Mem.Scope();
4649 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4656 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4657 D.setFunctionDefinitionKind(FDK_Declaration);
4658 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4660 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4661 Dcl && Dcl->getDeclContext()->isFileContext())
4662 Dcl->setTopLevelDeclInObjCContainer();
4667 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4668 /// If T is the name of a class, then each of the following shall have a
4669 /// name different from T:
4670 /// - every static data member of class T;
4671 /// - every member function of class T
4672 /// - every member of class T that is itself a type;
4673 /// \returns true if the declaration name violates these rules.
4674 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4675 DeclarationNameInfo NameInfo) {
4676 DeclarationName Name = NameInfo.getName();
4678 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4679 if (Record->getIdentifier() && Record->getDeclName() == Name) {
4680 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4687 /// \brief Diagnose a declaration whose declarator-id has the given
4688 /// nested-name-specifier.
4690 /// \param SS The nested-name-specifier of the declarator-id.
4692 /// \param DC The declaration context to which the nested-name-specifier
4695 /// \param Name The name of the entity being declared.
4697 /// \param Loc The location of the name of the entity being declared.
4699 /// \returns true if we cannot safely recover from this error, false otherwise.
4700 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4701 DeclarationName Name,
4702 SourceLocation Loc) {
4703 DeclContext *Cur = CurContext;
4704 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4705 Cur = Cur->getParent();
4707 // If the user provided a superfluous scope specifier that refers back to the
4708 // class in which the entity is already declared, diagnose and ignore it.
4714 // Note, it was once ill-formed to give redundant qualification in all
4715 // contexts, but that rule was removed by DR482.
4716 if (Cur->Equals(DC)) {
4717 if (Cur->isRecord()) {
4718 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4719 : diag::err_member_extra_qualification)
4720 << Name << FixItHint::CreateRemoval(SS.getRange());
4723 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4728 // Check whether the qualifying scope encloses the scope of the original
4730 if (!Cur->Encloses(DC)) {
4731 if (Cur->isRecord())
4732 Diag(Loc, diag::err_member_qualification)
4733 << Name << SS.getRange();
4734 else if (isa<TranslationUnitDecl>(DC))
4735 Diag(Loc, diag::err_invalid_declarator_global_scope)
4736 << Name << SS.getRange();
4737 else if (isa<FunctionDecl>(Cur))
4738 Diag(Loc, diag::err_invalid_declarator_in_function)
4739 << Name << SS.getRange();
4740 else if (isa<BlockDecl>(Cur))
4741 Diag(Loc, diag::err_invalid_declarator_in_block)
4742 << Name << SS.getRange();
4744 Diag(Loc, diag::err_invalid_declarator_scope)
4745 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4750 if (Cur->isRecord()) {
4751 // Cannot qualify members within a class.
4752 Diag(Loc, diag::err_member_qualification)
4753 << Name << SS.getRange();
4756 // C++ constructors and destructors with incorrect scopes can break
4757 // our AST invariants by having the wrong underlying types. If
4758 // that's the case, then drop this declaration entirely.
4759 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4760 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4761 !Context.hasSameType(Name.getCXXNameType(),
4762 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4768 // C++11 [dcl.meaning]p1:
4769 // [...] "The nested-name-specifier of the qualified declarator-id shall
4770 // not begin with a decltype-specifer"
4771 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4772 while (SpecLoc.getPrefix())
4773 SpecLoc = SpecLoc.getPrefix();
4774 if (dyn_cast_or_null<DecltypeType>(
4775 SpecLoc.getNestedNameSpecifier()->getAsType()))
4776 Diag(Loc, diag::err_decltype_in_declarator)
4777 << SpecLoc.getTypeLoc().getSourceRange();
4782 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4783 MultiTemplateParamsArg TemplateParamLists) {
4784 // TODO: consider using NameInfo for diagnostic.
4785 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4786 DeclarationName Name = NameInfo.getName();
4788 // All of these full declarators require an identifier. If it doesn't have
4789 // one, the ParsedFreeStandingDeclSpec action should be used.
4791 if (!D.isInvalidType()) // Reject this if we think it is valid.
4792 Diag(D.getDeclSpec().getLocStart(),
4793 diag::err_declarator_need_ident)
4794 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4796 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4799 // The scope passed in may not be a decl scope. Zip up the scope tree until
4800 // we find one that is.
4801 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4802 (S->getFlags() & Scope::TemplateParamScope) != 0)
4805 DeclContext *DC = CurContext;
4806 if (D.getCXXScopeSpec().isInvalid())
4808 else if (D.getCXXScopeSpec().isSet()) {
4809 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4810 UPPC_DeclarationQualifier))
4813 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4814 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4815 if (!DC || isa<EnumDecl>(DC)) {
4816 // If we could not compute the declaration context, it's because the
4817 // declaration context is dependent but does not refer to a class,
4818 // class template, or class template partial specialization. Complain
4819 // and return early, to avoid the coming semantic disaster.
4820 Diag(D.getIdentifierLoc(),
4821 diag::err_template_qualified_declarator_no_match)
4822 << D.getCXXScopeSpec().getScopeRep()
4823 << D.getCXXScopeSpec().getRange();
4826 bool IsDependentContext = DC->isDependentContext();
4828 if (!IsDependentContext &&
4829 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4832 // If a class is incomplete, do not parse entities inside it.
4833 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4834 Diag(D.getIdentifierLoc(),
4835 diag::err_member_def_undefined_record)
4836 << Name << DC << D.getCXXScopeSpec().getRange();
4839 if (!D.getDeclSpec().isFriendSpecified()) {
4840 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4841 Name, D.getIdentifierLoc())) {
4849 // Check whether we need to rebuild the type of the given
4850 // declaration in the current instantiation.
4851 if (EnteringContext && IsDependentContext &&
4852 TemplateParamLists.size() != 0) {
4853 ContextRAII SavedContext(*this, DC);
4854 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4859 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4860 QualType R = TInfo->getType();
4862 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4863 // If this is a typedef, we'll end up spewing multiple diagnostics.
4864 // Just return early; it's safer. If this is a function, let the
4865 // "constructor cannot have a return type" diagnostic handle it.
4866 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4869 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4870 UPPC_DeclarationType))
4873 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4876 // See if this is a redefinition of a variable in the same scope.
4877 if (!D.getCXXScopeSpec().isSet()) {
4878 bool IsLinkageLookup = false;
4879 bool CreateBuiltins = false;
4881 // If the declaration we're planning to build will be a function
4882 // or object with linkage, then look for another declaration with
4883 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4885 // If the declaration we're planning to build will be declared with
4886 // external linkage in the translation unit, create any builtin with
4888 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4890 else if (CurContext->isFunctionOrMethod() &&
4891 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4892 R->isFunctionType())) {
4893 IsLinkageLookup = true;
4895 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4896 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4897 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4898 CreateBuiltins = true;
4900 if (IsLinkageLookup)
4901 Previous.clear(LookupRedeclarationWithLinkage);
4903 LookupName(Previous, S, CreateBuiltins);
4904 } else { // Something like "int foo::x;"
4905 LookupQualifiedName(Previous, DC);
4907 // C++ [dcl.meaning]p1:
4908 // When the declarator-id is qualified, the declaration shall refer to a
4909 // previously declared member of the class or namespace to which the
4910 // qualifier refers (or, in the case of a namespace, of an element of the
4911 // inline namespace set of that namespace (7.3.1)) or to a specialization
4914 // Note that we already checked the context above, and that we do not have
4915 // enough information to make sure that Previous contains the declaration
4916 // we want to match. For example, given:
4923 // void X::f(int) { } // ill-formed
4925 // In this case, Previous will point to the overload set
4926 // containing the two f's declared in X, but neither of them
4929 // C++ [dcl.meaning]p1:
4930 // [...] the member shall not merely have been introduced by a
4931 // using-declaration in the scope of the class or namespace nominated by
4932 // the nested-name-specifier of the declarator-id.
4933 RemoveUsingDecls(Previous);
4936 if (Previous.isSingleResult() &&
4937 Previous.getFoundDecl()->isTemplateParameter()) {
4938 // Maybe we will complain about the shadowed template parameter.
4939 if (!D.isInvalidType())
4940 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4941 Previous.getFoundDecl());
4943 // Just pretend that we didn't see the previous declaration.
4947 // In C++, the previous declaration we find might be a tag type
4948 // (class or enum). In this case, the new declaration will hide the
4949 // tag type. Note that this does does not apply if we're declaring a
4950 // typedef (C++ [dcl.typedef]p4).
4951 if (Previous.isSingleTagDecl() &&
4952 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4955 // Check that there are no default arguments other than in the parameters
4956 // of a function declaration (C++ only).
4957 if (getLangOpts().CPlusPlus)
4958 CheckExtraCXXDefaultArguments(D);
4960 if (D.getDeclSpec().isConceptSpecified()) {
4961 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4962 // applied only to the definition of a function template or variable
4963 // template, declared in namespace scope
4964 if (!TemplateParamLists.size()) {
4965 Diag(D.getDeclSpec().getConceptSpecLoc(),
4966 diag:: err_concept_wrong_decl_kind);
4970 if (!DC->getRedeclContext()->isFileContext()) {
4971 Diag(D.getIdentifierLoc(),
4972 diag::err_concept_decls_may_only_appear_in_namespace_scope);
4979 bool AddToScope = true;
4980 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4981 if (TemplateParamLists.size()) {
4982 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4986 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4987 } else if (R->isFunctionType()) {
4988 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4992 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4999 // If this has an identifier and is not an invalid redeclaration or
5000 // function template specialization, add it to the scope stack.
5001 if (New->getDeclName() && AddToScope &&
5002 !(D.isRedeclaration() && New->isInvalidDecl())) {
5003 // Only make a locally-scoped extern declaration visible if it is the first
5004 // declaration of this entity. Qualified lookup for such an entity should
5005 // only find this declaration if there is no visible declaration of it.
5006 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5007 PushOnScopeChains(New, S, AddToContext);
5009 CurContext->addHiddenDecl(New);
5015 /// Helper method to turn variable array types into constant array
5016 /// types in certain situations which would otherwise be errors (for
5017 /// GCC compatibility).
5018 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5019 ASTContext &Context,
5020 bool &SizeIsNegative,
5021 llvm::APSInt &Oversized) {
5022 // This method tries to turn a variable array into a constant
5023 // array even when the size isn't an ICE. This is necessary
5024 // for compatibility with code that depends on gcc's buggy
5025 // constant expression folding, like struct {char x[(int)(char*)2];}
5026 SizeIsNegative = false;
5029 if (T->isDependentType())
5032 QualifierCollector Qs;
5033 const Type *Ty = Qs.strip(T);
5035 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5036 QualType Pointee = PTy->getPointeeType();
5037 QualType FixedType =
5038 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5040 if (FixedType.isNull()) return FixedType;
5041 FixedType = Context.getPointerType(FixedType);
5042 return Qs.apply(Context, FixedType);
5044 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5045 QualType Inner = PTy->getInnerType();
5046 QualType FixedType =
5047 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5049 if (FixedType.isNull()) return FixedType;
5050 FixedType = Context.getParenType(FixedType);
5051 return Qs.apply(Context, FixedType);
5054 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5057 // FIXME: We should probably handle this case
5058 if (VLATy->getElementType()->isVariablyModifiedType())
5062 if (!VLATy->getSizeExpr() ||
5063 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5066 // Check whether the array size is negative.
5067 if (Res.isSigned() && Res.isNegative()) {
5068 SizeIsNegative = true;
5072 // Check whether the array is too large to be addressed.
5073 unsigned ActiveSizeBits
5074 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5076 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5081 return Context.getConstantArrayType(VLATy->getElementType(),
5082 Res, ArrayType::Normal, 0);
5086 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5087 SrcTL = SrcTL.getUnqualifiedLoc();
5088 DstTL = DstTL.getUnqualifiedLoc();
5089 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5090 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5091 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5092 DstPTL.getPointeeLoc());
5093 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5096 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5097 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5098 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5099 DstPTL.getInnerLoc());
5100 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5101 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5104 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5105 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5106 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5107 TypeLoc DstElemTL = DstATL.getElementLoc();
5108 DstElemTL.initializeFullCopy(SrcElemTL);
5109 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5110 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5111 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5114 /// Helper method to turn variable array types into constant array
5115 /// types in certain situations which would otherwise be errors (for
5116 /// GCC compatibility).
5117 static TypeSourceInfo*
5118 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5119 ASTContext &Context,
5120 bool &SizeIsNegative,
5121 llvm::APSInt &Oversized) {
5123 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5124 SizeIsNegative, Oversized);
5125 if (FixedTy.isNull())
5127 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5128 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5129 FixedTInfo->getTypeLoc());
5133 /// \brief Register the given locally-scoped extern "C" declaration so
5134 /// that it can be found later for redeclarations. We include any extern "C"
5135 /// declaration that is not visible in the translation unit here, not just
5136 /// function-scope declarations.
5138 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5139 if (!getLangOpts().CPlusPlus &&
5140 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5141 // Don't need to track declarations in the TU in C.
5144 // Note that we have a locally-scoped external with this name.
5145 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5148 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5149 // FIXME: We can have multiple results via __attribute__((overloadable)).
5150 auto Result = Context.getExternCContextDecl()->lookup(Name);
5151 return Result.empty() ? nullptr : *Result.begin();
5154 /// \brief Diagnose function specifiers on a declaration of an identifier that
5155 /// does not identify a function.
5156 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5157 // FIXME: We should probably indicate the identifier in question to avoid
5158 // confusion for constructs like "inline int a(), b;"
5159 if (DS.isInlineSpecified())
5160 Diag(DS.getInlineSpecLoc(),
5161 diag::err_inline_non_function);
5163 if (DS.isVirtualSpecified())
5164 Diag(DS.getVirtualSpecLoc(),
5165 diag::err_virtual_non_function);
5167 if (DS.isExplicitSpecified())
5168 Diag(DS.getExplicitSpecLoc(),
5169 diag::err_explicit_non_function);
5171 if (DS.isNoreturnSpecified())
5172 Diag(DS.getNoreturnSpecLoc(),
5173 diag::err_noreturn_non_function);
5177 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5178 TypeSourceInfo *TInfo, LookupResult &Previous) {
5179 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5180 if (D.getCXXScopeSpec().isSet()) {
5181 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5182 << D.getCXXScopeSpec().getRange();
5184 // Pretend we didn't see the scope specifier.
5189 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5191 if (D.getDeclSpec().isConstexprSpecified())
5192 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5194 if (D.getDeclSpec().isConceptSpecified())
5195 Diag(D.getDeclSpec().getConceptSpecLoc(),
5196 diag::err_concept_wrong_decl_kind);
5198 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5199 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5200 << D.getName().getSourceRange();
5204 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5205 if (!NewTD) return nullptr;
5207 // Handle attributes prior to checking for duplicates in MergeVarDecl
5208 ProcessDeclAttributes(S, NewTD, D);
5210 CheckTypedefForVariablyModifiedType(S, NewTD);
5212 bool Redeclaration = D.isRedeclaration();
5213 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5214 D.setRedeclaration(Redeclaration);
5219 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5220 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5221 // then it shall have block scope.
5222 // Note that variably modified types must be fixed before merging the decl so
5223 // that redeclarations will match.
5224 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5225 QualType T = TInfo->getType();
5226 if (T->isVariablyModifiedType()) {
5227 getCurFunction()->setHasBranchProtectedScope();
5229 if (S->getFnParent() == nullptr) {
5230 bool SizeIsNegative;
5231 llvm::APSInt Oversized;
5232 TypeSourceInfo *FixedTInfo =
5233 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5237 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5238 NewTD->setTypeSourceInfo(FixedTInfo);
5241 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5242 else if (T->isVariableArrayType())
5243 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5244 else if (Oversized.getBoolValue())
5245 Diag(NewTD->getLocation(), diag::err_array_too_large)
5246 << Oversized.toString(10);
5248 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5249 NewTD->setInvalidDecl();
5256 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5257 /// declares a typedef-name, either using the 'typedef' type specifier or via
5258 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5260 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5261 LookupResult &Previous, bool &Redeclaration) {
5262 // Merge the decl with the existing one if appropriate. If the decl is
5263 // in an outer scope, it isn't the same thing.
5264 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5265 /*AllowInlineNamespace*/false);
5266 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5267 if (!Previous.empty()) {
5268 Redeclaration = true;
5269 MergeTypedefNameDecl(S, NewTD, Previous);
5272 // If this is the C FILE type, notify the AST context.
5273 if (IdentifierInfo *II = NewTD->getIdentifier())
5274 if (!NewTD->isInvalidDecl() &&
5275 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5276 if (II->isStr("FILE"))
5277 Context.setFILEDecl(NewTD);
5278 else if (II->isStr("jmp_buf"))
5279 Context.setjmp_bufDecl(NewTD);
5280 else if (II->isStr("sigjmp_buf"))
5281 Context.setsigjmp_bufDecl(NewTD);
5282 else if (II->isStr("ucontext_t"))
5283 Context.setucontext_tDecl(NewTD);
5289 /// \brief Determines whether the given declaration is an out-of-scope
5290 /// previous declaration.
5292 /// This routine should be invoked when name lookup has found a
5293 /// previous declaration (PrevDecl) that is not in the scope where a
5294 /// new declaration by the same name is being introduced. If the new
5295 /// declaration occurs in a local scope, previous declarations with
5296 /// linkage may still be considered previous declarations (C99
5297 /// 6.2.2p4-5, C++ [basic.link]p6).
5299 /// \param PrevDecl the previous declaration found by name
5302 /// \param DC the context in which the new declaration is being
5305 /// \returns true if PrevDecl is an out-of-scope previous declaration
5306 /// for a new delcaration with the same name.
5308 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5309 ASTContext &Context) {
5313 if (!PrevDecl->hasLinkage())
5316 if (Context.getLangOpts().CPlusPlus) {
5317 // C++ [basic.link]p6:
5318 // If there is a visible declaration of an entity with linkage
5319 // having the same name and type, ignoring entities declared
5320 // outside the innermost enclosing namespace scope, the block
5321 // scope declaration declares that same entity and receives the
5322 // linkage of the previous declaration.
5323 DeclContext *OuterContext = DC->getRedeclContext();
5324 if (!OuterContext->isFunctionOrMethod())
5325 // This rule only applies to block-scope declarations.
5328 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5329 if (PrevOuterContext->isRecord())
5330 // We found a member function: ignore it.
5333 // Find the innermost enclosing namespace for the new and
5334 // previous declarations.
5335 OuterContext = OuterContext->getEnclosingNamespaceContext();
5336 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5338 // The previous declaration is in a different namespace, so it
5339 // isn't the same function.
5340 if (!OuterContext->Equals(PrevOuterContext))
5347 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5348 CXXScopeSpec &SS = D.getCXXScopeSpec();
5349 if (!SS.isSet()) return;
5350 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5353 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5354 QualType type = decl->getType();
5355 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5356 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5357 // Various kinds of declaration aren't allowed to be __autoreleasing.
5358 unsigned kind = -1U;
5359 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5360 if (var->hasAttr<BlocksAttr>())
5361 kind = 0; // __block
5362 else if (!var->hasLocalStorage())
5364 } else if (isa<ObjCIvarDecl>(decl)) {
5366 } else if (isa<FieldDecl>(decl)) {
5371 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5374 } else if (lifetime == Qualifiers::OCL_None) {
5375 // Try to infer lifetime.
5376 if (!type->isObjCLifetimeType())
5379 lifetime = type->getObjCARCImplicitLifetime();
5380 type = Context.getLifetimeQualifiedType(type, lifetime);
5381 decl->setType(type);
5384 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5385 // Thread-local variables cannot have lifetime.
5386 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5387 var->getTLSKind()) {
5388 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5397 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5398 // Ensure that an auto decl is deduced otherwise the checks below might cache
5399 // the wrong linkage.
5400 assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5402 // 'weak' only applies to declarations with external linkage.
5403 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5404 if (!ND.isExternallyVisible()) {
5405 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5406 ND.dropAttr<WeakAttr>();
5409 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5410 if (ND.isExternallyVisible()) {
5411 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5412 ND.dropAttr<WeakRefAttr>();
5413 ND.dropAttr<AliasAttr>();
5417 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5418 if (VD->hasInit()) {
5419 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5420 assert(VD->isThisDeclarationADefinition() &&
5421 !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5422 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5423 VD->dropAttr<AliasAttr>();
5428 // 'selectany' only applies to externally visible variable declarations.
5429 // It does not apply to functions.
5430 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5431 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5432 S.Diag(Attr->getLocation(),
5433 diag::err_attribute_selectany_non_extern_data);
5434 ND.dropAttr<SelectAnyAttr>();
5438 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5439 // dll attributes require external linkage. Static locals may have external
5440 // linkage but still cannot be explicitly imported or exported.
5441 auto *VD = dyn_cast<VarDecl>(&ND);
5442 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5443 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5445 ND.setInvalidDecl();
5449 // Virtual functions cannot be marked as 'notail'.
5450 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5451 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5452 if (MD->isVirtual()) {
5453 S.Diag(ND.getLocation(),
5454 diag::err_invalid_attribute_on_virtual_function)
5456 ND.dropAttr<NotTailCalledAttr>();
5460 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5462 bool IsSpecialization) {
5463 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5464 OldDecl = OldTD->getTemplatedDecl();
5465 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5466 NewDecl = NewTD->getTemplatedDecl();
5468 if (!OldDecl || !NewDecl)
5471 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5472 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5473 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5474 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5476 // dllimport and dllexport are inheritable attributes so we have to exclude
5477 // inherited attribute instances.
5478 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5479 (NewExportAttr && !NewExportAttr->isInherited());
5481 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5482 // the only exception being explicit specializations.
5483 // Implicitly generated declarations are also excluded for now because there
5484 // is no other way to switch these to use dllimport or dllexport.
5485 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5487 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5488 // Allow with a warning for free functions and global variables.
5489 bool JustWarn = false;
5490 if (!OldDecl->isCXXClassMember()) {
5491 auto *VD = dyn_cast<VarDecl>(OldDecl);
5492 if (VD && !VD->getDescribedVarTemplate())
5494 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5495 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5499 // We cannot change a declaration that's been used because IR has already
5500 // been emitted. Dllimported functions will still work though (modulo
5501 // address equality) as they can use the thunk.
5502 if (OldDecl->isUsed())
5503 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5506 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5507 : diag::err_attribute_dll_redeclaration;
5508 S.Diag(NewDecl->getLocation(), DiagID)
5510 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5511 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5513 NewDecl->setInvalidDecl();
5518 // A redeclaration is not allowed to drop a dllimport attribute, the only
5519 // exceptions being inline function definitions, local extern declarations,
5520 // and qualified friend declarations.
5521 // NB: MSVC converts such a declaration to dllexport.
5522 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5523 if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5524 // Ignore static data because out-of-line definitions are diagnosed
5526 IsStaticDataMember = VD->isStaticDataMember();
5527 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5528 IsInline = FD->isInlined();
5529 IsQualifiedFriend = FD->getQualifier() &&
5530 FD->getFriendObjectKind() == Decl::FOK_Declared;
5533 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5534 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5535 S.Diag(NewDecl->getLocation(),
5536 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5537 << NewDecl << OldImportAttr;
5538 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5539 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5540 OldDecl->dropAttr<DLLImportAttr>();
5541 NewDecl->dropAttr<DLLImportAttr>();
5542 } else if (IsInline && OldImportAttr &&
5543 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5544 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5545 OldDecl->dropAttr<DLLImportAttr>();
5546 NewDecl->dropAttr<DLLImportAttr>();
5547 S.Diag(NewDecl->getLocation(),
5548 diag::warn_dllimport_dropped_from_inline_function)
5549 << NewDecl << OldImportAttr;
5553 /// Given that we are within the definition of the given function,
5554 /// will that definition behave like C99's 'inline', where the
5555 /// definition is discarded except for optimization purposes?
5556 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5557 // Try to avoid calling GetGVALinkageForFunction.
5559 // All cases of this require the 'inline' keyword.
5560 if (!FD->isInlined()) return false;
5562 // This is only possible in C++ with the gnu_inline attribute.
5563 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5566 // Okay, go ahead and call the relatively-more-expensive function.
5569 // AST quite reasonably asserts that it's working on a function
5570 // definition. We don't really have a way to tell it that we're
5571 // currently defining the function, so just lie to it in +Asserts
5572 // builds. This is an awful hack.
5577 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5586 /// Determine whether a variable is extern "C" prior to attaching
5587 /// an initializer. We can't just call isExternC() here, because that
5588 /// will also compute and cache whether the declaration is externally
5589 /// visible, which might change when we attach the initializer.
5591 /// This can only be used if the declaration is known to not be a
5592 /// redeclaration of an internal linkage declaration.
5598 /// Attaching the initializer here makes this declaration not externally
5599 /// visible, because its type has internal linkage.
5601 /// FIXME: This is a hack.
5602 template<typename T>
5603 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5604 if (S.getLangOpts().CPlusPlus) {
5605 // In C++, the overloadable attribute negates the effects of extern "C".
5606 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5609 // So do CUDA's host/device attributes if overloading is enabled.
5610 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5611 (D->template hasAttr<CUDADeviceAttr>() ||
5612 D->template hasAttr<CUDAHostAttr>()))
5615 return D->isExternC();
5618 static bool shouldConsiderLinkage(const VarDecl *VD) {
5619 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5620 if (DC->isFunctionOrMethod())
5621 return VD->hasExternalStorage();
5622 if (DC->isFileContext())
5626 llvm_unreachable("Unexpected context");
5629 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5630 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5631 if (DC->isFileContext() || DC->isFunctionOrMethod())
5635 llvm_unreachable("Unexpected context");
5638 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5639 AttributeList::Kind Kind) {
5640 for (const AttributeList *L = AttrList; L; L = L->getNext())
5641 if (L->getKind() == Kind)
5646 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5647 AttributeList::Kind Kind) {
5648 // Check decl attributes on the DeclSpec.
5649 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5652 // Walk the declarator structure, checking decl attributes that were in a type
5653 // position to the decl itself.
5654 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5655 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5659 // Finally, check attributes on the decl itself.
5660 return hasParsedAttr(S, PD.getAttributes(), Kind);
5663 /// Adjust the \c DeclContext for a function or variable that might be a
5664 /// function-local external declaration.
5665 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5666 if (!DC->isFunctionOrMethod())
5669 // If this is a local extern function or variable declared within a function
5670 // template, don't add it into the enclosing namespace scope until it is
5671 // instantiated; it might have a dependent type right now.
5672 if (DC->isDependentContext())
5675 // C++11 [basic.link]p7:
5676 // When a block scope declaration of an entity with linkage is not found to
5677 // refer to some other declaration, then that entity is a member of the
5678 // innermost enclosing namespace.
5680 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5681 // semantically-enclosing namespace, not a lexically-enclosing one.
5682 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5683 DC = DC->getParent();
5687 /// \brief Returns true if given declaration has external C language linkage.
5688 static bool isDeclExternC(const Decl *D) {
5689 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5690 return FD->isExternC();
5691 if (const auto *VD = dyn_cast<VarDecl>(D))
5692 return VD->isExternC();
5694 llvm_unreachable("Unknown type of decl!");
5698 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5699 TypeSourceInfo *TInfo, LookupResult &Previous,
5700 MultiTemplateParamsArg TemplateParamLists,
5702 QualType R = TInfo->getType();
5703 DeclarationName Name = GetNameForDeclarator(D).getName();
5705 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5706 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5708 // dllimport globals without explicit storage class are treated as extern. We
5709 // have to change the storage class this early to get the right DeclContext.
5710 if (SC == SC_None && !DC->isRecord() &&
5711 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5712 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5715 DeclContext *OriginalDC = DC;
5716 bool IsLocalExternDecl = SC == SC_Extern &&
5717 adjustContextForLocalExternDecl(DC);
5719 if (getLangOpts().OpenCL) {
5720 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5722 while (NR->isPointerType()) {
5723 if (NR->isFunctionPointerType()) {
5724 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5728 NR = NR->getPointeeType();
5731 if (!getOpenCLOptions().cl_khr_fp16) {
5732 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5733 // half array type (unless the cl_khr_fp16 extension is enabled).
5734 if (Context.getBaseElementType(R)->isHalfType()) {
5735 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5741 if (SCSpec == DeclSpec::SCS_mutable) {
5742 // mutable can only appear on non-static class members, so it's always
5744 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5749 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5750 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5751 D.getDeclSpec().getStorageClassSpecLoc())) {
5752 // In C++11, the 'register' storage class specifier is deprecated.
5753 // Suppress the warning in system macros, it's used in macros in some
5754 // popular C system headers, such as in glibc's htonl() macro.
5755 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5756 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5757 : diag::warn_deprecated_register)
5758 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5761 IdentifierInfo *II = Name.getAsIdentifierInfo();
5763 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5768 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5770 if (!DC->isRecord() && S->getFnParent() == nullptr) {
5771 // C99 6.9p2: The storage-class specifiers auto and register shall not
5772 // appear in the declaration specifiers in an external declaration.
5773 // Global Register+Asm is a GNU extension we support.
5774 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5775 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5780 if (getLangOpts().OpenCL) {
5781 // OpenCL v1.2 s6.9.b p4:
5782 // The sampler type cannot be used with the __local and __global address
5783 // space qualifiers.
5784 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5785 R.getAddressSpace() == LangAS::opencl_global)) {
5786 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5789 // OpenCL 1.2 spec, p6.9 r:
5790 // The event type cannot be used to declare a program scope variable.
5791 // The event type cannot be used with the __local, __constant and __global
5792 // address space qualifiers.
5793 if (R->isEventT()) {
5794 if (S->getParent() == nullptr) {
5795 Diag(D.getLocStart(), diag::err_event_t_global_var);
5799 if (R.getAddressSpace()) {
5800 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5806 bool IsExplicitSpecialization = false;
5807 bool IsVariableTemplateSpecialization = false;
5808 bool IsPartialSpecialization = false;
5809 bool IsVariableTemplate = false;
5810 VarDecl *NewVD = nullptr;
5811 VarTemplateDecl *NewTemplate = nullptr;
5812 TemplateParameterList *TemplateParams = nullptr;
5813 if (!getLangOpts().CPlusPlus) {
5814 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5815 D.getIdentifierLoc(), II,
5818 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5819 ParsingInitForAutoVars.insert(NewVD);
5821 if (D.isInvalidType())
5822 NewVD->setInvalidDecl();
5824 bool Invalid = false;
5826 if (DC->isRecord() && !CurContext->isRecord()) {
5827 // This is an out-of-line definition of a static data member.
5832 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5833 diag::err_static_out_of_line)
5834 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5839 // [dcl.stc] p2: The auto or register specifiers shall be applied only
5840 // to names of variables declared in a block or to function parameters.
5841 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5844 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5845 diag::err_storage_class_for_static_member)
5846 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5848 case SC_PrivateExtern:
5849 llvm_unreachable("C storage class in c++!");
5853 if (SC == SC_Static && CurContext->isRecord()) {
5854 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5855 if (RD->isLocalClass())
5856 Diag(D.getIdentifierLoc(),
5857 diag::err_static_data_member_not_allowed_in_local_class)
5858 << Name << RD->getDeclName();
5860 // C++98 [class.union]p1: If a union contains a static data member,
5861 // the program is ill-formed. C++11 drops this restriction.
5863 Diag(D.getIdentifierLoc(),
5864 getLangOpts().CPlusPlus11
5865 ? diag::warn_cxx98_compat_static_data_member_in_union
5866 : diag::ext_static_data_member_in_union) << Name;
5867 // We conservatively disallow static data members in anonymous structs.
5868 else if (!RD->getDeclName())
5869 Diag(D.getIdentifierLoc(),
5870 diag::err_static_data_member_not_allowed_in_anon_struct)
5871 << Name << RD->isUnion();
5875 // Match up the template parameter lists with the scope specifier, then
5876 // determine whether we have a template or a template specialization.
5877 TemplateParams = MatchTemplateParametersToScopeSpecifier(
5878 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5879 D.getCXXScopeSpec(),
5880 D.getName().getKind() == UnqualifiedId::IK_TemplateId
5881 ? D.getName().TemplateId
5884 /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5886 if (TemplateParams) {
5887 if (!TemplateParams->size() &&
5888 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5889 // There is an extraneous 'template<>' for this variable. Complain
5890 // about it, but allow the declaration of the variable.
5891 Diag(TemplateParams->getTemplateLoc(),
5892 diag::err_template_variable_noparams)
5894 << SourceRange(TemplateParams->getTemplateLoc(),
5895 TemplateParams->getRAngleLoc());
5896 TemplateParams = nullptr;
5898 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5899 // This is an explicit specialization or a partial specialization.
5900 // FIXME: Check that we can declare a specialization here.
5901 IsVariableTemplateSpecialization = true;
5902 IsPartialSpecialization = TemplateParams->size() > 0;
5903 } else { // if (TemplateParams->size() > 0)
5904 // This is a template declaration.
5905 IsVariableTemplate = true;
5907 // Check that we can declare a template here.
5908 if (CheckTemplateDeclScope(S, TemplateParams))
5911 // Only C++1y supports variable templates (N3651).
5912 Diag(D.getIdentifierLoc(),
5913 getLangOpts().CPlusPlus14
5914 ? diag::warn_cxx11_compat_variable_template
5915 : diag::ext_variable_template);
5920 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5921 "should have a 'template<>' for this decl");
5924 if (IsVariableTemplateSpecialization) {
5925 SourceLocation TemplateKWLoc =
5926 TemplateParamLists.size() > 0
5927 ? TemplateParamLists[0]->getTemplateLoc()
5929 DeclResult Res = ActOnVarTemplateSpecialization(
5930 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5931 IsPartialSpecialization);
5932 if (Res.isInvalid())
5934 NewVD = cast<VarDecl>(Res.get());
5937 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5938 D.getIdentifierLoc(), II, R, TInfo, SC);
5940 // If this is supposed to be a variable template, create it as such.
5941 if (IsVariableTemplate) {
5943 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5944 TemplateParams, NewVD);
5945 NewVD->setDescribedVarTemplate(NewTemplate);
5948 // If this decl has an auto type in need of deduction, make a note of the
5949 // Decl so we can diagnose uses of it in its own initializer.
5950 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5951 ParsingInitForAutoVars.insert(NewVD);
5953 if (D.isInvalidType() || Invalid) {
5954 NewVD->setInvalidDecl();
5956 NewTemplate->setInvalidDecl();
5959 SetNestedNameSpecifier(NewVD, D);
5961 // If we have any template parameter lists that don't directly belong to
5962 // the variable (matching the scope specifier), store them.
5963 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5964 if (TemplateParamLists.size() > VDTemplateParamLists)
5965 NewVD->setTemplateParameterListsInfo(
5966 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5968 if (D.getDeclSpec().isConstexprSpecified())
5969 NewVD->setConstexpr(true);
5971 if (D.getDeclSpec().isConceptSpecified()) {
5972 NewVD->setConcept(true);
5974 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5975 // be declared with the thread_local, inline, friend, or constexpr
5976 // specifiers, [...]
5977 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5978 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5979 diag::err_concept_decl_invalid_specifiers)
5981 NewVD->setInvalidDecl(true);
5984 if (D.getDeclSpec().isConstexprSpecified()) {
5985 Diag(D.getDeclSpec().getConstexprSpecLoc(),
5986 diag::err_concept_decl_invalid_specifiers)
5988 NewVD->setInvalidDecl(true);
5993 // Set the lexical context. If the declarator has a C++ scope specifier, the
5994 // lexical context will be different from the semantic context.
5995 NewVD->setLexicalDeclContext(CurContext);
5997 NewTemplate->setLexicalDeclContext(CurContext);
5999 if (IsLocalExternDecl)
6000 NewVD->setLocalExternDecl();
6002 bool EmitTLSUnsupportedError = false;
6003 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6004 // C++11 [dcl.stc]p4:
6005 // When thread_local is applied to a variable of block scope the
6006 // storage-class-specifier static is implied if it does not appear
6008 // Core issue: 'static' is not implied if the variable is declared
6010 if (NewVD->hasLocalStorage() &&
6011 (SCSpec != DeclSpec::SCS_unspecified ||
6012 TSCS != DeclSpec::TSCS_thread_local ||
6013 !DC->isFunctionOrMethod()))
6014 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6015 diag::err_thread_non_global)
6016 << DeclSpec::getSpecifierName(TSCS);
6017 else if (!Context.getTargetInfo().isTLSSupported()) {
6018 if (getLangOpts().CUDA) {
6019 // Postpone error emission until we've collected attributes required to
6020 // figure out whether it's a host or device variable and whether the
6021 // error should be ignored.
6022 EmitTLSUnsupportedError = true;
6023 // We still need to mark the variable as TLS so it shows up in AST with
6024 // proper storage class for other tools to use even if we're not going
6025 // to emit any code for it.
6026 NewVD->setTSCSpec(TSCS);
6028 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6029 diag::err_thread_unsupported);
6031 NewVD->setTSCSpec(TSCS);
6035 // An inline definition of a function with external linkage shall
6036 // not contain a definition of a modifiable object with static or
6037 // thread storage duration...
6038 // We only apply this when the function is required to be defined
6039 // elsewhere, i.e. when the function is not 'extern inline'. Note
6040 // that a local variable with thread storage duration still has to
6041 // be marked 'static'. Also note that it's possible to get these
6042 // semantics in C++ using __attribute__((gnu_inline)).
6043 if (SC == SC_Static && S->getFnParent() != nullptr &&
6044 !NewVD->getType().isConstQualified()) {
6045 FunctionDecl *CurFD = getCurFunctionDecl();
6046 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6047 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6048 diag::warn_static_local_in_extern_inline);
6049 MaybeSuggestAddingStaticToDecl(CurFD);
6053 if (D.getDeclSpec().isModulePrivateSpecified()) {
6054 if (IsVariableTemplateSpecialization)
6055 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6056 << (IsPartialSpecialization ? 1 : 0)
6057 << FixItHint::CreateRemoval(
6058 D.getDeclSpec().getModulePrivateSpecLoc());
6059 else if (IsExplicitSpecialization)
6060 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6062 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6063 else if (NewVD->hasLocalStorage())
6064 Diag(NewVD->getLocation(), diag::err_module_private_local)
6065 << 0 << NewVD->getDeclName()
6066 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6067 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6069 NewVD->setModulePrivate();
6071 NewTemplate->setModulePrivate();
6075 // Handle attributes prior to checking for duplicates in MergeVarDecl
6076 ProcessDeclAttributes(S, NewVD, D);
6078 if (getLangOpts().CUDA) {
6079 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6080 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6081 diag::err_thread_unsupported);
6082 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6083 // storage [duration]."
6084 if (SC == SC_None && S->getFnParent() != nullptr &&
6085 (NewVD->hasAttr<CUDASharedAttr>() ||
6086 NewVD->hasAttr<CUDAConstantAttr>())) {
6087 NewVD->setStorageClass(SC_Static);
6091 // Ensure that dllimport globals without explicit storage class are treated as
6092 // extern. The storage class is set above using parsed attributes. Now we can
6093 // check the VarDecl itself.
6094 assert(!NewVD->hasAttr<DLLImportAttr>() ||
6095 NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6096 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6098 // In auto-retain/release, infer strong retension for variables of
6100 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6101 NewVD->setInvalidDecl();
6103 // Handle GNU asm-label extension (encoded as an attribute).
6104 if (Expr *E = (Expr*)D.getAsmLabel()) {
6105 // The parser guarantees this is a string.
6106 StringLiteral *SE = cast<StringLiteral>(E);
6107 StringRef Label = SE->getString();
6108 if (S->getFnParent() != nullptr) {
6112 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6115 // Local Named register
6116 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6117 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6118 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6122 case SC_PrivateExtern:
6125 } else if (SC == SC_Register) {
6126 // Global Named register
6127 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6128 const auto &TI = Context.getTargetInfo();
6129 bool HasSizeMismatch;
6131 if (!TI.isValidGCCRegisterName(Label))
6132 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6133 else if (!TI.validateGlobalRegisterVariable(Label,
6134 Context.getTypeSize(R),
6136 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6137 else if (HasSizeMismatch)
6138 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6141 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6142 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6143 NewVD->setInvalidDecl(true);
6147 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6148 Context, Label, 0));
6149 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6150 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6151 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6152 if (I != ExtnameUndeclaredIdentifiers.end()) {
6153 if (isDeclExternC(NewVD)) {
6154 NewVD->addAttr(I->second);
6155 ExtnameUndeclaredIdentifiers.erase(I);
6157 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6158 << /*Variable*/1 << NewVD;
6162 // Diagnose shadowed variables before filtering for scope.
6163 if (D.getCXXScopeSpec().isEmpty())
6164 CheckShadow(S, NewVD, Previous);
6166 // Don't consider existing declarations that are in a different
6167 // scope and are out-of-semantic-context declarations (if the new
6168 // declaration has linkage).
6169 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6170 D.getCXXScopeSpec().isNotEmpty() ||
6171 IsExplicitSpecialization ||
6172 IsVariableTemplateSpecialization);
6174 // Check whether the previous declaration is in the same block scope. This
6175 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6176 if (getLangOpts().CPlusPlus &&
6177 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6178 NewVD->setPreviousDeclInSameBlockScope(
6179 Previous.isSingleResult() && !Previous.isShadowed() &&
6180 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6182 if (!getLangOpts().CPlusPlus) {
6183 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6185 // If this is an explicit specialization of a static data member, check it.
6186 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6187 CheckMemberSpecialization(NewVD, Previous))
6188 NewVD->setInvalidDecl();
6190 // Merge the decl with the existing one if appropriate.
6191 if (!Previous.empty()) {
6192 if (Previous.isSingleResult() &&
6193 isa<FieldDecl>(Previous.getFoundDecl()) &&
6194 D.getCXXScopeSpec().isSet()) {
6195 // The user tried to define a non-static data member
6196 // out-of-line (C++ [dcl.meaning]p1).
6197 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6198 << D.getCXXScopeSpec().getRange();
6200 NewVD->setInvalidDecl();
6202 } else if (D.getCXXScopeSpec().isSet()) {
6203 // No previous declaration in the qualifying scope.
6204 Diag(D.getIdentifierLoc(), diag::err_no_member)
6205 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6206 << D.getCXXScopeSpec().getRange();
6207 NewVD->setInvalidDecl();
6210 if (!IsVariableTemplateSpecialization)
6211 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6214 VarTemplateDecl *PrevVarTemplate =
6215 NewVD->getPreviousDecl()
6216 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6219 // Check the template parameter list of this declaration, possibly
6220 // merging in the template parameter list from the previous variable
6221 // template declaration.
6222 if (CheckTemplateParameterList(
6224 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6226 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6227 DC->isDependentContext())
6228 ? TPC_ClassTemplateMember
6230 NewVD->setInvalidDecl();
6232 // If we are providing an explicit specialization of a static variable
6233 // template, make a note of that.
6234 if (PrevVarTemplate &&
6235 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6236 PrevVarTemplate->setMemberSpecialization();
6240 ProcessPragmaWeak(S, NewVD);
6242 // If this is the first declaration of an extern C variable, update
6243 // the map of such variables.
6244 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6245 isIncompleteDeclExternC(*this, NewVD))
6246 RegisterLocallyScopedExternCDecl(NewVD, S);
6248 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6249 Decl *ManglingContextDecl;
6250 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6251 NewVD->getDeclContext(), ManglingContextDecl)) {
6252 Context.setManglingNumber(
6253 NewVD, MCtx->getManglingNumber(
6254 NewVD, getMSManglingNumber(getLangOpts(), S)));
6255 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6259 // Special handling of variable named 'main'.
6260 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6261 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6262 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6264 // C++ [basic.start.main]p3
6265 // A program that declares a variable main at global scope is ill-formed.
6266 if (getLangOpts().CPlusPlus)
6267 Diag(D.getLocStart(), diag::err_main_global_variable);
6269 // In C, and external-linkage variable named main results in undefined
6271 else if (NewVD->hasExternalFormalLinkage())
6272 Diag(D.getLocStart(), diag::warn_main_redefined);
6275 if (D.isRedeclaration() && !Previous.empty()) {
6276 checkDLLAttributeRedeclaration(
6277 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6278 IsExplicitSpecialization);
6282 if (NewVD->isInvalidDecl())
6283 NewTemplate->setInvalidDecl();
6284 ActOnDocumentableDecl(NewTemplate);
6291 /// \brief Diagnose variable or built-in function shadowing. Implements
6294 /// This method is called whenever a VarDecl is added to a "useful"
6297 /// \param S the scope in which the shadowing name is being declared
6298 /// \param R the lookup of the name
6300 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6301 // Return if warning is ignored.
6302 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6305 // Don't diagnose declarations at file scope.
6306 if (D->hasGlobalStorage())
6309 DeclContext *NewDC = D->getDeclContext();
6311 // Only diagnose if we're shadowing an unambiguous field or variable.
6312 if (R.getResultKind() != LookupResult::Found)
6315 NamedDecl* ShadowedDecl = R.getFoundDecl();
6316 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6319 // Fields are not shadowed by variables in C++ static methods.
6320 if (isa<FieldDecl>(ShadowedDecl))
6321 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6325 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6326 if (shadowedVar->isExternC()) {
6327 // For shadowing external vars, make sure that we point to the global
6328 // declaration, not a locally scoped extern declaration.
6329 for (auto I : shadowedVar->redecls())
6330 if (I->isFileVarDecl()) {
6336 DeclContext *OldDC = ShadowedDecl->getDeclContext();
6338 // Only warn about certain kinds of shadowing for class members.
6339 if (NewDC && NewDC->isRecord()) {
6340 // In particular, don't warn about shadowing non-class members.
6341 if (!OldDC->isRecord())
6344 // TODO: should we warn about static data members shadowing
6345 // static data members from base classes?
6347 // TODO: don't diagnose for inaccessible shadowed members.
6348 // This is hard to do perfectly because we might friend the
6349 // shadowing context, but that's just a false negative.
6352 // Determine what kind of declaration we're shadowing.
6354 if (isa<RecordDecl>(OldDC)) {
6355 if (isa<FieldDecl>(ShadowedDecl))
6358 Kind = 2; // static data member
6359 } else if (OldDC->isFileContext())
6364 DeclarationName Name = R.getLookupName();
6366 // Emit warning and note.
6367 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6369 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6370 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6373 /// \brief Check -Wshadow without the advantage of a previous lookup.
6374 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6375 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6378 LookupResult R(*this, D->getDeclName(), D->getLocation(),
6379 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6381 CheckShadow(S, D, R);
6384 /// Check for conflict between this global or extern "C" declaration and
6385 /// previous global or extern "C" declarations. This is only used in C++.
6386 template<typename T>
6387 static bool checkGlobalOrExternCConflict(
6388 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6389 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6390 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6392 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6393 // The common case: this global doesn't conflict with any extern "C"
6399 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6400 // Both the old and new declarations have C language linkage. This is a
6403 Previous.addDecl(Prev);
6407 // This is a global, non-extern "C" declaration, and there is a previous
6408 // non-global extern "C" declaration. Diagnose if this is a variable
6410 if (!isa<VarDecl>(ND))
6413 // The declaration is extern "C". Check for any declaration in the
6414 // translation unit which might conflict.
6416 // We have already performed the lookup into the translation unit.
6418 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6420 if (isa<VarDecl>(*I)) {
6426 DeclContext::lookup_result R =
6427 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6428 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6430 if (isa<VarDecl>(*I)) {
6434 // FIXME: If we have any other entity with this name in global scope,
6435 // the declaration is ill-formed, but that is a defect: it breaks the
6436 // 'stat' hack, for instance. Only variables can have mangled name
6437 // clashes with extern "C" declarations, so only they deserve a
6446 // Use the first declaration's location to ensure we point at something which
6447 // is lexically inside an extern "C" linkage-spec.
6448 assert(Prev && "should have found a previous declaration to diagnose");
6449 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6450 Prev = FD->getFirstDecl();
6452 Prev = cast<VarDecl>(Prev)->getFirstDecl();
6454 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6456 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6461 /// Apply special rules for handling extern "C" declarations. Returns \c true
6462 /// if we have found that this is a redeclaration of some prior entity.
6464 /// Per C++ [dcl.link]p6:
6465 /// Two declarations [for a function or variable] with C language linkage
6466 /// with the same name that appear in different scopes refer to the same
6467 /// [entity]. An entity with C language linkage shall not be declared with
6468 /// the same name as an entity in global scope.
6469 template<typename T>
6470 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6471 LookupResult &Previous) {
6472 if (!S.getLangOpts().CPlusPlus) {
6473 // In C, when declaring a global variable, look for a corresponding 'extern'
6474 // variable declared in function scope. We don't need this in C++, because
6475 // we find local extern decls in the surrounding file-scope DeclContext.
6476 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6477 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6479 Previous.addDecl(Prev);
6486 // A declaration in the translation unit can conflict with an extern "C"
6488 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6489 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6491 // An extern "C" declaration can conflict with a declaration in the
6492 // translation unit or can be a redeclaration of an extern "C" declaration
6493 // in another scope.
6494 if (isIncompleteDeclExternC(S,ND))
6495 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6497 // Neither global nor extern "C": nothing to do.
6501 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6502 // If the decl is already known invalid, don't check it.
6503 if (NewVD->isInvalidDecl())
6506 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6507 QualType T = TInfo->getType();
6509 // Defer checking an 'auto' type until its initializer is attached.
6510 if (T->isUndeducedType())
6513 if (NewVD->hasAttrs())
6514 CheckAlignasUnderalignment(NewVD);
6516 if (T->isObjCObjectType()) {
6517 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6518 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6519 T = Context.getObjCObjectPointerType(T);
6523 // Emit an error if an address space was applied to decl with local storage.
6524 // This includes arrays of objects with address space qualifiers, but not
6525 // automatic variables that point to other address spaces.
6526 // ISO/IEC TR 18037 S5.1.2
6527 if (!getLangOpts().OpenCL
6528 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6529 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6530 NewVD->setInvalidDecl();
6534 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6536 if (getLangOpts().OpenCLVersion == 120 &&
6537 !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6538 NewVD->isStaticLocal()) {
6539 Diag(NewVD->getLocation(), diag::err_static_function_scope);
6540 NewVD->setInvalidDecl();
6544 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6545 // __constant address space.
6546 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6547 // variables inside a function can also be declared in the global
6549 if (getLangOpts().OpenCL) {
6550 if (NewVD->isFileVarDecl()) {
6551 if (!T->isSamplerT() &&
6552 !(T.getAddressSpace() == LangAS::opencl_constant ||
6553 (T.getAddressSpace() == LangAS::opencl_global &&
6554 getLangOpts().OpenCLVersion == 200))) {
6555 if (getLangOpts().OpenCLVersion == 200)
6556 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6557 << "global or constant";
6559 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6561 NewVD->setInvalidDecl();
6565 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6566 // variables inside a function can also be declared in the global
6568 if (NewVD->isStaticLocal() &&
6569 !(T.getAddressSpace() == LangAS::opencl_constant ||
6570 (T.getAddressSpace() == LangAS::opencl_global &&
6571 getLangOpts().OpenCLVersion == 200))) {
6572 if (getLangOpts().OpenCLVersion == 200)
6573 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6574 << "global or constant";
6576 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6578 NewVD->setInvalidDecl();
6581 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6583 if (T.getAddressSpace() == LangAS::opencl_constant ||
6584 T.getAddressSpace() == LangAS::opencl_local) {
6585 FunctionDecl *FD = getCurFunctionDecl();
6586 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6587 if (T.getAddressSpace() == LangAS::opencl_constant)
6588 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6591 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6593 NewVD->setInvalidDecl();
6600 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6601 && !NewVD->hasAttr<BlocksAttr>()) {
6602 if (getLangOpts().getGC() != LangOptions::NonGC)
6603 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6605 assert(!getLangOpts().ObjCAutoRefCount);
6606 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6610 bool isVM = T->isVariablyModifiedType();
6611 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6612 NewVD->hasAttr<BlocksAttr>())
6613 getCurFunction()->setHasBranchProtectedScope();
6615 if ((isVM && NewVD->hasLinkage()) ||
6616 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6617 bool SizeIsNegative;
6618 llvm::APSInt Oversized;
6619 TypeSourceInfo *FixedTInfo =
6620 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6621 SizeIsNegative, Oversized);
6622 if (!FixedTInfo && T->isVariableArrayType()) {
6623 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6624 // FIXME: This won't give the correct result for
6626 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6628 if (NewVD->isFileVarDecl())
6629 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6631 else if (NewVD->isStaticLocal())
6632 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6635 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6637 NewVD->setInvalidDecl();
6642 if (NewVD->isFileVarDecl())
6643 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6645 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6646 NewVD->setInvalidDecl();
6650 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6651 NewVD->setType(FixedTInfo->getType());
6652 NewVD->setTypeSourceInfo(FixedTInfo);
6655 if (T->isVoidType()) {
6656 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6657 // of objects and functions.
6658 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6659 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6661 NewVD->setInvalidDecl();
6666 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6667 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6668 NewVD->setInvalidDecl();
6672 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6673 Diag(NewVD->getLocation(), diag::err_block_on_vm);
6674 NewVD->setInvalidDecl();
6678 if (NewVD->isConstexpr() && !T->isDependentType() &&
6679 RequireLiteralType(NewVD->getLocation(), T,
6680 diag::err_constexpr_var_non_literal)) {
6681 NewVD->setInvalidDecl();
6686 /// \brief Perform semantic checking on a newly-created variable
6689 /// This routine performs all of the type-checking required for a
6690 /// variable declaration once it has been built. It is used both to
6691 /// check variables after they have been parsed and their declarators
6692 /// have been translated into a declaration, and to check variables
6693 /// that have been instantiated from a template.
6695 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6697 /// Returns true if the variable declaration is a redeclaration.
6698 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6699 CheckVariableDeclarationType(NewVD);
6701 // If the decl is already known invalid, don't check it.
6702 if (NewVD->isInvalidDecl())
6705 // If we did not find anything by this name, look for a non-visible
6706 // extern "C" declaration with the same name.
6707 if (Previous.empty() &&
6708 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6709 Previous.setShadowed();
6711 if (!Previous.empty()) {
6712 MergeVarDecl(NewVD, Previous);
6719 struct FindOverriddenMethod {
6721 CXXMethodDecl *Method;
6723 /// Member lookup function that determines whether a given C++
6724 /// method overrides a method in a base class, to be used with
6725 /// CXXRecordDecl::lookupInBases().
6726 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6727 RecordDecl *BaseRecord =
6728 Specifier->getType()->getAs<RecordType>()->getDecl();
6730 DeclarationName Name = Method->getDeclName();
6732 // FIXME: Do we care about other names here too?
6733 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6734 // We really want to find the base class destructor here.
6735 QualType T = S->Context.getTypeDeclType(BaseRecord);
6736 CanQualType CT = S->Context.getCanonicalType(T);
6738 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6741 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6742 Path.Decls = Path.Decls.slice(1)) {
6743 NamedDecl *D = Path.Decls.front();
6744 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6745 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6754 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6755 } // end anonymous namespace
6757 /// \brief Report an error regarding overriding, along with any relevant
6758 /// overriden methods.
6760 /// \param DiagID the primary error to report.
6761 /// \param MD the overriding method.
6762 /// \param OEK which overrides to include as notes.
6763 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6764 OverrideErrorKind OEK = OEK_All) {
6765 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6766 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6767 E = MD->end_overridden_methods();
6769 // This check (& the OEK parameter) could be replaced by a predicate, but
6770 // without lambdas that would be overkill. This is still nicer than writing
6771 // out the diag loop 3 times.
6772 if ((OEK == OEK_All) ||
6773 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6774 (OEK == OEK_Deleted && (*I)->isDeleted()))
6775 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6779 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6780 /// and if so, check that it's a valid override and remember it.
6781 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6782 // Look for methods in base classes that this method might override.
6784 FindOverriddenMethod FOM;
6787 bool hasDeletedOverridenMethods = false;
6788 bool hasNonDeletedOverridenMethods = false;
6789 bool AddedAny = false;
6790 if (DC->lookupInBases(FOM, Paths)) {
6791 for (auto *I : Paths.found_decls()) {
6792 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6793 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6794 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6795 !CheckOverridingFunctionAttributes(MD, OldMD) &&
6796 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6797 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6798 hasDeletedOverridenMethods |= OldMD->isDeleted();
6799 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6806 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6807 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6809 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6810 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6817 // Struct for holding all of the extra arguments needed by
6818 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6819 struct ActOnFDArgs {
6822 MultiTemplateParamsArg TemplateParamLists;
6829 // Callback to only accept typo corrections that have a non-zero edit distance.
6830 // Also only accept corrections that have the same parent decl.
6831 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6833 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6834 CXXRecordDecl *Parent)
6835 : Context(Context), OriginalFD(TypoFD),
6836 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6838 bool ValidateCandidate(const TypoCorrection &candidate) override {
6839 if (candidate.getEditDistance() == 0)
6842 SmallVector<unsigned, 1> MismatchedParams;
6843 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6844 CDeclEnd = candidate.end();
6845 CDecl != CDeclEnd; ++CDecl) {
6846 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6848 if (FD && !FD->hasBody() &&
6849 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6850 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6851 CXXRecordDecl *Parent = MD->getParent();
6852 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6854 } else if (!ExpectedParent) {
6864 ASTContext &Context;
6865 FunctionDecl *OriginalFD;
6866 CXXRecordDecl *ExpectedParent;
6871 /// \brief Generate diagnostics for an invalid function redeclaration.
6873 /// This routine handles generating the diagnostic messages for an invalid
6874 /// function redeclaration, including finding possible similar declarations
6875 /// or performing typo correction if there are no previous declarations with
6878 /// Returns a NamedDecl iff typo correction was performed and substituting in
6879 /// the new declaration name does not cause new errors.
6880 static NamedDecl *DiagnoseInvalidRedeclaration(
6881 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6882 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6883 DeclarationName Name = NewFD->getDeclName();
6884 DeclContext *NewDC = NewFD->getDeclContext();
6885 SmallVector<unsigned, 1> MismatchedParams;
6886 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6887 TypoCorrection Correction;
6888 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6889 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6890 : diag::err_member_decl_does_not_match;
6891 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6892 IsLocalFriend ? Sema::LookupLocalFriendName
6893 : Sema::LookupOrdinaryName,
6894 Sema::ForRedeclaration);
6896 NewFD->setInvalidDecl();
6898 SemaRef.LookupName(Prev, S);
6900 SemaRef.LookupQualifiedName(Prev, NewDC);
6901 assert(!Prev.isAmbiguous() &&
6902 "Cannot have an ambiguity in previous-declaration lookup");
6903 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6904 if (!Prev.empty()) {
6905 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6906 Func != FuncEnd; ++Func) {
6907 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6909 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6910 // Add 1 to the index so that 0 can mean the mismatch didn't
6911 // involve a parameter
6913 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6914 NearMatches.push_back(std::make_pair(FD, ParamNum));
6917 // If the qualified name lookup yielded nothing, try typo correction
6918 } else if ((Correction = SemaRef.CorrectTypo(
6919 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6920 &ExtraArgs.D.getCXXScopeSpec(),
6921 llvm::make_unique<DifferentNameValidatorCCC>(
6922 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6923 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6924 // Set up everything for the call to ActOnFunctionDeclarator
6925 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6926 ExtraArgs.D.getIdentifierLoc());
6928 Previous.setLookupName(Correction.getCorrection());
6929 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6930 CDeclEnd = Correction.end();
6931 CDecl != CDeclEnd; ++CDecl) {
6932 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6933 if (FD && !FD->hasBody() &&
6934 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6935 Previous.addDecl(FD);
6938 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6941 // Retry building the function declaration with the new previous
6942 // declarations, and with errors suppressed.
6945 Sema::SFINAETrap Trap(SemaRef);
6947 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6948 // pieces need to verify the typo-corrected C++ declaration and hopefully
6949 // eliminate the need for the parameter pack ExtraArgs.
6950 Result = SemaRef.ActOnFunctionDeclarator(
6951 ExtraArgs.S, ExtraArgs.D,
6952 Correction.getCorrectionDecl()->getDeclContext(),
6953 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6954 ExtraArgs.AddToScope);
6956 if (Trap.hasErrorOccurred())
6961 // Determine which correction we picked.
6962 Decl *Canonical = Result->getCanonicalDecl();
6963 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6965 if ((*I)->getCanonicalDecl() == Canonical)
6966 Correction.setCorrectionDecl(*I);
6968 SemaRef.diagnoseTypo(
6970 SemaRef.PDiag(IsLocalFriend
6971 ? diag::err_no_matching_local_friend_suggest
6972 : diag::err_member_decl_does_not_match_suggest)
6973 << Name << NewDC << IsDefinition);
6977 // Pretend the typo correction never occurred
6978 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6979 ExtraArgs.D.getIdentifierLoc());
6980 ExtraArgs.D.setRedeclaration(wasRedeclaration);
6982 Previous.setLookupName(Name);
6985 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6986 << Name << NewDC << IsDefinition << NewFD->getLocation();
6988 bool NewFDisConst = false;
6989 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6990 NewFDisConst = NewMD->isConst();
6992 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6993 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6994 NearMatch != NearMatchEnd; ++NearMatch) {
6995 FunctionDecl *FD = NearMatch->first;
6996 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6997 bool FDisConst = MD && MD->isConst();
6998 bool IsMember = MD || !IsLocalFriend;
7000 // FIXME: These notes are poorly worded for the local friend case.
7001 if (unsigned Idx = NearMatch->second) {
7002 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7003 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7004 if (Loc.isInvalid()) Loc = FD->getLocation();
7005 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7006 : diag::note_local_decl_close_param_match)
7007 << Idx << FDParam->getType()
7008 << NewFD->getParamDecl(Idx - 1)->getType();
7009 } else if (FDisConst != NewFDisConst) {
7010 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7011 << NewFDisConst << FD->getSourceRange().getEnd();
7013 SemaRef.Diag(FD->getLocation(),
7014 IsMember ? diag::note_member_def_close_match
7015 : diag::note_local_decl_close_match);
7020 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7021 switch (D.getDeclSpec().getStorageClassSpec()) {
7022 default: llvm_unreachable("Unknown storage class!");
7023 case DeclSpec::SCS_auto:
7024 case DeclSpec::SCS_register:
7025 case DeclSpec::SCS_mutable:
7026 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7027 diag::err_typecheck_sclass_func);
7030 case DeclSpec::SCS_unspecified: break;
7031 case DeclSpec::SCS_extern:
7032 if (D.getDeclSpec().isExternInLinkageSpec())
7035 case DeclSpec::SCS_static: {
7036 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7038 // The declaration of an identifier for a function that has
7039 // block scope shall have no explicit storage-class specifier
7040 // other than extern
7041 // See also (C++ [dcl.stc]p4).
7042 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7043 diag::err_static_block_func);
7048 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7051 // No explicit storage class has already been returned
7055 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7056 DeclContext *DC, QualType &R,
7057 TypeSourceInfo *TInfo,
7059 bool &IsVirtualOkay) {
7060 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7061 DeclarationName Name = NameInfo.getName();
7063 FunctionDecl *NewFD = nullptr;
7064 bool isInline = D.getDeclSpec().isInlineSpecified();
7066 if (!SemaRef.getLangOpts().CPlusPlus) {
7067 // Determine whether the function was written with a
7068 // prototype. This true when:
7069 // - there is a prototype in the declarator, or
7070 // - the type R of the function is some kind of typedef or other reference
7071 // to a type name (which eventually refers to a function type).
7073 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7074 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7076 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7077 D.getLocStart(), NameInfo, R,
7078 TInfo, SC, isInline,
7079 HasPrototype, false);
7080 if (D.isInvalidType())
7081 NewFD->setInvalidDecl();
7086 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7087 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7089 // Check that the return type is not an abstract class type.
7090 // For record types, this is done by the AbstractClassUsageDiagnoser once
7091 // the class has been completely parsed.
7092 if (!DC->isRecord() &&
7093 SemaRef.RequireNonAbstractType(
7094 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7095 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7098 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7099 // This is a C++ constructor declaration.
7100 assert(DC->isRecord() &&
7101 "Constructors can only be declared in a member context");
7103 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7104 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7105 D.getLocStart(), NameInfo,
7106 R, TInfo, isExplicit, isInline,
7107 /*isImplicitlyDeclared=*/false,
7110 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7111 // This is a C++ destructor declaration.
7112 if (DC->isRecord()) {
7113 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7114 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7115 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7116 SemaRef.Context, Record,
7118 NameInfo, R, TInfo, isInline,
7119 /*isImplicitlyDeclared=*/false);
7121 // If the class is complete, then we now create the implicit exception
7122 // specification. If the class is incomplete or dependent, we can't do
7124 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7125 Record->getDefinition() && !Record->isBeingDefined() &&
7126 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7127 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7130 IsVirtualOkay = true;
7134 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7137 // Create a FunctionDecl to satisfy the function definition parsing
7139 return FunctionDecl::Create(SemaRef.Context, DC,
7141 D.getIdentifierLoc(), Name, R, TInfo,
7143 /*hasPrototype=*/true, isConstexpr);
7146 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7147 if (!DC->isRecord()) {
7148 SemaRef.Diag(D.getIdentifierLoc(),
7149 diag::err_conv_function_not_member);
7153 SemaRef.CheckConversionDeclarator(D, R, SC);
7154 IsVirtualOkay = true;
7155 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7156 D.getLocStart(), NameInfo,
7157 R, TInfo, isInline, isExplicit,
7158 isConstexpr, SourceLocation());
7160 } else if (DC->isRecord()) {
7161 // If the name of the function is the same as the name of the record,
7162 // then this must be an invalid constructor that has a return type.
7163 // (The parser checks for a return type and makes the declarator a
7164 // constructor if it has no return type).
7165 if (Name.getAsIdentifierInfo() &&
7166 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7167 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7168 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7169 << SourceRange(D.getIdentifierLoc());
7173 // This is a C++ method declaration.
7174 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7175 cast<CXXRecordDecl>(DC),
7176 D.getLocStart(), NameInfo, R,
7177 TInfo, SC, isInline,
7178 isConstexpr, SourceLocation());
7179 IsVirtualOkay = !Ret->isStatic();
7183 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7184 if (!isFriend && SemaRef.CurContext->isRecord())
7187 // Determine whether the function was written with a
7188 // prototype. This true when:
7189 // - we're in C++ (where every function has a prototype),
7190 return FunctionDecl::Create(SemaRef.Context, DC,
7192 NameInfo, R, TInfo, SC, isInline,
7193 true/*HasPrototype*/, isConstexpr);
7197 enum OpenCLParamType {
7201 PrivatePtrKernelParam,
7206 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7207 if (PT->isPointerType()) {
7208 QualType PointeeType = PT->getPointeeType();
7209 if (PointeeType->isPointerType())
7210 return PtrPtrKernelParam;
7211 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7215 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7216 // be used as builtin types.
7218 if (PT->isImageType())
7219 return PtrKernelParam;
7221 if (PT->isBooleanType())
7222 return InvalidKernelParam;
7225 return InvalidKernelParam;
7227 if (PT->isHalfType())
7228 return InvalidKernelParam;
7230 if (PT->isRecordType())
7231 return RecordKernelParam;
7233 return ValidKernelParam;
7236 static void checkIsValidOpenCLKernelParameter(
7240 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7241 QualType PT = Param->getType();
7243 // Cache the valid types we encounter to avoid rechecking structs that are
7245 if (ValidTypes.count(PT.getTypePtr()))
7248 switch (getOpenCLKernelParameterType(PT)) {
7249 case PtrPtrKernelParam:
7250 // OpenCL v1.2 s6.9.a:
7251 // A kernel function argument cannot be declared as a
7252 // pointer to a pointer type.
7253 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7257 case PrivatePtrKernelParam:
7258 // OpenCL v1.2 s6.9.a:
7259 // A kernel function argument cannot be declared as a
7260 // pointer to the private address space.
7261 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7265 // OpenCL v1.2 s6.9.k:
7266 // Arguments to kernel functions in a program cannot be declared with the
7267 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7268 // uintptr_t or a struct and/or union that contain fields declared to be
7269 // one of these built-in scalar types.
7271 case InvalidKernelParam:
7272 // OpenCL v1.2 s6.8 n:
7273 // A kernel function argument cannot be declared
7275 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7279 case PtrKernelParam:
7280 case ValidKernelParam:
7281 ValidTypes.insert(PT.getTypePtr());
7284 case RecordKernelParam:
7288 // Track nested structs we will inspect
7289 SmallVector<const Decl *, 4> VisitStack;
7291 // Track where we are in the nested structs. Items will migrate from
7292 // VisitStack to HistoryStack as we do the DFS for bad field.
7293 SmallVector<const FieldDecl *, 4> HistoryStack;
7294 HistoryStack.push_back(nullptr);
7296 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7297 VisitStack.push_back(PD);
7299 assert(VisitStack.back() && "First decl null?");
7302 const Decl *Next = VisitStack.pop_back_val();
7304 assert(!HistoryStack.empty());
7305 // Found a marker, we have gone up a level
7306 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7307 ValidTypes.insert(Hist->getType().getTypePtr());
7312 // Adds everything except the original parameter declaration (which is not a
7313 // field itself) to the history stack.
7314 const RecordDecl *RD;
7315 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7316 HistoryStack.push_back(Field);
7317 RD = Field->getType()->castAs<RecordType>()->getDecl();
7319 RD = cast<RecordDecl>(Next);
7322 // Add a null marker so we know when we've gone back up a level
7323 VisitStack.push_back(nullptr);
7325 for (const auto *FD : RD->fields()) {
7326 QualType QT = FD->getType();
7328 if (ValidTypes.count(QT.getTypePtr()))
7331 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7332 if (ParamType == ValidKernelParam)
7335 if (ParamType == RecordKernelParam) {
7336 VisitStack.push_back(FD);
7340 // OpenCL v1.2 s6.9.p:
7341 // Arguments to kernel functions that are declared to be a struct or union
7342 // do not allow OpenCL objects to be passed as elements of the struct or
7344 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7345 ParamType == PrivatePtrKernelParam) {
7346 S.Diag(Param->getLocation(),
7347 diag::err_record_with_pointers_kernel_param)
7348 << PT->isUnionType()
7351 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7354 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7355 << PD->getDeclName();
7357 // We have an error, now let's go back up through history and show where
7358 // the offending field came from
7359 for (ArrayRef<const FieldDecl *>::const_iterator
7360 I = HistoryStack.begin() + 1,
7361 E = HistoryStack.end();
7363 const FieldDecl *OuterField = *I;
7364 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7365 << OuterField->getType();
7368 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7369 << QT->isPointerType()
7374 } while (!VisitStack.empty());
7378 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7379 TypeSourceInfo *TInfo, LookupResult &Previous,
7380 MultiTemplateParamsArg TemplateParamLists,
7382 QualType R = TInfo->getType();
7384 assert(R.getTypePtr()->isFunctionType());
7386 // TODO: consider using NameInfo for diagnostic.
7387 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7388 DeclarationName Name = NameInfo.getName();
7389 StorageClass SC = getFunctionStorageClass(*this, D);
7391 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7392 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7393 diag::err_invalid_thread)
7394 << DeclSpec::getSpecifierName(TSCS);
7396 if (D.isFirstDeclarationOfMember())
7397 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7398 D.getIdentifierLoc());
7400 bool isFriend = false;
7401 FunctionTemplateDecl *FunctionTemplate = nullptr;
7402 bool isExplicitSpecialization = false;
7403 bool isFunctionTemplateSpecialization = false;
7405 bool isDependentClassScopeExplicitSpecialization = false;
7406 bool HasExplicitTemplateArgs = false;
7407 TemplateArgumentListInfo TemplateArgs;
7409 bool isVirtualOkay = false;
7411 DeclContext *OriginalDC = DC;
7412 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7414 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7416 if (!NewFD) return nullptr;
7418 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7419 NewFD->setTopLevelDeclInObjCContainer();
7421 // Set the lexical context. If this is a function-scope declaration, or has a
7422 // C++ scope specifier, or is the object of a friend declaration, the lexical
7423 // context will be different from the semantic context.
7424 NewFD->setLexicalDeclContext(CurContext);
7426 if (IsLocalExternDecl)
7427 NewFD->setLocalExternDecl();
7429 if (getLangOpts().CPlusPlus) {
7430 bool isInline = D.getDeclSpec().isInlineSpecified();
7431 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7432 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7433 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7434 bool isConcept = D.getDeclSpec().isConceptSpecified();
7435 isFriend = D.getDeclSpec().isFriendSpecified();
7436 if (isFriend && !isInline && D.isFunctionDefinition()) {
7437 // C++ [class.friend]p5
7438 // A function can be defined in a friend declaration of a
7439 // class . . . . Such a function is implicitly inline.
7440 NewFD->setImplicitlyInline();
7443 // If this is a method defined in an __interface, and is not a constructor
7444 // or an overloaded operator, then set the pure flag (isVirtual will already
7446 if (const CXXRecordDecl *Parent =
7447 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7448 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7449 NewFD->setPure(true);
7451 // C++ [class.union]p2
7452 // A union can have member functions, but not virtual functions.
7453 if (isVirtual && Parent->isUnion())
7454 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7457 SetNestedNameSpecifier(NewFD, D);
7458 isExplicitSpecialization = false;
7459 isFunctionTemplateSpecialization = false;
7460 if (D.isInvalidType())
7461 NewFD->setInvalidDecl();
7463 // Match up the template parameter lists with the scope specifier, then
7464 // determine whether we have a template or a template specialization.
7465 bool Invalid = false;
7466 if (TemplateParameterList *TemplateParams =
7467 MatchTemplateParametersToScopeSpecifier(
7468 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7469 D.getCXXScopeSpec(),
7470 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7471 ? D.getName().TemplateId
7473 TemplateParamLists, isFriend, isExplicitSpecialization,
7475 if (TemplateParams->size() > 0) {
7476 // This is a function template
7478 // Check that we can declare a template here.
7479 if (CheckTemplateDeclScope(S, TemplateParams))
7480 NewFD->setInvalidDecl();
7482 // A destructor cannot be a template.
7483 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7484 Diag(NewFD->getLocation(), diag::err_destructor_template);
7485 NewFD->setInvalidDecl();
7488 // If we're adding a template to a dependent context, we may need to
7489 // rebuilding some of the types used within the template parameter list,
7490 // now that we know what the current instantiation is.
7491 if (DC->isDependentContext()) {
7492 ContextRAII SavedContext(*this, DC);
7493 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7498 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7499 NewFD->getLocation(),
7500 Name, TemplateParams,
7502 FunctionTemplate->setLexicalDeclContext(CurContext);
7503 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7505 // For source fidelity, store the other template param lists.
7506 if (TemplateParamLists.size() > 1) {
7507 NewFD->setTemplateParameterListsInfo(Context,
7508 TemplateParamLists.drop_back(1));
7511 // This is a function template specialization.
7512 isFunctionTemplateSpecialization = true;
7513 // For source fidelity, store all the template param lists.
7514 if (TemplateParamLists.size() > 0)
7515 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7517 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7519 // We want to remove the "template<>", found here.
7520 SourceRange RemoveRange = TemplateParams->getSourceRange();
7522 // If we remove the template<> and the name is not a
7523 // template-id, we're actually silently creating a problem:
7524 // the friend declaration will refer to an untemplated decl,
7525 // and clearly the user wants a template specialization. So
7526 // we need to insert '<>' after the name.
7527 SourceLocation InsertLoc;
7528 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7529 InsertLoc = D.getName().getSourceRange().getEnd();
7530 InsertLoc = getLocForEndOfToken(InsertLoc);
7533 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7534 << Name << RemoveRange
7535 << FixItHint::CreateRemoval(RemoveRange)
7536 << FixItHint::CreateInsertion(InsertLoc, "<>");
7541 // All template param lists were matched against the scope specifier:
7542 // this is NOT (an explicit specialization of) a template.
7543 if (TemplateParamLists.size() > 0)
7544 // For source fidelity, store all the template param lists.
7545 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7549 NewFD->setInvalidDecl();
7550 if (FunctionTemplate)
7551 FunctionTemplate->setInvalidDecl();
7554 // C++ [dcl.fct.spec]p5:
7555 // The virtual specifier shall only be used in declarations of
7556 // nonstatic class member functions that appear within a
7557 // member-specification of a class declaration; see 10.3.
7559 if (isVirtual && !NewFD->isInvalidDecl()) {
7560 if (!isVirtualOkay) {
7561 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7562 diag::err_virtual_non_function);
7563 } else if (!CurContext->isRecord()) {
7564 // 'virtual' was specified outside of the class.
7565 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7566 diag::err_virtual_out_of_class)
7567 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7568 } else if (NewFD->getDescribedFunctionTemplate()) {
7569 // C++ [temp.mem]p3:
7570 // A member function template shall not be virtual.
7571 Diag(D.getDeclSpec().getVirtualSpecLoc(),
7572 diag::err_virtual_member_function_template)
7573 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7575 // Okay: Add virtual to the method.
7576 NewFD->setVirtualAsWritten(true);
7579 if (getLangOpts().CPlusPlus14 &&
7580 NewFD->getReturnType()->isUndeducedType())
7581 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7584 if (getLangOpts().CPlusPlus14 &&
7585 (NewFD->isDependentContext() ||
7586 (isFriend && CurContext->isDependentContext())) &&
7587 NewFD->getReturnType()->isUndeducedType()) {
7588 // If the function template is referenced directly (for instance, as a
7589 // member of the current instantiation), pretend it has a dependent type.
7590 // This is not really justified by the standard, but is the only sane
7592 // FIXME: For a friend function, we have not marked the function as being
7593 // a friend yet, so 'isDependentContext' on the FD doesn't work.
7594 const FunctionProtoType *FPT =
7595 NewFD->getType()->castAs<FunctionProtoType>();
7597 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7598 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7599 FPT->getExtProtoInfo()));
7602 // C++ [dcl.fct.spec]p3:
7603 // The inline specifier shall not appear on a block scope function
7605 if (isInline && !NewFD->isInvalidDecl()) {
7606 if (CurContext->isFunctionOrMethod()) {
7607 // 'inline' is not allowed on block scope function declaration.
7608 Diag(D.getDeclSpec().getInlineSpecLoc(),
7609 diag::err_inline_declaration_block_scope) << Name
7610 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7614 // C++ [dcl.fct.spec]p6:
7615 // The explicit specifier shall be used only in the declaration of a
7616 // constructor or conversion function within its class definition;
7617 // see 12.3.1 and 12.3.2.
7618 if (isExplicit && !NewFD->isInvalidDecl()) {
7619 if (!CurContext->isRecord()) {
7620 // 'explicit' was specified outside of the class.
7621 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7622 diag::err_explicit_out_of_class)
7623 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7624 } else if (!isa<CXXConstructorDecl>(NewFD) &&
7625 !isa<CXXConversionDecl>(NewFD)) {
7626 // 'explicit' was specified on a function that wasn't a constructor
7627 // or conversion function.
7628 Diag(D.getDeclSpec().getExplicitSpecLoc(),
7629 diag::err_explicit_non_ctor_or_conv_function)
7630 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7635 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7636 // are implicitly inline.
7637 NewFD->setImplicitlyInline();
7639 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7640 // be either constructors or to return a literal type. Therefore,
7641 // destructors cannot be declared constexpr.
7642 if (isa<CXXDestructorDecl>(NewFD))
7643 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7647 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7648 // applied only to the definition of a function template [...]
7649 if (!D.isFunctionDefinition()) {
7650 Diag(D.getDeclSpec().getConceptSpecLoc(),
7651 diag::err_function_concept_not_defined);
7652 NewFD->setInvalidDecl();
7655 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7656 // have no exception-specification and is treated as if it were specified
7657 // with noexcept(true) (15.4). [...]
7658 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7659 if (FPT->hasExceptionSpec()) {
7661 if (D.isFunctionDeclarator())
7662 Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7663 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7664 << FixItHint::CreateRemoval(Range);
7665 NewFD->setInvalidDecl();
7667 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7670 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7671 // following restrictions:
7672 // - The declaration's parameter list shall be equivalent to an empty
7674 if (FPT->getNumParams() > 0 || FPT->isVariadic())
7675 Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7678 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7679 // implicity defined to be a constexpr declaration (implicitly inline)
7680 NewFD->setImplicitlyInline();
7682 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7683 // be declared with the thread_local, inline, friend, or constexpr
7684 // specifiers, [...]
7686 Diag(D.getDeclSpec().getInlineSpecLoc(),
7687 diag::err_concept_decl_invalid_specifiers)
7689 NewFD->setInvalidDecl(true);
7693 Diag(D.getDeclSpec().getFriendSpecLoc(),
7694 diag::err_concept_decl_invalid_specifiers)
7696 NewFD->setInvalidDecl(true);
7700 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7701 diag::err_concept_decl_invalid_specifiers)
7703 NewFD->setInvalidDecl(true);
7707 // If __module_private__ was specified, mark the function accordingly.
7708 if (D.getDeclSpec().isModulePrivateSpecified()) {
7709 if (isFunctionTemplateSpecialization) {
7710 SourceLocation ModulePrivateLoc
7711 = D.getDeclSpec().getModulePrivateSpecLoc();
7712 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7714 << FixItHint::CreateRemoval(ModulePrivateLoc);
7716 NewFD->setModulePrivate();
7717 if (FunctionTemplate)
7718 FunctionTemplate->setModulePrivate();
7723 if (FunctionTemplate) {
7724 FunctionTemplate->setObjectOfFriendDecl();
7725 FunctionTemplate->setAccess(AS_public);
7727 NewFD->setObjectOfFriendDecl();
7728 NewFD->setAccess(AS_public);
7731 // If a function is defined as defaulted or deleted, mark it as such now.
7732 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7733 // definition kind to FDK_Definition.
7734 switch (D.getFunctionDefinitionKind()) {
7735 case FDK_Declaration:
7736 case FDK_Definition:
7740 NewFD->setDefaulted();
7744 NewFD->setDeletedAsWritten();
7748 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7749 D.isFunctionDefinition()) {
7750 // C++ [class.mfct]p2:
7751 // A member function may be defined (8.4) in its class definition, in
7752 // which case it is an inline member function (7.1.2)
7753 NewFD->setImplicitlyInline();
7756 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7757 !CurContext->isRecord()) {
7758 // C++ [class.static]p1:
7759 // A data or function member of a class may be declared static
7760 // in a class definition, in which case it is a static member of
7763 // Complain about the 'static' specifier if it's on an out-of-line
7764 // member function definition.
7765 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7766 diag::err_static_out_of_line)
7767 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7770 // C++11 [except.spec]p15:
7771 // A deallocation function with no exception-specification is treated
7772 // as if it were specified with noexcept(true).
7773 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7774 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7775 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7776 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7777 NewFD->setType(Context.getFunctionType(
7778 FPT->getReturnType(), FPT->getParamTypes(),
7779 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7782 // Filter out previous declarations that don't match the scope.
7783 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7784 D.getCXXScopeSpec().isNotEmpty() ||
7785 isExplicitSpecialization ||
7786 isFunctionTemplateSpecialization);
7788 // Handle GNU asm-label extension (encoded as an attribute).
7789 if (Expr *E = (Expr*) D.getAsmLabel()) {
7790 // The parser guarantees this is a string.
7791 StringLiteral *SE = cast<StringLiteral>(E);
7792 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7793 SE->getString(), 0));
7794 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7795 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7796 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7797 if (I != ExtnameUndeclaredIdentifiers.end()) {
7798 if (isDeclExternC(NewFD)) {
7799 NewFD->addAttr(I->second);
7800 ExtnameUndeclaredIdentifiers.erase(I);
7802 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7803 << /*Variable*/0 << NewFD;
7807 // Copy the parameter declarations from the declarator D to the function
7808 // declaration NewFD, if they are available. First scavenge them into Params.
7809 SmallVector<ParmVarDecl*, 16> Params;
7810 if (D.isFunctionDeclarator()) {
7811 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7813 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7814 // function that takes no arguments, not a function that takes a
7815 // single void argument.
7816 // We let through "const void" here because Sema::GetTypeForDeclarator
7817 // already checks for that case.
7818 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7819 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7820 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7821 assert(Param->getDeclContext() != NewFD && "Was set before ?");
7822 Param->setDeclContext(NewFD);
7823 Params.push_back(Param);
7825 if (Param->isInvalidDecl())
7826 NewFD->setInvalidDecl();
7830 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7831 // When we're declaring a function with a typedef, typeof, etc as in the
7832 // following example, we'll need to synthesize (unnamed)
7833 // parameters for use in the declaration.
7836 // typedef void fn(int);
7840 // Synthesize a parameter for each argument type.
7841 for (const auto &AI : FT->param_types()) {
7842 ParmVarDecl *Param =
7843 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7844 Param->setScopeInfo(0, Params.size());
7845 Params.push_back(Param);
7848 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7849 "Should not need args for typedef of non-prototype fn");
7852 // Finally, we know we have the right number of parameters, install them.
7853 NewFD->setParams(Params);
7855 // Find all anonymous symbols defined during the declaration of this function
7856 // and add to NewFD. This lets us track decls such 'enum Y' in:
7858 // void f(enum Y {AA} x) {}
7860 // which would otherwise incorrectly end up in the translation unit scope.
7861 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7862 DeclsInPrototypeScope.clear();
7864 if (D.getDeclSpec().isNoreturnSpecified())
7866 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7869 // Functions returning a variably modified type violate C99 6.7.5.2p2
7870 // because all functions have linkage.
7871 if (!NewFD->isInvalidDecl() &&
7872 NewFD->getReturnType()->isVariablyModifiedType()) {
7873 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7874 NewFD->setInvalidDecl();
7877 // Apply an implicit SectionAttr if #pragma code_seg is active.
7878 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7879 !NewFD->hasAttr<SectionAttr>()) {
7881 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7882 CodeSegStack.CurrentValue->getString(),
7883 CodeSegStack.CurrentPragmaLocation));
7884 if (UnifySection(CodeSegStack.CurrentValue->getString(),
7885 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7886 ASTContext::PSF_Read,
7888 NewFD->dropAttr<SectionAttr>();
7891 // Handle attributes.
7892 ProcessDeclAttributes(S, NewFD, D);
7894 if (getLangOpts().OpenCL) {
7895 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7896 // type declaration will generate a compilation error.
7897 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7898 if (AddressSpace == LangAS::opencl_local ||
7899 AddressSpace == LangAS::opencl_global ||
7900 AddressSpace == LangAS::opencl_constant) {
7901 Diag(NewFD->getLocation(),
7902 diag::err_opencl_return_value_with_address_space);
7903 NewFD->setInvalidDecl();
7907 if (!getLangOpts().CPlusPlus) {
7908 // Perform semantic checking on the function declaration.
7909 bool isExplicitSpecialization=false;
7910 if (!NewFD->isInvalidDecl() && NewFD->isMain())
7911 CheckMain(NewFD, D.getDeclSpec());
7913 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7914 CheckMSVCRTEntryPoint(NewFD);
7916 if (!NewFD->isInvalidDecl())
7917 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7918 isExplicitSpecialization));
7919 else if (!Previous.empty())
7920 // Recover gracefully from an invalid redeclaration.
7921 D.setRedeclaration(true);
7922 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7923 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7924 "previous declaration set still overloaded");
7926 // Diagnose no-prototype function declarations with calling conventions that
7927 // don't support variadic calls. Only do this in C and do it after merging
7928 // possibly prototyped redeclarations.
7929 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7930 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7931 CallingConv CC = FT->getExtInfo().getCC();
7932 if (!supportsVariadicCall(CC)) {
7933 // Windows system headers sometimes accidentally use stdcall without
7934 // (void) parameters, so we relax this to a warning.
7936 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7937 Diag(NewFD->getLocation(), DiagID)
7938 << FunctionType::getNameForCallConv(CC);
7942 // C++11 [replacement.functions]p3:
7943 // The program's definitions shall not be specified as inline.
7945 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7947 // Suppress the diagnostic if the function is __attribute__((used)), since
7948 // that forces an external definition to be emitted.
7949 if (D.getDeclSpec().isInlineSpecified() &&
7950 NewFD->isReplaceableGlobalAllocationFunction() &&
7951 !NewFD->hasAttr<UsedAttr>())
7952 Diag(D.getDeclSpec().getInlineSpecLoc(),
7953 diag::ext_operator_new_delete_declared_inline)
7954 << NewFD->getDeclName();
7956 // If the declarator is a template-id, translate the parser's template
7957 // argument list into our AST format.
7958 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7959 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7960 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7961 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7962 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7963 TemplateId->NumArgs);
7964 translateTemplateArguments(TemplateArgsPtr,
7967 HasExplicitTemplateArgs = true;
7969 if (NewFD->isInvalidDecl()) {
7970 HasExplicitTemplateArgs = false;
7971 } else if (FunctionTemplate) {
7972 // Function template with explicit template arguments.
7973 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7974 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7976 HasExplicitTemplateArgs = false;
7978 assert((isFunctionTemplateSpecialization ||
7979 D.getDeclSpec().isFriendSpecified()) &&
7980 "should have a 'template<>' for this decl");
7981 // "friend void foo<>(int);" is an implicit specialization decl.
7982 isFunctionTemplateSpecialization = true;
7984 } else if (isFriend && isFunctionTemplateSpecialization) {
7985 // This combination is only possible in a recovery case; the user
7986 // wrote something like:
7987 // template <> friend void foo(int);
7988 // which we're recovering from as if the user had written:
7989 // friend void foo<>(int);
7990 // Go ahead and fake up a template id.
7991 HasExplicitTemplateArgs = true;
7992 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7993 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7996 // If it's a friend (and only if it's a friend), it's possible
7997 // that either the specialized function type or the specialized
7998 // template is dependent, and therefore matching will fail. In
7999 // this case, don't check the specialization yet.
8000 bool InstantiationDependent = false;
8001 if (isFunctionTemplateSpecialization && isFriend &&
8002 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8003 TemplateSpecializationType::anyDependentTemplateArguments(
8004 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8005 InstantiationDependent))) {
8006 assert(HasExplicitTemplateArgs &&
8007 "friend function specialization without template args");
8008 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8010 NewFD->setInvalidDecl();
8011 } else if (isFunctionTemplateSpecialization) {
8012 if (CurContext->isDependentContext() && CurContext->isRecord()
8014 isDependentClassScopeExplicitSpecialization = true;
8015 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8016 diag::ext_function_specialization_in_class :
8017 diag::err_function_specialization_in_class)
8018 << NewFD->getDeclName();
8019 } else if (CheckFunctionTemplateSpecialization(NewFD,
8020 (HasExplicitTemplateArgs ? &TemplateArgs
8023 NewFD->setInvalidDecl();
8026 // A storage-class-specifier shall not be specified in an explicit
8027 // specialization (14.7.3)
8028 FunctionTemplateSpecializationInfo *Info =
8029 NewFD->getTemplateSpecializationInfo();
8030 if (Info && SC != SC_None) {
8031 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8032 Diag(NewFD->getLocation(),
8033 diag::err_explicit_specialization_inconsistent_storage_class)
8035 << FixItHint::CreateRemoval(
8036 D.getDeclSpec().getStorageClassSpecLoc());
8039 Diag(NewFD->getLocation(),
8040 diag::ext_explicit_specialization_storage_class)
8041 << FixItHint::CreateRemoval(
8042 D.getDeclSpec().getStorageClassSpecLoc());
8045 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8046 if (CheckMemberSpecialization(NewFD, Previous))
8047 NewFD->setInvalidDecl();
8050 // Perform semantic checking on the function declaration.
8051 if (!isDependentClassScopeExplicitSpecialization) {
8052 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8053 CheckMain(NewFD, D.getDeclSpec());
8055 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8056 CheckMSVCRTEntryPoint(NewFD);
8058 if (!NewFD->isInvalidDecl())
8059 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8060 isExplicitSpecialization));
8061 else if (!Previous.empty())
8062 // Recover gracefully from an invalid redeclaration.
8063 D.setRedeclaration(true);
8066 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8067 Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8068 "previous declaration set still overloaded");
8070 NamedDecl *PrincipalDecl = (FunctionTemplate
8071 ? cast<NamedDecl>(FunctionTemplate)
8074 if (isFriend && D.isRedeclaration()) {
8075 AccessSpecifier Access = AS_public;
8076 if (!NewFD->isInvalidDecl())
8077 Access = NewFD->getPreviousDecl()->getAccess();
8079 NewFD->setAccess(Access);
8080 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8083 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8084 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8085 PrincipalDecl->setNonMemberOperator();
8087 // If we have a function template, check the template parameter
8088 // list. This will check and merge default template arguments.
8089 if (FunctionTemplate) {
8090 FunctionTemplateDecl *PrevTemplate =
8091 FunctionTemplate->getPreviousDecl();
8092 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8093 PrevTemplate ? PrevTemplate->getTemplateParameters()
8095 D.getDeclSpec().isFriendSpecified()
8096 ? (D.isFunctionDefinition()
8097 ? TPC_FriendFunctionTemplateDefinition
8098 : TPC_FriendFunctionTemplate)
8099 : (D.getCXXScopeSpec().isSet() &&
8100 DC && DC->isRecord() &&
8101 DC->isDependentContext())
8102 ? TPC_ClassTemplateMember
8103 : TPC_FunctionTemplate);
8106 if (NewFD->isInvalidDecl()) {
8107 // Ignore all the rest of this.
8108 } else if (!D.isRedeclaration()) {
8109 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8111 // Fake up an access specifier if it's supposed to be a class member.
8112 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8113 NewFD->setAccess(AS_public);
8115 // Qualified decls generally require a previous declaration.
8116 if (D.getCXXScopeSpec().isSet()) {
8117 // ...with the major exception of templated-scope or
8118 // dependent-scope friend declarations.
8120 // TODO: we currently also suppress this check in dependent
8121 // contexts because (1) the parameter depth will be off when
8122 // matching friend templates and (2) we might actually be
8123 // selecting a friend based on a dependent factor. But there
8124 // are situations where these conditions don't apply and we
8125 // can actually do this check immediately.
8127 (TemplateParamLists.size() ||
8128 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8129 CurContext->isDependentContext())) {
8132 // The user tried to provide an out-of-line definition for a
8133 // function that is a member of a class or namespace, but there
8134 // was no such member function declared (C++ [class.mfct]p2,
8135 // C++ [namespace.memdef]p2). For example:
8141 // void X::f() { } // ill-formed
8143 // Complain about this problem, and attempt to suggest close
8144 // matches (e.g., those that differ only in cv-qualifiers and
8145 // whether the parameter types are references).
8147 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8148 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8149 AddToScope = ExtraArgs.AddToScope;
8154 // Unqualified local friend declarations are required to resolve
8156 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8157 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8158 *this, Previous, NewFD, ExtraArgs, true, S)) {
8159 AddToScope = ExtraArgs.AddToScope;
8164 } else if (!D.isFunctionDefinition() &&
8165 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8166 !isFriend && !isFunctionTemplateSpecialization &&
8167 !isExplicitSpecialization) {
8168 // An out-of-line member function declaration must also be a
8169 // definition (C++ [class.mfct]p2).
8170 // Note that this is not the case for explicit specializations of
8171 // function templates or member functions of class templates, per
8172 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8173 // extension for compatibility with old SWIG code which likes to
8175 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8176 << D.getCXXScopeSpec().getRange();
8180 ProcessPragmaWeak(S, NewFD);
8181 checkAttributesAfterMerging(*this, *NewFD);
8183 AddKnownFunctionAttributes(NewFD);
8185 if (NewFD->hasAttr<OverloadableAttr>() &&
8186 !NewFD->getType()->getAs<FunctionProtoType>()) {
8187 Diag(NewFD->getLocation(),
8188 diag::err_attribute_overloadable_no_prototype)
8191 // Turn this into a variadic function with no parameters.
8192 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8193 FunctionProtoType::ExtProtoInfo EPI(
8194 Context.getDefaultCallingConvention(true, false));
8195 EPI.Variadic = true;
8196 EPI.ExtInfo = FT->getExtInfo();
8198 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8202 // If there's a #pragma GCC visibility in scope, and this isn't a class
8203 // member, set the visibility of this function.
8204 if (!DC->isRecord() && NewFD->isExternallyVisible())
8205 AddPushedVisibilityAttribute(NewFD);
8207 // If there's a #pragma clang arc_cf_code_audited in scope, consider
8208 // marking the function.
8209 AddCFAuditedAttribute(NewFD);
8211 // If this is a function definition, check if we have to apply optnone due to
8213 if(D.isFunctionDefinition())
8214 AddRangeBasedOptnone(NewFD);
8216 // If this is the first declaration of an extern C variable, update
8217 // the map of such variables.
8218 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8219 isIncompleteDeclExternC(*this, NewFD))
8220 RegisterLocallyScopedExternCDecl(NewFD, S);
8222 // Set this FunctionDecl's range up to the right paren.
8223 NewFD->setRangeEnd(D.getSourceRange().getEnd());
8225 if (D.isRedeclaration() && !Previous.empty()) {
8226 checkDLLAttributeRedeclaration(
8227 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8228 isExplicitSpecialization || isFunctionTemplateSpecialization);
8231 if (getLangOpts().CPlusPlus) {
8232 if (FunctionTemplate) {
8233 if (NewFD->isInvalidDecl())
8234 FunctionTemplate->setInvalidDecl();
8235 return FunctionTemplate;
8239 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8240 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8241 if ((getLangOpts().OpenCLVersion >= 120)
8242 && (SC == SC_Static)) {
8243 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8247 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8248 if (!NewFD->getReturnType()->isVoidType()) {
8249 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8250 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8251 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8256 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8257 for (auto Param : NewFD->params())
8258 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8261 MarkUnusedFileScopedDecl(NewFD);
8263 if (getLangOpts().CUDA)
8264 if (IdentifierInfo *II = NewFD->getIdentifier())
8265 if (!NewFD->isInvalidDecl() &&
8266 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8267 if (II->isStr("cudaConfigureCall")) {
8268 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8269 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8271 Context.setcudaConfigureCallDecl(NewFD);
8275 // Here we have an function template explicit specialization at class scope.
8276 // The actually specialization will be postponed to template instatiation
8277 // time via the ClassScopeFunctionSpecializationDecl node.
8278 if (isDependentClassScopeExplicitSpecialization) {
8279 ClassScopeFunctionSpecializationDecl *NewSpec =
8280 ClassScopeFunctionSpecializationDecl::Create(
8281 Context, CurContext, SourceLocation(),
8282 cast<CXXMethodDecl>(NewFD),
8283 HasExplicitTemplateArgs, TemplateArgs);
8284 CurContext->addDecl(NewSpec);
8291 /// \brief Perform semantic checking of a new function declaration.
8293 /// Performs semantic analysis of the new function declaration
8294 /// NewFD. This routine performs all semantic checking that does not
8295 /// require the actual declarator involved in the declaration, and is
8296 /// used both for the declaration of functions as they are parsed
8297 /// (called via ActOnDeclarator) and for the declaration of functions
8298 /// that have been instantiated via C++ template instantiation (called
8299 /// via InstantiateDecl).
8301 /// \param IsExplicitSpecialization whether this new function declaration is
8302 /// an explicit specialization of the previous declaration.
8304 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8306 /// \returns true if the function declaration is a redeclaration.
8307 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8308 LookupResult &Previous,
8309 bool IsExplicitSpecialization) {
8310 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8311 "Variably modified return types are not handled here");
8313 // Determine whether the type of this function should be merged with
8314 // a previous visible declaration. This never happens for functions in C++,
8315 // and always happens in C if the previous declaration was visible.
8316 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8317 !Previous.isShadowed();
8319 bool Redeclaration = false;
8320 NamedDecl *OldDecl = nullptr;
8322 // Merge or overload the declaration with an existing declaration of
8323 // the same name, if appropriate.
8324 if (!Previous.empty()) {
8325 // Determine whether NewFD is an overload of PrevDecl or
8326 // a declaration that requires merging. If it's an overload,
8327 // there's no more work to do here; we'll just add the new
8328 // function to the scope.
8329 if (!AllowOverloadingOfFunction(Previous, Context)) {
8330 NamedDecl *Candidate = Previous.getRepresentativeDecl();
8331 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8332 Redeclaration = true;
8333 OldDecl = Candidate;
8336 switch (CheckOverload(S, NewFD, Previous, OldDecl,
8337 /*NewIsUsingDecl*/ false)) {
8339 Redeclaration = true;
8342 case Ovl_NonFunction:
8343 Redeclaration = true;
8347 Redeclaration = false;
8351 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8352 // If a function name is overloadable in C, then every function
8353 // with that name must be marked "overloadable".
8354 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8355 << Redeclaration << NewFD;
8356 NamedDecl *OverloadedDecl = nullptr;
8358 OverloadedDecl = OldDecl;
8359 else if (!Previous.empty())
8360 OverloadedDecl = Previous.getRepresentativeDecl();
8362 Diag(OverloadedDecl->getLocation(),
8363 diag::note_attribute_overloadable_prev_overload);
8364 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8369 // Check for a previous extern "C" declaration with this name.
8370 if (!Redeclaration &&
8371 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8372 if (!Previous.empty()) {
8373 // This is an extern "C" declaration with the same name as a previous
8374 // declaration, and thus redeclares that entity...
8375 Redeclaration = true;
8376 OldDecl = Previous.getFoundDecl();
8377 MergeTypeWithPrevious = false;
8379 // ... except in the presence of __attribute__((overloadable)).
8380 if (OldDecl->hasAttr<OverloadableAttr>()) {
8381 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8382 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8383 << Redeclaration << NewFD;
8384 Diag(Previous.getFoundDecl()->getLocation(),
8385 diag::note_attribute_overloadable_prev_overload);
8386 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8388 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8389 Redeclaration = false;
8396 // C++11 [dcl.constexpr]p8:
8397 // A constexpr specifier for a non-static member function that is not
8398 // a constructor declares that member function to be const.
8400 // This needs to be delayed until we know whether this is an out-of-line
8401 // definition of a static member function.
8403 // This rule is not present in C++1y, so we produce a backwards
8404 // compatibility warning whenever it happens in C++11.
8405 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8406 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8407 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8408 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8409 CXXMethodDecl *OldMD = nullptr;
8411 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8412 if (!OldMD || !OldMD->isStatic()) {
8413 const FunctionProtoType *FPT =
8414 MD->getType()->castAs<FunctionProtoType>();
8415 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8416 EPI.TypeQuals |= Qualifiers::Const;
8417 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8418 FPT->getParamTypes(), EPI));
8420 // Warn that we did this, if we're not performing template instantiation.
8421 // In that case, we'll have warned already when the template was defined.
8422 if (ActiveTemplateInstantiations.empty()) {
8423 SourceLocation AddConstLoc;
8424 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8425 .IgnoreParens().getAs<FunctionTypeLoc>())
8426 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8428 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8429 << FixItHint::CreateInsertion(AddConstLoc, " const");
8434 if (Redeclaration) {
8435 // NewFD and OldDecl represent declarations that need to be
8437 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8438 NewFD->setInvalidDecl();
8439 return Redeclaration;
8443 Previous.addDecl(OldDecl);
8445 if (FunctionTemplateDecl *OldTemplateDecl
8446 = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8447 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8448 FunctionTemplateDecl *NewTemplateDecl
8449 = NewFD->getDescribedFunctionTemplate();
8450 assert(NewTemplateDecl && "Template/non-template mismatch");
8451 if (CXXMethodDecl *Method
8452 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8453 Method->setAccess(OldTemplateDecl->getAccess());
8454 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8457 // If this is an explicit specialization of a member that is a function
8458 // template, mark it as a member specialization.
8459 if (IsExplicitSpecialization &&
8460 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8461 NewTemplateDecl->setMemberSpecialization();
8462 assert(OldTemplateDecl->isMemberSpecialization());
8466 // This needs to happen first so that 'inline' propagates.
8467 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8469 if (isa<CXXMethodDecl>(NewFD))
8470 NewFD->setAccess(OldDecl->getAccess());
8474 // Semantic checking for this function declaration (in isolation).
8476 if (getLangOpts().CPlusPlus) {
8477 // C++-specific checks.
8478 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8479 CheckConstructor(Constructor);
8480 } else if (CXXDestructorDecl *Destructor =
8481 dyn_cast<CXXDestructorDecl>(NewFD)) {
8482 CXXRecordDecl *Record = Destructor->getParent();
8483 QualType ClassType = Context.getTypeDeclType(Record);
8485 // FIXME: Shouldn't we be able to perform this check even when the class
8486 // type is dependent? Both gcc and edg can handle that.
8487 if (!ClassType->isDependentType()) {
8488 DeclarationName Name
8489 = Context.DeclarationNames.getCXXDestructorName(
8490 Context.getCanonicalType(ClassType));
8491 if (NewFD->getDeclName() != Name) {
8492 Diag(NewFD->getLocation(), diag::err_destructor_name);
8493 NewFD->setInvalidDecl();
8494 return Redeclaration;
8497 } else if (CXXConversionDecl *Conversion
8498 = dyn_cast<CXXConversionDecl>(NewFD)) {
8499 ActOnConversionDeclarator(Conversion);
8502 // Find any virtual functions that this function overrides.
8503 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8504 if (!Method->isFunctionTemplateSpecialization() &&
8505 !Method->getDescribedFunctionTemplate() &&
8506 Method->isCanonicalDecl()) {
8507 if (AddOverriddenMethods(Method->getParent(), Method)) {
8508 // If the function was marked as "static", we have a problem.
8509 if (NewFD->getStorageClass() == SC_Static) {
8510 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8515 if (Method->isStatic())
8516 checkThisInStaticMemberFunctionType(Method);
8519 // Extra checking for C++ overloaded operators (C++ [over.oper]).
8520 if (NewFD->isOverloadedOperator() &&
8521 CheckOverloadedOperatorDeclaration(NewFD)) {
8522 NewFD->setInvalidDecl();
8523 return Redeclaration;
8526 // Extra checking for C++0x literal operators (C++0x [over.literal]).
8527 if (NewFD->getLiteralIdentifier() &&
8528 CheckLiteralOperatorDeclaration(NewFD)) {
8529 NewFD->setInvalidDecl();
8530 return Redeclaration;
8533 // In C++, check default arguments now that we have merged decls. Unless
8534 // the lexical context is the class, because in this case this is done
8535 // during delayed parsing anyway.
8536 if (!CurContext->isRecord())
8537 CheckCXXDefaultArguments(NewFD);
8539 // If this function declares a builtin function, check the type of this
8540 // declaration against the expected type for the builtin.
8541 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8542 ASTContext::GetBuiltinTypeError Error;
8543 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8544 QualType T = Context.GetBuiltinType(BuiltinID, Error);
8545 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8546 // The type of this function differs from the type of the builtin,
8547 // so forget about the builtin entirely.
8548 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8552 // If this function is declared as being extern "C", then check to see if
8553 // the function returns a UDT (class, struct, or union type) that is not C
8554 // compatible, and if it does, warn the user.
8555 // But, issue any diagnostic on the first declaration only.
8556 if (Previous.empty() && NewFD->isExternC()) {
8557 QualType R = NewFD->getReturnType();
8558 if (R->isIncompleteType() && !R->isVoidType())
8559 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8561 else if (!R.isPODType(Context) && !R->isVoidType() &&
8562 !R->isObjCObjectPointerType())
8563 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8566 return Redeclaration;
8569 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8570 // C++11 [basic.start.main]p3:
8571 // A program that [...] declares main to be inline, static or
8572 // constexpr is ill-formed.
8573 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
8574 // appear in a declaration of main.
8575 // static main is not an error under C99, but we should warn about it.
8576 // We accept _Noreturn main as an extension.
8577 if (FD->getStorageClass() == SC_Static)
8578 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8579 ? diag::err_static_main : diag::warn_static_main)
8580 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8581 if (FD->isInlineSpecified())
8582 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8583 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8584 if (DS.isNoreturnSpecified()) {
8585 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8586 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8587 Diag(NoreturnLoc, diag::ext_noreturn_main);
8588 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8589 << FixItHint::CreateRemoval(NoreturnRange);
8591 if (FD->isConstexpr()) {
8592 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8593 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8594 FD->setConstexpr(false);
8597 if (getLangOpts().OpenCL) {
8598 Diag(FD->getLocation(), diag::err_opencl_no_main)
8599 << FD->hasAttr<OpenCLKernelAttr>();
8600 FD->setInvalidDecl();
8604 QualType T = FD->getType();
8605 assert(T->isFunctionType() && "function decl is not of function type");
8606 const FunctionType* FT = T->castAs<FunctionType>();
8608 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8609 // In C with GNU extensions we allow main() to have non-integer return
8610 // type, but we should warn about the extension, and we disable the
8611 // implicit-return-zero rule.
8613 // GCC in C mode accepts qualified 'int'.
8614 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8615 FD->setHasImplicitReturnZero(true);
8617 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8618 SourceRange RTRange = FD->getReturnTypeSourceRange();
8619 if (RTRange.isValid())
8620 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8621 << FixItHint::CreateReplacement(RTRange, "int");
8624 // In C and C++, main magically returns 0 if you fall off the end;
8625 // set the flag which tells us that.
8626 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8628 // All the standards say that main() should return 'int'.
8629 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8630 FD->setHasImplicitReturnZero(true);
8632 // Otherwise, this is just a flat-out error.
8633 SourceRange RTRange = FD->getReturnTypeSourceRange();
8634 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8635 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8637 FD->setInvalidDecl(true);
8641 // Treat protoless main() as nullary.
8642 if (isa<FunctionNoProtoType>(FT)) return;
8644 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8645 unsigned nparams = FTP->getNumParams();
8646 assert(FD->getNumParams() == nparams);
8648 bool HasExtraParameters = (nparams > 3);
8650 if (FTP->isVariadic()) {
8651 Diag(FD->getLocation(), diag::ext_variadic_main);
8652 // FIXME: if we had information about the location of the ellipsis, we
8653 // could add a FixIt hint to remove it as a parameter.
8656 // Darwin passes an undocumented fourth argument of type char**. If
8657 // other platforms start sprouting these, the logic below will start
8659 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8660 HasExtraParameters = false;
8662 if (HasExtraParameters) {
8663 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8664 FD->setInvalidDecl(true);
8668 // FIXME: a lot of the following diagnostics would be improved
8669 // if we had some location information about types.
8672 Context.getPointerType(Context.getPointerType(Context.CharTy));
8673 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8675 for (unsigned i = 0; i < nparams; ++i) {
8676 QualType AT = FTP->getParamType(i);
8678 bool mismatch = true;
8680 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8682 else if (Expected[i] == CharPP) {
8683 // As an extension, the following forms are okay:
8685 // char const * const *
8688 QualifierCollector qs;
8689 const PointerType* PT;
8690 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8691 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8692 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8695 mismatch = !qs.empty();
8700 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8701 // TODO: suggest replacing given type with expected type
8702 FD->setInvalidDecl(true);
8706 if (nparams == 1 && !FD->isInvalidDecl()) {
8707 Diag(FD->getLocation(), diag::warn_main_one_arg);
8710 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8711 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8712 FD->setInvalidDecl();
8716 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8717 QualType T = FD->getType();
8718 assert(T->isFunctionType() && "function decl is not of function type");
8719 const FunctionType *FT = T->castAs<FunctionType>();
8721 // Set an implicit return of 'zero' if the function can return some integral,
8722 // enumeration, pointer or nullptr type.
8723 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8724 FT->getReturnType()->isAnyPointerType() ||
8725 FT->getReturnType()->isNullPtrType())
8726 // DllMain is exempt because a return value of zero means it failed.
8727 if (FD->getName() != "DllMain")
8728 FD->setHasImplicitReturnZero(true);
8730 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8731 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8732 FD->setInvalidDecl();
8736 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8737 // FIXME: Need strict checking. In C89, we need to check for
8738 // any assignment, increment, decrement, function-calls, or
8739 // commas outside of a sizeof. In C99, it's the same list,
8740 // except that the aforementioned are allowed in unevaluated
8741 // expressions. Everything else falls under the
8742 // "may accept other forms of constant expressions" exception.
8743 // (We never end up here for C++, so the constant expression
8744 // rules there don't matter.)
8745 const Expr *Culprit;
8746 if (Init->isConstantInitializer(Context, false, &Culprit))
8748 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8749 << Culprit->getSourceRange();
8754 // Visits an initialization expression to see if OrigDecl is evaluated in
8755 // its own initialization and throws a warning if it does.
8756 class SelfReferenceChecker
8757 : public EvaluatedExprVisitor<SelfReferenceChecker> {
8762 bool isReferenceType;
8765 llvm::SmallVector<unsigned, 4> InitFieldIndex;
8767 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8769 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8770 S(S), OrigDecl(OrigDecl) {
8772 isRecordType = false;
8773 isReferenceType = false;
8775 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8776 isPODType = VD->getType().isPODType(S.Context);
8777 isRecordType = VD->getType()->isRecordType();
8778 isReferenceType = VD->getType()->isReferenceType();
8782 // For most expressions, just call the visitor. For initializer lists,
8783 // track the index of the field being initialized since fields are
8784 // initialized in order allowing use of previously initialized fields.
8785 void CheckExpr(Expr *E) {
8786 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8792 // Track and increment the index here.
8794 InitFieldIndex.push_back(0);
8795 for (auto Child : InitList->children()) {
8796 CheckExpr(cast<Expr>(Child));
8797 ++InitFieldIndex.back();
8799 InitFieldIndex.pop_back();
8802 // Returns true if MemberExpr is checked and no futher checking is needed.
8803 // Returns false if additional checking is required.
8804 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8805 llvm::SmallVector<FieldDecl*, 4> Fields;
8807 bool ReferenceField = false;
8809 // Get the field memebers used.
8810 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8811 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8814 Fields.push_back(FD);
8815 if (FD->getType()->isReferenceType())
8816 ReferenceField = true;
8817 Base = ME->getBase()->IgnoreParenImpCasts();
8820 // Keep checking only if the base Decl is the same.
8821 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8822 if (!DRE || DRE->getDecl() != OrigDecl)
8825 // A reference field can be bound to an unininitialized field.
8826 if (CheckReference && !ReferenceField)
8829 // Convert FieldDecls to their index number.
8830 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8831 for (const FieldDecl *I : llvm::reverse(Fields))
8832 UsedFieldIndex.push_back(I->getFieldIndex());
8834 // See if a warning is needed by checking the first difference in index
8835 // numbers. If field being used has index less than the field being
8836 // initialized, then the use is safe.
8837 for (auto UsedIter = UsedFieldIndex.begin(),
8838 UsedEnd = UsedFieldIndex.end(),
8839 OrigIter = InitFieldIndex.begin(),
8840 OrigEnd = InitFieldIndex.end();
8841 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8842 if (*UsedIter < *OrigIter)
8844 if (*UsedIter > *OrigIter)
8848 // TODO: Add a different warning which will print the field names.
8849 HandleDeclRefExpr(DRE);
8853 // For most expressions, the cast is directly above the DeclRefExpr.
8854 // For conditional operators, the cast can be outside the conditional
8855 // operator if both expressions are DeclRefExpr's.
8856 void HandleValue(Expr *E) {
8857 E = E->IgnoreParens();
8858 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8859 HandleDeclRefExpr(DRE);
8863 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8864 Visit(CO->getCond());
8865 HandleValue(CO->getTrueExpr());
8866 HandleValue(CO->getFalseExpr());
8870 if (BinaryConditionalOperator *BCO =
8871 dyn_cast<BinaryConditionalOperator>(E)) {
8872 Visit(BCO->getCond());
8873 HandleValue(BCO->getFalseExpr());
8877 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8878 HandleValue(OVE->getSourceExpr());
8882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8883 if (BO->getOpcode() == BO_Comma) {
8884 Visit(BO->getLHS());
8885 HandleValue(BO->getRHS());
8890 if (isa<MemberExpr>(E)) {
8892 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8893 false /*CheckReference*/))
8897 Expr *Base = E->IgnoreParenImpCasts();
8898 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8899 // Check for static member variables and don't warn on them.
8900 if (!isa<FieldDecl>(ME->getMemberDecl()))
8902 Base = ME->getBase()->IgnoreParenImpCasts();
8904 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8905 HandleDeclRefExpr(DRE);
8912 // Reference types not handled in HandleValue are handled here since all
8913 // uses of references are bad, not just r-value uses.
8914 void VisitDeclRefExpr(DeclRefExpr *E) {
8915 if (isReferenceType)
8916 HandleDeclRefExpr(E);
8919 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8920 if (E->getCastKind() == CK_LValueToRValue) {
8921 HandleValue(E->getSubExpr());
8925 Inherited::VisitImplicitCastExpr(E);
8928 void VisitMemberExpr(MemberExpr *E) {
8930 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8934 // Don't warn on arrays since they can be treated as pointers.
8935 if (E->getType()->canDecayToPointerType()) return;
8937 // Warn when a non-static method call is followed by non-static member
8938 // field accesses, which is followed by a DeclRefExpr.
8939 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8940 bool Warn = (MD && !MD->isStatic());
8941 Expr *Base = E->getBase()->IgnoreParenImpCasts();
8942 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8943 if (!isa<FieldDecl>(ME->getMemberDecl()))
8945 Base = ME->getBase()->IgnoreParenImpCasts();
8948 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8950 HandleDeclRefExpr(DRE);
8954 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8955 // Visit that expression.
8959 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8960 Expr *Callee = E->getCallee();
8962 if (isa<UnresolvedLookupExpr>(Callee))
8963 return Inherited::VisitCXXOperatorCallExpr(E);
8966 for (auto Arg: E->arguments())
8967 HandleValue(Arg->IgnoreParenImpCasts());
8970 void VisitUnaryOperator(UnaryOperator *E) {
8971 // For POD record types, addresses of its own members are well-defined.
8972 if (E->getOpcode() == UO_AddrOf && isRecordType &&
8973 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8975 HandleValue(E->getSubExpr());
8979 if (E->isIncrementDecrementOp()) {
8980 HandleValue(E->getSubExpr());
8984 Inherited::VisitUnaryOperator(E);
8987 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8989 void VisitCXXConstructExpr(CXXConstructExpr *E) {
8990 if (E->getConstructor()->isCopyConstructor()) {
8991 Expr *ArgExpr = E->getArg(0);
8992 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8993 if (ILE->getNumInits() == 1)
8994 ArgExpr = ILE->getInit(0);
8995 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8996 if (ICE->getCastKind() == CK_NoOp)
8997 ArgExpr = ICE->getSubExpr();
8998 HandleValue(ArgExpr);
9001 Inherited::VisitCXXConstructExpr(E);
9004 void VisitCallExpr(CallExpr *E) {
9005 // Treat std::move as a use.
9006 if (E->getNumArgs() == 1) {
9007 if (FunctionDecl *FD = E->getDirectCallee()) {
9008 if (FD->isInStdNamespace() && FD->getIdentifier() &&
9009 FD->getIdentifier()->isStr("move")) {
9010 HandleValue(E->getArg(0));
9016 Inherited::VisitCallExpr(E);
9019 void VisitBinaryOperator(BinaryOperator *E) {
9020 if (E->isCompoundAssignmentOp()) {
9021 HandleValue(E->getLHS());
9026 Inherited::VisitBinaryOperator(E);
9029 // A custom visitor for BinaryConditionalOperator is needed because the
9030 // regular visitor would check the condition and true expression separately
9031 // but both point to the same place giving duplicate diagnostics.
9032 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9033 Visit(E->getCond());
9034 Visit(E->getFalseExpr());
9037 void HandleDeclRefExpr(DeclRefExpr *DRE) {
9038 Decl* ReferenceDecl = DRE->getDecl();
9039 if (OrigDecl != ReferenceDecl) return;
9041 if (isReferenceType) {
9042 diag = diag::warn_uninit_self_reference_in_reference_init;
9043 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9044 diag = diag::warn_static_self_reference_in_init;
9045 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9046 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9047 DRE->getDecl()->getType()->isRecordType()) {
9048 diag = diag::warn_uninit_self_reference_in_init;
9050 // Local variables will be handled by the CFG analysis.
9054 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9056 << DRE->getNameInfo().getName()
9057 << OrigDecl->getLocation()
9058 << DRE->getSourceRange());
9062 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9063 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9065 // Parameters arguments are occassionially constructed with itself,
9066 // for instance, in recursive functions. Skip them.
9067 if (isa<ParmVarDecl>(OrigDecl))
9070 E = E->IgnoreParens();
9072 // Skip checking T a = a where T is not a record or reference type.
9073 // Doing so is a way to silence uninitialized warnings.
9074 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9076 if (ICE->getCastKind() == CK_LValueToRValue)
9077 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9078 if (DRE->getDecl() == OrigDecl)
9081 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9085 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9086 DeclarationName Name, QualType Type,
9087 TypeSourceInfo *TSI,
9088 SourceRange Range, bool DirectInit,
9090 bool IsInitCapture = !VDecl;
9091 assert((!VDecl || !VDecl->isInitCapture()) &&
9092 "init captures are expected to be deduced prior to initialization");
9094 ArrayRef<Expr *> DeduceInits = Init;
9096 if (auto *PL = dyn_cast<ParenListExpr>(Init))
9097 DeduceInits = PL->exprs();
9098 else if (auto *IL = dyn_cast<InitListExpr>(Init))
9099 DeduceInits = IL->inits();
9102 // Deduction only works if we have exactly one source expression.
9103 if (DeduceInits.empty()) {
9104 // It isn't possible to write this directly, but it is possible to
9105 // end up in this situation with "auto x(some_pack...);"
9106 Diag(Init->getLocStart(), IsInitCapture
9107 ? diag::err_init_capture_no_expression
9108 : diag::err_auto_var_init_no_expression)
9109 << Name << Type << Range;
9113 if (DeduceInits.size() > 1) {
9114 Diag(DeduceInits[1]->getLocStart(),
9115 IsInitCapture ? diag::err_init_capture_multiple_expressions
9116 : diag::err_auto_var_init_multiple_expressions)
9117 << Name << Type << Range;
9121 Expr *DeduceInit = DeduceInits[0];
9122 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9123 Diag(Init->getLocStart(), IsInitCapture
9124 ? diag::err_init_capture_paren_braces
9125 : diag::err_auto_var_init_paren_braces)
9126 << isa<InitListExpr>(Init) << Name << Type << Range;
9130 // Expressions default to 'id' when we're in a debugger.
9131 bool DefaultedAnyToId = false;
9132 if (getLangOpts().DebuggerCastResultToId &&
9133 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9134 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9135 if (Result.isInvalid()) {
9138 Init = Result.get();
9139 DefaultedAnyToId = true;
9142 QualType DeducedType;
9143 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9145 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9146 else if (isa<InitListExpr>(Init))
9147 Diag(Range.getBegin(),
9148 diag::err_init_capture_deduction_failure_from_init_list)
9150 << (DeduceInit->getType().isNull() ? TSI->getType()
9151 : DeduceInit->getType())
9152 << DeduceInit->getSourceRange();
9154 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9155 << Name << TSI->getType()
9156 << (DeduceInit->getType().isNull() ? TSI->getType()
9157 : DeduceInit->getType())
9158 << DeduceInit->getSourceRange();
9161 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9162 // 'id' instead of a specific object type prevents most of our usual
9164 // We only want to warn outside of template instantiations, though:
9165 // inside a template, the 'id' could have come from a parameter.
9166 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9167 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9168 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9169 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9175 /// AddInitializerToDecl - Adds the initializer Init to the
9176 /// declaration dcl. If DirectInit is true, this is C++ direct
9177 /// initialization rather than copy initialization.
9178 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9179 bool DirectInit, bool TypeMayContainAuto) {
9180 // If there is no declaration, there was an error parsing it. Just ignore
9182 if (!RealDecl || RealDecl->isInvalidDecl()) {
9183 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9188 // Pure-specifiers are handled in ActOnPureSpecifier.
9189 Diag(Method->getLocation(), diag::err_member_function_initialization)
9190 << Method->getDeclName() << Init->getSourceRange();
9191 Method->setInvalidDecl();
9195 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9197 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9198 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9199 RealDecl->setInvalidDecl();
9203 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9204 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9205 // Attempt typo correction early so that the type of the init expression can
9206 // be deduced based on the chosen correction if the original init contains a
9208 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9209 if (!Res.isUsable()) {
9210 RealDecl->setInvalidDecl();
9215 QualType DeducedType = deduceVarTypeFromInitializer(
9216 VDecl, VDecl->getDeclName(), VDecl->getType(),
9217 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9218 if (DeducedType.isNull()) {
9219 RealDecl->setInvalidDecl();
9223 VDecl->setType(DeducedType);
9224 assert(VDecl->isLinkageValid());
9226 // In ARC, infer lifetime.
9227 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9228 VDecl->setInvalidDecl();
9230 // If this is a redeclaration, check that the type we just deduced matches
9231 // the previously declared type.
9232 if (VarDecl *Old = VDecl->getPreviousDecl()) {
9233 // We never need to merge the type, because we cannot form an incomplete
9234 // array of auto, nor deduce such a type.
9235 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9238 // Check the deduced type is valid for a variable declaration.
9239 CheckVariableDeclarationType(VDecl);
9240 if (VDecl->isInvalidDecl())
9244 // dllimport cannot be used on variable definitions.
9245 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9246 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9247 VDecl->setInvalidDecl();
9251 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9252 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9253 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9254 VDecl->setInvalidDecl();
9258 if (!VDecl->getType()->isDependentType()) {
9259 // A definition must end up with a complete type, which means it must be
9260 // complete with the restriction that an array type might be completed by
9261 // the initializer; note that later code assumes this restriction.
9262 QualType BaseDeclType = VDecl->getType();
9263 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9264 BaseDeclType = Array->getElementType();
9265 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9266 diag::err_typecheck_decl_incomplete_type)) {
9267 RealDecl->setInvalidDecl();
9271 // The variable can not have an abstract class type.
9272 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9273 diag::err_abstract_type_in_decl,
9274 AbstractVariableType))
9275 VDecl->setInvalidDecl();
9279 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9280 NamedDecl *Hidden = nullptr;
9281 if (!hasVisibleDefinition(Def, &Hidden) &&
9282 (VDecl->getFormalLinkage() == InternalLinkage ||
9283 VDecl->getDescribedVarTemplate() ||
9284 VDecl->getNumTemplateParameterLists() ||
9285 VDecl->getDeclContext()->isDependentContext())) {
9286 // The previous definition is hidden, and multiple definitions are
9287 // permitted (in separate TUs). Form another definition of it.
9289 Diag(VDecl->getLocation(), diag::err_redefinition)
9290 << VDecl->getDeclName();
9291 Diag(Def->getLocation(), diag::note_previous_definition);
9292 VDecl->setInvalidDecl();
9297 if (getLangOpts().CPlusPlus) {
9298 // C++ [class.static.data]p4
9299 // If a static data member is of const integral or const
9300 // enumeration type, its declaration in the class definition can
9301 // specify a constant-initializer which shall be an integral
9302 // constant expression (5.19). In that case, the member can appear
9303 // in integral constant expressions. The member shall still be
9304 // defined in a namespace scope if it is used in the program and the
9305 // namespace scope definition shall not contain an initializer.
9307 // We already performed a redefinition check above, but for static
9308 // data members we also need to check whether there was an in-class
9309 // declaration with an initializer.
9310 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9311 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9312 << VDecl->getDeclName();
9313 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9314 diag::note_previous_initializer)
9319 if (VDecl->hasLocalStorage())
9320 getCurFunction()->setHasBranchProtectedScope();
9322 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9323 VDecl->setInvalidDecl();
9328 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9329 // a kernel function cannot be initialized."
9330 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9331 Diag(VDecl->getLocation(), diag::err_local_cant_init);
9332 VDecl->setInvalidDecl();
9336 // Get the decls type and save a reference for later, since
9337 // CheckInitializerTypes may change it.
9338 QualType DclT = VDecl->getType(), SavT = DclT;
9340 // Expressions default to 'id' when we're in a debugger
9341 // and we are assigning it to a variable of Objective-C pointer type.
9342 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9343 Init->getType() == Context.UnknownAnyTy) {
9344 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9345 if (Result.isInvalid()) {
9346 VDecl->setInvalidDecl();
9349 Init = Result.get();
9352 // Perform the initialization.
9353 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9354 if (!VDecl->isInvalidDecl()) {
9355 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9356 InitializationKind Kind =
9359 ? InitializationKind::CreateDirect(VDecl->getLocation(),
9360 Init->getLocStart(),
9362 : InitializationKind::CreateDirectList(VDecl->getLocation())
9363 : InitializationKind::CreateCopy(VDecl->getLocation(),
9364 Init->getLocStart());
9366 MultiExprArg Args = Init;
9368 Args = MultiExprArg(CXXDirectInit->getExprs(),
9369 CXXDirectInit->getNumExprs());
9371 // Try to correct any TypoExprs in the initialization arguments.
9372 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9373 ExprResult Res = CorrectDelayedTyposInExpr(
9374 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9375 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9376 return Init.Failed() ? ExprError() : E;
9378 if (Res.isInvalid()) {
9379 VDecl->setInvalidDecl();
9380 } else if (Res.get() != Args[Idx]) {
9381 Args[Idx] = Res.get();
9384 if (VDecl->isInvalidDecl())
9387 InitializationSequence InitSeq(*this, Entity, Kind, Args);
9388 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9389 if (Result.isInvalid()) {
9390 VDecl->setInvalidDecl();
9394 Init = Result.getAs<Expr>();
9397 // Check for self-references within variable initializers.
9398 // Variables declared within a function/method body (except for references)
9399 // are handled by a dataflow analysis.
9400 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9401 VDecl->getType()->isReferenceType()) {
9402 CheckSelfReference(*this, RealDecl, Init, DirectInit);
9405 // If the type changed, it means we had an incomplete type that was
9406 // completed by the initializer. For example:
9407 // int ary[] = { 1, 3, 5 };
9408 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9409 if (!VDecl->isInvalidDecl() && (DclT != SavT))
9410 VDecl->setType(DclT);
9412 if (!VDecl->isInvalidDecl()) {
9413 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9415 if (VDecl->hasAttr<BlocksAttr>())
9416 checkRetainCycles(VDecl, Init);
9418 // It is safe to assign a weak reference into a strong variable.
9419 // Although this code can still have problems:
9420 // id x = self.weakProp;
9421 // id y = self.weakProp;
9422 // we do not warn to warn spuriously when 'x' and 'y' are on separate
9423 // paths through the function. This should be revisited if
9424 // -Wrepeated-use-of-weak is made flow-sensitive.
9425 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9426 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9427 Init->getLocStart()))
9428 getCurFunction()->markSafeWeakUse(Init);
9431 // The initialization is usually a full-expression.
9433 // FIXME: If this is a braced initialization of an aggregate, it is not
9434 // an expression, and each individual field initializer is a separate
9435 // full-expression. For instance, in:
9437 // struct Temp { ~Temp(); };
9438 // struct S { S(Temp); };
9439 // struct T { S a, b; } t = { Temp(), Temp() }
9441 // we should destroy the first Temp before constructing the second.
9442 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9444 VDecl->isConstexpr());
9445 if (Result.isInvalid()) {
9446 VDecl->setInvalidDecl();
9449 Init = Result.get();
9451 // Attach the initializer to the decl.
9452 VDecl->setInit(Init);
9454 if (VDecl->isLocalVarDecl()) {
9455 // C99 6.7.8p4: All the expressions in an initializer for an object that has
9456 // static storage duration shall be constant expressions or string literals.
9457 // C++ does not have this restriction.
9458 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9459 const Expr *Culprit;
9460 if (VDecl->getStorageClass() == SC_Static)
9461 CheckForConstantInitializer(Init, DclT);
9462 // C89 is stricter than C99 for non-static aggregate types.
9463 // C89 6.5.7p3: All the expressions [...] in an initializer list
9464 // for an object that has aggregate or union type shall be
9465 // constant expressions.
9466 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9467 isa<InitListExpr>(Init) &&
9468 !Init->isConstantInitializer(Context, false, &Culprit))
9469 Diag(Culprit->getExprLoc(),
9470 diag::ext_aggregate_init_not_constant)
9471 << Culprit->getSourceRange();
9473 } else if (VDecl->isStaticDataMember() &&
9474 VDecl->getLexicalDeclContext()->isRecord()) {
9475 // This is an in-class initialization for a static data member, e.g.,
9478 // static const int value = 17;
9481 // C++ [class.mem]p4:
9482 // A member-declarator can contain a constant-initializer only
9483 // if it declares a static member (9.4) of const integral or
9484 // const enumeration type, see 9.4.2.
9486 // C++11 [class.static.data]p3:
9487 // If a non-volatile const static data member is of integral or
9488 // enumeration type, its declaration in the class definition can
9489 // specify a brace-or-equal-initializer in which every initalizer-clause
9490 // that is an assignment-expression is a constant expression. A static
9491 // data member of literal type can be declared in the class definition
9492 // with the constexpr specifier; if so, its declaration shall specify a
9493 // brace-or-equal-initializer in which every initializer-clause that is
9494 // an assignment-expression is a constant expression.
9496 // Do nothing on dependent types.
9497 if (DclT->isDependentType()) {
9499 // Allow any 'static constexpr' members, whether or not they are of literal
9500 // type. We separately check that every constexpr variable is of literal
9502 } else if (VDecl->isConstexpr()) {
9504 // Require constness.
9505 } else if (!DclT.isConstQualified()) {
9506 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9507 << Init->getSourceRange();
9508 VDecl->setInvalidDecl();
9510 // We allow integer constant expressions in all cases.
9511 } else if (DclT->isIntegralOrEnumerationType()) {
9512 // Check whether the expression is a constant expression.
9514 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9515 // In C++11, a non-constexpr const static data member with an
9516 // in-class initializer cannot be volatile.
9517 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9518 else if (Init->isValueDependent())
9519 ; // Nothing to check.
9520 else if (Init->isIntegerConstantExpr(Context, &Loc))
9521 ; // Ok, it's an ICE!
9522 else if (Init->isEvaluatable(Context)) {
9523 // If we can constant fold the initializer through heroics, accept it,
9524 // but report this as a use of an extension for -pedantic.
9525 Diag(Loc, diag::ext_in_class_initializer_non_constant)
9526 << Init->getSourceRange();
9528 // Otherwise, this is some crazy unknown case. Report the issue at the
9529 // location provided by the isIntegerConstantExpr failed check.
9530 Diag(Loc, diag::err_in_class_initializer_non_constant)
9531 << Init->getSourceRange();
9532 VDecl->setInvalidDecl();
9535 // We allow foldable floating-point constants as an extension.
9536 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9537 // In C++98, this is a GNU extension. In C++11, it is not, but we support
9538 // it anyway and provide a fixit to add the 'constexpr'.
9539 if (getLangOpts().CPlusPlus11) {
9540 Diag(VDecl->getLocation(),
9541 diag::ext_in_class_initializer_float_type_cxx11)
9542 << DclT << Init->getSourceRange();
9543 Diag(VDecl->getLocStart(),
9544 diag::note_in_class_initializer_float_type_cxx11)
9545 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9547 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9548 << DclT << Init->getSourceRange();
9550 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9551 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9552 << Init->getSourceRange();
9553 VDecl->setInvalidDecl();
9557 // Suggest adding 'constexpr' in C++11 for literal types.
9558 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9559 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9560 << DclT << Init->getSourceRange()
9561 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9562 VDecl->setConstexpr(true);
9565 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9566 << DclT << Init->getSourceRange();
9567 VDecl->setInvalidDecl();
9569 } else if (VDecl->isFileVarDecl()) {
9570 if (VDecl->getStorageClass() == SC_Extern &&
9571 (!getLangOpts().CPlusPlus ||
9572 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9573 VDecl->isExternC())) &&
9574 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9575 Diag(VDecl->getLocation(), diag::warn_extern_init);
9577 // C99 6.7.8p4. All file scoped initializers need to be constant.
9578 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9579 CheckForConstantInitializer(Init, DclT);
9582 // We will represent direct-initialization similarly to copy-initialization:
9583 // int x(1); -as-> int x = 1;
9584 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9586 // Clients that want to distinguish between the two forms, can check for
9587 // direct initializer using VarDecl::getInitStyle().
9588 // A major benefit is that clients that don't particularly care about which
9589 // exactly form was it (like the CodeGen) can handle both cases without
9590 // special case code.
9593 // The form of initialization (using parentheses or '=') is generally
9594 // insignificant, but does matter when the entity being initialized has a
9596 if (CXXDirectInit) {
9597 assert(DirectInit && "Call-style initializer must be direct init.");
9598 VDecl->setInitStyle(VarDecl::CallInit);
9599 } else if (DirectInit) {
9600 // This must be list-initialization. No other way is direct-initialization.
9601 VDecl->setInitStyle(VarDecl::ListInit);
9604 CheckCompleteVariableDeclaration(VDecl);
9607 /// ActOnInitializerError - Given that there was an error parsing an
9608 /// initializer for the given declaration, try to return to some form
9610 void Sema::ActOnInitializerError(Decl *D) {
9611 // Our main concern here is re-establishing invariants like "a
9612 // variable's type is either dependent or complete".
9613 if (!D || D->isInvalidDecl()) return;
9615 VarDecl *VD = dyn_cast<VarDecl>(D);
9618 // Auto types are meaningless if we can't make sense of the initializer.
9619 if (ParsingInitForAutoVars.count(D)) {
9620 D->setInvalidDecl();
9624 QualType Ty = VD->getType();
9625 if (Ty->isDependentType()) return;
9627 // Require a complete type.
9628 if (RequireCompleteType(VD->getLocation(),
9629 Context.getBaseElementType(Ty),
9630 diag::err_typecheck_decl_incomplete_type)) {
9631 VD->setInvalidDecl();
9635 // Require a non-abstract type.
9636 if (RequireNonAbstractType(VD->getLocation(), Ty,
9637 diag::err_abstract_type_in_decl,
9638 AbstractVariableType)) {
9639 VD->setInvalidDecl();
9643 // Don't bother complaining about constructors or destructors,
9647 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9648 bool TypeMayContainAuto) {
9649 // If there is no declaration, there was an error parsing it. Just ignore it.
9653 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9654 QualType Type = Var->getType();
9656 // C++11 [dcl.spec.auto]p3
9657 if (TypeMayContainAuto && Type->getContainedAutoType()) {
9658 Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9659 << Var->getDeclName() << Type;
9660 Var->setInvalidDecl();
9664 // C++11 [class.static.data]p3: A static data member can be declared with
9665 // the constexpr specifier; if so, its declaration shall specify
9666 // a brace-or-equal-initializer.
9667 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9668 // the definition of a variable [...] or the declaration of a static data
9670 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9671 if (Var->isStaticDataMember())
9672 Diag(Var->getLocation(),
9673 diag::err_constexpr_static_mem_var_requires_init)
9674 << Var->getDeclName();
9676 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9677 Var->setInvalidDecl();
9681 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template
9682 // definition having the concept specifier is called a variable concept. A
9683 // concept definition refers to [...] a variable concept and its initializer.
9684 if (Var->isConcept()) {
9685 Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9686 Var->setInvalidDecl();
9690 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9692 if (!Var->isInvalidDecl() &&
9693 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9694 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9695 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9696 Var->setInvalidDecl();
9700 switch (Var->isThisDeclarationADefinition()) {
9701 case VarDecl::Definition:
9702 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9705 // We have an out-of-line definition of a static data member
9706 // that has an in-class initializer, so we type-check this like
9711 case VarDecl::DeclarationOnly:
9712 // It's only a declaration.
9714 // Block scope. C99 6.7p7: If an identifier for an object is
9715 // declared with no linkage (C99 6.2.2p6), the type for the
9716 // object shall be complete.
9717 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9718 !Var->hasLinkage() && !Var->isInvalidDecl() &&
9719 RequireCompleteType(Var->getLocation(), Type,
9720 diag::err_typecheck_decl_incomplete_type))
9721 Var->setInvalidDecl();
9723 // Make sure that the type is not abstract.
9724 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9725 RequireNonAbstractType(Var->getLocation(), Type,
9726 diag::err_abstract_type_in_decl,
9727 AbstractVariableType))
9728 Var->setInvalidDecl();
9729 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9730 Var->getStorageClass() == SC_PrivateExtern) {
9731 Diag(Var->getLocation(), diag::warn_private_extern);
9732 Diag(Var->getLocation(), diag::note_private_extern);
9737 case VarDecl::TentativeDefinition:
9738 // File scope. C99 6.9.2p2: A declaration of an identifier for an
9739 // object that has file scope without an initializer, and without a
9740 // storage-class specifier or with the storage-class specifier "static",
9741 // constitutes a tentative definition. Note: A tentative definition with
9742 // external linkage is valid (C99 6.2.2p5).
9743 if (!Var->isInvalidDecl()) {
9744 if (const IncompleteArrayType *ArrayT
9745 = Context.getAsIncompleteArrayType(Type)) {
9746 if (RequireCompleteType(Var->getLocation(),
9747 ArrayT->getElementType(),
9748 diag::err_illegal_decl_array_incomplete_type))
9749 Var->setInvalidDecl();
9750 } else if (Var->getStorageClass() == SC_Static) {
9751 // C99 6.9.2p3: If the declaration of an identifier for an object is
9752 // a tentative definition and has internal linkage (C99 6.2.2p3), the
9753 // declared type shall not be an incomplete type.
9754 // NOTE: code such as the following
9756 // struct s { int a; };
9757 // is accepted by gcc. Hence here we issue a warning instead of
9758 // an error and we do not invalidate the static declaration.
9759 // NOTE: to avoid multiple warnings, only check the first declaration.
9760 if (Var->isFirstDecl())
9761 RequireCompleteType(Var->getLocation(), Type,
9762 diag::ext_typecheck_decl_incomplete_type);
9766 // Record the tentative definition; we're done.
9767 if (!Var->isInvalidDecl())
9768 TentativeDefinitions.push_back(Var);
9772 // Provide a specific diagnostic for uninitialized variable
9773 // definitions with incomplete array type.
9774 if (Type->isIncompleteArrayType()) {
9775 Diag(Var->getLocation(),
9776 diag::err_typecheck_incomplete_array_needs_initializer);
9777 Var->setInvalidDecl();
9781 // Provide a specific diagnostic for uninitialized variable
9782 // definitions with reference type.
9783 if (Type->isReferenceType()) {
9784 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9785 << Var->getDeclName()
9786 << SourceRange(Var->getLocation(), Var->getLocation());
9787 Var->setInvalidDecl();
9791 // Do not attempt to type-check the default initializer for a
9792 // variable with dependent type.
9793 if (Type->isDependentType())
9796 if (Var->isInvalidDecl())
9799 if (!Var->hasAttr<AliasAttr>()) {
9800 if (RequireCompleteType(Var->getLocation(),
9801 Context.getBaseElementType(Type),
9802 diag::err_typecheck_decl_incomplete_type)) {
9803 Var->setInvalidDecl();
9810 // The variable can not have an abstract class type.
9811 if (RequireNonAbstractType(Var->getLocation(), Type,
9812 diag::err_abstract_type_in_decl,
9813 AbstractVariableType)) {
9814 Var->setInvalidDecl();
9818 // Check for jumps past the implicit initializer. C++0x
9819 // clarifies that this applies to a "variable with automatic
9820 // storage duration", not a "local variable".
9821 // C++11 [stmt.dcl]p3
9822 // A program that jumps from a point where a variable with automatic
9823 // storage duration is not in scope to a point where it is in scope is
9824 // ill-formed unless the variable has scalar type, class type with a
9825 // trivial default constructor and a trivial destructor, a cv-qualified
9826 // version of one of these types, or an array of one of the preceding
9827 // types and is declared without an initializer.
9828 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9829 if (const RecordType *Record
9830 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9831 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9832 // Mark the function for further checking even if the looser rules of
9833 // C++11 do not require such checks, so that we can diagnose
9834 // incompatibilities with C++98.
9835 if (!CXXRecord->isPOD())
9836 getCurFunction()->setHasBranchProtectedScope();
9840 // C++03 [dcl.init]p9:
9841 // If no initializer is specified for an object, and the
9842 // object is of (possibly cv-qualified) non-POD class type (or
9843 // array thereof), the object shall be default-initialized; if
9844 // the object is of const-qualified type, the underlying class
9845 // type shall have a user-declared default
9846 // constructor. Otherwise, if no initializer is specified for
9847 // a non- static object, the object and its subobjects, if
9848 // any, have an indeterminate initial value); if the object
9849 // or any of its subobjects are of const-qualified type, the
9850 // program is ill-formed.
9851 // C++0x [dcl.init]p11:
9852 // If no initializer is specified for an object, the object is
9853 // default-initialized; [...].
9854 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9855 InitializationKind Kind
9856 = InitializationKind::CreateDefault(Var->getLocation());
9858 InitializationSequence InitSeq(*this, Entity, Kind, None);
9859 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9860 if (Init.isInvalid())
9861 Var->setInvalidDecl();
9862 else if (Init.get()) {
9863 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9864 // This is important for template substitution.
9865 Var->setInitStyle(VarDecl::CallInit);
9868 CheckCompleteVariableDeclaration(Var);
9872 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9873 VarDecl *VD = dyn_cast<VarDecl>(D);
9875 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9876 D->setInvalidDecl();
9880 VD->setCXXForRangeDecl(true);
9882 // for-range-declaration cannot be given a storage class specifier.
9884 switch (VD->getStorageClass()) {
9893 case SC_PrivateExtern:
9904 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9905 << VD->getDeclName() << Error;
9906 D->setInvalidDecl();
9911 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9912 IdentifierInfo *Ident,
9913 ParsedAttributes &Attrs,
9914 SourceLocation AttrEnd) {
9915 // C++1y [stmt.iter]p1:
9916 // A range-based for statement of the form
9917 // for ( for-range-identifier : for-range-initializer ) statement
9919 // for ( auto&& for-range-identifier : for-range-initializer ) statement
9920 DeclSpec DS(Attrs.getPool().getFactory());
9922 const char *PrevSpec;
9924 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9925 getPrintingPolicy());
9927 Declarator D(DS, Declarator::ForContext);
9928 D.SetIdentifier(Ident, IdentLoc);
9929 D.takeAttributes(Attrs, AttrEnd);
9931 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9932 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9933 EmptyAttrs, IdentLoc);
9934 Decl *Var = ActOnDeclarator(S, D);
9935 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9936 FinalizeDeclaration(Var);
9937 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9938 AttrEnd.isValid() ? AttrEnd : IdentLoc);
9941 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9942 if (var->isInvalidDecl()) return;
9944 // In Objective-C, don't allow jumps past the implicit initialization of a
9945 // local retaining variable.
9946 if (getLangOpts().ObjC1 &&
9947 var->hasLocalStorage()) {
9948 switch (var->getType().getObjCLifetime()) {
9949 case Qualifiers::OCL_None:
9950 case Qualifiers::OCL_ExplicitNone:
9951 case Qualifiers::OCL_Autoreleasing:
9954 case Qualifiers::OCL_Weak:
9955 case Qualifiers::OCL_Strong:
9956 getCurFunction()->setHasBranchProtectedScope();
9961 // Warn about externally-visible variables being defined without a
9962 // prior declaration. We only want to do this for global
9963 // declarations, but we also specifically need to avoid doing it for
9964 // class members because the linkage of an anonymous class can
9965 // change if it's later given a typedef name.
9966 if (var->isThisDeclarationADefinition() &&
9967 var->getDeclContext()->getRedeclContext()->isFileContext() &&
9968 var->isExternallyVisible() && var->hasLinkage() &&
9969 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9970 var->getLocation())) {
9971 // Find a previous declaration that's not a definition.
9972 VarDecl *prev = var->getPreviousDecl();
9973 while (prev && prev->isThisDeclarationADefinition())
9974 prev = prev->getPreviousDecl();
9977 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9980 if (var->getTLSKind() == VarDecl::TLS_Static) {
9981 const Expr *Culprit;
9982 if (var->getType().isDestructedType()) {
9983 // GNU C++98 edits for __thread, [basic.start.term]p3:
9984 // The type of an object with thread storage duration shall not
9985 // have a non-trivial destructor.
9986 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9987 if (getLangOpts().CPlusPlus11)
9988 Diag(var->getLocation(), diag::note_use_thread_local);
9989 } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9990 !var->getInit()->isConstantInitializer(
9991 Context, var->getType()->isReferenceType(), &Culprit)) {
9992 // GNU C++98 edits for __thread, [basic.start.init]p4:
9993 // An object of thread storage duration shall not require dynamic
9995 // FIXME: Need strict checking here.
9996 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9997 << Culprit->getSourceRange();
9998 if (getLangOpts().CPlusPlus11)
9999 Diag(var->getLocation(), diag::note_use_thread_local);
10004 // Apply section attributes and pragmas to global variables.
10005 bool GlobalStorage = var->hasGlobalStorage();
10006 if (GlobalStorage && var->isThisDeclarationADefinition() &&
10007 ActiveTemplateInstantiations.empty()) {
10008 PragmaStack<StringLiteral *> *Stack = nullptr;
10009 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10010 if (var->getType().isConstQualified())
10011 Stack = &ConstSegStack;
10012 else if (!var->getInit()) {
10013 Stack = &BSSSegStack;
10014 SectionFlags |= ASTContext::PSF_Write;
10016 Stack = &DataSegStack;
10017 SectionFlags |= ASTContext::PSF_Write;
10019 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10020 var->addAttr(SectionAttr::CreateImplicit(
10021 Context, SectionAttr::Declspec_allocate,
10022 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10024 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10025 if (UnifySection(SA->getName(), SectionFlags, var))
10026 var->dropAttr<SectionAttr>();
10028 // Apply the init_seg attribute if this has an initializer. If the
10029 // initializer turns out to not be dynamic, we'll end up ignoring this
10031 if (CurInitSeg && var->getInit())
10032 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10036 // All the following checks are C++ only.
10037 if (!getLangOpts().CPlusPlus) return;
10039 QualType type = var->getType();
10040 if (type->isDependentType()) return;
10042 // __block variables might require us to capture a copy-initializer.
10043 if (var->hasAttr<BlocksAttr>()) {
10044 // It's currently invalid to ever have a __block variable with an
10045 // array type; should we diagnose that here?
10047 // Regardless, we don't want to ignore array nesting when
10048 // constructing this copy.
10049 if (type->isStructureOrClassType()) {
10050 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10051 SourceLocation poi = var->getLocation();
10052 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10054 = PerformMoveOrCopyInitialization(
10055 InitializedEntity::InitializeBlock(poi, type, false),
10056 var, var->getType(), varRef, /*AllowNRVO=*/true);
10057 if (!result.isInvalid()) {
10058 result = MaybeCreateExprWithCleanups(result);
10059 Expr *init = result.getAs<Expr>();
10060 Context.setBlockVarCopyInits(var, init);
10065 Expr *Init = var->getInit();
10066 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10067 QualType baseType = Context.getBaseElementType(type);
10069 if (!var->getDeclContext()->isDependentContext() &&
10070 Init && !Init->isValueDependent()) {
10071 if (IsGlobal && !var->isConstexpr() &&
10072 !getDiagnostics().isIgnored(diag::warn_global_constructor,
10073 var->getLocation())) {
10074 // Warn about globals which don't have a constant initializer. Don't
10075 // warn about globals with a non-trivial destructor because we already
10076 // warned about them.
10077 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10078 if (!(RD && !RD->hasTrivialDestructor()) &&
10079 !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10080 Diag(var->getLocation(), diag::warn_global_constructor)
10081 << Init->getSourceRange();
10084 if (var->isConstexpr()) {
10085 SmallVector<PartialDiagnosticAt, 8> Notes;
10086 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10087 SourceLocation DiagLoc = var->getLocation();
10088 // If the note doesn't add any useful information other than a source
10089 // location, fold it into the primary diagnostic.
10090 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10091 diag::note_invalid_subexpr_in_const_expr) {
10092 DiagLoc = Notes[0].first;
10095 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10096 << var << Init->getSourceRange();
10097 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10098 Diag(Notes[I].first, Notes[I].second);
10100 } else if (var->isUsableInConstantExpressions(Context)) {
10101 // Check whether the initializer of a const variable of integral or
10102 // enumeration type is an ICE now, since we can't tell whether it was
10103 // initialized by a constant expression if we check later.
10104 var->checkInitIsICE();
10108 // Require the destructor.
10109 if (const RecordType *recordType = baseType->getAs<RecordType>())
10110 FinalizeVarWithDestructor(var, recordType);
10113 /// \brief Determines if a variable's alignment is dependent.
10114 static bool hasDependentAlignment(VarDecl *VD) {
10115 if (VD->getType()->isDependentType())
10117 for (auto *I : VD->specific_attrs<AlignedAttr>())
10118 if (I->isAlignmentDependent())
10123 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10124 /// any semantic actions necessary after any initializer has been attached.
10126 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10127 // Note that we are no longer parsing the initializer for this declaration.
10128 ParsingInitForAutoVars.erase(ThisDecl);
10130 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10134 checkAttributesAfterMerging(*this, *VD);
10136 // Perform TLS alignment check here after attributes attached to the variable
10137 // which may affect the alignment have been processed. Only perform the check
10138 // if the target has a maximum TLS alignment (zero means no constraints).
10139 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10140 // Protect the check so that it's not performed on dependent types and
10141 // dependent alignments (we can't determine the alignment in that case).
10142 if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10143 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10144 if (Context.getDeclAlign(VD) > MaxAlignChars) {
10145 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10146 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10147 << (unsigned)MaxAlignChars.getQuantity();
10152 // Static locals inherit dll attributes from their function.
10153 if (VD->isStaticLocal()) {
10154 if (FunctionDecl *FD =
10155 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10156 if (Attr *A = getDLLAttr(FD)) {
10157 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10158 NewAttr->setInherited(true);
10159 VD->addAttr(NewAttr);
10164 // Grab the dllimport or dllexport attribute off of the VarDecl.
10165 const InheritableAttr *DLLAttr = getDLLAttr(VD);
10167 // Imported static data members cannot be defined out-of-line.
10168 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10169 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10170 VD->isThisDeclarationADefinition()) {
10171 // We allow definitions of dllimport class template static data members
10173 CXXRecordDecl *Context =
10174 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10175 bool IsClassTemplateMember =
10176 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10177 Context->getDescribedClassTemplate();
10179 Diag(VD->getLocation(),
10180 IsClassTemplateMember
10181 ? diag::warn_attribute_dllimport_static_field_definition
10182 : diag::err_attribute_dllimport_static_field_definition);
10183 Diag(IA->getLocation(), diag::note_attribute);
10184 if (!IsClassTemplateMember)
10185 VD->setInvalidDecl();
10189 // dllimport/dllexport variables cannot be thread local, their TLS index
10190 // isn't exported with the variable.
10191 if (DLLAttr && VD->getTLSKind()) {
10192 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10193 if (F && getDLLAttr(F)) {
10194 assert(VD->isStaticLocal());
10195 // But if this is a static local in a dlimport/dllexport function, the
10196 // function will never be inlined, which means the var would never be
10197 // imported, so having it marked import/export is safe.
10199 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10201 VD->setInvalidDecl();
10205 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10206 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10207 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10208 VD->dropAttr<UsedAttr>();
10212 const DeclContext *DC = VD->getDeclContext();
10213 // If there's a #pragma GCC visibility in scope, and this isn't a class
10214 // member, set the visibility of this variable.
10215 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10216 AddPushedVisibilityAttribute(VD);
10218 // FIXME: Warn on unused templates.
10219 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10220 !isa<VarTemplatePartialSpecializationDecl>(VD))
10221 MarkUnusedFileScopedDecl(VD);
10223 // Now we have parsed the initializer and can update the table of magic
10225 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10226 !VD->getType()->isIntegralOrEnumerationType())
10229 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10230 const Expr *MagicValueExpr = VD->getInit();
10231 if (!MagicValueExpr) {
10234 llvm::APSInt MagicValueInt;
10235 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10236 Diag(I->getRange().getBegin(),
10237 diag::err_type_tag_for_datatype_not_ice)
10238 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10241 if (MagicValueInt.getActiveBits() > 64) {
10242 Diag(I->getRange().getBegin(),
10243 diag::err_type_tag_for_datatype_too_large)
10244 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10247 uint64_t MagicValue = MagicValueInt.getZExtValue();
10248 RegisterTypeTagForDatatype(I->getArgumentKind(),
10250 I->getMatchingCType(),
10251 I->getLayoutCompatible(),
10252 I->getMustBeNull());
10256 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10257 ArrayRef<Decl *> Group) {
10258 SmallVector<Decl*, 8> Decls;
10260 if (DS.isTypeSpecOwned())
10261 Decls.push_back(DS.getRepAsDecl());
10263 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10264 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10265 if (Decl *D = Group[i]) {
10266 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10267 if (!FirstDeclaratorInGroup)
10268 FirstDeclaratorInGroup = DD;
10269 Decls.push_back(D);
10272 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10273 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10274 handleTagNumbering(Tag, S);
10275 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10276 getLangOpts().CPlusPlus)
10277 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10281 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10284 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10285 /// group, performing any necessary semantic checking.
10286 Sema::DeclGroupPtrTy
10287 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10288 bool TypeMayContainAuto) {
10289 // C++0x [dcl.spec.auto]p7:
10290 // If the type deduced for the template parameter U is not the same in each
10291 // deduction, the program is ill-formed.
10292 // FIXME: When initializer-list support is added, a distinction is needed
10293 // between the deduced type U and the deduced type which 'auto' stands for.
10294 // auto a = 0, b = { 1, 2, 3 };
10295 // is legal because the deduced type U is 'int' in both cases.
10296 if (TypeMayContainAuto && Group.size() > 1) {
10298 CanQualType DeducedCanon;
10299 VarDecl *DeducedDecl = nullptr;
10300 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10301 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10302 AutoType *AT = D->getType()->getContainedAutoType();
10303 // Don't reissue diagnostics when instantiating a template.
10304 if (AT && D->isInvalidDecl())
10306 QualType U = AT ? AT->getDeducedType() : QualType();
10308 CanQualType UCanon = Context.getCanonicalType(U);
10309 if (Deduced.isNull()) {
10311 DeducedCanon = UCanon;
10313 } else if (DeducedCanon != UCanon) {
10314 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10315 diag::err_auto_different_deductions)
10316 << (unsigned)AT->getKeyword()
10317 << Deduced << DeducedDecl->getDeclName()
10318 << U << D->getDeclName()
10319 << DeducedDecl->getInit()->getSourceRange()
10320 << D->getInit()->getSourceRange();
10321 D->setInvalidDecl();
10329 ActOnDocumentableDecls(Group);
10331 return DeclGroupPtrTy::make(
10332 DeclGroupRef::Create(Context, Group.data(), Group.size()));
10335 void Sema::ActOnDocumentableDecl(Decl *D) {
10336 ActOnDocumentableDecls(D);
10339 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10340 // Don't parse the comment if Doxygen diagnostics are ignored.
10341 if (Group.empty() || !Group[0])
10344 if (Diags.isIgnored(diag::warn_doc_param_not_found,
10345 Group[0]->getLocation()) &&
10346 Diags.isIgnored(diag::warn_unknown_comment_command_name,
10347 Group[0]->getLocation()))
10350 if (Group.size() >= 2) {
10351 // This is a decl group. Normally it will contain only declarations
10352 // produced from declarator list. But in case we have any definitions or
10353 // additional declaration references:
10354 // 'typedef struct S {} S;'
10355 // 'typedef struct S *S;'
10357 // FinalizeDeclaratorGroup adds these as separate declarations.
10358 Decl *MaybeTagDecl = Group[0];
10359 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10360 Group = Group.slice(1);
10364 // See if there are any new comments that are not attached to a decl.
10365 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10366 if (!Comments.empty() &&
10367 !Comments.back()->isAttached()) {
10368 // There is at least one comment that not attached to a decl.
10369 // Maybe it should be attached to one of these decls?
10371 // Note that this way we pick up not only comments that precede the
10372 // declaration, but also comments that *follow* the declaration -- thanks to
10373 // the lookahead in the lexer: we've consumed the semicolon and looked
10374 // ahead through comments.
10375 for (unsigned i = 0, e = Group.size(); i != e; ++i)
10376 Context.getCommentForDecl(Group[i], &PP);
10380 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10381 /// to introduce parameters into function prototype scope.
10382 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10383 const DeclSpec &DS = D.getDeclSpec();
10385 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10387 // C++03 [dcl.stc]p2 also permits 'auto'.
10388 StorageClass SC = SC_None;
10389 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10391 } else if (getLangOpts().CPlusPlus &&
10392 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10394 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10395 Diag(DS.getStorageClassSpecLoc(),
10396 diag::err_invalid_storage_class_in_func_decl);
10397 D.getMutableDeclSpec().ClearStorageClassSpecs();
10400 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10401 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10402 << DeclSpec::getSpecifierName(TSCS);
10403 if (DS.isConstexprSpecified())
10404 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10406 if (DS.isConceptSpecified())
10407 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10409 DiagnoseFunctionSpecifiers(DS);
10411 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10412 QualType parmDeclType = TInfo->getType();
10414 if (getLangOpts().CPlusPlus) {
10415 // Check that there are no default arguments inside the type of this
10417 CheckExtraCXXDefaultArguments(D);
10419 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10420 if (D.getCXXScopeSpec().isSet()) {
10421 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10422 << D.getCXXScopeSpec().getRange();
10423 D.getCXXScopeSpec().clear();
10427 // Ensure we have a valid name
10428 IdentifierInfo *II = nullptr;
10430 II = D.getIdentifier();
10432 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10433 << GetNameForDeclarator(D).getName();
10434 D.setInvalidType(true);
10438 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10440 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10443 if (R.isSingleResult()) {
10444 NamedDecl *PrevDecl = R.getFoundDecl();
10445 if (PrevDecl->isTemplateParameter()) {
10446 // Maybe we will complain about the shadowed template parameter.
10447 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10448 // Just pretend that we didn't see the previous declaration.
10449 PrevDecl = nullptr;
10450 } else if (S->isDeclScope(PrevDecl)) {
10451 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10452 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10454 // Recover by removing the name
10456 D.SetIdentifier(nullptr, D.getIdentifierLoc());
10457 D.setInvalidType(true);
10462 // Temporarily put parameter variables in the translation unit, not
10463 // the enclosing context. This prevents them from accidentally
10464 // looking like class members in C++.
10465 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10467 D.getIdentifierLoc(), II,
10468 parmDeclType, TInfo,
10471 if (D.isInvalidType())
10472 New->setInvalidDecl();
10474 assert(S->isFunctionPrototypeScope());
10475 assert(S->getFunctionPrototypeDepth() >= 1);
10476 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10477 S->getNextFunctionPrototypeIndex());
10479 // Add the parameter declaration into this scope.
10482 IdResolver.AddDecl(New);
10484 ProcessDeclAttributes(S, New, D);
10486 if (D.getDeclSpec().isModulePrivateSpecified())
10487 Diag(New->getLocation(), diag::err_module_private_local)
10488 << 1 << New->getDeclName()
10489 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10490 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10492 if (New->hasAttr<BlocksAttr>()) {
10493 Diag(New->getLocation(), diag::err_block_on_nonlocal);
10498 /// \brief Synthesizes a variable for a parameter arising from a
10500 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10501 SourceLocation Loc,
10503 /* FIXME: setting StartLoc == Loc.
10504 Would it be worth to modify callers so as to provide proper source
10505 location for the unnamed parameters, embedding the parameter's type? */
10506 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10507 T, Context.getTrivialTypeSourceInfo(T, Loc),
10509 Param->setImplicit();
10513 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10514 ParmVarDecl * const *ParamEnd) {
10515 // Don't diagnose unused-parameter errors in template instantiations; we
10516 // will already have done so in the template itself.
10517 if (!ActiveTemplateInstantiations.empty())
10520 for (; Param != ParamEnd; ++Param) {
10521 if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10522 !(*Param)->hasAttr<UnusedAttr>()) {
10523 Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10524 << (*Param)->getDeclName();
10529 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10530 ParmVarDecl * const *ParamEnd,
10533 if (LangOpts.NumLargeByValueCopy == 0) // No check.
10536 // Warn if the return value is pass-by-value and larger than the specified
10538 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10539 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10540 if (Size > LangOpts.NumLargeByValueCopy)
10541 Diag(D->getLocation(), diag::warn_return_value_size)
10542 << D->getDeclName() << Size;
10545 // Warn if any parameter is pass-by-value and larger than the specified
10547 for (; Param != ParamEnd; ++Param) {
10548 QualType T = (*Param)->getType();
10549 if (T->isDependentType() || !T.isPODType(Context))
10551 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10552 if (Size > LangOpts.NumLargeByValueCopy)
10553 Diag((*Param)->getLocation(), diag::warn_parameter_size)
10554 << (*Param)->getDeclName() << Size;
10558 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10559 SourceLocation NameLoc, IdentifierInfo *Name,
10560 QualType T, TypeSourceInfo *TSInfo,
10562 // In ARC, infer a lifetime qualifier for appropriate parameter types.
10563 if (getLangOpts().ObjCAutoRefCount &&
10564 T.getObjCLifetime() == Qualifiers::OCL_None &&
10565 T->isObjCLifetimeType()) {
10567 Qualifiers::ObjCLifetime lifetime;
10569 // Special cases for arrays:
10570 // - if it's const, use __unsafe_unretained
10571 // - otherwise, it's an error
10572 if (T->isArrayType()) {
10573 if (!T.isConstQualified()) {
10574 DelayedDiagnostics.add(
10575 sema::DelayedDiagnostic::makeForbiddenType(
10576 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10578 lifetime = Qualifiers::OCL_ExplicitNone;
10580 lifetime = T->getObjCARCImplicitLifetime();
10582 T = Context.getLifetimeQualifiedType(T, lifetime);
10585 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10586 Context.getAdjustedParameterType(T),
10587 TSInfo, SC, nullptr);
10589 // Parameters can not be abstract class types.
10590 // For record types, this is done by the AbstractClassUsageDiagnoser once
10591 // the class has been completely parsed.
10592 if (!CurContext->isRecord() &&
10593 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10594 AbstractParamType))
10595 New->setInvalidDecl();
10597 // Parameter declarators cannot be interface types. All ObjC objects are
10598 // passed by reference.
10599 if (T->isObjCObjectType()) {
10600 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10602 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10603 << FixItHint::CreateInsertion(TypeEndLoc, "*");
10604 T = Context.getObjCObjectPointerType(T);
10608 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10609 // duration shall not be qualified by an address-space qualifier."
10610 // Since all parameters have automatic store duration, they can not have
10611 // an address space.
10612 if (T.getAddressSpace() != 0) {
10613 // OpenCL allows function arguments declared to be an array of a type
10614 // to be qualified with an address space.
10615 if (!(getLangOpts().OpenCL && T->isArrayType())) {
10616 Diag(NameLoc, diag::err_arg_with_address_space);
10617 New->setInvalidDecl();
10624 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10625 SourceLocation LocAfterDecls) {
10626 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10628 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10629 // for a K&R function.
10630 if (!FTI.hasPrototype) {
10631 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10633 if (FTI.Params[i].Param == nullptr) {
10634 SmallString<256> Code;
10635 llvm::raw_svector_ostream(Code)
10636 << " int " << FTI.Params[i].Ident->getName() << ";\n";
10637 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10638 << FTI.Params[i].Ident
10639 << FixItHint::CreateInsertion(LocAfterDecls, Code);
10641 // Implicitly declare the argument as type 'int' for lack of a better
10643 AttributeFactory attrs;
10644 DeclSpec DS(attrs);
10645 const char* PrevSpec; // unused
10646 unsigned DiagID; // unused
10647 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10648 DiagID, Context.getPrintingPolicy());
10649 // Use the identifier location for the type source range.
10650 DS.SetRangeStart(FTI.Params[i].IdentLoc);
10651 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10652 Declarator ParamD(DS, Declarator::KNRTypeListContext);
10653 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10654 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10661 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10662 MultiTemplateParamsArg TemplateParameterLists,
10663 SkipBodyInfo *SkipBody) {
10664 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10665 assert(D.isFunctionDeclarator() && "Not a function declarator!");
10666 Scope *ParentScope = FnBodyScope->getParent();
10668 D.setFunctionDefinitionKind(FDK_Definition);
10669 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10670 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10673 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10674 Consumer.HandleInlineMethodDefinition(D);
10677 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10678 const FunctionDecl*& PossibleZeroParamPrototype) {
10679 // Don't warn about invalid declarations.
10680 if (FD->isInvalidDecl())
10683 // Or declarations that aren't global.
10684 if (!FD->isGlobal())
10687 // Don't warn about C++ member functions.
10688 if (isa<CXXMethodDecl>(FD))
10691 // Don't warn about 'main'.
10695 // Don't warn about inline functions.
10696 if (FD->isInlined())
10699 // Don't warn about function templates.
10700 if (FD->getDescribedFunctionTemplate())
10703 // Don't warn about function template specializations.
10704 if (FD->isFunctionTemplateSpecialization())
10707 // Don't warn for OpenCL kernels.
10708 if (FD->hasAttr<OpenCLKernelAttr>())
10711 // Don't warn on explicitly deleted functions.
10712 if (FD->isDeleted())
10715 bool MissingPrototype = true;
10716 for (const FunctionDecl *Prev = FD->getPreviousDecl();
10717 Prev; Prev = Prev->getPreviousDecl()) {
10718 // Ignore any declarations that occur in function or method
10719 // scope, because they aren't visible from the header.
10720 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10723 MissingPrototype = !Prev->getType()->isFunctionProtoType();
10724 if (FD->getNumParams() == 0)
10725 PossibleZeroParamPrototype = Prev;
10729 return MissingPrototype;
10733 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10734 const FunctionDecl *EffectiveDefinition,
10735 SkipBodyInfo *SkipBody) {
10736 // Don't complain if we're in GNU89 mode and the previous definition
10737 // was an extern inline function.
10738 const FunctionDecl *Definition = EffectiveDefinition;
10740 if (!FD->isDefined(Definition))
10743 if (canRedefineFunction(Definition, getLangOpts()))
10746 // If we don't have a visible definition of the function, and it's inline or
10747 // a template, skip the new definition.
10748 if (SkipBody && !hasVisibleDefinition(Definition) &&
10749 (Definition->getFormalLinkage() == InternalLinkage ||
10750 Definition->isInlined() ||
10751 Definition->getDescribedFunctionTemplate() ||
10752 Definition->getNumTemplateParameterLists())) {
10753 SkipBody->ShouldSkip = true;
10754 if (auto *TD = Definition->getDescribedFunctionTemplate())
10755 makeMergedDefinitionVisible(TD, FD->getLocation());
10757 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10758 FD->getLocation());
10762 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10763 Definition->getStorageClass() == SC_Extern)
10764 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10765 << FD->getDeclName() << getLangOpts().CPlusPlus;
10767 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10769 Diag(Definition->getLocation(), diag::note_previous_definition);
10770 FD->setInvalidDecl();
10774 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10776 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10778 LambdaScopeInfo *LSI = S.PushLambdaScope();
10779 LSI->CallOperator = CallOperator;
10780 LSI->Lambda = LambdaClass;
10781 LSI->ReturnType = CallOperator->getReturnType();
10782 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10784 if (LCD == LCD_None)
10785 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10786 else if (LCD == LCD_ByCopy)
10787 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10788 else if (LCD == LCD_ByRef)
10789 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10790 DeclarationNameInfo DNI = CallOperator->getNameInfo();
10792 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10793 LSI->Mutable = !CallOperator->isConst();
10795 // Add the captures to the LSI so they can be noted as already
10796 // captured within tryCaptureVar.
10797 auto I = LambdaClass->field_begin();
10798 for (const auto &C : LambdaClass->captures()) {
10799 if (C.capturesVariable()) {
10800 VarDecl *VD = C.getCapturedVar();
10801 if (VD->isInitCapture())
10802 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10803 QualType CaptureType = VD->getType();
10804 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10805 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10806 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10807 /*EllipsisLoc*/C.isPackExpansion()
10808 ? C.getEllipsisLoc() : SourceLocation(),
10809 CaptureType, /*Expr*/ nullptr);
10811 } else if (C.capturesThis()) {
10812 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10813 S.getCurrentThisType(), /*Expr*/ nullptr);
10815 LSI->addVLATypeCapture(C.getLocation(), I->getType());
10821 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10822 SkipBodyInfo *SkipBody) {
10823 // Clear the last template instantiation error context.
10824 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10828 FunctionDecl *FD = nullptr;
10830 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10831 FD = FunTmpl->getTemplatedDecl();
10833 FD = cast<FunctionDecl>(D);
10835 // See if this is a redefinition.
10836 if (!FD->isLateTemplateParsed()) {
10837 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10839 // If we're skipping the body, we're done. Don't enter the scope.
10840 if (SkipBody && SkipBody->ShouldSkip)
10844 // If we are instantiating a generic lambda call operator, push
10845 // a LambdaScopeInfo onto the function stack. But use the information
10846 // that's already been calculated (ActOnLambdaExpr) to prime the current
10847 // LambdaScopeInfo.
10848 // When the template operator is being specialized, the LambdaScopeInfo,
10849 // has to be properly restored so that tryCaptureVariable doesn't try
10850 // and capture any new variables. In addition when calculating potential
10851 // captures during transformation of nested lambdas, it is necessary to
10852 // have the LSI properly restored.
10853 if (isGenericLambdaCallOperatorSpecialization(FD)) {
10854 assert(ActiveTemplateInstantiations.size() &&
10855 "There should be an active template instantiation on the stack "
10856 "when instantiating a generic lambda!");
10857 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10860 // Enter a new function scope
10861 PushFunctionScope();
10863 // Builtin functions cannot be defined.
10864 if (unsigned BuiltinID = FD->getBuiltinID()) {
10865 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10866 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10867 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10868 FD->setInvalidDecl();
10872 // The return type of a function definition must be complete
10873 // (C99 6.9.1p3, C++ [dcl.fct]p6).
10874 QualType ResultType = FD->getReturnType();
10875 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10876 !FD->isInvalidDecl() &&
10877 RequireCompleteType(FD->getLocation(), ResultType,
10878 diag::err_func_def_incomplete_result))
10879 FD->setInvalidDecl();
10882 PushDeclContext(FnBodyScope, FD);
10884 // Check the validity of our function parameters
10885 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10886 /*CheckParameterNames=*/true);
10888 // Introduce our parameters into the function scope
10889 for (auto Param : FD->params()) {
10890 Param->setOwningFunction(FD);
10892 // If this has an identifier, add it to the scope stack.
10893 if (Param->getIdentifier() && FnBodyScope) {
10894 CheckShadow(FnBodyScope, Param);
10896 PushOnScopeChains(Param, FnBodyScope);
10900 // If we had any tags defined in the function prototype,
10901 // introduce them into the function scope.
10903 for (ArrayRef<NamedDecl *>::iterator
10904 I = FD->getDeclsInPrototypeScope().begin(),
10905 E = FD->getDeclsInPrototypeScope().end();
10909 // Some of these decls (like enums) may have been pinned to the
10910 // translation unit for lack of a real context earlier. If so, remove
10911 // from the translation unit and reattach to the current context.
10912 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10913 // Is the decl actually in the context?
10914 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10916 Context.getTranslationUnitDecl()->removeDecl(D);
10920 // Either way, reassign the lexical decl context to our FunctionDecl.
10921 D->setLexicalDeclContext(CurContext);
10924 // If the decl has a non-null name, make accessible in the current scope.
10925 if (!D->getName().empty())
10926 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10928 // Similarly, dive into enums and fish their constants out, making them
10929 // accessible in this scope.
10930 if (auto *ED = dyn_cast<EnumDecl>(D)) {
10931 for (auto *EI : ED->enumerators())
10932 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10937 // Ensure that the function's exception specification is instantiated.
10938 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10939 ResolveExceptionSpec(D->getLocation(), FPT);
10941 // dllimport cannot be applied to non-inline function definitions.
10942 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10943 !FD->isTemplateInstantiation()) {
10944 assert(!FD->hasAttr<DLLExportAttr>());
10945 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10946 FD->setInvalidDecl();
10949 // We want to attach documentation to original Decl (which might be
10950 // a function template).
10951 ActOnDocumentableDecl(D);
10952 if (getCurLexicalContext()->isObjCContainer() &&
10953 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10954 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10955 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10960 /// \brief Given the set of return statements within a function body,
10961 /// compute the variables that are subject to the named return value
10964 /// Each of the variables that is subject to the named return value
10965 /// optimization will be marked as NRVO variables in the AST, and any
10966 /// return statement that has a marked NRVO variable as its NRVO candidate can
10967 /// use the named return value optimization.
10969 /// This function applies a very simplistic algorithm for NRVO: if every return
10970 /// statement in the scope of a variable has the same NRVO candidate, that
10971 /// candidate is an NRVO variable.
10972 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10973 ReturnStmt **Returns = Scope->Returns.data();
10975 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10976 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10977 if (!NRVOCandidate->isNRVOVariable())
10978 Returns[I]->setNRVOCandidate(nullptr);
10983 bool Sema::canDelayFunctionBody(const Declarator &D) {
10984 // We can't delay parsing the body of a constexpr function template (yet).
10985 if (D.getDeclSpec().isConstexprSpecified())
10988 // We can't delay parsing the body of a function template with a deduced
10989 // return type (yet).
10990 if (D.getDeclSpec().containsPlaceholderType()) {
10991 // If the placeholder introduces a non-deduced trailing return type,
10992 // we can still delay parsing it.
10993 if (D.getNumTypeObjects()) {
10994 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10995 if (Outer.Kind == DeclaratorChunk::Function &&
10996 Outer.Fun.hasTrailingReturnType()) {
10997 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10998 return Ty.isNull() || !Ty->isUndeducedType();
11007 bool Sema::canSkipFunctionBody(Decl *D) {
11008 // We cannot skip the body of a function (or function template) which is
11009 // constexpr, since we may need to evaluate its body in order to parse the
11010 // rest of the file.
11011 // We cannot skip the body of a function with an undeduced return type,
11012 // because any callers of that function need to know the type.
11013 if (const FunctionDecl *FD = D->getAsFunction())
11014 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11016 return Consumer.shouldSkipFunctionBody(D);
11019 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11020 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11021 FD->setHasSkippedBody();
11022 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11023 MD->setHasSkippedBody();
11024 return ActOnFinishFunctionBody(Decl, nullptr);
11027 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11028 return ActOnFinishFunctionBody(D, BodyArg, false);
11031 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11032 bool IsInstantiation) {
11033 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11035 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11036 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11038 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11039 CheckCompletedCoroutineBody(FD, Body);
11044 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11045 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11046 // If the function has a deduced result type but contains no 'return'
11047 // statements, the result type as written must be exactly 'auto', and
11048 // the deduced result type is 'void'.
11049 if (!FD->getReturnType()->getAs<AutoType>()) {
11050 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11051 << FD->getReturnType();
11052 FD->setInvalidDecl();
11054 // Substitute 'void' for the 'auto' in the type.
11055 TypeLoc ResultType = getReturnTypeLoc(FD);
11056 Context.adjustDeducedFunctionResultType(
11057 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11059 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11060 auto *LSI = getCurLambda();
11061 if (LSI->HasImplicitReturnType) {
11062 deduceClosureReturnType(*LSI);
11064 // C++11 [expr.prim.lambda]p4:
11065 // [...] if there are no return statements in the compound-statement
11066 // [the deduced type is] the type void
11068 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11070 // Update the return type to the deduced type.
11071 const FunctionProtoType *Proto =
11072 FD->getType()->getAs<FunctionProtoType>();
11073 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11074 Proto->getExtProtoInfo()));
11078 // The only way to be included in UndefinedButUsed is if there is an
11079 // ODR use before the definition. Avoid the expensive map lookup if this
11080 // is the first declaration.
11081 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11082 if (!FD->isExternallyVisible())
11083 UndefinedButUsed.erase(FD);
11084 else if (FD->isInlined() &&
11085 !LangOpts.GNUInline &&
11086 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11087 UndefinedButUsed.erase(FD);
11090 // If the function implicitly returns zero (like 'main') or is naked,
11091 // don't complain about missing return statements.
11092 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11093 WP.disableCheckFallThrough();
11095 // MSVC permits the use of pure specifier (=0) on function definition,
11096 // defined at class scope, warn about this non-standard construct.
11097 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11098 Diag(FD->getLocation(), diag::ext_pure_function_definition);
11100 if (!FD->isInvalidDecl()) {
11101 // Don't diagnose unused parameters of defaulted or deleted functions.
11102 if (!FD->isDeleted() && !FD->isDefaulted())
11103 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11104 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11105 FD->getReturnType(), FD);
11107 // If this is a structor, we need a vtable.
11108 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11109 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11110 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11111 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11113 // Try to apply the named return value optimization. We have to check
11114 // if we can do this here because lambdas keep return statements around
11115 // to deduce an implicit return type.
11116 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11117 !FD->isDependentContext())
11118 computeNRVO(Body, getCurFunction());
11121 // GNU warning -Wmissing-prototypes:
11122 // Warn if a global function is defined without a previous
11123 // prototype declaration. This warning is issued even if the
11124 // definition itself provides a prototype. The aim is to detect
11125 // global functions that fail to be declared in header files.
11126 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11127 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11128 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11130 if (PossibleZeroParamPrototype) {
11131 // We found a declaration that is not a prototype,
11132 // but that could be a zero-parameter prototype
11133 if (TypeSourceInfo *TI =
11134 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11135 TypeLoc TL = TI->getTypeLoc();
11136 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11137 Diag(PossibleZeroParamPrototype->getLocation(),
11138 diag::note_declaration_not_a_prototype)
11139 << PossibleZeroParamPrototype
11140 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11145 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11146 const CXXMethodDecl *KeyFunction;
11147 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11149 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11150 MD == KeyFunction->getCanonicalDecl()) {
11151 // Update the key-function state if necessary for this ABI.
11152 if (FD->isInlined() &&
11153 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11154 Context.setNonKeyFunction(MD);
11156 // If the newly-chosen key function is already defined, then we
11157 // need to mark the vtable as used retroactively.
11158 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11159 const FunctionDecl *Definition;
11160 if (KeyFunction && KeyFunction->isDefined(Definition))
11161 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11163 // We just defined they key function; mark the vtable as used.
11164 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11169 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11170 "Function parsing confused");
11171 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11172 assert(MD == getCurMethodDecl() && "Method parsing confused");
11174 if (!MD->isInvalidDecl()) {
11175 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11176 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11177 MD->getReturnType(), MD);
11180 computeNRVO(Body, getCurFunction());
11182 if (getCurFunction()->ObjCShouldCallSuper) {
11183 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11184 << MD->getSelector().getAsString();
11185 getCurFunction()->ObjCShouldCallSuper = false;
11187 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11188 const ObjCMethodDecl *InitMethod = nullptr;
11189 bool isDesignated =
11190 MD->isDesignatedInitializerForTheInterface(&InitMethod);
11191 assert(isDesignated && InitMethod);
11192 (void)isDesignated;
11194 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11195 auto IFace = MD->getClassInterface();
11198 auto SuperD = IFace->getSuperClass();
11201 return SuperD->getIdentifier() ==
11202 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11204 // Don't issue this warning for unavailable inits or direct subclasses
11206 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11207 Diag(MD->getLocation(),
11208 diag::warn_objc_designated_init_missing_super_call);
11209 Diag(InitMethod->getLocation(),
11210 diag::note_objc_designated_init_marked_here);
11212 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11214 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11215 // Don't issue this warning for unavaialable inits.
11216 if (!MD->isUnavailable())
11217 Diag(MD->getLocation(),
11218 diag::warn_objc_secondary_init_missing_init_call);
11219 getCurFunction()->ObjCWarnForNoInitDelegation = false;
11225 assert(!getCurFunction()->ObjCShouldCallSuper &&
11226 "This should only be set for ObjC methods, which should have been "
11227 "handled in the block above.");
11229 // Verify and clean out per-function state.
11230 if (Body && (!FD || !FD->isDefaulted())) {
11231 // C++ constructors that have function-try-blocks can't have return
11232 // statements in the handlers of that block. (C++ [except.handle]p14)
11234 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11235 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11237 // Verify that gotos and switch cases don't jump into scopes illegally.
11238 if (getCurFunction()->NeedsScopeChecking() &&
11239 !PP.isCodeCompletionEnabled())
11240 DiagnoseInvalidJumps(Body);
11242 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11243 if (!Destructor->getParent()->isDependentType())
11244 CheckDestructor(Destructor);
11246 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11247 Destructor->getParent());
11250 // If any errors have occurred, clear out any temporaries that may have
11251 // been leftover. This ensures that these temporaries won't be picked up for
11252 // deletion in some later function.
11253 if (getDiagnostics().hasErrorOccurred() ||
11254 getDiagnostics().getSuppressAllDiagnostics()) {
11255 DiscardCleanupsInEvaluationContext();
11257 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11258 !isa<FunctionTemplateDecl>(dcl)) {
11259 // Since the body is valid, issue any analysis-based warnings that are
11261 ActivePolicy = &WP;
11264 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11265 (!CheckConstexprFunctionDecl(FD) ||
11266 !CheckConstexprFunctionBody(FD, Body)))
11267 FD->setInvalidDecl();
11269 if (FD && FD->hasAttr<NakedAttr>()) {
11270 for (const Stmt *S : Body->children()) {
11271 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11272 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11273 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11274 FD->setInvalidDecl();
11280 assert(ExprCleanupObjects.size() ==
11281 ExprEvalContexts.back().NumCleanupObjects &&
11282 "Leftover temporaries in function");
11283 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11284 assert(MaybeODRUseExprs.empty() &&
11285 "Leftover expressions for odr-use checking");
11288 if (!IsInstantiation)
11291 PopFunctionScopeInfo(ActivePolicy, dcl);
11292 // If any errors have occurred, clear out any temporaries that may have
11293 // been leftover. This ensures that these temporaries won't be picked up for
11294 // deletion in some later function.
11295 if (getDiagnostics().hasErrorOccurred()) {
11296 DiscardCleanupsInEvaluationContext();
11303 /// When we finish delayed parsing of an attribute, we must attach it to the
11305 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11306 ParsedAttributes &Attrs) {
11307 // Always attach attributes to the underlying decl.
11308 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11309 D = TD->getTemplatedDecl();
11310 ProcessDeclAttributeList(S, D, Attrs.getList());
11312 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11313 if (Method->isStatic())
11314 checkThisInStaticMemberFunctionAttributes(Method);
11318 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11319 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11320 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11321 IdentifierInfo &II, Scope *S) {
11322 // Before we produce a declaration for an implicitly defined
11323 // function, see whether there was a locally-scoped declaration of
11324 // this name as a function or variable. If so, use that
11325 // (non-visible) declaration, and complain about it.
11326 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11327 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11328 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11329 return ExternCPrev;
11332 // Extension in C99. Legal in C90, but warn about it.
11334 if (II.getName().startswith("__builtin_"))
11335 diag_id = diag::warn_builtin_unknown;
11336 else if (getLangOpts().C99)
11337 diag_id = diag::ext_implicit_function_decl;
11339 diag_id = diag::warn_implicit_function_decl;
11340 Diag(Loc, diag_id) << &II;
11342 // Because typo correction is expensive, only do it if the implicit
11343 // function declaration is going to be treated as an error.
11344 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11345 TypoCorrection Corrected;
11347 (Corrected = CorrectTypo(
11348 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11349 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11350 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11351 /*ErrorRecovery*/false);
11354 // Set a Declarator for the implicit definition: int foo();
11356 AttributeFactory attrFactory;
11357 DeclSpec DS(attrFactory);
11359 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11360 Context.getPrintingPolicy());
11361 (void)Error; // Silence warning.
11362 assert(!Error && "Error setting up implicit decl!");
11363 SourceLocation NoLoc;
11364 Declarator D(DS, Declarator::BlockContext);
11365 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11366 /*IsAmbiguous=*/false,
11367 /*LParenLoc=*/NoLoc,
11368 /*Params=*/nullptr,
11370 /*EllipsisLoc=*/NoLoc,
11371 /*RParenLoc=*/NoLoc,
11373 /*RefQualifierIsLvalueRef=*/true,
11374 /*RefQualifierLoc=*/NoLoc,
11375 /*ConstQualifierLoc=*/NoLoc,
11376 /*VolatileQualifierLoc=*/NoLoc,
11377 /*RestrictQualifierLoc=*/NoLoc,
11378 /*MutableLoc=*/NoLoc,
11380 /*ESpecRange=*/SourceRange(),
11381 /*Exceptions=*/nullptr,
11382 /*ExceptionRanges=*/nullptr,
11383 /*NumExceptions=*/0,
11384 /*NoexceptExpr=*/nullptr,
11385 /*ExceptionSpecTokens=*/nullptr,
11387 DS.getAttributes(),
11389 D.SetIdentifier(&II, Loc);
11391 // Insert this function into translation-unit scope.
11393 DeclContext *PrevDC = CurContext;
11394 CurContext = Context.getTranslationUnitDecl();
11396 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11399 CurContext = PrevDC;
11401 AddKnownFunctionAttributes(FD);
11406 /// \brief Adds any function attributes that we know a priori based on
11407 /// the declaration of this function.
11409 /// These attributes can apply both to implicitly-declared builtins
11410 /// (like __builtin___printf_chk) or to library-declared functions
11411 /// like NSLog or printf.
11413 /// We need to check for duplicate attributes both here and where user-written
11414 /// attributes are applied to declarations.
11415 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11416 if (FD->isInvalidDecl())
11419 // If this is a built-in function, map its builtin attributes to
11420 // actual attributes.
11421 if (unsigned BuiltinID = FD->getBuiltinID()) {
11422 // Handle printf-formatting attributes.
11423 unsigned FormatIdx;
11425 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11426 if (!FD->hasAttr<FormatAttr>()) {
11427 const char *fmt = "printf";
11428 unsigned int NumParams = FD->getNumParams();
11429 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11430 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11432 FD->addAttr(FormatAttr::CreateImplicit(Context,
11433 &Context.Idents.get(fmt),
11435 HasVAListArg ? 0 : FormatIdx+2,
11436 FD->getLocation()));
11439 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11441 if (!FD->hasAttr<FormatAttr>())
11442 FD->addAttr(FormatAttr::CreateImplicit(Context,
11443 &Context.Idents.get("scanf"),
11445 HasVAListArg ? 0 : FormatIdx+2,
11446 FD->getLocation()));
11449 // Mark const if we don't care about errno and that is the only
11450 // thing preventing the function from being const. This allows
11451 // IRgen to use LLVM intrinsics for such functions.
11452 if (!getLangOpts().MathErrno &&
11453 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11454 if (!FD->hasAttr<ConstAttr>())
11455 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11458 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11459 !FD->hasAttr<ReturnsTwiceAttr>())
11460 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11461 FD->getLocation()));
11462 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11463 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11464 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11465 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11466 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11467 Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11468 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11469 // Assign appropriate attribute depending on CUDA compilation
11470 // mode and the target builtin belongs to. E.g. during host
11471 // compilation, aux builtins are __device__, the rest are __host__.
11472 if (getLangOpts().CUDAIsDevice !=
11473 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11474 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11476 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11480 IdentifierInfo *Name = FD->getIdentifier();
11483 if ((!getLangOpts().CPlusPlus &&
11484 FD->getDeclContext()->isTranslationUnit()) ||
11485 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11486 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11487 LinkageSpecDecl::lang_c)) {
11488 // Okay: this could be a libc/libm/Objective-C function we know
11493 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11494 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11495 // target-specific builtins, perhaps?
11496 if (!FD->hasAttr<FormatAttr>())
11497 FD->addAttr(FormatAttr::CreateImplicit(Context,
11498 &Context.Idents.get("printf"), 2,
11499 Name->isStr("vasprintf") ? 0 : 3,
11500 FD->getLocation()));
11503 if (Name->isStr("__CFStringMakeConstantString")) {
11504 // We already have a __builtin___CFStringMakeConstantString,
11505 // but builds that use -fno-constant-cfstrings don't go through that.
11506 if (!FD->hasAttr<FormatArgAttr>())
11507 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11508 FD->getLocation()));
11512 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11513 TypeSourceInfo *TInfo) {
11514 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11515 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11518 assert(D.isInvalidType() && "no declarator info for valid type");
11519 TInfo = Context.getTrivialTypeSourceInfo(T);
11522 // Scope manipulation handled by caller.
11523 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11525 D.getIdentifierLoc(),
11529 // Bail out immediately if we have an invalid declaration.
11530 if (D.isInvalidType()) {
11531 NewTD->setInvalidDecl();
11535 if (D.getDeclSpec().isModulePrivateSpecified()) {
11536 if (CurContext->isFunctionOrMethod())
11537 Diag(NewTD->getLocation(), diag::err_module_private_local)
11538 << 2 << NewTD->getDeclName()
11539 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11540 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11542 NewTD->setModulePrivate();
11545 // C++ [dcl.typedef]p8:
11546 // If the typedef declaration defines an unnamed class (or
11547 // enum), the first typedef-name declared by the declaration
11548 // to be that class type (or enum type) is used to denote the
11549 // class type (or enum type) for linkage purposes only.
11550 // We need to check whether the type was declared in the declaration.
11551 switch (D.getDeclSpec().getTypeSpecType()) {
11554 case TST_interface:
11557 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11558 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11570 /// \brief Check that this is a valid underlying type for an enum declaration.
11571 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11572 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11573 QualType T = TI->getType();
11575 if (T->isDependentType())
11578 if (const BuiltinType *BT = T->getAs<BuiltinType>())
11579 if (BT->isInteger())
11582 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11586 /// Check whether this is a valid redeclaration of a previous enumeration.
11587 /// \return true if the redeclaration was invalid.
11588 bool Sema::CheckEnumRedeclaration(
11589 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11590 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11591 bool IsFixed = !EnumUnderlyingTy.isNull();
11593 if (IsScoped != Prev->isScoped()) {
11594 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11595 << Prev->isScoped();
11596 Diag(Prev->getLocation(), diag::note_previous_declaration);
11600 if (IsFixed && Prev->isFixed()) {
11601 if (!EnumUnderlyingTy->isDependentType() &&
11602 !Prev->getIntegerType()->isDependentType() &&
11603 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11604 Prev->getIntegerType())) {
11605 // TODO: Highlight the underlying type of the redeclaration.
11606 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11607 << EnumUnderlyingTy << Prev->getIntegerType();
11608 Diag(Prev->getLocation(), diag::note_previous_declaration)
11609 << Prev->getIntegerTypeRange();
11612 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11614 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11616 } else if (IsFixed != Prev->isFixed()) {
11617 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11618 << Prev->isFixed();
11619 Diag(Prev->getLocation(), diag::note_previous_declaration);
11626 /// \brief Get diagnostic %select index for tag kind for
11627 /// redeclaration diagnostic message.
11628 /// WARNING: Indexes apply to particular diagnostics only!
11630 /// \returns diagnostic %select index.
11631 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11633 case TTK_Struct: return 0;
11634 case TTK_Interface: return 1;
11635 case TTK_Class: return 2;
11636 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11640 /// \brief Determine if tag kind is a class-key compatible with
11641 /// class for redeclaration (class, struct, or __interface).
11643 /// \returns true iff the tag kind is compatible.
11644 static bool isClassCompatTagKind(TagTypeKind Tag)
11646 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11649 /// \brief Determine whether a tag with a given kind is acceptable
11650 /// as a redeclaration of the given tag declaration.
11652 /// \returns true if the new tag kind is acceptable, false otherwise.
11653 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11654 TagTypeKind NewTag, bool isDefinition,
11655 SourceLocation NewTagLoc,
11656 const IdentifierInfo *Name) {
11657 // C++ [dcl.type.elab]p3:
11658 // The class-key or enum keyword present in the
11659 // elaborated-type-specifier shall agree in kind with the
11660 // declaration to which the name in the elaborated-type-specifier
11661 // refers. This rule also applies to the form of
11662 // elaborated-type-specifier that declares a class-name or
11663 // friend class since it can be construed as referring to the
11664 // definition of the class. Thus, in any
11665 // elaborated-type-specifier, the enum keyword shall be used to
11666 // refer to an enumeration (7.2), the union class-key shall be
11667 // used to refer to a union (clause 9), and either the class or
11668 // struct class-key shall be used to refer to a class (clause 9)
11669 // declared using the class or struct class-key.
11670 TagTypeKind OldTag = Previous->getTagKind();
11671 if (!isDefinition || !isClassCompatTagKind(NewTag))
11672 if (OldTag == NewTag)
11675 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11676 // Warn about the struct/class tag mismatch.
11677 bool isTemplate = false;
11678 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11679 isTemplate = Record->getDescribedClassTemplate();
11681 if (!ActiveTemplateInstantiations.empty()) {
11682 // In a template instantiation, do not offer fix-its for tag mismatches
11683 // since they usually mess up the template instead of fixing the problem.
11684 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11685 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11686 << getRedeclDiagFromTagKind(OldTag);
11690 if (isDefinition) {
11691 // On definitions, check previous tags and issue a fix-it for each
11692 // one that doesn't match the current tag.
11693 if (Previous->getDefinition()) {
11694 // Don't suggest fix-its for redefinitions.
11698 bool previousMismatch = false;
11699 for (auto I : Previous->redecls()) {
11700 if (I->getTagKind() != NewTag) {
11701 if (!previousMismatch) {
11702 previousMismatch = true;
11703 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11704 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11705 << getRedeclDiagFromTagKind(I->getTagKind());
11707 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11708 << getRedeclDiagFromTagKind(NewTag)
11709 << FixItHint::CreateReplacement(I->getInnerLocStart(),
11710 TypeWithKeyword::getTagTypeKindName(NewTag));
11716 // Check for a previous definition. If current tag and definition
11717 // are same type, do nothing. If no definition, but disagree with
11718 // with previous tag type, give a warning, but no fix-it.
11719 const TagDecl *Redecl = Previous->getDefinition() ?
11720 Previous->getDefinition() : Previous;
11721 if (Redecl->getTagKind() == NewTag) {
11725 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11726 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11727 << getRedeclDiagFromTagKind(OldTag);
11728 Diag(Redecl->getLocation(), diag::note_previous_use);
11730 // If there is a previous definition, suggest a fix-it.
11731 if (Previous->getDefinition()) {
11732 Diag(NewTagLoc, diag::note_struct_class_suggestion)
11733 << getRedeclDiagFromTagKind(Redecl->getTagKind())
11734 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11735 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11743 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11744 /// from an outer enclosing namespace or file scope inside a friend declaration.
11745 /// This should provide the commented out code in the following snippet:
11749 /// struct Y { friend struct /*N::*/ X; };
11752 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11753 SourceLocation NameLoc) {
11754 // While the decl is in a namespace, do repeated lookup of that name and see
11755 // if we get the same namespace back. If we do not, continue until
11756 // translation unit scope, at which point we have a fully qualified NNS.
11757 SmallVector<IdentifierInfo *, 4> Namespaces;
11758 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11759 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11760 // This tag should be declared in a namespace, which can only be enclosed by
11761 // other namespaces. Bail if there's an anonymous namespace in the chain.
11762 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11763 if (!Namespace || Namespace->isAnonymousNamespace())
11764 return FixItHint();
11765 IdentifierInfo *II = Namespace->getIdentifier();
11766 Namespaces.push_back(II);
11767 NamedDecl *Lookup = SemaRef.LookupSingleName(
11768 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11769 if (Lookup == Namespace)
11773 // Once we have all the namespaces, reverse them to go outermost first, and
11775 SmallString<64> Insertion;
11776 llvm::raw_svector_ostream OS(Insertion);
11777 if (DC->isTranslationUnit())
11779 std::reverse(Namespaces.begin(), Namespaces.end());
11780 for (auto *II : Namespaces)
11781 OS << II->getName() << "::";
11782 return FixItHint::CreateInsertion(NameLoc, Insertion);
11785 /// \brief Determine whether a tag originally declared in context \p OldDC can
11786 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11787 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11788 /// using-declaration).
11789 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11790 DeclContext *NewDC) {
11791 OldDC = OldDC->getRedeclContext();
11792 NewDC = NewDC->getRedeclContext();
11794 if (OldDC->Equals(NewDC))
11797 // In MSVC mode, we allow a redeclaration if the contexts are related (either
11798 // encloses the other).
11799 if (S.getLangOpts().MSVCCompat &&
11800 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11806 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
11807 /// former case, Name will be non-null. In the later case, Name will be null.
11808 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11809 /// reference/declaration/definition of a tag.
11811 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11812 /// trailing-type-specifier) other than one in an alias-declaration.
11814 /// \param SkipBody If non-null, will be set to indicate if the caller should
11815 /// skip the definition of this tag and treat it as if it were a declaration.
11816 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11817 SourceLocation KWLoc, CXXScopeSpec &SS,
11818 IdentifierInfo *Name, SourceLocation NameLoc,
11819 AttributeList *Attr, AccessSpecifier AS,
11820 SourceLocation ModulePrivateLoc,
11821 MultiTemplateParamsArg TemplateParameterLists,
11822 bool &OwnedDecl, bool &IsDependent,
11823 SourceLocation ScopedEnumKWLoc,
11824 bool ScopedEnumUsesClassTag,
11825 TypeResult UnderlyingType,
11826 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11827 // If this is not a definition, it must have a name.
11828 IdentifierInfo *OrigName = Name;
11829 assert((Name != nullptr || TUK == TUK_Definition) &&
11830 "Nameless record must be a definition!");
11831 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11834 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11835 bool ScopedEnum = ScopedEnumKWLoc.isValid();
11837 // FIXME: Check explicit specializations more carefully.
11838 bool isExplicitSpecialization = false;
11839 bool Invalid = false;
11841 // We only need to do this matching if we have template parameters
11842 // or a scope specifier, which also conveniently avoids this work
11843 // for non-C++ cases.
11844 if (TemplateParameterLists.size() > 0 ||
11845 (SS.isNotEmpty() && TUK != TUK_Reference)) {
11846 if (TemplateParameterList *TemplateParams =
11847 MatchTemplateParametersToScopeSpecifier(
11848 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11849 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11850 if (Kind == TTK_Enum) {
11851 Diag(KWLoc, diag::err_enum_template);
11855 if (TemplateParams->size() > 0) {
11856 // This is a declaration or definition of a class template (which may
11857 // be a member of another template).
11863 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11864 SS, Name, NameLoc, Attr,
11865 TemplateParams, AS,
11867 /*FriendLoc*/SourceLocation(),
11868 TemplateParameterLists.size()-1,
11869 TemplateParameterLists.data(),
11871 return Result.get();
11873 // The "template<>" header is extraneous.
11874 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11875 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11876 isExplicitSpecialization = true;
11881 // Figure out the underlying type if this a enum declaration. We need to do
11882 // this early, because it's needed to detect if this is an incompatible
11884 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11885 bool EnumUnderlyingIsImplicit = false;
11887 if (Kind == TTK_Enum) {
11888 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11889 // No underlying type explicitly specified, or we failed to parse the
11890 // type, default to int.
11891 EnumUnderlying = Context.IntTy.getTypePtr();
11892 else if (UnderlyingType.get()) {
11893 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11894 // integral type; any cv-qualification is ignored.
11895 TypeSourceInfo *TI = nullptr;
11896 GetTypeFromParser(UnderlyingType.get(), &TI);
11897 EnumUnderlying = TI;
11899 if (CheckEnumUnderlyingType(TI))
11900 // Recover by falling back to int.
11901 EnumUnderlying = Context.IntTy.getTypePtr();
11903 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11904 UPPC_FixedUnderlyingType))
11905 EnumUnderlying = Context.IntTy.getTypePtr();
11907 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11908 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11909 // Microsoft enums are always of int type.
11910 EnumUnderlying = Context.IntTy.getTypePtr();
11911 EnumUnderlyingIsImplicit = true;
11916 DeclContext *SearchDC = CurContext;
11917 DeclContext *DC = CurContext;
11918 bool isStdBadAlloc = false;
11920 RedeclarationKind Redecl = ForRedeclaration;
11921 if (TUK == TUK_Friend || TUK == TUK_Reference)
11922 Redecl = NotForRedeclaration;
11924 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11925 if (Name && SS.isNotEmpty()) {
11926 // We have a nested-name tag ('struct foo::bar').
11928 // Check for invalid 'foo::'.
11929 if (SS.isInvalid()) {
11931 goto CreateNewDecl;
11934 // If this is a friend or a reference to a class in a dependent
11935 // context, don't try to make a decl for it.
11936 if (TUK == TUK_Friend || TUK == TUK_Reference) {
11937 DC = computeDeclContext(SS, false);
11939 IsDependent = true;
11943 DC = computeDeclContext(SS, true);
11945 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11951 if (RequireCompleteDeclContext(SS, DC))
11955 // Look-up name inside 'foo::'.
11956 LookupQualifiedName(Previous, DC);
11958 if (Previous.isAmbiguous())
11961 if (Previous.empty()) {
11962 // Name lookup did not find anything. However, if the
11963 // nested-name-specifier refers to the current instantiation,
11964 // and that current instantiation has any dependent base
11965 // classes, we might find something at instantiation time: treat
11966 // this as a dependent elaborated-type-specifier.
11967 // But this only makes any sense for reference-like lookups.
11968 if (Previous.wasNotFoundInCurrentInstantiation() &&
11969 (TUK == TUK_Reference || TUK == TUK_Friend)) {
11970 IsDependent = true;
11974 // A tag 'foo::bar' must already exist.
11975 Diag(NameLoc, diag::err_not_tag_in_scope)
11976 << Kind << Name << DC << SS.getRange();
11979 goto CreateNewDecl;
11982 // C++14 [class.mem]p14:
11983 // If T is the name of a class, then each of the following shall have a
11984 // name different from T:
11985 // -- every member of class T that is itself a type
11986 if (TUK != TUK_Reference && TUK != TUK_Friend &&
11987 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11990 // If this is a named struct, check to see if there was a previous forward
11991 // declaration or definition.
11992 // FIXME: We're looking into outer scopes here, even when we
11993 // shouldn't be. Doing so can result in ambiguities that we
11994 // shouldn't be diagnosing.
11995 LookupName(Previous, S);
11997 // When declaring or defining a tag, ignore ambiguities introduced
11998 // by types using'ed into this scope.
11999 if (Previous.isAmbiguous() &&
12000 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12001 LookupResult::Filter F = Previous.makeFilter();
12002 while (F.hasNext()) {
12003 NamedDecl *ND = F.next();
12004 if (ND->getDeclContext()->getRedeclContext() != SearchDC)
12010 // C++11 [namespace.memdef]p3:
12011 // If the name in a friend declaration is neither qualified nor
12012 // a template-id and the declaration is a function or an
12013 // elaborated-type-specifier, the lookup to determine whether
12014 // the entity has been previously declared shall not consider
12015 // any scopes outside the innermost enclosing namespace.
12017 // MSVC doesn't implement the above rule for types, so a friend tag
12018 // declaration may be a redeclaration of a type declared in an enclosing
12019 // scope. They do implement this rule for friend functions.
12021 // Does it matter that this should be by scope instead of by
12022 // semantic context?
12023 if (!Previous.empty() && TUK == TUK_Friend) {
12024 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12025 LookupResult::Filter F = Previous.makeFilter();
12026 bool FriendSawTagOutsideEnclosingNamespace = false;
12027 while (F.hasNext()) {
12028 NamedDecl *ND = F.next();
12029 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12030 if (DC->isFileContext() &&
12031 !EnclosingNS->Encloses(ND->getDeclContext())) {
12032 if (getLangOpts().MSVCCompat)
12033 FriendSawTagOutsideEnclosingNamespace = true;
12040 // Diagnose this MSVC extension in the easy case where lookup would have
12041 // unambiguously found something outside the enclosing namespace.
12042 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12043 NamedDecl *ND = Previous.getFoundDecl();
12044 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12045 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12049 // Note: there used to be some attempt at recovery here.
12050 if (Previous.isAmbiguous())
12053 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12054 // FIXME: This makes sure that we ignore the contexts associated
12055 // with C structs, unions, and enums when looking for a matching
12056 // tag declaration or definition. See the similar lookup tweak
12057 // in Sema::LookupName; is there a better way to deal with this?
12058 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12059 SearchDC = SearchDC->getParent();
12063 if (Previous.isSingleResult() &&
12064 Previous.getFoundDecl()->isTemplateParameter()) {
12065 // Maybe we will complain about the shadowed template parameter.
12066 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12067 // Just pretend that we didn't see the previous declaration.
12071 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12072 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12073 // This is a declaration of or a reference to "std::bad_alloc".
12074 isStdBadAlloc = true;
12076 if (Previous.empty() && StdBadAlloc) {
12077 // std::bad_alloc has been implicitly declared (but made invisible to
12078 // name lookup). Fill in this implicit declaration as the previous
12079 // declaration, so that the declarations get chained appropriately.
12080 Previous.addDecl(getStdBadAlloc());
12084 // If we didn't find a previous declaration, and this is a reference
12085 // (or friend reference), move to the correct scope. In C++, we
12086 // also need to do a redeclaration lookup there, just in case
12087 // there's a shadow friend decl.
12088 if (Name && Previous.empty() &&
12089 (TUK == TUK_Reference || TUK == TUK_Friend)) {
12090 if (Invalid) goto CreateNewDecl;
12091 assert(SS.isEmpty());
12093 if (TUK == TUK_Reference) {
12094 // C++ [basic.scope.pdecl]p5:
12095 // -- for an elaborated-type-specifier of the form
12097 // class-key identifier
12099 // if the elaborated-type-specifier is used in the
12100 // decl-specifier-seq or parameter-declaration-clause of a
12101 // function defined in namespace scope, the identifier is
12102 // declared as a class-name in the namespace that contains
12103 // the declaration; otherwise, except as a friend
12104 // declaration, the identifier is declared in the smallest
12105 // non-class, non-function-prototype scope that contains the
12108 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12109 // C structs and unions.
12111 // It is an error in C++ to declare (rather than define) an enum
12112 // type, including via an elaborated type specifier. We'll
12113 // diagnose that later; for now, declare the enum in the same
12114 // scope as we would have picked for any other tag type.
12116 // GNU C also supports this behavior as part of its incomplete
12117 // enum types extension, while GNU C++ does not.
12119 // Find the context where we'll be declaring the tag.
12120 // FIXME: We would like to maintain the current DeclContext as the
12121 // lexical context,
12122 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
12123 SearchDC = SearchDC->getParent();
12125 // Find the scope where we'll be declaring the tag.
12126 while (S->isClassScope() ||
12127 (getLangOpts().CPlusPlus &&
12128 S->isFunctionPrototypeScope()) ||
12129 ((S->getFlags() & Scope::DeclScope) == 0) ||
12130 (S->getEntity() && S->getEntity()->isTransparentContext()))
12131 S = S->getParent();
12133 assert(TUK == TUK_Friend);
12134 // C++ [namespace.memdef]p3:
12135 // If a friend declaration in a non-local class first declares a
12136 // class or function, the friend class or function is a member of
12137 // the innermost enclosing namespace.
12138 SearchDC = SearchDC->getEnclosingNamespaceContext();
12141 // In C++, we need to do a redeclaration lookup to properly
12142 // diagnose some problems.
12143 // FIXME: redeclaration lookup is also used (with and without C++) to find a
12144 // hidden declaration so that we don't get ambiguity errors when using a
12145 // type declared by an elaborated-type-specifier. In C that is not correct
12146 // and we should instead merge compatible types found by lookup.
12147 if (getLangOpts().CPlusPlus) {
12148 Previous.setRedeclarationKind(ForRedeclaration);
12149 LookupQualifiedName(Previous, SearchDC);
12151 Previous.setRedeclarationKind(ForRedeclaration);
12152 LookupName(Previous, S);
12156 // If we have a known previous declaration to use, then use it.
12157 if (Previous.empty() && SkipBody && SkipBody->Previous)
12158 Previous.addDecl(SkipBody->Previous);
12160 if (!Previous.empty()) {
12161 NamedDecl *PrevDecl = Previous.getFoundDecl();
12162 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12164 // It's okay to have a tag decl in the same scope as a typedef
12165 // which hides a tag decl in the same scope. Finding this
12166 // insanity with a redeclaration lookup can only actually happen
12169 // This is also okay for elaborated-type-specifiers, which is
12170 // technically forbidden by the current standard but which is
12171 // okay according to the likely resolution of an open issue;
12172 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12173 if (getLangOpts().CPlusPlus) {
12174 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12175 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12176 TagDecl *Tag = TT->getDecl();
12177 if (Tag->getDeclName() == Name &&
12178 Tag->getDeclContext()->getRedeclContext()
12179 ->Equals(TD->getDeclContext()->getRedeclContext())) {
12182 Previous.addDecl(Tag);
12183 Previous.resolveKind();
12189 // If this is a redeclaration of a using shadow declaration, it must
12190 // declare a tag in the same context. In MSVC mode, we allow a
12191 // redefinition if either context is within the other.
12192 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12193 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12194 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12195 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12196 !(OldTag && isAcceptableTagRedeclContext(
12197 *this, OldTag->getDeclContext(), SearchDC))) {
12198 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12199 Diag(Shadow->getTargetDecl()->getLocation(),
12200 diag::note_using_decl_target);
12201 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12203 // Recover by ignoring the old declaration.
12205 goto CreateNewDecl;
12209 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12210 // If this is a use of a previous tag, or if the tag is already declared
12211 // in the same scope (so that the definition/declaration completes or
12212 // rementions the tag), reuse the decl.
12213 if (TUK == TUK_Reference || TUK == TUK_Friend ||
12214 isDeclInScope(DirectPrevDecl, SearchDC, S,
12215 SS.isNotEmpty() || isExplicitSpecialization)) {
12216 // Make sure that this wasn't declared as an enum and now used as a
12217 // struct or something similar.
12218 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12219 TUK == TUK_Definition, KWLoc,
12221 bool SafeToContinue
12222 = (PrevTagDecl->getTagKind() != TTK_Enum &&
12224 if (SafeToContinue)
12225 Diag(KWLoc, diag::err_use_with_wrong_tag)
12227 << FixItHint::CreateReplacement(SourceRange(KWLoc),
12228 PrevTagDecl->getKindName());
12230 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12231 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12233 if (SafeToContinue)
12234 Kind = PrevTagDecl->getTagKind();
12236 // Recover by making this an anonymous redefinition.
12243 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12244 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12246 // If this is an elaborated-type-specifier for a scoped enumeration,
12247 // the 'class' keyword is not necessary and not permitted.
12248 if (TUK == TUK_Reference || TUK == TUK_Friend) {
12250 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12251 << PrevEnum->isScoped()
12252 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12253 return PrevTagDecl;
12256 QualType EnumUnderlyingTy;
12257 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12258 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12259 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12260 EnumUnderlyingTy = QualType(T, 0);
12262 // All conflicts with previous declarations are recovered by
12263 // returning the previous declaration, unless this is a definition,
12264 // in which case we want the caller to bail out.
12265 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12266 ScopedEnum, EnumUnderlyingTy,
12267 EnumUnderlyingIsImplicit, PrevEnum))
12268 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12271 // C++11 [class.mem]p1:
12272 // A member shall not be declared twice in the member-specification,
12273 // except that a nested class or member class template can be declared
12274 // and then later defined.
12275 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12276 S->isDeclScope(PrevDecl)) {
12277 Diag(NameLoc, diag::ext_member_redeclared);
12278 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12282 // If this is a use, just return the declaration we found, unless
12283 // we have attributes.
12285 // FIXME: In the future, return a variant or some other clue
12286 // for the consumer of this Decl to know it doesn't own it.
12287 // For our current ASTs this shouldn't be a problem, but will
12288 // need to be changed with DeclGroups.
12290 ((TUK == TUK_Reference &&
12291 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
12292 || TUK == TUK_Friend))
12293 return PrevTagDecl;
12295 // Diagnose attempts to redefine a tag.
12296 if (TUK == TUK_Definition) {
12297 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12298 // If we're defining a specialization and the previous definition
12299 // is from an implicit instantiation, don't emit an error
12300 // here; we'll catch this in the general case below.
12301 bool IsExplicitSpecializationAfterInstantiation = false;
12302 if (isExplicitSpecialization) {
12303 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12304 IsExplicitSpecializationAfterInstantiation =
12305 RD->getTemplateSpecializationKind() !=
12306 TSK_ExplicitSpecialization;
12307 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12308 IsExplicitSpecializationAfterInstantiation =
12309 ED->getTemplateSpecializationKind() !=
12310 TSK_ExplicitSpecialization;
12313 NamedDecl *Hidden = nullptr;
12314 if (SkipBody && getLangOpts().CPlusPlus &&
12315 !hasVisibleDefinition(Def, &Hidden)) {
12316 // There is a definition of this tag, but it is not visible. We
12317 // explicitly make use of C++'s one definition rule here, and
12318 // assume that this definition is identical to the hidden one
12319 // we already have. Make the existing definition visible and
12320 // use it in place of this one.
12321 SkipBody->ShouldSkip = true;
12322 makeMergedDefinitionVisible(Hidden, KWLoc);
12324 } else if (!IsExplicitSpecializationAfterInstantiation) {
12325 // A redeclaration in function prototype scope in C isn't
12326 // visible elsewhere, so merely issue a warning.
12327 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12328 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12330 Diag(NameLoc, diag::err_redefinition) << Name;
12331 Diag(Def->getLocation(), diag::note_previous_definition);
12332 // If this is a redefinition, recover by making this
12333 // struct be anonymous, which will make any later
12334 // references get the previous definition.
12340 // If the type is currently being defined, complain
12341 // about a nested redefinition.
12342 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12343 if (TD->isBeingDefined()) {
12344 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12345 Diag(PrevTagDecl->getLocation(),
12346 diag::note_previous_definition);
12353 // Okay, this is definition of a previously declared or referenced
12354 // tag. We're going to create a new Decl for it.
12357 // Okay, we're going to make a redeclaration. If this is some kind
12358 // of reference, make sure we build the redeclaration in the same DC
12359 // as the original, and ignore the current access specifier.
12360 if (TUK == TUK_Friend || TUK == TUK_Reference) {
12361 SearchDC = PrevTagDecl->getDeclContext();
12365 // If we get here we have (another) forward declaration or we
12366 // have a definition. Just create a new decl.
12369 // If we get here, this is a definition of a new tag type in a nested
12370 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12371 // new decl/type. We set PrevDecl to NULL so that the entities
12372 // have distinct types.
12375 // If we get here, we're going to create a new Decl. If PrevDecl
12376 // is non-NULL, it's a definition of the tag declared by
12377 // PrevDecl. If it's NULL, we have a new definition.
12380 // Otherwise, PrevDecl is not a tag, but was found with tag
12381 // lookup. This is only actually possible in C++, where a few
12382 // things like templates still live in the tag namespace.
12384 // Use a better diagnostic if an elaborated-type-specifier
12385 // found the wrong kind of type on the first
12386 // (non-redeclaration) lookup.
12387 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12388 !Previous.isForRedeclaration()) {
12390 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12391 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12392 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12393 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12394 Diag(PrevDecl->getLocation(), diag::note_declared_at);
12397 // Otherwise, only diagnose if the declaration is in scope.
12398 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12399 SS.isNotEmpty() || isExplicitSpecialization)) {
12402 // Diagnose implicit declarations introduced by elaborated types.
12403 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12405 if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12406 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12407 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12408 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12409 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12412 // Otherwise it's a declaration. Call out a particularly common
12414 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12416 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12417 Diag(NameLoc, diag::err_tag_definition_of_typedef)
12418 << Name << Kind << TND->getUnderlyingType();
12419 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12422 // Otherwise, diagnose.
12424 // The tag name clashes with something else in the target scope,
12425 // issue an error and recover by making this tag be anonymous.
12426 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12427 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12432 // The existing declaration isn't relevant to us; we're in a
12433 // new scope, so clear out the previous declaration.
12440 TagDecl *PrevDecl = nullptr;
12441 if (Previous.isSingleResult())
12442 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12444 // If there is an identifier, use the location of the identifier as the
12445 // location of the decl, otherwise use the location of the struct/union
12447 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12449 // Otherwise, create a new declaration. If there is a previous
12450 // declaration of the same entity, the two will be linked via
12454 bool IsForwardReference = false;
12455 if (Kind == TTK_Enum) {
12456 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12457 // enum X { A, B, C } D; D should chain to X.
12458 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12459 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12460 ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12461 // If this is an undefined enum, warn.
12462 if (TUK != TUK_Definition && !Invalid) {
12464 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12465 cast<EnumDecl>(New)->isFixed()) {
12466 // C++0x: 7.2p2: opaque-enum-declaration.
12467 // Conflicts are diagnosed above. Do nothing.
12469 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12470 Diag(Loc, diag::ext_forward_ref_enum_def)
12472 Diag(Def->getLocation(), diag::note_previous_definition);
12474 unsigned DiagID = diag::ext_forward_ref_enum;
12475 if (getLangOpts().MSVCCompat)
12476 DiagID = diag::ext_ms_forward_ref_enum;
12477 else if (getLangOpts().CPlusPlus)
12478 DiagID = diag::err_forward_ref_enum;
12481 // If this is a forward-declared reference to an enumeration, make a
12482 // note of it; we won't actually be introducing the declaration into
12483 // the declaration context.
12484 if (TUK == TUK_Reference)
12485 IsForwardReference = true;
12489 if (EnumUnderlying) {
12490 EnumDecl *ED = cast<EnumDecl>(New);
12491 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12492 ED->setIntegerTypeSourceInfo(TI);
12494 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12495 ED->setPromotionType(ED->getIntegerType());
12499 // struct/union/class
12501 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12502 // struct X { int A; } D; D should chain to X.
12503 if (getLangOpts().CPlusPlus) {
12504 // FIXME: Look for a way to use RecordDecl for simple structs.
12505 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12506 cast_or_null<CXXRecordDecl>(PrevDecl));
12508 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12509 StdBadAlloc = cast<CXXRecordDecl>(New);
12511 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12512 cast_or_null<RecordDecl>(PrevDecl));
12515 // C++11 [dcl.type]p3:
12516 // A type-specifier-seq shall not define a class or enumeration [...].
12517 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12518 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12519 << Context.getTagDeclType(New);
12523 // Maybe add qualifier info.
12524 if (SS.isNotEmpty()) {
12526 // If this is either a declaration or a definition, check the
12527 // nested-name-specifier against the current context. We don't do this
12528 // for explicit specializations, because they have similar checking
12529 // (with more specific diagnostics) in the call to
12530 // CheckMemberSpecialization, below.
12531 if (!isExplicitSpecialization &&
12532 (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12533 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12536 New->setQualifierInfo(SS.getWithLocInContext(Context));
12537 if (TemplateParameterLists.size() > 0) {
12538 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12545 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12546 // Add alignment attributes if necessary; these attributes are checked when
12547 // the ASTContext lays out the structure.
12549 // It is important for implementing the correct semantics that this
12550 // happen here (in act on tag decl). The #pragma pack stack is
12551 // maintained as a result of parser callbacks which can occur at
12552 // many points during the parsing of a struct declaration (because
12553 // the #pragma tokens are effectively skipped over during the
12554 // parsing of the struct).
12555 if (TUK == TUK_Definition) {
12556 AddAlignmentAttributesForRecord(RD);
12557 AddMsStructLayoutForRecord(RD);
12561 if (ModulePrivateLoc.isValid()) {
12562 if (isExplicitSpecialization)
12563 Diag(New->getLocation(), diag::err_module_private_specialization)
12565 << FixItHint::CreateRemoval(ModulePrivateLoc);
12566 // __module_private__ does not apply to local classes. However, we only
12567 // diagnose this as an error when the declaration specifiers are
12568 // freestanding. Here, we just ignore the __module_private__.
12569 else if (!SearchDC->isFunctionOrMethod())
12570 New->setModulePrivate();
12573 // If this is a specialization of a member class (of a class template),
12574 // check the specialization.
12575 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12578 // If we're declaring or defining a tag in function prototype scope in C,
12579 // note that this type can only be used within the function and add it to
12580 // the list of decls to inject into the function definition scope.
12581 if ((Name || Kind == TTK_Enum) &&
12582 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12583 if (getLangOpts().CPlusPlus) {
12584 // C++ [dcl.fct]p6:
12585 // Types shall not be defined in return or parameter types.
12586 if (TUK == TUK_Definition && !IsTypeSpecifier) {
12587 Diag(Loc, diag::err_type_defined_in_param_type)
12592 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12594 DeclsInPrototypeScope.push_back(New);
12598 New->setInvalidDecl();
12601 ProcessDeclAttributeList(S, New, Attr);
12603 // Set the lexical context. If the tag has a C++ scope specifier, the
12604 // lexical context will be different from the semantic context.
12605 New->setLexicalDeclContext(CurContext);
12607 // Mark this as a friend decl if applicable.
12608 // In Microsoft mode, a friend declaration also acts as a forward
12609 // declaration so we always pass true to setObjectOfFriendDecl to make
12610 // the tag name visible.
12611 if (TUK == TUK_Friend)
12612 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12614 // Set the access specifier.
12615 if (!Invalid && SearchDC->isRecord())
12616 SetMemberAccessSpecifier(New, PrevDecl, AS);
12618 if (TUK == TUK_Definition)
12619 New->startDefinition();
12621 // If this has an identifier, add it to the scope stack.
12622 if (TUK == TUK_Friend) {
12623 // We might be replacing an existing declaration in the lookup tables;
12624 // if so, borrow its access specifier.
12626 New->setAccess(PrevDecl->getAccess());
12628 DeclContext *DC = New->getDeclContext()->getRedeclContext();
12629 DC->makeDeclVisibleInContext(New);
12630 if (Name) // can be null along some error paths
12631 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12632 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12634 S = getNonFieldDeclScope(S);
12635 PushOnScopeChains(New, S, !IsForwardReference);
12636 if (IsForwardReference)
12637 SearchDC->makeDeclVisibleInContext(New);
12640 CurContext->addDecl(New);
12643 // If this is the C FILE type, notify the AST context.
12644 if (IdentifierInfo *II = New->getIdentifier())
12645 if (!New->isInvalidDecl() &&
12646 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12648 Context.setFILEDecl(New);
12651 mergeDeclAttributes(New, PrevDecl);
12653 // If there's a #pragma GCC visibility in scope, set the visibility of this
12655 AddPushedVisibilityAttribute(New);
12658 // In C++, don't return an invalid declaration. We can't recover well from
12659 // the cases where we make the type anonymous.
12660 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12663 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12664 AdjustDeclIfTemplate(TagD);
12665 TagDecl *Tag = cast<TagDecl>(TagD);
12667 // Enter the tag context.
12668 PushDeclContext(S, Tag);
12670 ActOnDocumentableDecl(TagD);
12672 // If there's a #pragma GCC visibility in scope, set the visibility of this
12674 AddPushedVisibilityAttribute(Tag);
12677 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12678 assert(isa<ObjCContainerDecl>(IDecl) &&
12679 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12680 DeclContext *OCD = cast<DeclContext>(IDecl);
12681 assert(getContainingDC(OCD) == CurContext &&
12682 "The next DeclContext should be lexically contained in the current one.");
12687 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12688 SourceLocation FinalLoc,
12689 bool IsFinalSpelledSealed,
12690 SourceLocation LBraceLoc) {
12691 AdjustDeclIfTemplate(TagD);
12692 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12694 FieldCollector->StartClass();
12696 if (!Record->getIdentifier())
12699 if (FinalLoc.isValid())
12700 Record->addAttr(new (Context)
12701 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12704 // [...] The class-name is also inserted into the scope of the
12705 // class itself; this is known as the injected-class-name. For
12706 // purposes of access checking, the injected-class-name is treated
12707 // as if it were a public member name.
12708 CXXRecordDecl *InjectedClassName
12709 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12710 Record->getLocStart(), Record->getLocation(),
12711 Record->getIdentifier(),
12712 /*PrevDecl=*/nullptr,
12713 /*DelayTypeCreation=*/true);
12714 Context.getTypeDeclType(InjectedClassName, Record);
12715 InjectedClassName->setImplicit();
12716 InjectedClassName->setAccess(AS_public);
12717 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12718 InjectedClassName->setDescribedClassTemplate(Template);
12719 PushOnScopeChains(InjectedClassName, S);
12720 assert(InjectedClassName->isInjectedClassName() &&
12721 "Broken injected-class-name");
12724 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12725 SourceLocation RBraceLoc) {
12726 AdjustDeclIfTemplate(TagD);
12727 TagDecl *Tag = cast<TagDecl>(TagD);
12728 Tag->setRBraceLoc(RBraceLoc);
12730 // Make sure we "complete" the definition even it is invalid.
12731 if (Tag->isBeingDefined()) {
12732 assert(Tag->isInvalidDecl() && "We should already have completed it");
12733 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12734 RD->completeDefinition();
12737 if (isa<CXXRecordDecl>(Tag))
12738 FieldCollector->FinishClass();
12740 // Exit this scope of this tag's definition.
12743 if (getCurLexicalContext()->isObjCContainer() &&
12744 Tag->getDeclContext()->isFileContext())
12745 Tag->setTopLevelDeclInObjCContainer();
12747 // Notify the consumer that we've defined a tag.
12748 if (!Tag->isInvalidDecl())
12749 Consumer.HandleTagDeclDefinition(Tag);
12752 void Sema::ActOnObjCContainerFinishDefinition() {
12753 // Exit this scope of this interface definition.
12757 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12758 assert(DC == CurContext && "Mismatch of container contexts");
12759 OriginalLexicalContext = DC;
12760 ActOnObjCContainerFinishDefinition();
12763 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12764 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12765 OriginalLexicalContext = nullptr;
12768 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12769 AdjustDeclIfTemplate(TagD);
12770 TagDecl *Tag = cast<TagDecl>(TagD);
12771 Tag->setInvalidDecl();
12773 // Make sure we "complete" the definition even it is invalid.
12774 if (Tag->isBeingDefined()) {
12775 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12776 RD->completeDefinition();
12779 // We're undoing ActOnTagStartDefinition here, not
12780 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12781 // the FieldCollector.
12786 // Note that FieldName may be null for anonymous bitfields.
12787 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12788 IdentifierInfo *FieldName,
12789 QualType FieldTy, bool IsMsStruct,
12790 Expr *BitWidth, bool *ZeroWidth) {
12791 // Default to true; that shouldn't confuse checks for emptiness
12795 // C99 6.7.2.1p4 - verify the field type.
12796 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12797 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12798 // Handle incomplete types with specific error.
12799 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12800 return ExprError();
12802 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12803 << FieldName << FieldTy << BitWidth->getSourceRange();
12804 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12805 << FieldTy << BitWidth->getSourceRange();
12806 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12807 UPPC_BitFieldWidth))
12808 return ExprError();
12810 // If the bit-width is type- or value-dependent, don't try to check
12812 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12815 llvm::APSInt Value;
12816 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12817 if (ICE.isInvalid())
12819 BitWidth = ICE.get();
12821 if (Value != 0 && ZeroWidth)
12822 *ZeroWidth = false;
12824 // Zero-width bitfield is ok for anonymous field.
12825 if (Value == 0 && FieldName)
12826 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12828 if (Value.isSigned() && Value.isNegative()) {
12830 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12831 << FieldName << Value.toString(10);
12832 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12833 << Value.toString(10);
12836 if (!FieldTy->isDependentType()) {
12837 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12838 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12839 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12841 // Over-wide bitfields are an error in C or when using the MSVC bitfield
12843 bool CStdConstraintViolation =
12844 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12845 bool MSBitfieldViolation =
12846 Value.ugt(TypeStorageSize) &&
12847 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12848 if (CStdConstraintViolation || MSBitfieldViolation) {
12849 unsigned DiagWidth =
12850 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12852 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12853 << FieldName << (unsigned)Value.getZExtValue()
12854 << !CStdConstraintViolation << DiagWidth;
12856 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12857 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12861 // Warn on types where the user might conceivably expect to get all
12862 // specified bits as value bits: that's all integral types other than
12864 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12866 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12867 << FieldName << (unsigned)Value.getZExtValue()
12868 << (unsigned)TypeWidth;
12870 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12871 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12878 /// ActOnField - Each field of a C struct/union is passed into this in order
12879 /// to create a FieldDecl object for it.
12880 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12881 Declarator &D, Expr *BitfieldWidth) {
12882 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12883 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12884 /*InitStyle=*/ICIS_NoInit, AS_public);
12888 /// HandleField - Analyze a field of a C struct or a C++ data member.
12890 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12891 SourceLocation DeclStart,
12892 Declarator &D, Expr *BitWidth,
12893 InClassInitStyle InitStyle,
12894 AccessSpecifier AS) {
12895 IdentifierInfo *II = D.getIdentifier();
12896 SourceLocation Loc = DeclStart;
12897 if (II) Loc = D.getIdentifierLoc();
12899 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12900 QualType T = TInfo->getType();
12901 if (getLangOpts().CPlusPlus) {
12902 CheckExtraCXXDefaultArguments(D);
12904 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12905 UPPC_DataMemberType)) {
12906 D.setInvalidType();
12908 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12912 // TR 18037 does not allow fields to be declared with address spaces.
12913 if (T.getQualifiers().hasAddressSpace()) {
12914 Diag(Loc, diag::err_field_with_address_space);
12915 D.setInvalidType();
12918 // OpenCL 1.2 spec, s6.9 r:
12919 // The event type cannot be used to declare a structure or union field.
12920 if (LangOpts.OpenCL && T->isEventT()) {
12921 Diag(Loc, diag::err_event_t_struct_field);
12922 D.setInvalidType();
12925 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12927 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12928 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12929 diag::err_invalid_thread)
12930 << DeclSpec::getSpecifierName(TSCS);
12932 // Check to see if this name was declared as a member previously
12933 NamedDecl *PrevDecl = nullptr;
12934 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12935 LookupName(Previous, S);
12936 switch (Previous.getResultKind()) {
12937 case LookupResult::Found:
12938 case LookupResult::FoundUnresolvedValue:
12939 PrevDecl = Previous.getAsSingle<NamedDecl>();
12942 case LookupResult::FoundOverloaded:
12943 PrevDecl = Previous.getRepresentativeDecl();
12946 case LookupResult::NotFound:
12947 case LookupResult::NotFoundInCurrentInstantiation:
12948 case LookupResult::Ambiguous:
12951 Previous.suppressDiagnostics();
12953 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12954 // Maybe we will complain about the shadowed template parameter.
12955 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12956 // Just pretend that we didn't see the previous declaration.
12957 PrevDecl = nullptr;
12960 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12961 PrevDecl = nullptr;
12964 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12965 SourceLocation TSSL = D.getLocStart();
12967 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12968 TSSL, AS, PrevDecl, &D);
12970 if (NewFD->isInvalidDecl())
12971 Record->setInvalidDecl();
12973 if (D.getDeclSpec().isModulePrivateSpecified())
12974 NewFD->setModulePrivate();
12976 if (NewFD->isInvalidDecl() && PrevDecl) {
12977 // Don't introduce NewFD into scope; there's already something
12978 // with the same name in the same scope.
12980 PushOnScopeChains(NewFD, S);
12982 Record->addDecl(NewFD);
12987 /// \brief Build a new FieldDecl and check its well-formedness.
12989 /// This routine builds a new FieldDecl given the fields name, type,
12990 /// record, etc. \p PrevDecl should refer to any previous declaration
12991 /// with the same name and in the same scope as the field to be
12994 /// \returns a new FieldDecl.
12996 /// \todo The Declarator argument is a hack. It will be removed once
12997 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12998 TypeSourceInfo *TInfo,
12999 RecordDecl *Record, SourceLocation Loc,
13000 bool Mutable, Expr *BitWidth,
13001 InClassInitStyle InitStyle,
13002 SourceLocation TSSL,
13003 AccessSpecifier AS, NamedDecl *PrevDecl,
13005 IdentifierInfo *II = Name.getAsIdentifierInfo();
13006 bool InvalidDecl = false;
13007 if (D) InvalidDecl = D->isInvalidType();
13009 // If we receive a broken type, recover by assuming 'int' and
13010 // marking this declaration as invalid.
13012 InvalidDecl = true;
13016 QualType EltTy = Context.getBaseElementType(T);
13017 if (!EltTy->isDependentType()) {
13018 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13019 // Fields of incomplete type force their record to be invalid.
13020 Record->setInvalidDecl();
13021 InvalidDecl = true;
13024 EltTy->isIncompleteType(&Def);
13025 if (Def && Def->isInvalidDecl()) {
13026 Record->setInvalidDecl();
13027 InvalidDecl = true;
13032 // OpenCL v1.2 s6.9.c: bitfields are not supported.
13033 if (BitWidth && getLangOpts().OpenCL) {
13034 Diag(Loc, diag::err_opencl_bitfields);
13035 InvalidDecl = true;
13038 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13039 // than a variably modified type.
13040 if (!InvalidDecl && T->isVariablyModifiedType()) {
13041 bool SizeIsNegative;
13042 llvm::APSInt Oversized;
13044 TypeSourceInfo *FixedTInfo =
13045 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13049 Diag(Loc, diag::warn_illegal_constant_array_size);
13050 TInfo = FixedTInfo;
13051 T = FixedTInfo->getType();
13053 if (SizeIsNegative)
13054 Diag(Loc, diag::err_typecheck_negative_array_size);
13055 else if (Oversized.getBoolValue())
13056 Diag(Loc, diag::err_array_too_large)
13057 << Oversized.toString(10);
13059 Diag(Loc, diag::err_typecheck_field_variable_size);
13060 InvalidDecl = true;
13064 // Fields can not have abstract class types
13065 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13066 diag::err_abstract_type_in_decl,
13067 AbstractFieldType))
13068 InvalidDecl = true;
13070 bool ZeroWidth = false;
13072 BitWidth = nullptr;
13073 // If this is declared as a bit-field, check the bit-field.
13075 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13078 InvalidDecl = true;
13079 BitWidth = nullptr;
13084 // Check that 'mutable' is consistent with the type of the declaration.
13085 if (!InvalidDecl && Mutable) {
13086 unsigned DiagID = 0;
13087 if (T->isReferenceType())
13088 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13089 : diag::err_mutable_reference;
13090 else if (T.isConstQualified())
13091 DiagID = diag::err_mutable_const;
13094 SourceLocation ErrLoc = Loc;
13095 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13096 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13097 Diag(ErrLoc, DiagID);
13098 if (DiagID != diag::ext_mutable_reference) {
13100 InvalidDecl = true;
13105 // C++11 [class.union]p8 (DR1460):
13106 // At most one variant member of a union may have a
13107 // brace-or-equal-initializer.
13108 if (InitStyle != ICIS_NoInit)
13109 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13111 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13112 BitWidth, Mutable, InitStyle);
13114 NewFD->setInvalidDecl();
13116 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13117 Diag(Loc, diag::err_duplicate_member) << II;
13118 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13119 NewFD->setInvalidDecl();
13122 if (!InvalidDecl && getLangOpts().CPlusPlus) {
13123 if (Record->isUnion()) {
13124 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13125 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13126 if (RDecl->getDefinition()) {
13127 // C++ [class.union]p1: An object of a class with a non-trivial
13128 // constructor, a non-trivial copy constructor, a non-trivial
13129 // destructor, or a non-trivial copy assignment operator
13130 // cannot be a member of a union, nor can an array of such
13132 if (CheckNontrivialField(NewFD))
13133 NewFD->setInvalidDecl();
13137 // C++ [class.union]p1: If a union contains a member of reference type,
13138 // the program is ill-formed, except when compiling with MSVC extensions
13140 if (EltTy->isReferenceType()) {
13141 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13142 diag::ext_union_member_of_reference_type :
13143 diag::err_union_member_of_reference_type)
13144 << NewFD->getDeclName() << EltTy;
13145 if (!getLangOpts().MicrosoftExt)
13146 NewFD->setInvalidDecl();
13151 // FIXME: We need to pass in the attributes given an AST
13152 // representation, not a parser representation.
13154 // FIXME: The current scope is almost... but not entirely... correct here.
13155 ProcessDeclAttributes(getCurScope(), NewFD, *D);
13157 if (NewFD->hasAttrs())
13158 CheckAlignasUnderalignment(NewFD);
13161 // In auto-retain/release, infer strong retension for fields of
13162 // retainable type.
13163 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13164 NewFD->setInvalidDecl();
13166 if (T.isObjCGCWeak())
13167 Diag(Loc, diag::warn_attribute_weak_on_field);
13169 NewFD->setAccess(AS);
13173 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13175 assert(getLangOpts().CPlusPlus && "valid check only for C++");
13177 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13180 QualType EltTy = Context.getBaseElementType(FD->getType());
13181 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13182 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13183 if (RDecl->getDefinition()) {
13184 // We check for copy constructors before constructors
13185 // because otherwise we'll never get complaints about
13186 // copy constructors.
13188 CXXSpecialMember member = CXXInvalid;
13189 // We're required to check for any non-trivial constructors. Since the
13190 // implicit default constructor is suppressed if there are any
13191 // user-declared constructors, we just need to check that there is a
13192 // trivial default constructor and a trivial copy constructor. (We don't
13193 // worry about move constructors here, since this is a C++98 check.)
13194 if (RDecl->hasNonTrivialCopyConstructor())
13195 member = CXXCopyConstructor;
13196 else if (!RDecl->hasTrivialDefaultConstructor())
13197 member = CXXDefaultConstructor;
13198 else if (RDecl->hasNonTrivialCopyAssignment())
13199 member = CXXCopyAssignment;
13200 else if (RDecl->hasNonTrivialDestructor())
13201 member = CXXDestructor;
13203 if (member != CXXInvalid) {
13204 if (!getLangOpts().CPlusPlus11 &&
13205 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13206 // Objective-C++ ARC: it is an error to have a non-trivial field of
13207 // a union. However, system headers in Objective-C programs
13208 // occasionally have Objective-C lifetime objects within unions,
13209 // and rather than cause the program to fail, we make those
13210 // members unavailable.
13211 SourceLocation Loc = FD->getLocation();
13212 if (getSourceManager().isInSystemHeader(Loc)) {
13213 if (!FD->hasAttr<UnavailableAttr>())
13214 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13215 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13220 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13221 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13222 diag::err_illegal_union_or_anon_struct_member)
13223 << FD->getParent()->isUnion() << FD->getDeclName() << member;
13224 DiagnoseNontrivial(RDecl, member);
13225 return !getLangOpts().CPlusPlus11;
13233 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13234 /// AST enum value.
13235 static ObjCIvarDecl::AccessControl
13236 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13237 switch (ivarVisibility) {
13238 default: llvm_unreachable("Unknown visitibility kind");
13239 case tok::objc_private: return ObjCIvarDecl::Private;
13240 case tok::objc_public: return ObjCIvarDecl::Public;
13241 case tok::objc_protected: return ObjCIvarDecl::Protected;
13242 case tok::objc_package: return ObjCIvarDecl::Package;
13246 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13247 /// in order to create an IvarDecl object for it.
13248 Decl *Sema::ActOnIvar(Scope *S,
13249 SourceLocation DeclStart,
13250 Declarator &D, Expr *BitfieldWidth,
13251 tok::ObjCKeywordKind Visibility) {
13253 IdentifierInfo *II = D.getIdentifier();
13254 Expr *BitWidth = (Expr*)BitfieldWidth;
13255 SourceLocation Loc = DeclStart;
13256 if (II) Loc = D.getIdentifierLoc();
13258 // FIXME: Unnamed fields can be handled in various different ways, for
13259 // example, unnamed unions inject all members into the struct namespace!
13261 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13262 QualType T = TInfo->getType();
13265 // 6.7.2.1p3, 6.7.2.1p4
13266 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13268 D.setInvalidType();
13275 if (T->isReferenceType()) {
13276 Diag(Loc, diag::err_ivar_reference_type);
13277 D.setInvalidType();
13279 // C99 6.7.2.1p8: A member of a structure or union may have any type other
13280 // than a variably modified type.
13281 else if (T->isVariablyModifiedType()) {
13282 Diag(Loc, diag::err_typecheck_ivar_variable_size);
13283 D.setInvalidType();
13286 // Get the visibility (access control) for this ivar.
13287 ObjCIvarDecl::AccessControl ac =
13288 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13289 : ObjCIvarDecl::None;
13290 // Must set ivar's DeclContext to its enclosing interface.
13291 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13292 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13294 ObjCContainerDecl *EnclosingContext;
13295 if (ObjCImplementationDecl *IMPDecl =
13296 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13297 if (LangOpts.ObjCRuntime.isFragile()) {
13298 // Case of ivar declared in an implementation. Context is that of its class.
13299 EnclosingContext = IMPDecl->getClassInterface();
13300 assert(EnclosingContext && "Implementation has no class interface!");
13303 EnclosingContext = EnclosingDecl;
13305 if (ObjCCategoryDecl *CDecl =
13306 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13307 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13308 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13312 EnclosingContext = EnclosingDecl;
13315 // Construct the decl.
13316 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13317 DeclStart, Loc, II, T,
13318 TInfo, ac, (Expr *)BitfieldWidth);
13321 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13323 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13324 && !isa<TagDecl>(PrevDecl)) {
13325 Diag(Loc, diag::err_duplicate_member) << II;
13326 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13327 NewID->setInvalidDecl();
13331 // Process attributes attached to the ivar.
13332 ProcessDeclAttributes(S, NewID, D);
13334 if (D.isInvalidType())
13335 NewID->setInvalidDecl();
13337 // In ARC, infer 'retaining' for ivars of retainable type.
13338 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13339 NewID->setInvalidDecl();
13341 if (D.getDeclSpec().isModulePrivateSpecified())
13342 NewID->setModulePrivate();
13345 // FIXME: When interfaces are DeclContexts, we'll need to add
13346 // these to the interface.
13348 IdResolver.AddDecl(NewID);
13351 if (LangOpts.ObjCRuntime.isNonFragile() &&
13352 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13353 Diag(Loc, diag::warn_ivars_in_interface);
13358 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13359 /// class and class extensions. For every class \@interface and class
13360 /// extension \@interface, if the last ivar is a bitfield of any type,
13361 /// then add an implicit `char :0` ivar to the end of that interface.
13362 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13363 SmallVectorImpl<Decl *> &AllIvarDecls) {
13364 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13367 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13368 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13370 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13372 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13374 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13375 if (!CD->IsClassExtension())
13378 // No need to add this to end of @implementation.
13382 // All conditions are met. Add a new bitfield to the tail end of ivars.
13383 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13384 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13386 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13387 DeclLoc, DeclLoc, nullptr,
13389 Context.getTrivialTypeSourceInfo(Context.CharTy,
13391 ObjCIvarDecl::Private, BW,
13393 AllIvarDecls.push_back(Ivar);
13396 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13397 ArrayRef<Decl *> Fields, SourceLocation LBrac,
13398 SourceLocation RBrac, AttributeList *Attr) {
13399 assert(EnclosingDecl && "missing record or interface decl");
13401 // If this is an Objective-C @implementation or category and we have
13402 // new fields here we should reset the layout of the interface since
13403 // it will now change.
13404 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13405 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13406 switch (DC->getKind()) {
13408 case Decl::ObjCCategory:
13409 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13411 case Decl::ObjCImplementation:
13413 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13418 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13420 // Start counting up the number of named members; make sure to include
13421 // members of anonymous structs and unions in the total.
13422 unsigned NumNamedMembers = 0;
13424 for (const auto *I : Record->decls()) {
13425 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13426 if (IFD->getDeclName())
13431 // Verify that all the fields are okay.
13432 SmallVector<FieldDecl*, 32> RecFields;
13434 bool ARCErrReported = false;
13435 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13437 FieldDecl *FD = cast<FieldDecl>(*i);
13439 // Get the type for the field.
13440 const Type *FDTy = FD->getType().getTypePtr();
13442 if (!FD->isAnonymousStructOrUnion()) {
13443 // Remember all fields written by the user.
13444 RecFields.push_back(FD);
13447 // If the field is already invalid for some reason, don't emit more
13448 // diagnostics about it.
13449 if (FD->isInvalidDecl()) {
13450 EnclosingDecl->setInvalidDecl();
13455 // A structure or union shall not contain a member with
13456 // incomplete or function type (hence, a structure shall not
13457 // contain an instance of itself, but may contain a pointer to
13458 // an instance of itself), except that the last member of a
13459 // structure with more than one named member may have incomplete
13460 // array type; such a structure (and any union containing,
13461 // possibly recursively, a member that is such a structure)
13462 // shall not be a member of a structure or an element of an
13464 if (FDTy->isFunctionType()) {
13465 // Field declared as a function.
13466 Diag(FD->getLocation(), diag::err_field_declared_as_function)
13467 << FD->getDeclName();
13468 FD->setInvalidDecl();
13469 EnclosingDecl->setInvalidDecl();
13471 } else if (FDTy->isIncompleteArrayType() && Record &&
13472 ((i + 1 == Fields.end() && !Record->isUnion()) ||
13473 ((getLangOpts().MicrosoftExt ||
13474 getLangOpts().CPlusPlus) &&
13475 (i + 1 == Fields.end() || Record->isUnion())))) {
13476 // Flexible array member.
13477 // Microsoft and g++ is more permissive regarding flexible array.
13478 // It will accept flexible array in union and also
13479 // as the sole element of a struct/class.
13480 unsigned DiagID = 0;
13481 if (Record->isUnion())
13482 DiagID = getLangOpts().MicrosoftExt
13483 ? diag::ext_flexible_array_union_ms
13484 : getLangOpts().CPlusPlus
13485 ? diag::ext_flexible_array_union_gnu
13486 : diag::err_flexible_array_union;
13487 else if (Fields.size() == 1)
13488 DiagID = getLangOpts().MicrosoftExt
13489 ? diag::ext_flexible_array_empty_aggregate_ms
13490 : getLangOpts().CPlusPlus
13491 ? diag::ext_flexible_array_empty_aggregate_gnu
13492 : NumNamedMembers < 1
13493 ? diag::err_flexible_array_empty_aggregate
13497 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13498 << Record->getTagKind();
13499 // While the layout of types that contain virtual bases is not specified
13500 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13501 // virtual bases after the derived members. This would make a flexible
13502 // array member declared at the end of an object not adjacent to the end
13504 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13505 if (RD->getNumVBases() != 0)
13506 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13507 << FD->getDeclName() << Record->getTagKind();
13508 if (!getLangOpts().C99)
13509 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13510 << FD->getDeclName() << Record->getTagKind();
13512 // If the element type has a non-trivial destructor, we would not
13513 // implicitly destroy the elements, so disallow it for now.
13515 // FIXME: GCC allows this. We should probably either implicitly delete
13516 // the destructor of the containing class, or just allow this.
13517 QualType BaseElem = Context.getBaseElementType(FD->getType());
13518 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13519 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13520 << FD->getDeclName() << FD->getType();
13521 FD->setInvalidDecl();
13522 EnclosingDecl->setInvalidDecl();
13525 // Okay, we have a legal flexible array member at the end of the struct.
13526 Record->setHasFlexibleArrayMember(true);
13527 } else if (!FDTy->isDependentType() &&
13528 RequireCompleteType(FD->getLocation(), FD->getType(),
13529 diag::err_field_incomplete)) {
13531 FD->setInvalidDecl();
13532 EnclosingDecl->setInvalidDecl();
13534 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13535 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13536 // A type which contains a flexible array member is considered to be a
13537 // flexible array member.
13538 Record->setHasFlexibleArrayMember(true);
13539 if (!Record->isUnion()) {
13540 // If this is a struct/class and this is not the last element, reject
13541 // it. Note that GCC supports variable sized arrays in the middle of
13543 if (i + 1 != Fields.end())
13544 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13545 << FD->getDeclName() << FD->getType();
13547 // We support flexible arrays at the end of structs in
13548 // other structs as an extension.
13549 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13550 << FD->getDeclName();
13554 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13555 RequireNonAbstractType(FD->getLocation(), FD->getType(),
13556 diag::err_abstract_type_in_decl,
13557 AbstractIvarType)) {
13558 // Ivars can not have abstract class types
13559 FD->setInvalidDecl();
13561 if (Record && FDTTy->getDecl()->hasObjectMember())
13562 Record->setHasObjectMember(true);
13563 if (Record && FDTTy->getDecl()->hasVolatileMember())
13564 Record->setHasVolatileMember(true);
13565 } else if (FDTy->isObjCObjectType()) {
13566 /// A field cannot be an Objective-c object
13567 Diag(FD->getLocation(), diag::err_statically_allocated_object)
13568 << FixItHint::CreateInsertion(FD->getLocation(), "*");
13569 QualType T = Context.getObjCObjectPointerType(FD->getType());
13571 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13572 (!getLangOpts().CPlusPlus || Record->isUnion())) {
13573 // It's an error in ARC if a field has lifetime.
13574 // We don't want to report this in a system header, though,
13575 // so we just make the field unavailable.
13576 // FIXME: that's really not sufficient; we need to make the type
13577 // itself invalid to, say, initialize or copy.
13578 QualType T = FD->getType();
13579 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13580 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13581 SourceLocation loc = FD->getLocation();
13582 if (getSourceManager().isInSystemHeader(loc)) {
13583 if (!FD->hasAttr<UnavailableAttr>()) {
13584 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13585 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13588 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13589 << T->isBlockPointerType() << Record->getTagKind();
13591 ARCErrReported = true;
13593 } else if (getLangOpts().ObjC1 &&
13594 getLangOpts().getGC() != LangOptions::NonGC &&
13595 Record && !Record->hasObjectMember()) {
13596 if (FD->getType()->isObjCObjectPointerType() ||
13597 FD->getType().isObjCGCStrong())
13598 Record->setHasObjectMember(true);
13599 else if (Context.getAsArrayType(FD->getType())) {
13600 QualType BaseType = Context.getBaseElementType(FD->getType());
13601 if (BaseType->isRecordType() &&
13602 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13603 Record->setHasObjectMember(true);
13604 else if (BaseType->isObjCObjectPointerType() ||
13605 BaseType.isObjCGCStrong())
13606 Record->setHasObjectMember(true);
13609 if (Record && FD->getType().isVolatileQualified())
13610 Record->setHasVolatileMember(true);
13611 // Keep track of the number of named members.
13612 if (FD->getIdentifier())
13616 // Okay, we successfully defined 'Record'.
13618 bool Completed = false;
13619 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13620 if (!CXXRecord->isInvalidDecl()) {
13621 // Set access bits correctly on the directly-declared conversions.
13622 for (CXXRecordDecl::conversion_iterator
13623 I = CXXRecord->conversion_begin(),
13624 E = CXXRecord->conversion_end(); I != E; ++I)
13625 I.setAccess((*I)->getAccess());
13627 if (!CXXRecord->isDependentType()) {
13628 if (CXXRecord->hasUserDeclaredDestructor()) {
13629 // Adjust user-defined destructor exception spec.
13630 if (getLangOpts().CPlusPlus11)
13631 AdjustDestructorExceptionSpec(CXXRecord,
13632 CXXRecord->getDestructor());
13635 // Add any implicitly-declared members to this class.
13636 AddImplicitlyDeclaredMembersToClass(CXXRecord);
13638 // If we have virtual base classes, we may end up finding multiple
13639 // final overriders for a given virtual function. Check for this
13641 if (CXXRecord->getNumVBases()) {
13642 CXXFinalOverriderMap FinalOverriders;
13643 CXXRecord->getFinalOverriders(FinalOverriders);
13645 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13646 MEnd = FinalOverriders.end();
13648 for (OverridingMethods::iterator SO = M->second.begin(),
13649 SOEnd = M->second.end();
13650 SO != SOEnd; ++SO) {
13651 assert(SO->second.size() > 0 &&
13652 "Virtual function without overridding functions?");
13653 if (SO->second.size() == 1)
13656 // C++ [class.virtual]p2:
13657 // In a derived class, if a virtual member function of a base
13658 // class subobject has more than one final overrider the
13659 // program is ill-formed.
13660 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13661 << (const NamedDecl *)M->first << Record;
13662 Diag(M->first->getLocation(),
13663 diag::note_overridden_virtual_function);
13664 for (OverridingMethods::overriding_iterator
13665 OM = SO->second.begin(),
13666 OMEnd = SO->second.end();
13668 Diag(OM->Method->getLocation(), diag::note_final_overrider)
13669 << (const NamedDecl *)M->first << OM->Method->getParent();
13671 Record->setInvalidDecl();
13674 CXXRecord->completeDefinition(&FinalOverriders);
13682 Record->completeDefinition();
13684 if (Record->hasAttrs()) {
13685 CheckAlignasUnderalignment(Record);
13687 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13688 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13689 IA->getRange(), IA->getBestCase(),
13690 IA->getSemanticSpelling());
13693 // Check if the structure/union declaration is a type that can have zero
13694 // size in C. For C this is a language extension, for C++ it may cause
13695 // compatibility problems.
13696 bool CheckForZeroSize;
13697 if (!getLangOpts().CPlusPlus) {
13698 CheckForZeroSize = true;
13700 // For C++ filter out types that cannot be referenced in C code.
13701 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13703 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13704 !CXXRecord->isDependentType() &&
13705 CXXRecord->isCLike();
13707 if (CheckForZeroSize) {
13708 bool ZeroSize = true;
13709 bool IsEmpty = true;
13710 unsigned NonBitFields = 0;
13711 for (RecordDecl::field_iterator I = Record->field_begin(),
13712 E = Record->field_end();
13713 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13715 if (I->isUnnamedBitfield()) {
13716 if (I->getBitWidthValue(Context) > 0)
13720 QualType FieldType = I->getType();
13721 if (FieldType->isIncompleteType() ||
13722 !Context.getTypeSizeInChars(FieldType).isZero())
13727 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13728 // allowed in C++, but warn if its declaration is inside
13729 // extern "C" block.
13731 Diag(RecLoc, getLangOpts().CPlusPlus ?
13732 diag::warn_zero_size_struct_union_in_extern_c :
13733 diag::warn_zero_size_struct_union_compat)
13734 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13737 // Structs without named members are extension in C (C99 6.7.2.1p7),
13738 // but are accepted by GCC.
13739 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13740 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13741 diag::ext_no_named_members_in_struct_union)
13742 << Record->isUnion();
13746 ObjCIvarDecl **ClsFields =
13747 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13748 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13749 ID->setEndOfDefinitionLoc(RBrac);
13750 // Add ivar's to class's DeclContext.
13751 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13752 ClsFields[i]->setLexicalDeclContext(ID);
13753 ID->addDecl(ClsFields[i]);
13755 // Must enforce the rule that ivars in the base classes may not be
13757 if (ID->getSuperClass())
13758 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13759 } else if (ObjCImplementationDecl *IMPDecl =
13760 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13761 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13762 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13763 // Ivar declared in @implementation never belongs to the implementation.
13764 // Only it is in implementation's lexical context.
13765 ClsFields[I]->setLexicalDeclContext(IMPDecl);
13766 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13767 IMPDecl->setIvarLBraceLoc(LBrac);
13768 IMPDecl->setIvarRBraceLoc(RBrac);
13769 } else if (ObjCCategoryDecl *CDecl =
13770 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13771 // case of ivars in class extension; all other cases have been
13772 // reported as errors elsewhere.
13773 // FIXME. Class extension does not have a LocEnd field.
13774 // CDecl->setLocEnd(RBrac);
13775 // Add ivar's to class extension's DeclContext.
13776 // Diagnose redeclaration of private ivars.
13777 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13778 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13780 if (const ObjCIvarDecl *ClsIvar =
13781 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13782 Diag(ClsFields[i]->getLocation(),
13783 diag::err_duplicate_ivar_declaration);
13784 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13787 for (const auto *Ext : IDecl->known_extensions()) {
13788 if (const ObjCIvarDecl *ClsExtIvar
13789 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13790 Diag(ClsFields[i]->getLocation(),
13791 diag::err_duplicate_ivar_declaration);
13792 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13797 ClsFields[i]->setLexicalDeclContext(CDecl);
13798 CDecl->addDecl(ClsFields[i]);
13800 CDecl->setIvarLBraceLoc(LBrac);
13801 CDecl->setIvarRBraceLoc(RBrac);
13806 ProcessDeclAttributeList(S, Record, Attr);
13809 /// \brief Determine whether the given integral value is representable within
13810 /// the given type T.
13811 static bool isRepresentableIntegerValue(ASTContext &Context,
13812 llvm::APSInt &Value,
13814 assert(T->isIntegralType(Context) && "Integral type required!");
13815 unsigned BitWidth = Context.getIntWidth(T);
13817 if (Value.isUnsigned() || Value.isNonNegative()) {
13818 if (T->isSignedIntegerOrEnumerationType())
13820 return Value.getActiveBits() <= BitWidth;
13822 return Value.getMinSignedBits() <= BitWidth;
13825 // \brief Given an integral type, return the next larger integral type
13826 // (or a NULL type of no such type exists).
13827 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13828 // FIXME: Int128/UInt128 support, which also needs to be introduced into
13829 // enum checking below.
13830 assert(T->isIntegralType(Context) && "Integral type required!");
13831 const unsigned NumTypes = 4;
13832 QualType SignedIntegralTypes[NumTypes] = {
13833 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13835 QualType UnsignedIntegralTypes[NumTypes] = {
13836 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13837 Context.UnsignedLongLongTy
13840 unsigned BitWidth = Context.getTypeSize(T);
13841 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13842 : UnsignedIntegralTypes;
13843 for (unsigned I = 0; I != NumTypes; ++I)
13844 if (Context.getTypeSize(Types[I]) > BitWidth)
13850 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13851 EnumConstantDecl *LastEnumConst,
13852 SourceLocation IdLoc,
13853 IdentifierInfo *Id,
13855 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13856 llvm::APSInt EnumVal(IntWidth);
13859 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13863 Val = DefaultLvalueConversion(Val).get();
13866 if (Enum->isDependentType() || Val->isTypeDependent())
13867 EltTy = Context.DependentTy;
13869 SourceLocation ExpLoc;
13870 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13871 !getLangOpts().MSVCCompat) {
13872 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13873 // constant-expression in the enumerator-definition shall be a converted
13874 // constant expression of the underlying type.
13875 EltTy = Enum->getIntegerType();
13876 ExprResult Converted =
13877 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13879 if (Converted.isInvalid())
13882 Val = Converted.get();
13883 } else if (!Val->isValueDependent() &&
13884 !(Val = VerifyIntegerConstantExpression(Val,
13885 &EnumVal).get())) {
13886 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13888 if (Enum->isFixed()) {
13889 EltTy = Enum->getIntegerType();
13891 // In Obj-C and Microsoft mode, require the enumeration value to be
13892 // representable in the underlying type of the enumeration. In C++11,
13893 // we perform a non-narrowing conversion as part of converted constant
13894 // expression checking.
13895 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13896 if (getLangOpts().MSVCCompat) {
13897 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13898 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13900 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13902 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13903 } else if (getLangOpts().CPlusPlus) {
13904 // C++11 [dcl.enum]p5:
13905 // If the underlying type is not fixed, the type of each enumerator
13906 // is the type of its initializing value:
13907 // - If an initializer is specified for an enumerator, the
13908 // initializing value has the same type as the expression.
13909 EltTy = Val->getType();
13912 // The expression that defines the value of an enumeration constant
13913 // shall be an integer constant expression that has a value
13914 // representable as an int.
13916 // Complain if the value is not representable in an int.
13917 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13918 Diag(IdLoc, diag::ext_enum_value_not_int)
13919 << EnumVal.toString(10) << Val->getSourceRange()
13920 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13921 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13922 // Force the type of the expression to 'int'.
13923 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13925 EltTy = Val->getType();
13932 if (Enum->isDependentType())
13933 EltTy = Context.DependentTy;
13934 else if (!LastEnumConst) {
13935 // C++0x [dcl.enum]p5:
13936 // If the underlying type is not fixed, the type of each enumerator
13937 // is the type of its initializing value:
13938 // - If no initializer is specified for the first enumerator, the
13939 // initializing value has an unspecified integral type.
13941 // GCC uses 'int' for its unspecified integral type, as does
13943 if (Enum->isFixed()) {
13944 EltTy = Enum->getIntegerType();
13947 EltTy = Context.IntTy;
13950 // Assign the last value + 1.
13951 EnumVal = LastEnumConst->getInitVal();
13953 EltTy = LastEnumConst->getType();
13955 // Check for overflow on increment.
13956 if (EnumVal < LastEnumConst->getInitVal()) {
13957 // C++0x [dcl.enum]p5:
13958 // If the underlying type is not fixed, the type of each enumerator
13959 // is the type of its initializing value:
13961 // - Otherwise the type of the initializing value is the same as
13962 // the type of the initializing value of the preceding enumerator
13963 // unless the incremented value is not representable in that type,
13964 // in which case the type is an unspecified integral type
13965 // sufficient to contain the incremented value. If no such type
13966 // exists, the program is ill-formed.
13967 QualType T = getNextLargerIntegralType(Context, EltTy);
13968 if (T.isNull() || Enum->isFixed()) {
13969 // There is no integral type larger enough to represent this
13970 // value. Complain, then allow the value to wrap around.
13971 EnumVal = LastEnumConst->getInitVal();
13972 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13974 if (Enum->isFixed())
13975 // When the underlying type is fixed, this is ill-formed.
13976 Diag(IdLoc, diag::err_enumerator_wrapped)
13977 << EnumVal.toString(10)
13980 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13981 << EnumVal.toString(10);
13986 // Retrieve the last enumerator's value, extent that type to the
13987 // type that is supposed to be large enough to represent the incremented
13988 // value, then increment.
13989 EnumVal = LastEnumConst->getInitVal();
13990 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13991 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13994 // If we're not in C++, diagnose the overflow of enumerator values,
13995 // which in C99 means that the enumerator value is not representable in
13996 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13997 // permits enumerator values that are representable in some larger
13999 if (!getLangOpts().CPlusPlus && !T.isNull())
14000 Diag(IdLoc, diag::warn_enum_value_overflow);
14001 } else if (!getLangOpts().CPlusPlus &&
14002 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14003 // Enforce C99 6.7.2.2p2 even when we compute the next value.
14004 Diag(IdLoc, diag::ext_enum_value_not_int)
14005 << EnumVal.toString(10) << 1;
14010 if (!EltTy->isDependentType()) {
14011 // Make the enumerator value match the signedness and size of the
14012 // enumerator's type.
14013 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14014 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14017 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14021 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14022 SourceLocation IILoc) {
14023 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14024 !getLangOpts().CPlusPlus)
14025 return SkipBodyInfo();
14027 // We have an anonymous enum definition. Look up the first enumerator to
14028 // determine if we should merge the definition with an existing one and
14030 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14032 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14034 return SkipBodyInfo();
14036 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14038 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14040 Skip.Previous = Hidden;
14044 return SkipBodyInfo();
14047 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14048 SourceLocation IdLoc, IdentifierInfo *Id,
14049 AttributeList *Attr,
14050 SourceLocation EqualLoc, Expr *Val) {
14051 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14052 EnumConstantDecl *LastEnumConst =
14053 cast_or_null<EnumConstantDecl>(lastEnumConst);
14055 // The scope passed in may not be a decl scope. Zip up the scope tree until
14056 // we find one that is.
14057 S = getNonFieldDeclScope(S);
14059 // Verify that there isn't already something declared with this name in this
14061 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14063 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14064 // Maybe we will complain about the shadowed template parameter.
14065 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14066 // Just pretend that we didn't see the previous declaration.
14067 PrevDecl = nullptr;
14070 // C++ [class.mem]p15:
14071 // If T is the name of a class, then each of the following shall have a name
14072 // different from T:
14073 // - every enumerator of every member of class T that is an unscoped
14075 if (!TheEnumDecl->isScoped())
14076 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14077 DeclarationNameInfo(Id, IdLoc));
14079 EnumConstantDecl *New =
14080 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14085 // When in C++, we may get a TagDecl with the same name; in this case the
14086 // enum constant will 'hide' the tag.
14087 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14088 "Received TagDecl when not in C++!");
14089 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14090 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14091 if (isa<EnumConstantDecl>(PrevDecl))
14092 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14094 Diag(IdLoc, diag::err_redefinition) << Id;
14095 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14100 // Process attributes.
14101 if (Attr) ProcessDeclAttributeList(S, New, Attr);
14103 // Register this decl in the current scope stack.
14104 New->setAccess(TheEnumDecl->getAccess());
14105 PushOnScopeChains(New, S);
14107 ActOnDocumentableDecl(New);
14112 // Returns true when the enum initial expression does not trigger the
14113 // duplicate enum warning. A few common cases are exempted as follows:
14114 // Element2 = Element1
14115 // Element2 = Element1 + 1
14116 // Element2 = Element1 - 1
14117 // Where Element2 and Element1 are from the same enum.
14118 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14119 Expr *InitExpr = ECD->getInitExpr();
14122 InitExpr = InitExpr->IgnoreImpCasts();
14124 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14125 if (!BO->isAdditiveOp())
14127 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14130 if (IL->getValue() != 1)
14133 InitExpr = BO->getLHS();
14136 // This checks if the elements are from the same enum.
14137 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14141 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14145 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14155 bool isTombstoneOrEmptyKey;
14156 DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14157 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14160 static DupKey GetDupKey(const llvm::APSInt& Val) {
14161 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14165 struct DenseMapInfoDupKey {
14166 static DupKey getEmptyKey() { return DupKey(0, true); }
14167 static DupKey getTombstoneKey() { return DupKey(1, true); }
14168 static unsigned getHashValue(const DupKey Key) {
14169 return (unsigned)(Key.val * 37);
14171 static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14172 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14173 LHS.val == RHS.val;
14176 } // end anonymous namespace
14178 // Emits a warning when an element is implicitly set a value that
14179 // a previous element has already been set to.
14180 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14182 QualType EnumType) {
14183 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14185 // Avoid anonymous enums
14186 if (!Enum->getIdentifier())
14189 // Only check for small enums.
14190 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14193 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14194 typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14196 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14197 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14200 DuplicatesVector DupVector;
14201 ValueToVectorMap EnumMap;
14203 // Populate the EnumMap with all values represented by enum constants without
14205 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14206 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14208 // Null EnumConstantDecl means a previous diagnostic has been emitted for
14209 // this constant. Skip this enum since it may be ill-formed.
14214 if (ECD->getInitExpr())
14217 DupKey Key = GetDupKey(ECD->getInitVal());
14218 DeclOrVector &Entry = EnumMap[Key];
14220 // First time encountering this value.
14221 if (Entry.isNull())
14225 // Create vectors for any values that has duplicates.
14226 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14227 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14228 if (!ValidDuplicateEnum(ECD, Enum))
14231 DupKey Key = GetDupKey(ECD->getInitVal());
14233 DeclOrVector& Entry = EnumMap[Key];
14234 if (Entry.isNull())
14237 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14238 // Ensure constants are different.
14242 // Create new vector and push values onto it.
14243 ECDVector *Vec = new ECDVector();
14245 Vec->push_back(ECD);
14247 // Update entry to point to the duplicates vector.
14250 // Store the vector somewhere we can consult later for quick emission of
14252 DupVector.push_back(Vec);
14256 ECDVector *Vec = Entry.get<ECDVector*>();
14257 // Make sure constants are not added more than once.
14258 if (*Vec->begin() == ECD)
14261 Vec->push_back(ECD);
14264 // Emit diagnostics.
14265 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14266 DupVectorEnd = DupVector.end();
14267 DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14268 ECDVector *Vec = *DupVectorIter;
14269 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14271 // Emit warning for one enum constant.
14272 ECDVector::iterator I = Vec->begin();
14273 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14274 << (*I)->getName() << (*I)->getInitVal().toString(10)
14275 << (*I)->getSourceRange();
14278 // Emit one note for each of the remaining enum constants with
14280 for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14281 S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14282 << (*I)->getName() << (*I)->getInitVal().toString(10)
14283 << (*I)->getSourceRange();
14288 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14289 bool AllowMask) const {
14290 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14291 assert(ED->isCompleteDefinition() && "expected enum definition");
14293 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14294 llvm::APInt &FlagBits = R.first->second;
14297 for (auto *E : ED->enumerators()) {
14298 const auto &EVal = E->getInitVal();
14299 // Only single-bit enumerators introduce new flag values.
14300 if (EVal.isPowerOf2())
14301 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14305 // A value is in a flag enum if either its bits are a subset of the enum's
14306 // flag bits (the first condition) or we are allowing masks and the same is
14307 // true of its complement (the second condition). When masks are allowed, we
14308 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14310 // While it's true that any value could be used as a mask, the assumption is
14311 // that a mask will have all of the insignificant bits set. Anything else is
14312 // likely a logic error.
14313 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14314 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14317 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14318 SourceLocation RBraceLoc, Decl *EnumDeclX,
14319 ArrayRef<Decl *> Elements,
14320 Scope *S, AttributeList *Attr) {
14321 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14322 QualType EnumType = Context.getTypeDeclType(Enum);
14325 ProcessDeclAttributeList(S, Enum, Attr);
14327 if (Enum->isDependentType()) {
14328 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14329 EnumConstantDecl *ECD =
14330 cast_or_null<EnumConstantDecl>(Elements[i]);
14331 if (!ECD) continue;
14333 ECD->setType(EnumType);
14336 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14340 // TODO: If the result value doesn't fit in an int, it must be a long or long
14341 // long value. ISO C does not support this, but GCC does as an extension,
14343 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14344 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14345 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14347 // Verify that all the values are okay, compute the size of the values, and
14348 // reverse the list.
14349 unsigned NumNegativeBits = 0;
14350 unsigned NumPositiveBits = 0;
14352 // Keep track of whether all elements have type int.
14353 bool AllElementsInt = true;
14355 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14356 EnumConstantDecl *ECD =
14357 cast_or_null<EnumConstantDecl>(Elements[i]);
14358 if (!ECD) continue; // Already issued a diagnostic.
14360 const llvm::APSInt &InitVal = ECD->getInitVal();
14362 // Keep track of the size of positive and negative values.
14363 if (InitVal.isUnsigned() || InitVal.isNonNegative())
14364 NumPositiveBits = std::max(NumPositiveBits,
14365 (unsigned)InitVal.getActiveBits());
14367 NumNegativeBits = std::max(NumNegativeBits,
14368 (unsigned)InitVal.getMinSignedBits());
14370 // Keep track of whether every enum element has type int (very commmon).
14371 if (AllElementsInt)
14372 AllElementsInt = ECD->getType() == Context.IntTy;
14375 // Figure out the type that should be used for this enum.
14377 unsigned BestWidth;
14379 // C++0x N3000 [conv.prom]p3:
14380 // An rvalue of an unscoped enumeration type whose underlying
14381 // type is not fixed can be converted to an rvalue of the first
14382 // of the following types that can represent all the values of
14383 // the enumeration: int, unsigned int, long int, unsigned long
14384 // int, long long int, or unsigned long long int.
14386 // An identifier declared as an enumeration constant has type int.
14387 // The C99 rule is modified by a gcc extension
14388 QualType BestPromotionType;
14390 bool Packed = Enum->hasAttr<PackedAttr>();
14391 // -fshort-enums is the equivalent to specifying the packed attribute on all
14392 // enum definitions.
14393 if (LangOpts.ShortEnums)
14396 if (Enum->isFixed()) {
14397 BestType = Enum->getIntegerType();
14398 if (BestType->isPromotableIntegerType())
14399 BestPromotionType = Context.getPromotedIntegerType(BestType);
14401 BestPromotionType = BestType;
14403 BestWidth = Context.getIntWidth(BestType);
14405 else if (NumNegativeBits) {
14406 // If there is a negative value, figure out the smallest integer type (of
14407 // int/long/longlong) that fits.
14408 // If it's packed, check also if it fits a char or a short.
14409 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14410 BestType = Context.SignedCharTy;
14411 BestWidth = CharWidth;
14412 } else if (Packed && NumNegativeBits <= ShortWidth &&
14413 NumPositiveBits < ShortWidth) {
14414 BestType = Context.ShortTy;
14415 BestWidth = ShortWidth;
14416 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14417 BestType = Context.IntTy;
14418 BestWidth = IntWidth;
14420 BestWidth = Context.getTargetInfo().getLongWidth();
14422 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14423 BestType = Context.LongTy;
14425 BestWidth = Context.getTargetInfo().getLongLongWidth();
14427 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14428 Diag(Enum->getLocation(), diag::ext_enum_too_large);
14429 BestType = Context.LongLongTy;
14432 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14434 // If there is no negative value, figure out the smallest type that fits
14435 // all of the enumerator values.
14436 // If it's packed, check also if it fits a char or a short.
14437 if (Packed && NumPositiveBits <= CharWidth) {
14438 BestType = Context.UnsignedCharTy;
14439 BestPromotionType = Context.IntTy;
14440 BestWidth = CharWidth;
14441 } else if (Packed && NumPositiveBits <= ShortWidth) {
14442 BestType = Context.UnsignedShortTy;
14443 BestPromotionType = Context.IntTy;
14444 BestWidth = ShortWidth;
14445 } else if (NumPositiveBits <= IntWidth) {
14446 BestType = Context.UnsignedIntTy;
14447 BestWidth = IntWidth;
14449 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14450 ? Context.UnsignedIntTy : Context.IntTy;
14451 } else if (NumPositiveBits <=
14452 (BestWidth = Context.getTargetInfo().getLongWidth())) {
14453 BestType = Context.UnsignedLongTy;
14455 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14456 ? Context.UnsignedLongTy : Context.LongTy;
14458 BestWidth = Context.getTargetInfo().getLongLongWidth();
14459 assert(NumPositiveBits <= BestWidth &&
14460 "How could an initializer get larger than ULL?");
14461 BestType = Context.UnsignedLongLongTy;
14463 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14464 ? Context.UnsignedLongLongTy : Context.LongLongTy;
14468 // Loop over all of the enumerator constants, changing their types to match
14469 // the type of the enum if needed.
14470 for (auto *D : Elements) {
14471 auto *ECD = cast_or_null<EnumConstantDecl>(D);
14472 if (!ECD) continue; // Already issued a diagnostic.
14474 // Standard C says the enumerators have int type, but we allow, as an
14475 // extension, the enumerators to be larger than int size. If each
14476 // enumerator value fits in an int, type it as an int, otherwise type it the
14477 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
14478 // that X has type 'int', not 'unsigned'.
14480 // Determine whether the value fits into an int.
14481 llvm::APSInt InitVal = ECD->getInitVal();
14483 // If it fits into an integer type, force it. Otherwise force it to match
14484 // the enum decl type.
14488 if (!getLangOpts().CPlusPlus &&
14489 !Enum->isFixed() &&
14490 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14491 NewTy = Context.IntTy;
14492 NewWidth = IntWidth;
14494 } else if (ECD->getType() == BestType) {
14495 // Already the right type!
14496 if (getLangOpts().CPlusPlus)
14497 // C++ [dcl.enum]p4: Following the closing brace of an
14498 // enum-specifier, each enumerator has the type of its
14500 ECD->setType(EnumType);
14504 NewWidth = BestWidth;
14505 NewSign = BestType->isSignedIntegerOrEnumerationType();
14508 // Adjust the APSInt value.
14509 InitVal = InitVal.extOrTrunc(NewWidth);
14510 InitVal.setIsSigned(NewSign);
14511 ECD->setInitVal(InitVal);
14513 // Adjust the Expr initializer and type.
14514 if (ECD->getInitExpr() &&
14515 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14516 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14518 ECD->getInitExpr(),
14519 /*base paths*/ nullptr,
14521 if (getLangOpts().CPlusPlus)
14522 // C++ [dcl.enum]p4: Following the closing brace of an
14523 // enum-specifier, each enumerator has the type of its
14525 ECD->setType(EnumType);
14527 ECD->setType(NewTy);
14530 Enum->completeDefinition(BestType, BestPromotionType,
14531 NumPositiveBits, NumNegativeBits);
14533 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14535 if (Enum->hasAttr<FlagEnumAttr>()) {
14536 for (Decl *D : Elements) {
14537 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14538 if (!ECD) continue; // Already issued a diagnostic.
14540 llvm::APSInt InitVal = ECD->getInitVal();
14541 if (InitVal != 0 && !InitVal.isPowerOf2() &&
14542 !IsValueInFlagEnum(Enum, InitVal, true))
14543 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14548 // Now that the enum type is defined, ensure it's not been underaligned.
14549 if (Enum->hasAttrs())
14550 CheckAlignasUnderalignment(Enum);
14553 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14554 SourceLocation StartLoc,
14555 SourceLocation EndLoc) {
14556 StringLiteral *AsmString = cast<StringLiteral>(expr);
14558 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14559 AsmString, StartLoc,
14561 CurContext->addDecl(New);
14565 static void checkModuleImportContext(Sema &S, Module *M,
14566 SourceLocation ImportLoc, DeclContext *DC,
14567 bool FromInclude = false) {
14568 SourceLocation ExternCLoc;
14570 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14571 switch (LSD->getLanguage()) {
14572 case LinkageSpecDecl::lang_c:
14573 if (ExternCLoc.isInvalid())
14574 ExternCLoc = LSD->getLocStart();
14576 case LinkageSpecDecl::lang_cxx:
14579 DC = LSD->getParent();
14582 while (isa<LinkageSpecDecl>(DC))
14583 DC = DC->getParent();
14585 if (!isa<TranslationUnitDecl>(DC)) {
14586 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14587 ? diag::ext_module_import_not_at_top_level_noop
14588 : diag::err_module_import_not_at_top_level_fatal)
14589 << M->getFullModuleName() << DC;
14590 S.Diag(cast<Decl>(DC)->getLocStart(),
14591 diag::note_module_import_not_at_top_level) << DC;
14592 } else if (!M->IsExternC && ExternCLoc.isValid()) {
14593 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14594 << M->getFullModuleName();
14595 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14599 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14600 return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14603 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14604 SourceLocation ImportLoc,
14605 ModuleIdPath Path) {
14607 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14608 /*IsIncludeDirective=*/false);
14612 VisibleModules.setVisible(Mod, ImportLoc);
14614 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14616 // FIXME: we should support importing a submodule within a different submodule
14617 // of the same top-level module. Until we do, make it an error rather than
14618 // silently ignoring the import.
14619 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14620 Diag(ImportLoc, diag::err_module_self_import)
14621 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14622 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14623 Diag(ImportLoc, diag::err_module_import_in_implementation)
14624 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14626 SmallVector<SourceLocation, 2> IdentifierLocs;
14627 Module *ModCheck = Mod;
14628 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14629 // If we've run out of module parents, just drop the remaining identifiers.
14630 // We need the length to be consistent.
14633 ModCheck = ModCheck->Parent;
14635 IdentifierLocs.push_back(Path[I].second);
14638 ImportDecl *Import = ImportDecl::Create(Context,
14639 Context.getTranslationUnitDecl(),
14640 AtLoc.isValid()? AtLoc : ImportLoc,
14641 Mod, IdentifierLocs);
14642 Context.getTranslationUnitDecl()->addDecl(Import);
14646 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14647 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14649 // Determine whether we're in the #include buffer for a module. The #includes
14650 // in that buffer do not qualify as module imports; they're just an
14651 // implementation detail of us building the module.
14653 // FIXME: Should we even get ActOnModuleInclude calls for those?
14654 bool IsInModuleIncludes =
14655 TUKind == TU_Module &&
14656 getSourceManager().isWrittenInMainFile(DirectiveLoc);
14658 // If this module import was due to an inclusion directive, create an
14659 // implicit import declaration to capture it in the AST.
14660 if (!IsInModuleIncludes) {
14661 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14662 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14665 TU->addDecl(ImportD);
14666 Consumer.HandleImplicitImportDecl(ImportD);
14669 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14670 VisibleModules.setVisible(Mod, DirectiveLoc);
14673 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14674 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14676 if (getLangOpts().ModulesLocalVisibility)
14677 VisibleModulesStack.push_back(std::move(VisibleModules));
14678 VisibleModules.setVisible(Mod, DirectiveLoc);
14681 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14682 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14684 if (getLangOpts().ModulesLocalVisibility) {
14685 VisibleModules = std::move(VisibleModulesStack.back());
14686 VisibleModulesStack.pop_back();
14687 VisibleModules.setVisible(Mod, DirectiveLoc);
14691 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14693 // Bail if we're not allowed to implicitly import a module here.
14694 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14697 // Create the implicit import declaration.
14698 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14699 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14701 TU->addDecl(ImportD);
14702 Consumer.HandleImplicitImportDecl(ImportD);
14704 // Make the module visible.
14705 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14706 VisibleModules.setVisible(Mod, Loc);
14709 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14710 IdentifierInfo* AliasName,
14711 SourceLocation PragmaLoc,
14712 SourceLocation NameLoc,
14713 SourceLocation AliasNameLoc) {
14714 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14715 LookupOrdinaryName);
14716 AsmLabelAttr *Attr =
14717 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14719 // If a declaration that:
14720 // 1) declares a function or a variable
14721 // 2) has external linkage
14722 // already exists, add a label attribute to it.
14723 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14724 if (isDeclExternC(PrevDecl))
14725 PrevDecl->addAttr(Attr);
14727 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14728 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14729 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14731 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14734 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14735 SourceLocation PragmaLoc,
14736 SourceLocation NameLoc) {
14737 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14740 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14742 (void)WeakUndeclaredIdentifiers.insert(
14743 std::pair<IdentifierInfo*,WeakInfo>
14744 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14748 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14749 IdentifierInfo* AliasName,
14750 SourceLocation PragmaLoc,
14751 SourceLocation NameLoc,
14752 SourceLocation AliasNameLoc) {
14753 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14754 LookupOrdinaryName);
14755 WeakInfo W = WeakInfo(Name, NameLoc);
14757 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14758 if (!PrevDecl->hasAttr<AliasAttr>())
14759 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14760 DeclApplyPragmaWeak(TUScope, ND, W);
14762 (void)WeakUndeclaredIdentifiers.insert(
14763 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14767 Decl *Sema::getObjCDeclContext() const {
14768 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14771 AvailabilityResult Sema::getCurContextAvailability() const {
14772 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14774 return AR_Available;
14776 // If we are within an Objective-C method, we should consult
14777 // both the availability of the method as well as the
14778 // enclosing class. If the class is (say) deprecated,
14779 // the entire method is considered deprecated from the
14780 // purpose of checking if the current context is deprecated.
14781 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14782 AvailabilityResult R = MD->getAvailability();
14783 if (R != AR_Available)
14785 D = MD->getClassInterface();
14787 // If we are within an Objective-c @implementation, it
14788 // gets the same availability context as the @interface.
14789 else if (const ObjCImplementationDecl *ID =
14790 dyn_cast<ObjCImplementationDecl>(D)) {
14791 D = ID->getClassInterface();
14793 // Recover from user error.
14794 return D ? D->getAvailability() : AR_Available;